简体   繁体   中英

Is the time complexity of this function I found online O(n)?

I am trying to do this problem on LeetCode , and the following is the solution I found online:

 // use quick select var findKthLargest = function(nums, k) { var smaller = []; var larger = []; var pivot = nums[parseInt(nums.length/2)]; var pivotCnt = 0; for (var i = 0; i < nums.length; i++) { var num = nums[i]; if(num > pivot) { larger.push(num); } else if(num < pivot) { smaller.push(num); } else { pivotCnt++; } } if (k <= larger.length) { // if larger includes k return findKthLargest(larger, k); } else if (k - larger.length - pivotCnt <= 0) { // k is part of pivot return pivot; } else { // if smaller inclues k return findKthLargest(smaller, k - larger.length - pivotCnt); } }; 

Now I believe this is an O(n) solution, because worst case is that we iterate through the entire array, but I'm not certain.

Your function appears to be using some sort of divide and conquer approach. For each call, it makes a single O(n) pass over the input array, bucketing values larger than, and smaller than, a certain pivot, into two separate arrays. Then, it makes a recursive call on the appropriate subarray. In an average case, it will divide the size of the input array by two, until a recursive call is made on just an array of size one, which is the base case.

I would estimate that the running time of this function is O(n*lgn) , which is typical for a divide and conquer algorithms. Each call does O(n) work, and there would typically be O(lgn) number of recursive calls.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM