剑指 Offer 53 - I. 在排序数组中查找数字 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

题目分析:
  1. 数组是有序的
  2. 要统计target在数组中出现的次数
思路一:

遍历数组,并判断当前元素于target是否相等,是的话,count+1,遍历结束返回count

代码实现:
class Solution {
    public int search(int[] nums, int target) {
        int len = nums.length;
        int count = 0;
        for (int i = 0; i < len; i++) {
            if (nums[i] == target) {
                count++;
            }
        }
        return count;
    }
}
思路二:

结果要统计target在数组中出现的次数,因为数组是有序的,我们可以通过二分法找到大于或小于target的索引,再以该索引为起点遍历,判断等于target的元素个数,例如:[1,5,8,8,9],target = 8; 我们只要找到小于target的索引1或大于target的索引4.再从1开始遍历判断即可。

代码实现:
class Solution {
    public int search(int[] nums, int target) {
        int len = nums.length;
        if (len == 0) {
            return 0;
        }
        int left = binarySearch(nums, target);
        if (nums[left] != target) {
            return 0;
        }
        int mark = 0;
        for (int i = left; i < nums.length; i++) {
            if (nums[i] == target) {
                mark++;
            }
        }
        return mark;
    }

    public int binarySearch(int[] arr, int target) {
        int low = 0, high = arr.length - 1;
        while (low < high) {
            int mid = (high - low) / 2 + low;
            if (arr[mid] < target) {
                low = mid + 1;
            } else {
                high = mid;
            }
        }
        return low;
    }
}

你可能感兴趣的:(剑指 Offer 53 - I. 在排序数组中查找数字 I)