連結:https://leetcode.com/problems/kth-largest-element-in-an-array/
class Solution {
public int findKthLargest(int[] nums, int k) {
PriorityQueue<Integer> heap = new PriorityQueue();
//iterate over the array
for (int n : nums) {
//first add the integer to heap
heap.add(n);
//if size of the heap is greater than k
if (heap.size() > k) {
//remove the root element (lowest of all)
heap.poll();
}
}
//finally heap has k largest elements left with root as the kth largest element
return heap.peek();
}
}
連結:https://leetcode.com/problems/kth-largest-element-in-an-array/
class Solution {
public void sortColors(int[] nums) {
int num0 = 0 ;
int num1 = 0 ;
int num2 = 0 ;
for(int num : nums ){
if (num == 0 ){
num0++ ;
}
if (num == 1 ){
num1++ ;
}
if (num == 2 ){
num2++ ;
}
}
int i = 0 ;
while ( num0 > 0){
nums[i++] = 0 ;
num0-- ;
}
while ( num1 > 0){
nums[i++] = 1;
num1-- ;
}
while ( num2 > 0){
nums[i++] = 2 ;
num2-- ;
}
}
}