您的位置:首页 > 其它

LeetCode-215.Kth Largest Element in an Array

2016-05-20 11:23 323 查看
https://leetcode.com/problems/kth-largest-element-in-an-array/

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.


public int FindKthLargest(int[] nums, int k)
{
Array.Sort(nums);
return nums[nums.Length-k];
}


2

使用基于红黑树实现的multiset数据结构

int findKthLargest(vector<int>& nums, int k)
{
multiset<int> res;
for (int num : nums)
{
if (res.size() < k)
res.insert(num);
else
{
if (num > *res.begin())
{
res.erase(res.begin());
res.insert(num);
}
}
}
return *res.begin();
}


3

快排

public class Solution
{
public int FindKthLargest(int[] nums, int k)
{
Sort(nums, 0, nums.Length - 1);
return nums[k-1];
}

private void Sort(int[] nums, int l, int r)
{
if (l<r)
{
int i = l,j=r,x=nums[i];
while (i<j)
{
while (i < j && nums[j] <= x)
j--;
if (i < j)
{
nums[i] = nums[j];
i++;
}

while (i < j && nums[i] > x)
i++;
if (i < j)
{
nums[j] = nums[i];
j--;
}
}
nums[i] = x;
Sort(nums, l, i - 1);
Sort(nums, i + 1, r);
}
}
}

针对此题优化排序函数,

因为只要第k大,所以不用全排序

private void Sort(int[] nums, int l, int r,int k)
{
if (l<r)
{
int i = l,j=r,x=nums[i];
while (i<j)
{
while (i < j && nums[j] <= x)
j--;
if (i < j)
{
nums[i] = nums[j];
i++;
}

while (i < j && nums[i] > x)
i++;
if (i < j)
{
nums[j] = nums[i];
j--;
}
}
nums[i] = x;
if (i+1 == k)
return;
else if(i+1>k)
Sort(nums, l, i - 1,k);
else
Sort(nums, i + 1, r,k);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode