leedcode-二分查找

1. 搜索旋转排序数组(leedcode-33)

  • 数组中不存在重复的元素
    public int search(int[] nums, int target) {

        int left = 0;
        int right = nums.length - 1;
        int mid;

        while(left <= right){
            mid = (left + right) / 2;
            if(nums[mid] == target){
                return mid;
            }
            // 前半段有序(必须包含等于,否则后半段就会无序,例:[3,1])
            if(nums[left] <= nums[mid]){
                // 在有序的前半段进行查找
                if(nums[left] <= target && target < nums[mid]){
                    right = mid - 1;
                }else{
                    left = mid + 1;
                }
            // 后半段有序
            }else{
                // 在有序的后半段进行查找
                if(nums[mid] < target && target <= nums[right]){
                    left = mid + 1;
                }else{
                    right = mid - 1;
                }
            }
        }
        return -1;
    }

2. 搜索旋转排序数组 (leedcode-81)

  • 允许重复元素
    public boolean search(int[] nums, int target) {

        int left = 0;
        int right = nums.length - 1;
        int mid;

        while(left <= right){
            mid = (left + right) / 2;
            if(nums[mid] == target){
                return true;
            }
            // 去除掉前面的重复元素
            if(nums[left] == nums[mid]){
                left++;
                continue;
            }
            if(nums[left] < nums[mid]){
                if(nums[left] <= target && target < nums[mid]){
                    right = mid - 1;
                }else{
                    left = mid + 1;
                }
            }else{
                if(nums[mid] < target && target <= nums[right]){
                    left = mid + 1;
                }else{
                    right = mid - 1;
                }
            }
        }

        return false;
    }

你可能感兴趣的:(leedcode)