LeetCode(33) Search in Rotated Sorted Array解题报告

来源:互联网 发布:手机个人理财软件 编辑:程序博客网 时间:2024/06/06 07:29

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.

Subscribe to see which companies asked this question

public int search(int[] nums, int target) {        int start,end,mid;        start = 0;        end = nums.length-1;        while(start <= end){            mid = (start+end) / 2;            if(nums[mid] == target)                return mid;            else if(nums[start] < nums[mid]){                if(nums[start] <= target && nums[mid] > target){                    end = mid-1;                }                else{                    start = mid+1;                }            }            else if(nums[mid] < nums[end]){                    if(nums[mid] < target && nums[end] >= target){                        start = mid+1;                    }                    else{                        end = mid-1;                    }            }        }        return -1;    }
0 0
原创粉丝点击