functionquick(nums) { //the base case if (nums.length <= 1) return nums; let mid = Math.floor(nums.length / 2); let pivot = nums.splice(mid, 1); let left = [], right = []; //break into two smaller array; for (num of nums) { if (num < pivot) left.push(num); if (num >= pivot) right.push(num); } //recursively pass the smaller sacle let sortedLeft =quick(left); let sortedRight = quick(right); //combine the returned result return [...sortedLeft, ...pivot, ...sortedRight]; }
var maxSubArray = function (nums) { //base case if (nums.length == 1) return nums[0]; //split const mid = Math.floor(nums.length / 2); const left = nums.slice(0, mid); const right = nums.slice(mid, nums.length); //rec //console.log(left); return combine(maxSubArray(left), maxSubArray(right)); //combination fun β οΈβ οΈβ οΈthis is the hardest part functioncombine(lSum, rSum) { let leftMax = -Number.MAX_SAFE_INTEGER; let rightMax = -Number.MAX_SAFE_INTEGER; let ltorSum = 0, rtolSum = 0; for (let i = left.length - 1; i >= 0; i--) { ltorSum += left[i];
A pivot is chosen, and βshuffleβ the array into two side: left side is smaller than pivot and right side is bigger.
Check if the index of the pivot is greater than K, if yes, meaning the number weβre looking for is in the lefter part; otherwise in the right part. Recursivly look through the half part of the array untile the index of pivot is equal to K.
var findKthLargest = function (nums, k) { var left = 0; var right = nums.length - 1; return quickSelect(nums, left, right, k); };
functionquickSelect(nums, left, right, k) { //base case if (nums.length <= 1) return nums[0]; //randomnize the pivot, to aviod the pivot was constantly assign to the max/min number of array let random = Math.floor(Math.random() * (right - left + 1) + left); let pivot = nums[random]; [nums[random], nums[right]] = [nums[right], nums[random]]; //use two pointer similar as leetcode[75] let j = left, i = left; while (j < right) { if (nums[j] <= pivot) { [nums[j], nums[i]] = [nums[i], nums[j]]; i++; j++; } else { j++; } } [nums[j], nums[i]] = [nums[i], nums[j]]; //campare the i with the N-k if (i === right + 1 - k) return nums[i]; if (i < right + 1 - k) { return quickSelect(nums, i + 1, right, k); } else { return quickSelect(nums, left, i - 1, k - right + i - 1); } }