Skip to content

[剑指 Offer] 53 - I. 在排序数组中查找数字 I #18

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
frdmu opened this issue Jul 16, 2021 · 0 comments
Open

[剑指 Offer] 53 - I. 在排序数组中查找数字 I #18

frdmu opened this issue Jul 16, 2021 · 0 comments

Comments

@frdmu
Copy link
Owner

frdmu commented Jul 16, 2021

统计一个数字在排序数组中出现的次数。

 

示例 1:

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

示例 2:

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

限制:

  • 0 <= 数组长度 <= 50000

数组有序,用两次二分查找,第一次找第一个=target的元素,第二次找第一个>target的元素,返回值是两个元素的索引相减。代码如下:

class Solution {
public:
    int search(vector<int>& nums, int target) {
        int n = nums.size(); 
        int left = 0, right = n; 
        
        while (left < right) {
            int mid = left + (right - left) / 2;
            if (nums[mid] < target) left = mid + 1;
            else right = mid;
        }
        if (right >= n || nums[right] != target)
            return 0;
        int start = right;
        
        left = start, right = n;
        while (left < right) {
            int mid = left + (right - left) / 2;
            if (nums[mid] <= target) left = mid + 1;
            else right = mid;
        }
        
        return right-start;
    }
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant