LeetCode Search in Rotated Sorted Array II
2012-11-21 13:36
519 查看
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.
Tips:
Notice the equal cases.
Solution:
class Solution {
public:
bool search(int A[], int n, int target) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
int left=0,right=n-1;
while(left<=right){
int mid=(left+right)/2;
if(A[mid]==target)
return true;
if(A[mid]<A[right]){
if(target>A[mid]&&target<=A[right]){
left=mid+1;
}else
right=mid-1;
}else if(A[mid]>A[right]){
if(target<A[mid]&&target>=A[left]){
right=mid-1;
}else{
left=mid+1;
}
}else{
--right;
}
}
return false;
}
};
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.
Tips:
Notice the equal cases.
Solution:
class Solution {
public:
bool search(int A[], int n, int target) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
int left=0,right=n-1;
while(left<=right){
int mid=(left+right)/2;
if(A[mid]==target)
return true;
if(A[mid]<A[right]){
if(target>A[mid]&&target<=A[right]){
left=mid+1;
}else
right=mid-1;
}else if(A[mid]>A[right]){
if(target<A[mid]&&target>=A[left]){
right=mid-1;
}else{
left=mid+1;
}
}else{
--right;
}
}
return false;
}
};
相关文章推荐
- leetcode Search in Rotated Sorted Array II
- LeetCode(33)(81) Search in Rotated Sorted Array I II
- [LeetCode] Search in Rotated Sorted Array II
- [LeetCode]Search in Rotated Sorted Array II
- 89_leetcode_Search in Rotated Sorted Array II
- leetcode 81. Search in Rotated Sorted Array II
- LeetCode --- 81. Search in Rotated Sorted Array II
- [Leetcode] Search in Rotated Sorted Array II
- 【Leetcode】Search in Rotated Sorted Array II
- leetcode--Search in Rotated Sorted Array II
- LeetCode 81. Search in Rotated Sorted Array II
- LeetCode Search in Rotated Sorted Array II
- leetcode之Search in Rotated Sorted Array II
- leetcode - Search in Rotated Sorted Array I & II
- LeetCode Search in Rotated Sorted Array II
- LeetCode 33. Search in Rotated Sorted Array && 81. Search in Rotated Sorted Array II
- LeetCode之Search in Rotated Sorted Array II
- Leetcode -- Search in Rotated Sorted Array II
- Leetcode 81. Search in Rotated Sorted Array II
- Leetcode: Search in Rotated Sorted Array II