[代码随想录算法训练营]刷题笔记 Day 1

数组

数组在内存中是一连续的空间,用来存放相同数据格式。下标从零开始,且多维数组在内存中其地址也是连成一条线的。

704.二分查找

class Solution {
public:
    int search(vector& nums, int target) {
       int mid = nums.size()/2;
       int left = 0;
       int right = nums.size() - 1;
       int result = -1;

       while(left <= right){
            mid = left + ((right - left) / 2);
            if(nums[mid] == target){
                result = mid;
                break;
            }
            else if(nums[mid] > target){
               right = mid - 1;
            }
            else
                left = mid + 1;
            cout << "mid index: " << mid << endl;
            cout << "left index: " << left << endl;
            cout << "right index: " << right << endl;
       }

       return result;
    }
};

先考虑中间值,如果target大于mid值,则新的左值就等于mid + 1,反之亦然。

27.移除元素

class Solution {
public:
    int removeElement(vector& nums, int val) {
        auto slowIndex = 0;
        for(auto fastIndex = 0; fastIndex < nums.size(); fastIndex++){
            if(nums[fastIndex] != val){
                nums[slowIndex] = nums[fastIndex];
                slowIndex++;
            }
        }

        return slowIndex;
    }
};

你可能感兴趣的:(数据结构)