Created
September 15, 2018 02:22
-
-
Save njujerry/7c21ee0a3d509bd7aca3827b0ed61d2a to your computer and use it in GitHub Desktop.
查找数组中第K大的数字
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public int findKthLargest(int[] nums, int k){ | |
int index = searchIndex(nums, 0, nums.length-1, k); | |
return nums[index]; | |
} | |
public int partition(int[] nums, int low, int high){ | |
int key=nums[low]; | |
while(low < high){ | |
// 大到小排序 | |
while(low<high && nums[high]<=key){ | |
high--; | |
} | |
nums[low] = nums[high]; | |
while(low<high && nums[low]>=key){ | |
low++; | |
} | |
nums[high] = nums[low]; | |
} | |
nums[low] = key; | |
return low; | |
} | |
public int searchIndex(int[] nums, int x, int y, int k){ | |
int index=partition(nums, x, y); | |
if(index == k-1){ | |
return index; | |
}else if(index > k-1){ | |
return searchIndex(nums, x, index-1, k); | |
}else { | |
return searchIndex(nums, index+1, y, k); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment