码迷,mamicode.com
首页 > 编程语言 > 详细

【LeetCode-面试算法经典-Java实现】【215-Kth Largest Element in an Array(数组中第K大的数)】

时间:2015-08-28 07:20:26      阅读:368      评论:0      收藏:0      [点我收藏+]

标签:数组   算法   面试   java   

【215-Kth Largest Element in an Array(数组中第K大的数)】


【LeetCode-面试算法经典-Java实现】【所有题目目录索引】


代码下载【https://github.com/Wang-Jun-Chao】

原题

  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.

题目大意

  从一个未经排序的数组中找出第k大的元素。注意是排序之后的第k大,而非第k个不重复的元素可以假设k一定是有效的, 1 ≤ k ≤ 数组长度

解题思路

  O(n)解法:快速选择(QuickSelect)算法

代码实现

算法实现类

import java.util.Collections;

public class Solution {

    public int findKthLargest(int[] nums, int k) {

        if (k < 1 || nums == null || nums.length < k) {
            throw new IllegalArgumentException();
        }

        return findKthLargest(nums, 0, nums.length - 1, k);
    }

    public int findKthLargest(int[] nums, int start, int end, int k) {

        // 中枢值
        int pivot = nums[start];
        int lo = start;
        int hi = end;

        while (lo < hi) {
            // 将小于中枢值的数移动到数组左边
            while (lo < hi && nums[hi] >= pivot) {
                hi--;
            }
            nums[lo] = nums[hi];

            // 将大于中枢值的数移动到数组右边
            while (lo < hi && nums[lo] <= pivot) {
                lo++;
            }
            nums[hi] = nums[lo];
        }

        nums[lo] = pivot;

        // 如果已经找到了
        if (end - lo + 1 == k) {
            return pivot;
        }
        // 第k大的数在lo位置的右边
        else if (end - lo + 1 > k){
            return findKthLargest(nums, lo + 1, end, k);
        }
        // 第k大的数在lo位置的左边
        else {
            // k-(end-lo+1)
            // (end-lo+1):表示从lo位置开始到end位置的元素个数,就是舍掉右半部分
            // 原来的第k大变成k-(end-lo+1)大
            return findKthLargest(nums, start, lo - 1, k - (end - lo + 1));
        }
    }
}

评测结果

  点击图片,鼠标不释放,拖动一段位置,释放后在新的窗口中查看完整图片。

技术分享

特别说明

欢迎转载,转载请注明出处【http://blog.csdn.net/derrantcm/article/details/48046265

版权声明:本文为博主原创文章,未经博主允许不得转载。

【LeetCode-面试算法经典-Java实现】【215-Kth Largest Element in an Array(数组中第K大的数)】

标签:数组   算法   面试   java   

原文地址:http://blog.csdn.net/derrantcm/article/details/48046265

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