-
Notifications
You must be signed in to change notification settings - Fork 1
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
ea85845
commit 17a325d
Showing
4 changed files
with
46 additions
and
0 deletions.
There are no files selected for viewing
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
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1 @@ | ||
export { kthLargest, kthSmallest } from './quickSelect'; |
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,13 @@ | ||
import { kthLargest, kthSmallest } from './quickSelect'; | ||
|
||
describe('quickSelect', () => { | ||
it('returns the kth largest element', () => { | ||
const arr = [3, 2, 1, 5, 6, 4]; | ||
expect(kthLargest(arr, 2)).toBe(5); | ||
}); | ||
|
||
it('returns the kth smallest element with duplicate inputs', () => { | ||
const arr = [-1, -1, 0, 5, 12]; | ||
expect(kthSmallest(arr, 3)).toEqual(0); | ||
}); | ||
}); |
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,31 @@ | ||
function quickSelect(arr: number[], k: number, left = 0, right = arr.length - 1): number { | ||
const pivot = arr[right]; | ||
let p = left; | ||
|
||
for (let i = left; i < right; i++) { | ||
if (arr[i] <= pivot) { | ||
[arr[i], arr[p]] = [arr[p], arr[i]]; | ||
p++; | ||
} | ||
} | ||
|
||
[arr[p], arr[right]] = [arr[right], arr[p]]; | ||
|
||
if (p === k) { | ||
return arr[p]; | ||
} | ||
|
||
if (p > k) { | ||
return quickSelect(arr, k, left, p - 1); | ||
} else { | ||
return quickSelect(arr, k, p + 1, right); | ||
} | ||
} | ||
|
||
export function kthLargest(arr: number[], k: number): number { | ||
return quickSelect(arr, arr.length - k); | ||
} | ||
|
||
export function kthSmallest(arr: number[], k: number): number { | ||
return quickSelect(arr, k - 1); | ||
} |