码迷,mamicode.com
首页 > 其他好文 > 详细

leetcode刷题

时间:2017-03-01 22:59:41      阅读:244      评论:0      收藏:0      [点我收藏+]

标签:contract   find   poll   exp   解法   turn   isp   splay   for   

2017/3/1

215. 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.

自己的代码:

技术分享
/**
* 先利用Arrays的sort()函数对给定的数组进行排序,
* 得到的数组是升序排列的,然后获得数组的长度,重新申请一个新的数组,
* 将之前的数组从最后一个开始,一次存入新数组的第一个位置开始,
* 这样新的数组就成了降序排列,这是返回数组当中的第k个位置的数值即可
* @param nums
* @param k
* @return
*/

public class Solution {
    public int findKthLargest(int[] nums, int k) {
        Arrays.sort(nums);
        int n=nums.length;
        int[] res=new int[n];
        for(int i=nums.length-1,j=0;i>=0;i--,j++) {
            res[j]=nums[i];
        }
        return res[k-1];
    }
}
View Code

另一种解法是利用PriorityQueue,关于priorityQueue的使用详情,博客如下http://www.cnblogs.com/CarpenterLee/p/5488070.html,具体代码如下:

技术分享
class Solution {
    /**
     * @return
     */
    public int findKthLargest(int[] nums, int k) {
        PriorityQueue<Integer> largek = new PriorityQueue<Integer>();
        for (int i : nums) {
            largek.add(i);
            if (largek.size() > k) {
                largek.poll();
            }
        }
        return largek.poll();
    }
};
View Code

最优解有待继续解答。。

---------------------------------------------------------------------------------------------------------------------------------

leetcode刷题

标签:contract   find   poll   exp   解法   turn   isp   splay   for   

原文地址:http://www.cnblogs.com/upcwanghaibo/p/6486476.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!