Q704 Binary Search
[Q704]
def binarysearch(nums: list[int], target: int)->int:
# [left, right]
left, right = 0, len(nums)-1
while left <= right:
mid = left + (right-left)//2
if nums[mid]>target:
right = mid - 1
elif nums[mid]<target:
left = mid + 1
else:
return mid
return -1
var search = function(nums, target) {
let left = 0;
let right = nums.length-1;
while (left<=right){
mid = left+((right-left)>>1)
if (nums[mid]>target){
right = mid - 1
}
else if (nums[mid]<target) {
left = mid + 1
}
else{
return mid;
}
}
return -1
};
Q27 Remove Element
[Q27]
def removeElement(self, nums: List[int], val: int) -> int:
fast = 0 # as index looping nums
slow = 0 # make sure at the end [0, slow) it the border of non-val
for fast in range(len(nums)):
if nums[fast] != val:
nums[slow] = nums[fast]
slow += 1
return slow
// Way1 快慢双指针
var removeElement = function(nums, val) {
let slow = 0;
for (let fast=0;fast<nums.length;fast++) {
if (nums[fast]!== val){
nums[slow] = nums[fast]
slow ++
}
}
return slow;
};
// Way2: 相向双指针
var removeElement = function(nums, val) {
let left = 0;
let right = nums.length-1;
//将right移到从右数第一个值不为val的位置
while (right>=0 && nums[right]==val) right--;
while (left<=right){
if (nums[left] == val){
//将right位置的元素移到left(覆盖),right位置移除
nums[left] = nums[right];
right --;
}
left ++;
while(right >= 0 && nums[right] == val) right--;
}
return left;
};
Reference from: https://programmercarl.com/