C語言刷陣列題記錄
阿新 • • 發佈:2021-10-16
講解: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; }