算法训练营笔记day01|704.二分查找、27.移除元素

704.二分查找

题目连接

笔记

注意数组的边界,当数组为左闭右闭时:

  • while (left <= right), right = mid - 1

数组为左闭右开时:

  • while (left < right), right = mid
class Solution {
public:
    int search(vector& nums, int target) {
        int left = 0;
        int right = nums.size() - 1;
        int mid = (left + right) / 2;
        while (left <= right) {
            mid = (left + right) / 2;
            if (nums[mid] < target) {
                left = mid + 1;
            }
            else if (nums[mid] > target) {
                right = mid - 1;
            }
            else {
                return mid;
            }
        }
        return -1;
    }
};

27. 移除元素

题目连接

笔记

双指针法:

  • 快指针:用于遍历数组
  • 慢指针:用于指向需要覆盖的元素
class Solution {
public:
    int removeElement(vector& nums, int val) {
        int size = nums.size();
        int slowIndex = 0;
        for (int fastIndex = 0;fastIndex < nums.size(); fastIndex++) {
            if (slowIndex == val) {
                nums[slowIndex] = nums[fastIndex];
                size--;
            }
            else {
                slowIndex++;
            }
        }
        return size;
    }
};

你可能感兴趣的:(leetcode,算法,数据结构)