代码实现:
二分法:
方法一:非递归,左闭右闭
int searchInsert(int *nums, int numsSize, int target) { int l = 0, r = numsSize - 1; // 左闭右闭 int mid; while (l <= r) { mid = (l + r) / 2; if (nums[mid] == target) { return mid; } if (nums[mid] > target) { r = mid - 1; } else { l = mid + 1; } } return l; // return r + 1; }
方法二:非递归,左闭右开
int searchInsert(int *nums, int numsSize, int target) { int l = 0, r = numsSize; // 左闭右开 int mid; while (l < r) { mid = (l + r) / 2; if (nums[mid] == target) { return mid; } if (nums[mid] > target) { r = mid; } else { l = mid + 1; } } return l; // return r }
方法三:递归,左闭右开
// 左闭右开 int search(int *nums, int l, int r, int target) { if (l >= r) { return l; // return r; } int mid = (l + r) / 2; if (nums[mid] == target) { return mid; } if (nums[mid] > target) { r = mid; } else { l = mid + 1; } return search(nums, l, r, target); } int searchInsert(int *nums, int numsSize, int target) { return search(nums, 0, numsSize, target); }