找一个值
找左边界和右边界

啥,不知道边界取值,看https://leetcode-cn.com/problems/find-first-and-last-position-of-element-in-sorted-array/solution/er-fen-cha-zhao-suan-fa-xi-jie-xiang-jie-by-labula/

704. 二分查找(easy)

  1. int search(vector<int>& nums, int target) {
  2. int left = 0, right = nums.size() - 1;
  3. while(left <= right){
  4. int mid = (left + right) / 2;
  5. if(nums[mid] == target){
  6. return mid;
  7. }else if(nums[mid] < target){
  8. left = mid + 1;
  9. }else{ // nums[mid] > target
  10. right = mid - 1;
  11. }
  12. }
  13. return -1;
  14. }

34. 在排序数组中查找元素的第一个和最后一个位置

给定一个按照升序排列的整数数组 nums,和一个目标值 target。找出给定目标值在数组中的开始位置和结束位置。
你的算法时间复杂度必须是 O(log n) 级别。

  1. int binary_search(int[] nums, int target) {
  2. int left = 0, right = nums.length - 1;
  3. while(left <= right) {
  4. int mid = left + (right - left) / 2;
  5. if (nums[mid] < target) {
  6. left = mid + 1;
  7. } else if (nums[mid] > target) {
  8. right = mid - 1;
  9. } else if(nums[mid] == target) {
  10. // 直接返回
  11. return mid;
  12. }
  13. }
  14. // 直接返回
  15. return -1;
  16. }
  17. int left_bound(int[] nums, int target) {
  18. int left = 0, right = nums.length - 1;
  19. while (left <= right) {
  20. int mid = left + (right - left) / 2;
  21. if (nums[mid] < target) {
  22. left = mid + 1;
  23. } else if (nums[mid] > target) {
  24. right = mid - 1;
  25. } else if (nums[mid] == target) {
  26. // 别返回,锁定左侧边界
  27. right = mid - 1;
  28. }
  29. }
  30. // 最后要检查 left 越界的情况
  31. if (left >= nums.length || nums[left] != target)
  32. return -1;
  33. return left;
  34. }
  35. int right_bound(int[] nums, int target) {
  36. int left = 0, right = nums.length - 1;
  37. while (left <= right) {
  38. int mid = left + (right - left) / 2;
  39. if (nums[mid] < target) {
  40. left = mid + 1;
  41. } else if (nums[mid] > target) {
  42. right = mid - 1;
  43. } else if (nums[mid] == target) {
  44. // 别返回,锁定右侧边界
  45. left = mid + 1;
  46. }
  47. }
  48. // 最后要检查 right 越界的情况
  49. if (right < 0 || nums[right] != target)
  50. return -1;
  51. return right;
  52. }