intbinarySearch(vector<int> nums, int target) { // 查找区间 int l = 0; int r = nums.size() - 1; // 终止条件 while(l <= r) { // 中点计算 int m = l + (r - l) / 2; // 区间缩减 if(nums[m] == target) return m; elseif (nums[m] < target) l = m + 1; elseif (nums[m] > target) r = m - 1; } return-1; }
classSolution { publicintsearch(int[] nums, int target) { // 左闭右闭 intl=0; intr= nums.length - 1; while(l <= r){ // 防止溢出 intm= l + (r - l) / 2; if(target == nums[m]){ // 如果找到,直接返回 return m; } elseif(target > nums[m]){ // 右边界缩小 r = m - 1; } elseif(target > nums[m]){ // 左边界缩小 l = m + 1; } } // 未找到,返回-1 return -1; } }
python版本
1 2 3 4 5 6 7 8 9 10 11 12
classSolution: defsearch(self, nums: List[int], target: int) -> int: l, r = 0, len(nums) - 1 while l <= r: m = l + (r - l) // 2 if target == nums[m]: return m elif target < nums[m]: r = m - 1 else: l = m + 1 return -1
classSolution { publicintsearchInsert(int[] nums, int target) { // 左闭右闭 intl=0; intr= nums.length - 1; while(l <= r){ // 防止溢出 intm= l + (r - l)/2; if(target == nums[m]){ // 如果找到,直接返回 return m; } elseif(target > nums[m]){ // 右边界缩小 r = m - 1; } elseif(target > nums[m]){ // 左边界缩小 l = m + 1; } } // 返回左边界 return l; } }
python版本
1 2 3 4 5 6 7 8 9 10 11 12
classSolution: defsearchInsert(self, nums: List[int], target: int) -> int: l, r = 0, len(nums) - 1 while l <= r: m = l + (r - l) // 2 if nums[m] == target: return m elif target < nums[m]: r = m - 1 else: l = m + 1 return l
l, r = 0, len(nums) - 1 while l <= r: m = l + (r - l) // 2 if target <= nums[m]: r = m - 1 else: l = m + 1 if l < len(nums) and nums[l] == target: result[0] = l l, r = 0, len(nums) - 1 while l <= r: m = l + (r - l) // 2 if target >= nums[m]: l = m + 1 else: r = m - 1 if r >= 0and nums[r] == target: result[1] = r