1. 程式人生 > 其它 >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;
}