面试题42:数字在排序数组中出现的次数

来源:互联网 发布:钉钉管理员能看到数据 编辑:程序博客网 时间:2024/06/05 19:00
题目:

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

边界条件及异常:

数组中没有这个数字

思路:
方法一:用二分查找法,先找到这个数字,在向左和右遍历,看是否依然是这个数字。

时间复杂度:O(n)

方法二:先找到该数字最前面的下标,和最后面的下标,然后做差。最前面的下标可以通过寻找K-0.5,最后面的下标可以通过寻找K+0.5。

时间复杂度:O(lgn)

#include <iostream>    #include <vector> #include <queue>#include <string>    #include <stack>    #include <algorithm>  #include <hash_set>  //for hashtable#include <hash_map>#include <unordered_map>#include <set>#include <ctime>using namespace std;int BinarySearch(vector<int> nums, int start, int end, double target){if (start >= end) return start;int mid = (start + end) / 2;if ((double)nums[mid] == target) return mid;else if ((double)nums[mid] > target) return BinarySearch(nums, start, mid - 1, target);else return BinarySearch(nums, mid + 1, end, target);}int GetNumberOfK(vector<int> nums, int K){int firstIndex = BinarySearch(nums, 0, nums.size() - 1, K - 0.5);int lastIndex = BinarySearch(nums, 0, nums.size() - 1, K + 0.5);if (nums[firstIndex] != K &&firstIndex<nums.size()-1) ++firstIndex;if (nums[lastIndex] != K&&lastIndex>0) --lastIndex;if (nums[firstIndex] != K || nums[lastIndex] != K) return -1;return lastIndex - firstIndex + 1;}int main(){int arr[] = { 1, 2, 3, 3, 4, 4, 4, 4, 4, 5, 5, 6, 7, 8 };vector<int> nums(arr, arr + 14);cout << GetNumberOfK(nums,8) << endl;return 0;}

方法三:思路和方法二相同,只不过寻找最前面的index和最后面的index方法不同。

首先看如何寻找第一个K出现的位置。二分查找法总是拿中间的数字和K比较,如果比K大,说明K只可能出现在数组的前半段;如果比K小,说明只可能出现在数组的后半段;如果等于K,则首先看这个数字是不是第一个K(即看前一个数字是不是K),如果不是,则第一个K还是在数组的前半段,下一轮仍然在前半段找。

同样的方法可以找到最后一个K的位置。

时间复杂度:O(lgn)

0 0
原创粉丝点击