[CareerCup][Google Interview] 找出现次数
生活随笔
收集整理的這篇文章主要介紹了
[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; }轉載于:https://www.cnblogs.com/chkkch/archive/2012/10/29/2744640.html
《新程序員》:云原生和全面數字化實踐50位技術專家共同創作,文字、視頻、音頻交互閱讀總結
以上是生活随笔為你收集整理的[CareerCup][Google Interview] 找出现次数的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 一步一步实现网站的多语言版本
- 下一篇: 开发75条(写的不错) 选择自 chur