您的位置:首页 > 其它

LeetCode Kth Largest Element in an Array

2015-07-09 15:50 323 查看
Description:

Find all possible combinations of k numbers that add up to a number n, given that only numbers from 1 to 9 can
be used and each combination should be a unique set of numbers.

Ensure that numbers within the set are sorted in ascending order.
Solution:

似乎一个排序就出来了,可能是数据卡的不够严。

import java.util.*;

public class Solution {

public int findKthLargest(int[] nums, int k) {
Arrays.sort(nums);
return nums[nums.length - k];
}
}


网上找到了一个更加靠谱的解决方案,是快速选择法(Quick Select)Quick Select

其实很类似快排。

import java.util.*;

public class Solution {

public int findKthLargest(int[] nums, int k) {
Arrays.sort(nums);
return nums[nums.length - k];
}

int findKth(int nums[], int start, int end, int k) {
int mark = partition(nums, start, end);
if (mark == k)
return nums[mark];
else if (mark < k)
return findKth(nums, mark + 1, end, k - mark);
else
return findKth(nums, start, mark, k);

}

int partition(int[] nums, int start, int end) {
int mark = nums[start];
int tot = start + 1;

for (int i = start + 1; i <= end; i++) {
if (nums[i] <= mark) {
swap(nums, tot++, i);
}
}

swap(nums, start, tot);
return tot;
}

void swap(int[] nums, int i, int j) {
int c = nums[i];
nums[i] = nums[j];
nums[j] = c;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: