53-01 数字在排序数组中出现的次数
题目
统计一个数字在排序数组中出现的次数。例如输入排序数组{1,2,3,3,3,3,4,5}和数字3,由于3在这个数组中出现了4次,因此输出4。
C 语言题解
二分查找,找到第一次出现的位置以及最后出现的位置:
int GetFirstK(const int* data, int length, int k, int start, int end);
int GetLastK(const int* data, int length, int k, int start, int end);
int GetNumberOfK(const int* data, int length, int k)
{
int number = 0;
if (data != nullptr && length > 0)
{
int first = GetFirstK(data, length, k, 0, length - 1);
int last = GetLastK(data, length, k, 0, length - 1);
// 最后一个k的位置与第一个k的位置作差+1即为数字k出现的次数
if (first > -1 && last > -1)
number = last - first + 1;
}
return number;
}
// 找到数组中第一个k的下标。如果数组中不存在k,返回-1
int GetFirstK(const int* data, int length, int k, int start, int end)
{
if (start > end)
return -1;
int middleIndex = (start + end) / 2;
int middleData = data[middleIndex];
if (middleData == k)
{
if ((middleIndex > 0 && data[middleIndex - 1] != k)
|| middleIndex == 0)
return middleIndex;
else
end = middleIndex - 1;
}
else if (middleData > k)
end = middleIndex - 1;
else
start = middleIndex + 1;
return GetFirstK(data, length, k, start, end);
}
// 找到数组中最后一个k的下标。如果数组中不存在k,返回-1
int GetLastK(const int* data, int length, int k, int start, int end)
{
if (start > end)
return -1;
int middleIndex = (start + end) / 2;
int middleData = data[middleIndex];
if (middleData == k)
{
if ((middleIndex < length - 1 && data[middleIndex + 1] != k)
|| middleIndex == length - 1)
return middleIndex;
else
start = middleIndex + 1;
}
else if (middleData < k)
start = middleIndex + 1;
else
end = middleIndex - 1;
return GetLastK(data, length, k, start, end);
}
C++ 题解
class Solution {
public:
int GetNumberOfK(vector<int> data ,int k) {
int first = getFirstK(data,k);
int last = getLastK(data,k);
return last - first + 1;
}
int getFirstK(vector<int>data,int k)
{
int length = data.size();
int left = 0;
int right = length - 1;
int mid = (left+right)/2;
while(left <= right)
{
// 这里需要带等于号
if (data[mid] >= k)
{
right = mid - 1;
}
else
{
left = mid + 1;
}
mid = (right+left) / 2;
}
return left;
}
int getLastK(vector<int>data,int k)
{
int length = data.size();
int left = 0;
int right = length - 1;
int mid = (left+right) /2;
// 这里需要带等于号
while(left <= right)
{
if (data[mid] <= k)
{
left = mid + 1;
}
else
{
right = mid - 1;
}
mid = (right+left) / 2;
}
return right;
}
};
python 题解
# -*- coding:utf-8 -*-
class Solution:
def GetNumberOfK(self, data, k):
# write code here
first = self.getFirstK(data,k)
last = self.getLastK(data,k)
return last - first + 1
def getFirstK(self,num,k):
left,right = 0,len(num)-1
mid = (left + right) // 2
while left <= right:
if num[mid] >= k:
right = mid -1
else:
left = mid +1
mid = (left + right) // 2
return left
def getLastK(self,num,k):
left,right = 0,len(num)-1
mid = (left + right) // 2
while left <= right:
if num[mid] <= k:
left = mid + 1
else:
right = mid - 1
mid = (left + right) // 2
return right
注意:
- python除法采用
//