欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

数组练习题10--在排序数组中查找数字I

程序员文章站 2022-04-06 12:32:13
...

题意:
统计一个数字在排序数组中出现的次数。
示例 1:

输入: nums = [5,7,7,8,8,10], target = 8
输出: 2

示例 2:

输入: nums = [5,7,7,8,8,10], target = 6
输出: 0

方法1:哈希表
思路:统计出现次数,直接返回次数即可

class Solution {
    public int search(int[] nums, int target) {
    	Map<Integer,Integer> record=HashMap<>();
    	for(int i=0;i<nums.length;i++){
    		record.put(nums[i],record.getOrDefault(nums[i],0)+1);
    	}
    	return record.getOrDefault(target,0);
    }
}

方法2:二分
思路:找到target的左右端点,将端点相减+1得到出现次数:

class Solution {
    public int search(int[] nums, int target) {
        int left=binaySearchLeftBound(nums,target);
        int right=binarySearchRightBound(nums,target);
        if(left!=-1)
            return right-left+1;
        return 0;
    }
    public int binaySearchLeftBound(int[] nums,int target){
        int low=0,high=nums.length-1;
        while(low<=high){
            int mid=low+(high-low)/2;
            if (nums[mid]==target){
                if(mid==0||nums[mid-1]<target)
                    return mid;
                high=mid-1;
            }
            else if(nums[mid]>target){
                high=mid-1;
            }
            else if(nums[mid]<target){
                low=mid+1;
            }
        }
        return -1;
    }
    public int binarySearchRightBound(int[] nums,int target){
        int low=0,high=nums.length-1;
        while(low<=high){
            int mid=low+(high-low)/2;
            if (nums[mid]==target){
                if(mid==nums.length-1||nums[mid+1]>target)
                    return mid;
                low=mid+1;
            }
            else if(nums[mid]>target){
                high=mid-1;
            }
            else if(nums[mid]<target){
                low=mid+1;
            }
        }
        return -1;
    }
}
相关标签: LeetCode刷题