搜索旋转数组

package daily20201230;

/**
 * @author : zhaoliang
 * @program :newCoder
 * @description : 搜索旋转数组
 * @create : 2020/12/30 19:29
 */
public class search {
     
    //升序排列的整数数组 nums 在预先未知的某个点上进行了旋转(例如, [0,1,2,4,5,6,7] 经旋转后可能变为 [4,5,6,7,0,1,2] )。
    //
    //请你在数组中搜索 target ,如果数组中存在这个目标值,则返回它的索引,否则返回 -1 。
    public int search(int[] nums,int target){
     
        if (nums == null || nums.length==0)return -1;
        int start = 0;
        int end = nums.length-1;
        int mid;
        while(start +1 < end){
     
            mid = start+(end-start)/2;
            if (nums[mid] == target){
     
                return mid;
            }
            if (nums[start] <nums[mid] ){
     
                if (nums[start] <= target && target <= nums[mid]){
     
                    end = mid;
                }else {
     
                    start = mid;
                }
            }else {
     
                if (nums[mid] <= target && target <= nums[end]){
     
                    start = mid;
                }else {
     
                    end = mid;
                }
            }
        }
        if (nums[start] == target){
     
            return start;
        }
        if (nums[end] == target){
     
            return end;
        }
        return -1;
    }
}

你可能感兴趣的:(剑指Offer刷题(Java),常见算法题,LeetCode刷题,java,leetcode)