Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 2f9c7d7

Browse files
kth largest element in unsorted array LC215
1 parent 238252a commit 2f9c7d7

File tree

2 files changed

+60
-1
lines changed

2 files changed

+60
-1
lines changed

‎ArraysAndStrings/Tutorial.md‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -260,4 +260,6 @@ void printTwoSum(int[] array, int k)
260260
}
261261
}
262262
}
263-
```
263+
```
264+
265+
**[Kth Largest in an array](https://github.com/ankurjuneja/React-Java-Concepts/blob/master/src/ArraysAndStrings/Kthlargest.java)**

‎src/ArraysAndStrings/Kthlargest.java‎

Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
package ArraysAndStrings;
2+
3+
public class Kthlargest
4+
{
5+
public static int findKthLargest(int[] nums, int k)
6+
{
7+
if (null == nums || nums.length == 0)
8+
{
9+
return Integer.MIN_VALUE;
10+
}
11+
12+
return qSort(nums, 0, nums.length-1, k);
13+
}
14+
15+
private static int qSort(int[] nums, int left, int right, int k)
16+
{
17+
if (nums[left] >= nums[right])
18+
{
19+
return nums[right];
20+
}
21+
22+
int i = left;
23+
for (int j = left + 1; j <= right; j++)
24+
{
25+
if (nums[j] > nums[i]) {
26+
i++;
27+
swap(nums, i, j);
28+
}
29+
}
30+
swap(nums, i, left);
31+
32+
if (k == i + 1)
33+
{
34+
return nums[i];
35+
}
36+
else if (k > i + 1)
37+
{
38+
return qSort(nums, i+1, right, k);
39+
}
40+
else
41+
{
42+
return qSort(nums, left, i-1, k);
43+
}
44+
}
45+
46+
private static void swap(int[] nums, int i, int j)
47+
{
48+
int tmp = nums[i];
49+
nums[i] = nums[j];
50+
nums[j] = tmp;
51+
}
52+
53+
public static void main(String[] args)
54+
{
55+
int secondlargest = findKthLargest(new int[]{3,2,5,1,6,4}, 2);
56+
}
57+
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /