215. Kth Largest Element in an Array
https://leetcode.com/problems/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.
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.
這題只要懂得快速排序的partition函式就行了。快速排序的partition函式執行一次是log(n)時間,一次執行完了會返回pivot在陣列中的正確位置,那麼這個位置+1如果正好是k,就是我們要找的結果了。
不過這個時間複雜度有點難判斷啊,首先肯定是高於n*log(n)的,因為每次搜尋都丟掉一半,比quicksort快。網上說是O(n)。
public int findKthLargest(int[] nums, int k) {
if (k < 1 || k > nums.length || nums == null) return Integer.MAX_VALUE;
return helper(nums, 0, nums.length - 1, k);
}
//要注意index需要+1
private int helper(int[] nums, int low, int high, int k) {
int index = partition(nums, low, high);
if (index + 1 == k) {
return nums[index];
} else if (index + 1 < k) {
return helper(nums, index + 1, high, k);
} else {
return helper(nums, low, index - 1, k);
}
}
private int partition(int[] nums, int low, int high) {
int i = low, pivot = nums[high];
for (int j = low; j < high; j++) {
if (nums[j] > pivot) {
swap(i, j, nums);
i++;
}
}
swap(i, high, nums);
return i;
}
private void swap(int a, int b, int[] arr) {
int tmp = arr[a];
arr[a] = arr[b];
arr[b] = tmp;
}
相關文章
- python leetcode 215. Kth Largest Element in an ArrayPythonLeetCode
- LeetCode Kth Largest Element in an ArrayLeetCode
- 【LEETCODE】模擬面試-215. Kth Largest EleLeetCode面試
- LeetCode C++ 703. Kth Largest Element in a Stream【Heap/Design】簡單LeetCodeC++
- [LeetCode] 230. Kth Smallest Element in a BSTLeetCode
- [LeetCode] 378. Kth Smallest Element in a Sorted MatrixLeetCode
- Leetcode 34 Find First and Last Position of Element in Sorted ArrayLeetCodeAST
- LeetCode之N-Repeated Element in Size 2N Array(Kotlin)LeetCodeKotlin
- [LeetCode/LintCode] Largest Palindrome ProductLeetCode
- HDU2665 Kth number【主席樹】
- leetcode 368. Largest Divisible SubsetLeetCode
- 對Largest函式的測試函式
- [LeetCode] 1545. Find Kth Bit in Nth Binary StringLeetCode
- 515-Find Largest Value in Each Tree Row
- 什麼是 Dynatrace 的 Largest Contentful PaintAI
- 215. 陣列中的第K個最大元素陣列
- Array.from和 Array.of
- [leetcode] 1624. Largest Substring Between Two Equal CharactersLeetCode
- [LeetCode] 2275. Largest Combination With Bitwise AND Greater Than ZeroLeetCode
- array
- PHP用foreach來表達array_walk/array_filter/array_map/array_reducePHPFilter
- Array()與Array.of()方法區別
- JS Array.reduce 實現 Array.map 和 Array.filterJSFilter
- Largest Submatrix of All 1’s(思維+單調棧)
- abc372E K-th Largest Connected Components
- 976. Largest Perimeter Triangle(Leetcode每日一題-2020.11.29)LeetCode每日一題
- array_filter ()、array_map ()、array_walk () 區別?容易記混淆!!!Filter
- 力扣-215. 陣列中的第K個最大元素力扣陣列
- Array物件物件
- Array Repetition
- Unique Array
- Array Division
- element
- JavaScript Array 物件JavaScript物件
- array_chunk
- Array.from()
- JavaScript Array物件JavaScript物件
- Leetcode Sort ArrayLeetCode