Skip to content

Commit 12cd36a

Browse files
committed
Add problem 215 - Kth Largest Element In An Array
1 parent df43321 commit 12cd36a

File tree

2 files changed

+55
-0
lines changed

2 files changed

+55
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
package quick_select
2+
3+
func FindKthLargestElementInAnArray(nums []int, k int) int {
4+
k = len(nums) - k
5+
left, right := 0, len(nums)-1
6+
for left < right {
7+
pivotIndex := partition(nums, left, right)
8+
if pivotIndex < k {
9+
left = pivotIndex + 1
10+
} else if pivotIndex > k {
11+
right = pivotIndex - 1
12+
} else {
13+
break
14+
}
15+
}
16+
return nums[k]
17+
}
18+
19+
func partition(nums []int, left, right int) int {
20+
pivot := nums[right]
21+
pivotIndex := left
22+
for i := left; i < right; i++ {
23+
if nums[i] <= pivot {
24+
nums[pivotIndex], nums[i] = nums[i], nums[pivotIndex]
25+
pivotIndex++
26+
}
27+
}
28+
nums[right], nums[pivotIndex] = nums[pivotIndex], nums[right]
29+
return pivotIndex
30+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
package quick_select_test
2+
3+
import (
4+
"testing"
5+
6+
"github.com/anirudhology/leetcode-go/problems/quick_select"
7+
)
8+
9+
func TestFindKthLargest(t *testing.T) {
10+
if res := quick_select.FindKthLargestElementInAnArray([]int{3, 2, 1, 5, 6, 4}, 2); res != 5 {
11+
t.Errorf("expected 5, got %v", res)
12+
}
13+
if res := quick_select.FindKthLargestElementInAnArray([]int{3, 2, 3, 1, 2, 4, 5, 5, 6}, 4); res != 4 {
14+
t.Errorf("expected 4, got %v", res)
15+
}
16+
if res := quick_select.FindKthLargestElementInAnArray([]int{1}, 1); res != 1 {
17+
t.Errorf("expected 1, got %v", res)
18+
}
19+
if res := quick_select.FindKthLargestElementInAnArray([]int{1, 2}, 1); res != 2 {
20+
t.Errorf("expected 2, got %v", res)
21+
}
22+
if res := quick_select.FindKthLargestElementInAnArray([]int{-1, -1}, 2); res != -1 {
23+
t.Errorf("expected -1, got %v", res)
24+
}
25+
}

0 commit comments

Comments
 (0)