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:
似乎一个排序就出来了,可能是数据卡的不够严。
网上找到了一个更加靠谱的解决方案,是快速选择法(Quick Select)Quick Select
其实很类似快排。
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; } }
相关文章推荐
- 用SignalR 2.0开发客服系统[系列2:实现聊天室]
- 会话Session和cookie
- linux 邮件服务器
- 光纤熔接损耗原因?
- VS 2008的64位编译环境的安装和使用
- 用JAVA 查询 Active Directory(AD)
- linux vim 去掉 bomb
- Apple Developer Registration and DUNS Number Not Accepted
- Android LayoutInflater详解 (转)
- 用JAVA 查询 Active Directory(AD)
- 计数排序,基数排序,桶排序
- 16-linux中停止tomcat服务器Connection Refused
- 运维自动化之使用Cobbler自动化部署Linux操作系统
- 28.字符串的排列
- 计算机视觉的一些测试数据集和源码站点
- 在Android中引入Java8的lambda表达式
- Visual Studio shortcut keys
- 《云计算》学习笔记3——Google的云计算原理与应用(分布式锁服务——Chubby)
- layer_list和shape的混搭使用
- java基础--基本数据类型