- 删除数组中的元素
数组的元素在内存地址中是连续的,不能单独删除数组中的某个元素,只能覆盖。
#include <stdio.h>
#include <stdbool.h>// 函数声明
int deleteElement(int arr[], int size, int element);int main() {int arr[] = {1, 2, 3, 4, 3, 5, 6};int size = sizeof(arr) / sizeof(arr[0]);int elementToDelete = 3;printf("Original array: ");for (int i = 0; i < size; i++) {printf("%d ", arr[i]);}printf("\n");int newSize = deleteElement(arr, size, elementToDelete);printf("Array after deleting %d: ", elementToDelete);for (int i = 0; i < newSize; i++) {printf("%d ", arr[i]);}printf("\n");return 0;
}// 删除数组中的元素,返回新数组的大小
int deleteElement(int arr[], int size, int element) {int newSize = 0;for (int i = 0; i < size; i++) {if (arr[i] != element) {arr[newSize] = arr[i];newSize++;}}return newSize;
}
2. 给定⼀个n个元素有序的(升序)整型数组nums和⼀个⽬标值target,写⼀个函数A搜索nums中的target,如果⽬标值存在返回下标,否则返回-1。
#include <stdio.h>// 二分查找函数,返回元素在数组中的索引,如果未找到则返回-1
int binarySearch(int arr[], int size, int target) {int left = 0;int right = size - 1;while (left <= right) {int mid = left + (right - left) / 2; // 防止(left + right)可能导致的溢出// 检查中间元素是否是目标值if (arr[mid] == target) {return mid; // 找到目标,返回索引}// 如果目标值大于中间元素,则在右半部分查找if (arr[mid] < target) {left = mid + 1;} else { // 如果目标值小于中间元素,则在左半部分查找right = mid - 1;}}// 未找到目标值,返回-1return -1;
}int main() {int arr[] = {2, 3, 4, 10, 40};int size = sizeof(arr) / sizeof(arr[0]);int target = 10;int result = binarySearch(arr, size, target);if (result != -1) {printf("元素在数组中的索引为: %d\n", result);} else {printf("数组中未找到该元素\n");}return 0;
}
3. 给定⼀个含有n个正整数的数组和⼀个正整数s,找出该数组中满⾜其和≥s的⻓度最⼩的连续⼦数组,并返回其⻓度。如果不存在符合条件的⼦数组,返回0。
#include <stdio.h>
#define MAX_INT 2147483647 int minSubArrayLen(int nums[], int numsSize, int s) {int minLength = MAX_INT; int currentSum = 0;int left = 0;for (int right = 0; right < numsSize; right++) {currentSum += nums[right];while (currentSum >= s) {minLength = (minLength < (right - left + 1)) ? minLength : (right - left + 1);currentSum -= nums[left];left++;}}// 检查是否找到了符合条件的子数组return (minLength == MAX_INT) ? 0 : minLength;
}int main() {int nums[] = {2, 3, 1, 2, 4, 6};int s = 6;int numsSize = sizeof(nums) / sizeof(nums[0]);int result = minSubArrayLen(nums, numsSize, s);printf("满足和大于等于 %d 的最小长度连续子数组的长度是: %d\n", s, result);return 0;
}