# 每日一练（24）：在排序数组中查找数字

+关注继续查看

0 <= nums.length <= 105

-109 <= nums[i] <= 109

nums 是一个非递减数组

-109 <= target <= 109

## 方法一：STL（一行搞定）

count函数可以用来统计字符串中某个字符的个数

int search(vector<int>& nums, int target) {
return count(nums.begin(),nums.end(),target);
}

## 方法二：暴力解法

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;
}

## 方法三：二分查找

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;
}

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)

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);
}

35 0

14 0

17 0

23 0

33 0
JS中数组排序
JS中数组排序
804 0

413 0
111

0