全球最实用的IT互联网信息网站!

AI人工智能P2P分享&下载搜索网页发布信息网站地图

当前位置:诺佳网 > 电子/半导体 > 区块链 >

LeetCode 215. Kth Largest Element in an Array

时间:2018-01-17 01:46

人气:

作者:admin

标签: leetcode  Kth  215.  Elem  Largest 

导读:LeetCode 215. Kth Largest Element in an Array-LeetCode 215. Kth Largest Element in an ArrayDescription 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 eleme...

LeetCode 215. Kth Largest Element in an Array Description

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.

public class Solution { public int findKthLargest(int[] nums, int k) { int index = quickSelect(nums, 0, nums.length-1, k-1); return nums[index]; } private int quickSelect(int[] nums, int lo, int hi, int k) { int lt = lo; int gt = hi + 1; int i = lo + 1; int pivot = nums[lo]; while (i < gt) { if (nums[i] > pivot) { swap(nums, i, lt + 1); lt++; i++; } else if (nums[i] < pivot) { swap(nums, i, gt - 1); gt--; } else { i++; } } swap(nums, lo, lt); if (lt == k) { return lt; } else if (lt < k) { return quickSelect(nums, lt + 1, hi, k); } else { return quickSelect(nums, lo, lt - 1, k); } } private void swap(int[] a, int i, int j) { int temp = a[i]; a[i] = a[j]; a[j] = temp; } } Complexity analysis

Time complexity : O(n).
Space complexity : O(log(n

温馨提示:以上内容整理于网络,仅供参考,如果对您有帮助,留下您的阅读感言吧!
相关阅读
本类排行
相关标签
本类推荐

CPU | 内存 | 硬盘 | 显卡 | 显示器 | 主板 | 电源 | 键鼠 | 网站地图

Copyright © 2025-2035 诺佳网 版权所有 备案号:赣ICP备2025066733号
本站资料均来源互联网收集整理,作品版权归作者所有,如果侵犯了您的版权,请跟我们联系。

关注微信