Looking for a large number of K in the integer array

Description Title: In an array of integers, depending on the idea fast row, find the array of a large number of K

Ideas:

  1. Thought using fast discharge, for example, looking for the first 24 elements in the large elements 49,
  2. First, a fast row, (the first half into a large, into the second half of the know), the central axis is assumed to give p
  3. Analyzing p-low + 1 == k, if established directly outputs a [p], (since the first half is larger than the k-1 has a [p] element, so that a [p] is the k-th largest element)
  4. If the p-low + 1> k, the k-th largest element of the front half, when updating high = p-1, continue to Step 2
  5. If the p-low + <k, the k-th largest element in the second half of this time updated low = p + 1, and k = k- (p = low + 1), the complexity continues to Step 2 [time of O ( n-)]

Code shows:

package com.bittech.Test;

/**
 * package:com.bittech.Test
 * Description:TODO
 * @date:2019/5/26
 * @Author:weiwei
 **/
public class Test0526 {
    public int findKth(int[] a, int n, int k) {
        return findKth(a, 0, n - 1, k);
    }

    public int findKth(int[] a, int low, int high, int k) {
        int part = partation(a, low, high);

        if (k == part - low + 1) {
            return a[part];
        } else if (k > part - low + 1) {
            return findKth(a, part + 1, high, k - part + low - 1);
        } else {
            return findKth(a, low, part - 1, k);
        }
    }

    public int partation(int[] a, int low, int high) {
        int key = a[low];
        while (low < high) {
            while (low < high && a[high] <= key) {
                high--;
                a[low] = a[high];
            }
            while (low < high && a[low] >= key) {
                low++;
                a[high] = a[low];
            }
            a[low] = key;
            return low;
        }
        return low;
    }
}

 

Guess you like

Origin blog.csdn.net/weixin_43224539/article/details/90579859