leetcode------Search in Rotated Sorted Array
标题: | Search in Rotated Sorted Array |
通过率: | 28.9% |
难度: | 难 |
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.
这个题目是升级版的难度定为中等,我再做这个升级版时不知道什么旋转排序数组,然后来先做这个版本,然后我才弄明白,这种类型有两种情况
1. 4567012中间为7且 start=4<7,那么target如果在4-7之间的或者在7以外
2.45670123中间位置为0 且 start=4>0,那么target在4-0之间或者0以外。
直接看代码,最后一个else操作是start++ 看一个例子 【1,3】target=3.当mid=0时 start=0 ,mid对应的元素和start对应的元素是相等,但是又不等于target
代码如下:
1 public class Solution { 2 public int search(int[] A, int target) { 3 int start=0,end=A.length-1,mid=0; 4 while(start<=end){ 5 mid=(start+end)/2; 6 if(A[mid]==target)return mid; 7 if(A[start]<A[mid]){ 8 if((target<A[mid])&&(target>=A[start])) 9 end=mid-1; 10 else start=mid+1; 11 } 12 else if(A[start]>A[mid]){ 13 if((target<A[mid])||(target>=A[start])) 14 end=mid-1; 15 else start=mid+1; 16 } 17 else start++; 18 } 19 return -1; 20 } 21 }
python:
1 class Solution: 2 # @param A, a list of integers 3 # @param target, an integer to be searched 4 # @return an integer 5 6 def search(self, A, target): 7 left = 0 8 right = len(A) - 1 9 10 while left <= right: 11 mid = (left + right) >> 1 12 if target == A[mid]: 13 return mid 14 # print mid, A[mid], left, A[left], right, A[right], '..', 15 if A[left] <= A[mid]: 16 if A[left] <= target and target <= A[mid]: 17 right = mid - 1 18 else: 19 left = mid + 1 20 else: 21 if A[mid] < target and target <= A[right]: 22 left = mid + 1 23 else: 24 right = mid - 1 25 return -1