无序数组求第K大数


int findKthLargest(int []nums, int k) {
        int m = nums.length;
        k = m - k;
        return helper(nums, 0, m - 1, k);
    }
  int helper(int []nums, int left, int right, int k) {
        int pos = partion2(nums, left, right);
        if (pos == k) {
            return nums[pos];
        }
        if (pos < k) {
            return helper(nums, pos + 1, right, k);
        }
        return helper(nums, left, pos - 1, k);
    }   
 int partion2(int []nums, int left, int right) {//第二种partion的写法
        int i = left, j = right + 1;
        int pivot = nums[left];
        while (i < j) {
            while (i < right && nums[++i] < pivot);
            while (j > left && nums[--j] > pivot);
            if (i >= j) {
                break;
            }
            swap(nums, i,j);
        }
        swap(nums,left,j);
        return j;
    }
    private void swap(int [] nums,int i, int j) {
		// TODO Auto-generated method stub
		int temp ;
		temp = nums[i];
		nums[i] = nums[j];
		nums[j] = temp;
	}
	
   
    

你可能感兴趣的:(算法学习)