C语言刷数组题记录
讲解: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; }
977. 有序数组的平方
/** * Note: The returned array must be malloced, assume caller calls free(). */ int Double(int a) { return a * a; } int* sortedSquares(int* nums, int numsSize, int* returnSize) { int left = 0; int right = numsSize - 1; int index = right; *returnSize = numsSize; int *res = (int *)malloc(sizeof(int) * numsSize); while (left <= right) { if (Double(nums[left]) <= Double(nums[right])) { printf("1 %d <= %d index=%d\n", Double(nums[left]), Double(nums[right]), index); res[index--] = Double(nums[right]); right--; } else { printf("2 %d > %d index=%d\n", Double(nums[left]), Double(nums[right]), index); res[index--] = Double(nums[left]); left++; } } return res; }
209. 长度最小的子数组
滑动窗口
int minSubArrayLen(int target, int* nums, int numsSize) { int slow = 0; int fast = 0; int sum = 0; int res = 1e7; for (int fast = 0; fast < numsSize; fast++) { sum += nums[fast]; while (sum >= target) { int len = fast - slow + 1; res = res < len ? res : len; // sum = 0; 这是不对的! printf("slow:%d\n", slow); sum -= nums[slow++]; } } return res == 1e7 ? 0 : res; }