面试题53 - I. 在排序数组中查找数字 I(一般)
统计一个数字在排序数组中出现的次数。
示例 1:
输入: nums = [5,7,7,8,8,10], target = 8
输出: 2
示例 2:
输入: nums = [5,7,7,8,8,10], target = 6
输出: 0
限制:
0 <= 数组长度 <= 50000
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/zai-pai-xu-shu-zu-zhong-cha-zhao-shu-zi-lcof
思路:
二分查找的变体形式,利用两次二分找到第一次出现的下标和最后一次出现的下标,计算长度即可,注意练习二分查找变体的代码
代码1:
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
| class Solution { public int search(int[] nums, int target) { int low = 0; int high = nums.length-1; int lpos = 0,hpos = 0; while(low<=high){ int mid = low+((high-low)>>1); if(nums[mid]>=target){ high = mid-1; }else{ low = mid+1; } } lpos = low; low = 0; high = nums.length-1; while(low<=high){ int mid = low+((high-low)>>1); if(nums[mid]<=target){ low = mid+1; }else{ high = mid-1; } } hpos = high; return hpos-lpos+1; } }
|