讲解:https://mp.weixin.qq.com/s/weyitJcVHBgFtSc19cbPdw
二分法:
704. 二分查找
int search(int* nums, int numsSize, int target) { int left = 0; int right = numsSize; while (left < right) { // int cur = (left + right) / 2; int cur = left + (right - left) / 2; if (nums[cur] == target) { return cur; } else if (nums[cur] > target) { right = cur; } else { left = cur + 1; } } return -1; }
27. 移除元素
暴力法(两层for循环)和 双指针
int removeElement(int* nums, int numsSize, int val) { for (int i = 0; i < numsSize; i++) { if (nums[i] == val) { // 数组整体向前移一步 for (int j = i; j < numsSize - 1; j++) { nums[j] = nums[j + 1]; } numsSize--; i--; } } return numsSize; }
双指针(快慢指针)
int removeElement(int* nums, int numsSize, int val) { int slow = 0; for (int fast = 0; fast < numsSize; fast++) { if (nums[fast] != val) { nums[slow++] = nums[fast]; } } return slow; }