剑指 Offer 53 - I. 在排序数组中查找数字 I
统计一个数字在排序数组中出现的次数。
/** * @param {number[]} nums * @param {number} target * @return {number} */ var search = function(nums, target) { return nums.filter((val)=> val == target).length; };
二分查找
/** * @param {number[]} nums * @param {number} target * @return {number} */ var search = function(nums, target) { let n = nums.length; let res = 0; var binarySearch = (nums, target) =>{ let left = 0, right = n - 1; while(left <= right){ let mid = Math.floor((left+right)/2); if(nums[mid] < target){ left = mid + 1; }else if(nums[mid] > target){ right = mid -1; }else{ return mid; } } return -1; } let find = binarySearch(nums, target); if(find == -1) { return 0; } for(let i = find;i>=0;i--){ if(nums[i] === target){ res += 1; }else{ break; } } for(let i = find+1;i<n;i++){ if(nums[i] === target){ res += 1; }else{ break; } } return res; };
示例 1:
输入: nums = [5,7,7,8,8,10]
, target = 8
输出: 2
示例 2:
输入: nums = [5,7,7,8,8,10]
, target = 6
输出: 0
限制:
0 <= 数组长度 <= 50000
注意:本题与主站 34 题相同(仅返回值不同):https://leetcode-cn.com/problems/find-first-and-last-position-of-element-in-sorted-array/