title: Exercise of the Day (24): Finding Numbers in a Sorted Array
categories:[Swords offer]
tags:[Daily practice]
date: 2022/02/23
Exercise of the Day (24): Finding Numbers in a Sorted Array
Counts the number of times a number appears in a sorted array.
Example 1:
Input: nums = [5,7,7,8,8,10], target = 8
Output: 2
Example 2:
Input: nums = [5,7,7,8,8,10], target = 6
output: 0
hint:
0 <= nums.length <= 105
-109 <= nums[i] <= 109
nums is a non-decreasing array
-109 <= target <= 109
Source: LeetCode
Link: https://leetcode-cn.com/problems/zai-pai-xu-shu-zu-zhong-cha-zhao-shu-zi-lcof
Method 1: STL (one line)
The count function can be used to count the number of characters in a string
The usage method is count(ivec.begin() , ivec.end() , searchValue), where begin refers to the starting address, end refers to the ending address, and the third parameter refers to the character to be searched.
int search(vector<int>& nums, int target) {
return count(nums.begin(),nums.end(),target);
}
Method 2: Violent solution
Direct for loop to traverse to find target and count
int search(vector<int>& nums, int target) {
if (nums.size() == 0) {
return 0;
}
if (nums.size() == 1) {
if (nums[0] == target) {
return 1;
} else {
return 0;
}
}
int count = 0;
for (int i = 0; i < nums.size(); i++) {
if (nums[i] == target) {
count++; //循环计数
}
}
return count;
}
Method 3: Binary search
Dichotomous Template:
Template 1
When we divide the interval [l, r] into [l, mid] and [mid + 1, r], the update operation is r = mid or l = mid + 1, and we do not need to add 1 when calculating mid, that is, mid = (l + r)/2.
int bsearch_1(int l, int r)
{
while (l < r)
{
int mid = (l + r)/2;
if (check(mid)) {
r = mid;
} else {
l = mid + 1;
}
}
return l;
}
Template 2
When we divide the interval [l, r] into [l, mid - 1] and [mid, r], the update operation is r = mid - 1 or l = mid. At this time, in order to prevent an infinite loop, when calculating mid Need to add 1, that is mid = ( l + r + 1 ) / 2.
int bsearch_2(int l, int r)
{
while (l < r)
{
int mid = ( l + r + 1 ) /2;
if (check(mid)) {
l = mid;
} else {
r = mid - 1;
}
}
return l;
}
lowerBound(target)
upper(target+1)
Time complexity analysis of : The time complexity of two binary search is O(logn).
space complexity analysis: does not use an extra array, so the space complexity is O(1).
int lowerBound(vector<int>& nums, int target) {
int l, r;
l = 0;
r = nums.size();
while (l < r) {
int mid = (l + r) >> 1;
if (target <= nums[mid]) {
r = mid;
} else {
l = mid + 1;
}
}
return l;
}
int search(vector<int>& nums, int target) {
int lower = lowerBound(nums, target);
int upper = lowerBound(nums, target + 1);
return (upper - lower);
}
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。