Binary Search
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
| class Solution { public int search(int[] nums, int target) { return findRightBoundExclusiveIndex(nums, target) - findRightBoundExclusiveIndex(nums, target - 1); }
private int findRightBoundExclusiveIndex(int[] nums, int target) { int left = 0, right = nums.length - 1; while (left <= right) { int mid = (left + right) >>> 1; if (nums[mid] > target) { right = mid - 1; } else if (nums[mid] < target) { left = mid + 1; } else { left = mid + 1; } }
return left; } }
|
References
剑指 Offer 53 - I. 在排序数组中查找数字 I