题目
https://leetcode-cn.com/problems/find-first-and-last-position-of-element-in-sorted-array/
解法
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58
| public int binarySearch (int[] nums, int target) { if (nums==null||nums.length==0) { return -1; } int left=0, right=nums.length-1; while (left<=right) { int mid = left + ((right-left)>>1); if (nums[mid] == target) { return mid; } else if (nums[mid] < target) { left = mid+1; } else if (nums[mid] > target) { right = mid-1; } } return -1; }
int left_bound(int[] nums, int target) { if (nums==null||nums.length==0) { return -1; } int left=0, right = nums.length-1; while (left<=right) { int mid = left + ((right-left)>>1); if (nums[mid] < target) { left = mid + 1; } else if(nums[mid]>target) { right = mid - 1; } else if (nums[mid] == target) { right = mid - 1; } } if (left>=nums.length || nums[left] != target) { return -1; } return left; } int right_bound(int[] nums, int target) { if (nums==null||nums.length==0) { return 0; } int left=0, right=nums.length-1; while (left<=right) { int mid = left+((right-left)>>1); if (nums[mid] == target) { left = mid + 1; } else if (nums[mid] < target) { left = mid + 1; } else if(nums[mid] > target) { right = mid - 1; } } if (right<0 || nums[right] != target) { return -1; } return right; }
|