Created
June 20, 2019 01:27
-
-
Save sogwiz/0405cb17cc3430462bbc682e955ab071 to your computer and use it in GitHub Desktop.
This file contains 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
package com.learning.leet.strsarrs; | |
import java.util.Arrays; | |
/** | |
* Created by sargonbenjamin on 6/19/19. | |
* https://leetcode.com/problems/kth-largest-element-in-an-array/ | |
*/ | |
public class KthLargestElement { | |
public static void main(String args[]){ | |
//int[] testArr = {3,2,3,1,2,4,5,5,6}; | |
int[] testArr = {3,2,1,5,6,4}; | |
KthLargestElement kth = new KthLargestElement(); | |
int out = kth.findKthLargest(testArr, 2); | |
System.out.println("hi"); | |
} | |
//why is this method faster? | |
public int findKthLargestEasy(int[] nums, int k) { | |
if(nums==null || nums.length==0)return 0; | |
Arrays.sort(nums); | |
return nums[nums.length-k]; | |
} | |
//why is this method slower? | |
//this bubble sorts until we sort to the kth element | |
public int findKthLargest(int[] nums, int k) { | |
if(nums==null || nums.length==0)return 0; | |
int loopCount = 0; | |
while(loopCount<k){ | |
for(int i = 1; i<nums.length-loopCount; i++){ | |
if(nums[i-1]>nums[i]){ | |
int temp = nums[i-1]; | |
nums[i-1] = nums[i]; | |
nums[i] = temp; | |
} | |
} | |
loopCount++; | |
} | |
return nums[nums.length-k]; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment