首页 > 代码库 > LeetCode--Search in Rotated Sorted Array II
LeetCode--Search in Rotated Sorted Array II
Follow up for "Search in Rotated Sorted Array":
What if duplicates are allowed?
Would this affect the run-time complexity? How and why?
Write a function to determine if a given target is in the array.
#include <vector> #include <string> using std::string; using std::vector; class Solution { public: bool search(int A[], int n, int target) { if(n==0) return false; int loc = find_max(A,n); bool flag = binary_search(A,0,loc,target); if(flag) return flag; flag = binary_search(A,loc+1,n-1,target); return flag; } int find_max(int* a, int n) { for(int i=0; i<n-1; i++) { if(a[i] > a[i+1]) return i; } return 0; } bool binary_search(int* a, int low, int high, int target) { while(low<=high) { int mid = (low+high)/2; if(a[mid] > target) high--; else if(a[mid] < target) low++; else return true; } return false; } };
LeetCode--Search in Rotated Sorted Array II
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。