[CareerCup][Google Interview] 找出现次数
Given a sorted array and a number n.How can u find the number of occurance of n in the array . should be o(logn)
http://www.careercup.com/question?id=8877058
改变一下二分查找的方法,一次找到最左边,另一次找到最右边。
#include <iostream> #include <vector> using namespace std; int findPos(vector<int> &a, int left, int right, int key, bool findLeft) { if (left > right) return -1; int mid = (left + right) / 2; if (a[mid] == key) { int pos = findLeft ? findPos(a, left, mid - 1, key, findLeft) : findPos(a, mid + 1, right, key, findLeft); return (pos == -1 ? mid : pos); } else if (a[mid] > key) { return findPos(a, left, mid - 1, key, findLeft); } else { return findPos(a, mid + 1, right, key, findLeft); } } int main() { vector<int> a; for(int i = 0; i < 9; i++) for(int j = 0; j < 5; j++) a.push_back(i); int pos1 = findPos(a, 0, a.size() - 1, 5, true); int pos2 = findPos(a, 0, a.size() - 1, 5, false); cout << pos1 << ' ' << pos2 << endl; }
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步