C语言刷数组题记录

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. 移除元素

https://mp.weixin.qq.com/s?__biz=MzUxNjY5NTYxNA==&mid=2247484304&idx=1&sn=ad2e11d171f74ad772fd23b10142e3f3&scene=21#wechat_redirect

暴力法(两层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;
}

 

上一篇:【跟着英雄哥学算法】 线性枚举 -- 最值算法


下一篇:删除有序数组的重复项--C语言--力扣