LeetCode 在排序数组中查找数字 I [简单]
统计一个数字在排序数组中出现的次数。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/zai-pai-xu-shu-zu-zhong-cha-zhao-shu-zi-lcof
示例 1:
输入: nums = [5,7,7,8,8,10], target = 8
输出: 2
示例 2:
输入: nums = [5,7,7,8,8,10], target = 6
输出: 0
限制:
0 <= 数组长度 <= 50000
题目分析
解法1
for迭代,因为有序,所以当大于目标数据的时候就结束方法
解法2
二分法 通过二分法找到目标,然后向两边探测 都结束之后,返回结果
代码实现
public class SearchTargetNumberCounts {
public static void main(String[] args) {
int[] nums = {2, 2};
int target = 2;
System.out.println(search(nums, target));
System.out.println(search1(nums, target));
}
public static int search1(int[] nums, int target) {
if (nums == null || nums.length == 0) {
return 0;
}
int index = Arrays.binarySearch(nums, target);
if (index < 0) {
return 0;
} else {
int res = 1;
int indexLeft = index - 1;
int indexRight = index + 1;
while (indexLeft >= 0 && nums[indexLeft--] == target) {
res++;
}
while (indexRight <= nums.length - 1 && nums[indexRight++] == target) {
res++;
}
return res;
}
}
public static int search(int[] nums, int target) {
if (nums == null || nums.length == 0) {
return 0;
}
int res = 0;
for (int i = 0; i < nums.length; i++) {
if (nums[i] == target) {
res++;
}
}
return res;
}
}
网友评论