问题描述:
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.
"Search in Rotated Sorted Array" can be seen here
基本思路:
与"Search in Rotated Sorted Array" 类似,只对返回值做少许修改即可。具体参见《Search in Rotated Sorted Array》
代码:
bool search(int A[], int n, int target) { //C++ if(n < 0) return false; if(n == 1) { if(A[0] == target) return true; else return false; } if(A[0] == target) return true; for(int i = 1; i < n; i++) { if(A[i] < A[i-1]) { if(A[i] > target || A[i-1] < target || target > A[n-1]) return false; } if(A[i] == target ) return true; } return false; }
时间: 2024-11-06 11:12:00