(Leetcode)215.Kth Largest Element in an Array(medium)

来源:互联网 发布:app数据查询 编辑:程序博客网 时间:2024/06/06 20:54

Find the kth largest element in an unsorted array. Note that it is the kth largest element in the sorted order, not the kth distinct element.
For example,
Given [3,2,1,5,6,4] and k = 2, return 5.
Note:
You may assume k is always valid, 1 ≤ k ≤ array’s length.

在一个数组中求第k大的数,采用分治的方法,先任取一个数作为标准(我取得是第一个数),遍历数组,将比标准大的放左边,比标准小的放右边,得到标准数在数组中的排位x,若x即为k,则返回标准数,若k比x小或大,则在相应区域重复上面步骤,直到x与k相同。
我的代码:

class Solution {public:    int findKthLargest(vector<int>& nums, int k) {        int i = 0;        while (i<nums.size()) {            if (nums.size() == 1)                return nums[0];            int pivot = nums[i];            int x = i + 1;            int y = i + 1;    //用于确立pivot的位置            while (y < nums.size()) {                if (nums[y] > pivot) {                    swap(nums[x], nums[y]);                    x++;               }                y++;            }            swap(nums[i], nums[x-1]); //x-1即为pivot所在的位置            if (x-1 == (k-1)) {                return nums[x-1];            }            else if ((k-1) < x-1) {                continue;            }            else {                i = x;                continue;            }        }        return 0;    }};
0 0