I am trying to do this problem on LeetCode , and the following is the solution I came up with:
var findKthLargest = function(nums, k) { //var tmp = nums.slice(); var iteration = 0; while (iteration < k) { var max = -Infinity; for (var i = 0; i < nums.length; i++) { var cut; if (nums[i] > max) { max = nums[i]; cut = i; } } nums.splice(cut, 1); iteration++; } return max; };
Now, I believe this is a log n solution because what I'm basically doing is removing the largest value in the array, which decreases my number of comparisons. However, it only beats 59% of the JavaScript solutions, which makes me think I might not have the right complexity.
There are k
iterations of the while()
loop (which, I think, would be more idiomatically written as for(var j = 0; j < k; j++)
).
The first iteration then performs n
iterations of the for
loop, and nums.splice(cut, 1)
is O(n)
because it has to shift all the array elements from cut
to n
. O(2n)
is the same as O(n)
because constant factors are ignored in big-O calculation.
The second iteration performs n-1
iterations. This is also O(n)
because we ignore constant adjustments in big-O notation. The same goes for the splice
.
So the final result is that it's O(k * n)
, since you have k
iterations of the outer loop, and the inner loops are each O(n)
. The worst case, when k >= n
, is O(n^2)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.