# 问一道算法题，希望能得到最优解。

• 3.1k

• -10000 <= array[i] <= 10000
• 0 <= array.length <= 100000
• 1 <= n <= array.length * 数组中的元素可能会出现重复，数组里面的每个数值都大于 JS 整形的数值下界， 小于 JS 整形的数值上界

``````    var findNthNumber = function(array,n){
return array.sort((a,b) => a - b)[n - 1];
}``````

``````var findNthNumber = function (array, n) {
let min = Math.min.apply(null,array);
let countMin = 0;
for (let i = 0; i < array.length; i++) {
if (array[i] === min) {
countMin++;
array.splice(i, 1);
n -= countMin;
}
}
if (n > 0) {
return findNthNumber(array, n);
} else {
return Math.min.apply(null,array);
}
}``````

##### 6个回答

https://leetcode-cn.com/probl...

``````function findKthLargest(nums: number[], k: number): number {
const swap = (i: number, j: number): void => {
const t = nums[i]
nums[i] = nums[j]
nums[j] = t
}
const partition = (low: number, hi: number): number => {
const v = nums[low]

let i = low
let j = hi + 1
while (true) {
while (nums[++i] < v) if (i >= hi) break

while (nums[--j] > v) if (j <= low) break

if (i >= j) break

swap(i, j)
}

swap(low, j)
return j
}

let low = 0
let hi = nums.length - 1
let index
k = nums.length - k

do {
index = partition(low, hi)

if (index > k) {
hi = index - 1
} else if (index < k) {
low = index + 1
}
} while (index !== k)

return nums[index]
}``````