classSolution{ publicintsearch(int[] nums, int target){ // 搜索右边界 right int i = 0, j = nums.length - 1; while(i <= j) { int m = (i + j) / 2; if(nums[m] <= target) i = m + 1; else j = m - 1; } int right = i; // 若数组中无 target ,则提前返回 if(j >= 0 && nums[j] != target) return0; // 搜索左边界 right i = 0; j = nums.length - 1; while(i <= j) { int m = (i + j) / 2; if(nums[m] < target) i = m + 1; else j = m - 1; } int left = j; return right - left - 1; } }
// 包装成函数 // nums = [5,7,7,8,8,10] // helper(nums, target)=5 helper(nums, target-1)=3 classSolution{ publicintsearch(int[] nums, int target){ return helper(nums, target) - helper(nums, target - 1); } inthelper(int[] nums, int tar){ int i = 0, j = nums.length - 1; while(i <= j) { int m = (i + j) / 2; if(nums[m] <= tar) i = m + 1; else j = m - 1; } return i; } }