标签:
题目来源:《剑指offer》面试题38
题目:统计一个数字在排序数组中出现的次数。例如输入排序数组{1,2,3,3,3,3,4,5}和数字3,由于3在这个数组中出现了4次,因此输出4.
分析:排序数组,使用二分查找。分别找到数组中第一个k的索引,和最后一个k的索引。相减加一便可。
#include<iostream> using namespace std; int GetFirstK(int *nums, int len, int k) { if (nums == NULL || len <= 0) return -1; int start = 0; int end = len - 1; int mid = 0; while (start < end) { mid = start + (end - start) / 2; if (nums[mid] == k) { end = mid; } else if (nums[mid] < k) { start = mid + 1; } else { end = mid - 1; } } return start; } int GetLastK(int *nums, int len, int k) { if (nums == NULL || len <= 0) return -1; int start = 0; int end = len - 1; int mid = 0; while (start < end) { if (start + 1 == end) { if (nums[start] == nums[end]) { //防止死循环,注意 return end; } else { return start; } } mid = start + (end - start) / 2; if (nums[mid] == k) { start = mid; } else if (nums[mid] < k) { start = mid + 1; } else { end = mid - 1; } } return end; } int GetNum(int *nums, int len, int k) { if (nums == NULL || len <= 0) return k; int start_pos = GetFirstK(nums, len, k); int end_pos = GetLastK(nums, len, k); return end_pos - start_pos + 1; } int main() { int nums[] = {1,2,3,3,3,3,4,5}; int nums1[] = {3}; int nums2[] = {1,3,3,3,4}; cout<<GetNum(nums, 8, 3)<<endl; return 0; }
标签:
原文地址:http://www.cnblogs.com/vincently/p/4782441.html