Day1 数组专项—二分查找

LeetCode 704. 二分查找

解题思路:重点在于数组右区间开闭不同时,while循环判断条件,以及right下标的赋值

右闭:

  • while ( left <= right )
  • right = mid - 1,因为mid已判断过不是target,下一次的右边界应该为mid - 1

右开:

  • while ( left < right ),因为取不到right
  • right = mid
// 左闭右闭
int binary_search(vector& nums, int target) {
    int left = 0;
    int right = nums.size() - 1;
    int mid = (left + right) / 2;
    while (left <= right) {
        if (nums[mid] == target) {
            return mid;
        } else if (nums[mid] > target) {
            right = mid - 1;
            mid = (left + right) / 2;
        } else {
            left = mid + 1;
            mid = (left + right) / 2;
        }
    }
    return -1;
}

// 左闭右开
int binary_search(vector& nums, int target) {
    int left = 0;
    int right = nums.size();
    int mid = (left + right) / 2;
    while (left < right) {
      if (nums[mid] == target) {
        return mid;
      } else if (nums[mid] > target) {
        right = mid;
        mid = (left + right) / 2;
      } else {
        left = mid + 1;
        mid = (left + right) / 2;
      }
    }
    return -1;
}

LeetCode 27. 移除元素

解题思路:相似于双指针法,每次访问到待移除元素时直接与当前数组最后一位互换,同时数组长度减1,待访问数组下标不变,则一次访问结束可得最终结果,时间复杂度O(n)。

int removeElement(vector& nums, int val) {
    int len = nums.size();
    for (int i = 0; i < len; i++) {
        if (nums[i] == val) {
            nums[i] = nums[len - 1];
            i--;
            len--;
        }
    }
    return len;
}

你可能感兴趣的:(算法学习,算法,c++)