[leetcode#215] Kth largest Element in an Array

Source: Internet
Author: User

problem:

Find the kth largest element in an unsorted array. Note that it was the kth largest element in the sorted order and not the kth distinct element.

For example,
Given [3,2,1,5,6,4] and k = 2, return 5.

Note:
You may assume k are always valid, 1≤k≤array ' s length.

Analysis:

This problem isgreat!It's a good time to make a good summary!We are alwaysTryTo take advantage of a sorted array.1. Find Duplicates2. Missing number ... However, forAny kind of sorting alogrithm, as Long  asYou want toGetAn array completely sorted. Least O (LOGN) time forIt. For some CaseYou really don't need to get all elements sorted, since the just want to find a qualifiedelement meets certain characteristic. Quick Sort isA weired algorithm compared with and other algorithm. Rather than take all other elements forEach iteration, it finds the position of one element once a time. ThenContinueTo find elements forOther elements. The Sub-algorthm of Quick Sort isTo find an element's rank in the array. (which could is acheive at O (n)). to make things moreBeautiful, the average time ofusingQuick Find kth Element isactually O (n) time. The idea behind it isIt indeed take some minds to understand. Unit function:randomly Pick an element (usually the first or last element of the valid range), find it isRankinchThe array. (Please be noted the rank isStart from 0) Basic Idea:pick An element, we put all elements smaller than it before it, and put all elements larger than it after it.1. To achieve This, we need to use pointers, one starts fromThe low and the other starts fromThe end. intleft =Low ; intright =High ;2. Once the left pointer finds outAn element larger than the pivot, and the right pointer finds outThe element smaller than the pivot. We Exchange them! while(true) {     while(Right > Left && nums[right] >pivot) right--;  while(Left < right && Nums[left] <=pivot) left++; if(left = =Right ) Break; Swap (Nums, left, right);} Note:during the process of finding right elements to exchange, the "left" and "right" pointer may meet with each other. Inch This  Case, we should jump outThe process of finding elements to exchange.3. When the left and right pointer meets with each other. The meet up position is wherewe should put the pivot.intPivot =Nums[low];...swap (nums, Low, right);4. IFF the pivot's rank (index of Meet up position) was just the rank we want to find. We return it.(The most beautiful part of quickSelectMethod isThat is, we never need to update on K!!!)if(Cur_pos = = k-1)    returnpivot;//Note Pivot ' s Ranke is in realtive with base 0 index.5. IFF the pivot's rank smaller than the rank we want to find, and is sure all elements before pivot actually with even smaller rank, We search the target at the ' after pivot '.if(Cur_pos < K-1)     returnFindkth (Nums, K, cur_pos+1, high);6. IFF the pivot's rank larger than the rank we ant to find, we search the target in the left part before pivot.if(Cur_pos < K-1)     returnFindkth (Nums, K, Low, cur_pos-1); the idea isSo powerful and beautiful, right?But there is some pitfallsinchThe implementation, you should is very careful!!!mistake1: Try to start fromThe element after the pivot (Nums[low]).intPivot =Nums[low]; ..intleft = low+1; 1st Concern:whatifThere is only one element left???? MayTryTo fix it through"if (low = = Hight) return Nums[low]" is and right?Nope!!!ifThe pivot's right index is low!!! The meet up position would isn't be it. (since we have left = low+1)mistake2: Underestimate the order of moving and pointer: while(Left < right && Nums[left] <=pivot) left++; while(Right > Left && nums[right] >pivot) right--; The above code makes the same mistakeinchThe mistake1. The Logicif(Nums[left] <=pivot) left++; Would skip the" Low"Index!!! If the real Index forPivot is " Low", we wouldGetwrong answer. butifWe put: while(Right > Left && nums[right] >pivot) right--; at the first . Since Low isThe smallest elementinchThe range (it'S real index is low), we right pointer would go straightly to meet it.

Solution:

 Public classSolution { Public intFindkthlargest (int[] Nums,intk) {returnFindkth (nums, Nums.length-k +1,0, Nums.length-1); }            Private intFindkth (int[] Nums,intKintLowintHigh ) {        intPivot =Nums[low]; intleft =Low ; intright =High ;  while(true) {             while(Right > Left && nums[right] >pivot) right--;  while(Left < right && Nums[left] <=pivot) left++; if(left = =Right ) Break;        Swap (Nums, left, right);        } Swap (Nums, Low, right); intCur_pos =Right ; if(Cur_pos = = k-1) {            returnpivot; } Else if(Cur_pos < K-1) {            returnFindkth (Nums, K, cur_pos+1, high); } Else {            returnFindkth (Nums, K, Low, cur_pos-1); }    }            Private voidSwapint[] Nums,intLowintHigh ) {        inttemp =Nums[low]; Nums[low]=Nums[high]; Nums[high]=temp; }}

[leetcode#215] Kth largest Element in an Array

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.