2161. Partition Array According to Given Pivot

# leetcode, array, two pointer, quick sort, simple solution

var pivotArray = function(nums, pivot) {
const res = new Array(nums.length).fill(pivot);
let l = 0, r = nums.length – 1;
for (let i = 0, j = nums.length-1; i < nums.length; i++, j--) { if (nums[i] < pivot) { res[l++] = nums[i]; } if (nums[j] > pivot) {
res[r–] = nums[j];
}
}
return res;
};

At first I built three new array to separate the array into three part and concat them in the end, but there’s a smarter way, we first create a new array full of pivot, and maintain the left and right pointer for start and the end, once we met the element smaller than pivot, we put it in the left pointer position, and move the left pointer, so is right pointer, once we run through all the array, the unrun middle missing part is pivot value, since we assign the pivot value at first, we don’t need to change it anymore. BTW, this method is a lot faster than three array, since we don’t need to run the concat again.

Leave a Reply

Your email address will not be published. Required fields are marked *