关闭

LeetCode Kth Largest Element in an Array

标签: javaleetcodeQuick Select
130人阅读 评论(0) 收藏 举报
分类:

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;
	}
}


0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:62648次
    • 积分:3261
    • 等级:
    • 排名:第10459名
    • 原创:288篇
    • 转载:0篇
    • 译文:0篇
    • 评论:4条
    最新评论