搜索旋转排序数组
2017-07-07 11:15
381 查看
假设有一个排序的按未知的旋转轴旋转的数组(比如,0 1 2 4 5 6 7 可能成为4
5 6 7 0 1 2)。给定一个目标值进行搜索,如果在数组中找到目标值返回数组中的索引位置,否则返回-1。
你可以假设数组中不存在重复的元素。
样例
给出[4, 5, 1, 2, 3]和target=1,返回 2
给出[4, 5, 1, 2, 3]和target=0,返回 -1
5 6 7 0 1 2)。给定一个目标值进行搜索,如果在数组中找到目标值返回数组中的索引位置,否则返回-1。
你可以假设数组中不存在重复的元素。
样例
给出[4, 5, 1, 2, 3]和target=1,返回 2
给出[4, 5, 1, 2, 3]和target=0,返回 -1
public class Solution { /** *@param A : an integer rotated sorted array *@param target : an integer to be searched *return : an integer */ public int search(int[] A, int target) { // write your code here if(A==null||A.length==0){ return -1; } int start=0; int end=A.length-1; int mid; while(start+1<end){ mid=start+(end-start)/2; if(A[mid]>A[start]){ //第一种情况 if(target>=A[start]&&target<=A[mid]){ end=mid; }else{ start=mid; } }else{ //第二种情况 if(target>=A[mid]&&target<=A[end]){ start=mid; }else{ end=mid; } } } if(target==A[start]){ return start; } if(target==A[end]){ return end; } return -1; } }
相关文章推荐
- 搜索旋转排序数组
- LintCode:搜索旋转排序数组
- [Lintcode] 搜索旋转排序数组 II Search in Rotated Sorted Array II
- 搜索旋转排序数组 II
- 搜索旋转排序数组
- 搜索旋转排序数组 II
- [LintCode] 搜索旋转排序数组 Search in Rotated Sorted Array
- [Lintcode] Search in Rotated Sorted Array II 搜索旋转排序数组 II
- 搜索旋转排序数组
- Lintcode 搜索旋转排序数组 II
- LintCode : 搜索旋转排序数组
- LeetCode 33 Search in Rotated Sorted Array(在旋转排序数组中搜索)(*)
- lintcode :search in rotated sorted array 搜索旋转排序数组
- *[Lintcode]搜索旋转排序数组
- LintCode-搜索旋转排序数组 II
- lintcode-搜索旋转排序数组II-63
- LintCode:搜索旋转排序数组 II
- 搜索旋转排序数组 II
- Lintcode 搜索旋转排序数组
- LintCode 62 搜索旋转排序数组