题目:
Suppose a sorted array is rotated at some pivot unknown to you beforehand.
(i.e., 0 1 2 4 5 6 7
might become 4 5 6 7 0 1 2
).
You are given a target value to search. If found in the array return its index, otherwise return -1.
You may assume no duplicate exists in the array.
代码:
class Solution { public: int search(int A[], int n, int target) { int begin = 0; int end = n-1; while (begin != end) { if( begin+1 == end ) { if (A[begin]==target) return begin; if (A[end]==target) return end; return -1; } const int mid = (end+begin)/2; if (A[mid]==target) return mid; if(target<A[mid]) { if(A[begin]<A[mid]) { if(target>=A[begin]) { end = mid-1; } else { begin = mid+1; } } else { end = mid-1; } } else { if(A[begin]<A[mid]) { begin = mid+1; } else { if(target<=A[end]) { begin = mid+1; } else { end = mid-1; } } } } if (A[begin]==target) return begin; return -1; } };
Tips:
1. 分target与A[mid]大小情况先讨论
2. 由于前半截或后半截至少一个是有序的,再按照这个来分条件讨论
if else代码中有一些逻辑可以合并,但是考虑到保留原始逻辑更容易被理解,就保留现状了
时间: 2024-10-10 03:51:42