题目 : 统计一个数字在排序数组中出现的次数。
思路 :看见有序,肯定是二分查找了,算大比较简单,不多说,值得一提的是,不要拘泥于递归,要会写循环算法
1、java版本
public static int getNumberOfK (int []array ,int k) {
int length = array.length;
if (length == 0) {
return 0;
}
int firstK = getFirstK(array, k, 0, length-1);
int lastK = getLastK(array, k, 0, length -1);
if (firstK != -1 && lastK != -1) {
return lastK - firstK + 1;
}
return 0;
}
// 递归写法
public static int getFirstK(int[] array, int k, int start, int end) {
if (start > end) {
return -1;
}
int mid = (start + end) >> 1;
if (array[mid] > k) {
return getFirstK(array, k, start, mid - 1);
} else if (array[mid] < k) {
return getFirstK(array, k, mid + 1, end);
} else if (mid - 1 > 0 && array[mid - 1] == k) {
return getFirstK(array, k, start, mid - 1);
} else {
return mid;
}
}
// 递归写法
public static int getLastK(int[] array, int k, int start, int end) {
int length = array.length;
int mid = (start + end) >> 1;
while (start <= end) {
if (array[mid] > k) {
end = mid - 1;
} else if (array[mid] < k) {
start = mid + 1;
} else if (mid + 1 < length && array[mid + 1] == k) {
start = mid + 1;
} else {
return mid;
}
mid = (start + end) >> 1;
}
return -1;
}
2、C++版本
class Solution {
public:
int GetNumberOfK(vector<int> nums ,int target) {
int lbound = 0, rbound = 0;
// 寻找上界
int l = 0, r = nums.size();
while (l < r) {
int mid = l + (r - l) / 2;
if (nums[mid] < target) {
l = mid + 1;
}
else {
r = mid;
}
}
lbound = l;
// 寻找下界
l = 0, r = nums.size();
while (l < r) {
int mid = l + (r - l) / 2;
if (nums[mid] <= target) {
l = mid + 1;
}
else {
r = mid;
}
}
rbound = l;
return rbound - lbound;
}
};
//
// Created by stephen on 2021/3/11.
//
#include <vector>
using namespace std;
class Solution {
public:
int GetNumberOfK(vector<int> data ,int k) {
int count = 0;
for (int num:data){
if (num == k)
count++;
}
return count;
}
};