intsearch(vector<int> &nums, int target) { if (nums.size() <= 0 || target < nums[0] || target > nums[nums.size() - 1]) return0; int i = 0, j = nums.size() - 1; int m = 0; //查找右边界 while(i <= j){ m = (i + j) / 2; if(nums[m] <= target){//此时右边界如果存在,则在m-j之间 i = m + 1; } else{ j = m - 1;//此时右边界如果存在,则在i-m之间 } } if(j >= 0 && nums[j] != target) return0;//判断target是否真的存在 int right = i;//保存右边界 //查找左边界,与上同理 j = i, i = 0;//j直接初始化为右边界 while (i <= j) { m = (i + j) / 2; if(nums[m] < target){ i = m + 1; } else{ j = m - 1; } } int left = j;
inthelper(vector<int> &nums, int target) { int i = 0, j = nums.size() - 1; while (i <= j) { int m = (i + j) / 2; if (nums[m] <= target) { i = m + 1; } else { j = m - 1; } } return i; }