215. Kth Largest Element in an Array

栏目: Java · 发布时间: 5年前

内容简介: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.Example 1:Example 2:

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.

Example 1:

Input: [3,2,1,5,6,4] and k = 2
Output: 5

Example 2:

Input: [3,2,3,1,2,4,5,5,6] and k = 4
Output: 4

Note:

You may assume k is always valid, 1 ≤ k ≤ array's length.

难度:medium

题目:找出在没有 排序 的数组中第K大的元素,注意是排序后的第K大的元素,不是第K个不同元素。

思路:快速排序

Runtime: 29 ms, faster than 36.08% of Java online submissions for Kth Largest Element in an Array.

Memory Usage: 38.8 MB, less than 51.09% of Java online submissions for Kth Largest Element in an Array.

class Solution {
    public int findKthLargest(int[] nums, int k) {
        int idx = -1;
        k = nums.length - k;
        for (int i = 0, j = nums.length - 1; i <= j && idx != k;) {
            idx = quickSort(nums, i, j);
            if (idx < k) {
                i = idx + 1;
            } else if (idx > k) {
                j = idx - 1;
            }
        }
        
        return nums[idx];
    }
    
    private int quickSort(int[] nums, int i, int j) {
        int piovt = nums[i];
        while (i < j) {
            while (i < j && nums[j] >= piovt) {
                j--;
            }
            nums[i] = nums[j];
            while (i < j && nums[i] < piovt) {
                i++;
            }
            nums[j] = nums[i];
        }
        nums[i] = piovt;
        
        return i;
    }
}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

阿里传

阿里传

波特·埃里斯曼 / 张光磊、吕靖纬、崔玉开 / 中信出版社 / 2015-9-15 / CNY 49.00

你只知道阿里巴巴故事的中国部分,而这本书会完整呈现故事的全部。 波特•埃里斯曼是阿里巴巴创业时期为数不多的外国高管。他于2000~2008年在阿里巴巴担任副总裁,这本书记录了他在阿里巴巴8年的时间里的创业故事、商业经验以及在阿里巴巴和马云、蔡崇信、关明生等阿里巴巴早期团队并肩奋战的故事。 在波特眼中,阿里巴巴的成功经验和模式是可以复制的,阿里巴巴曾经犯过的错误,走过的弯路,我们也可以绕......一起来看看 《阿里传》 这本书的介绍吧!

JS 压缩/解压工具
JS 压缩/解压工具

在线压缩/解压 JS 代码

图片转BASE64编码
图片转BASE64编码

在线图片转Base64编码工具

UNIX 时间戳转换
UNIX 时间戳转换

UNIX 时间戳转换