215. Kth Largest Element in an Array

Find K-th largest element in an array.

 Notice

You can swap elements in the array

Example

In array [9,3,2,4,8], the 3rd largest element is 4.

In array [1,2,3,4,5], the 1st largest element is 5, 2nd largest element is 4, 3rd largest element is 3 and etc.

分析:

使用partion把array分成两组,然后看中间那个数在哪个位置。然后再确定是继续在左半部分找还是在右半部分找。

 1 public class Solution {
 2     public int findKthLargest(int[] nums, int k) {
 3         if (nums == null || nums.length == 0 || k > nums.length) return -1;
 4         int start = 0, end = nums.length - 1;
 5         while (start <= end) {
 6             int p = partition(nums, start, end);
 7             if (p == nums.length - k) {
 8                 return nums[p];
 9             } else if (p < nums.length - k) {
10                 start = p + 1;
11             } else {
12                 end = p - 1;
13             }
14         }
15         return -1;
16     }
17     
18     private int partition(int[] nums, int start, int end) {
19         int p = start;
20         for (int i = start; i <= end - 1; i++) {
21             if (nums[i] < nums[end]) {
22                 swap(nums, p, i);
23                 p++;
24             }
25         }
26         swap(nums, p, end);
27         return p;
28     }
29     
30     private void swap(int[] nums, int i, int j) {
31         int temp = nums[i];
32         nums[i] = nums[j];
33         nums[j] = temp;
34     }
35 }

 

 1 class Solution {
 2     public int findKthLargest(int[] nums, int k) {
 3         PriorityQueue<Integer> pq = new PriorityQueue<>(k + 1);
 4         
 5         for (int num : nums) {
 6             pq.offer(num);
 7             if (pq.size() == k + 1) {
 8                 pq.poll();
 9             }
10         }
11         return pq.peek();
12     }
13 }

 

 1 public void print3largest(int[] arr) {
 2         if (arr == null || arr.length < 3) {
 3             System.out.print(" Invalid Input ");
 4             return;
 5         }
 6 
 7         int i, first, second, third;
 8 
 9         third = first = second = Integer.MIN_VALUE;
10         for (i = 0; i < arr.length; i++) {
11             if (arr[i] > first) {
12                 third = second;
13                 second = first;
14                 first = arr[i];
15             } else if (arr[i] > second) {
16                 third = second;
17                 second = arr[i];
18             } else if (arr[i] > third) {
19                 third = arr[i];
20             }
21         }
22 
23         System.out.println("Three largest elements are " + first + " " + second + " " + third);
24     }

转载请注明出处:cnblogs.com/beiyeqingteng/

 

posted @ 2016-07-02 12:03  北叶青藤  阅读(153)  评论(0编辑  收藏  举报