二分查找 变形
2014-05-17 12:59
375 查看
#include<iostream> using namespace std; int helper(int a[],int len,int t,bool isleft) { if(a == NULL || 0 >= t) return EOF; int last = EOF; int left = 0; int right = len - 1; while(left <= right) { int middle = (left + right)/2; if(a[middle] > t) { right = middle - 1; } else if(a[middle]<t) { left = middle + 1; }else{ last = middle; if(isleft) right = middle-1; else left = middle + 1; } } return last; } int main() { int a[] = {1,1,2,2,2,2,3,4,5}; int left = helper(a,sizeof(a)/sizeof(a[0]),2,true); int right = helper(a,sizeof(a)/sizeof(a[0]),2,false); if(EOF != left && EOF != right) cout<<left<<" "<<right<<" "<<right-left + 1<<endl; else cout<<left<<" "<<right<<" "<<"can not found"<<endl; }
#include<stdio.h> int solver(const int a[],const int n,const int t) { int total = 0; if (NULL == a && 0 >= n) return total; int start = 0; int end = n-1; while(start <= end) { printf("%d %d\n",start,end); int middle = (start + end)/2; if(t == a[middle]) { total = 1; int cursor = 0; while(++cursor && middle + cursor < n && t == a[middle + cursor]) total++; cursor = 0; while(--cursor && middle + cursor >= 0 && t == a[middle + cursor]) total++; return total; } else if(t > a[middle]) end = middle - 1; else start = middle + 1; } return total; } int main() { int a[] = {1,1,1,1,1,1}; int b[] = {1,2,2,2,2,3}; int c[] = {1,2,3,5,6,7}; printf("%d",solver(b,6,4)); }
相关文章推荐
- 二分查找变形
- 51nod 1279 扔盘子 (二分查找的变形)
- 【小米笔试题】二分查找算法的变形
- 二分查找及其变形整理
- [二分查找变形]弯曲的木杆(POJ 1905)
- 二分查找及其几个变形
- 最长上升子序列变形题-二分查找DP
- 算法-分割有序数组后查值-二分查找的变形
- Find Peak Element——二分查找的变形
- 二分查找及其变形总结
- poj 1064 二分查找变形—判定并找到可行解
- 二分查找及其变形
- 二分查找及其变形算法
- 一种二分查找变形
- 二分查找及其变形
- 你真的能搞定二分查找吗 — 二分查找及变形
- 二分查找之变形
- 二分查找的变形应用
- 你真的能搞定二分查找吗 — 二分查找及变形
- 2014-04-04 循环递增数组查找元素(二分变形思想,百度面试题)