35. 搜索插入位置

35. 搜索插入位置 - 力扣(LeetCode)

二刷

class Solution {
public:
  int searchInsert(vector<int>& nums, int target) {
    int L = 0, R = nums.size();
    while (L != R) {
      int M = (L + R) / 2;
      if (nums[M] == target)
        return M;
      if (nums[M] < target)
        L = M + 1;
      else
        R = M;
    }
    return L;
  }
};

没什么好说的,按 C++ 的 \([L, R)\) 写法比用什么 R = nums.size() - 1; 舒服太多。

三刷

class Solution {
public:
  int searchInsert(vector<int>& nums, int target) {
    int L = 0, R = nums.size();
    while (L != R) {
      int M = L + (R - L) / 2;
      if (nums[M] == target)
        return M;
      if (nums[M] < target)
        L = M + 1;
      else
        R = M;
    }
    return L;
  }
};

左闭右开真好用。