81.搜索旋转排序数组

2020/10/1

方法一

class Solution {
    public boolean search(int[] nums, int target) {
        boolean result = false;
        int i = 0;
        while(i<nums.length){
            if(nums[i]==target){
                result = true;
                break;
            }else if(nums[i]>target){
                int j = i;
                i = nums.length - 1;
                while(i>j){
                    if(target == nums[i]){
                        result = true;
                        break;
                    }
                    i-=1;
                }

            }
            i+=1;
        }
        return result; 
    }
}

方法二:二分查找

public boolean search(int[] nums, int target) {
        if (nums == null || nums.length == 0) {
            return false;
        }
        int start = 0;
        int end = nums.length - 1;
        int mid;
        while (start <= end) {
            mid = start + (end - start) / 2;
            if (nums[mid] == target) {
                return true;
            }
            if (nums[start] == nums[mid]) {
                start++;
                continue;
            }
            //前半部分有序
            if (nums[start] < nums[mid]) {
                //target在前半部分
                if (nums[mid] > target && nums[start] <= target) {
                    end = mid - 1;
                } else {  //否则,去后半部分找
                    start = mid + 1;
                }
            } else {
                //后半部分有序
                //target在后半部分
                if (nums[mid] < target && nums[end] >= target) {
                    start = mid + 1;
                } else {  //否则,去后半部分找
                    end = mid - 1;

                }
            }
        }
        //一直没找到,返回false
        return false;

    }
Last Updated: 4/4/2024