LeetCode 81. Search in Rotated Sorted Array II(搜索旋转的数组)

28 篇文章 0 订阅
23 篇文章 0 订阅

原题网址:https://leetcode.com/problems/search-in-rotated-sorted-array-ii/

Follow up for "Search in Rotated Sorted Array":
What if duplicates are allowed?

Would this affect the run-time complexity? How and why?

Write a function to determine if a given target is in the array.

方法:二分法查找,注意当头尾相等时,前后两段都需要查找。

public class Solution {
    private boolean search(int[] nums, int target, int from, int to) {
        if (from > to) return false;
        if (from == to) return nums[from] == target;
        int m = (from+to)/2;
        if (nums[m] == target) return true;
        if (nums[from] == nums[to]) return search(nums, target, from, m-1) || search(nums, target, m+1, to);
        if (nums[from] < nums[to]) {
            if (nums[m] < target) return search(nums, target, m+1, to);
            else return search(nums, target, from, m-1);
        }
        // nums[from] > nums[to]
        if (nums[from] <= nums[m]) {
            if (nums[from] <= target && target < nums[m]) return search(nums, target, from, m-1);
            return search(nums, target, m+1, to);
        } else {
            if (nums[m] < target && target <= nums[to]) return search(nums, target, m+1, to);
            return search(nums, target, from, m-1);
        }
        //此处错误!!!
        // if ((nums[from] <= target && target < nums[m]) || (target < nums[m] && nums[m] <= nums[to])) return search(nums, target, from, m-1);
        // return search(nums, target, m+1, to);
    }
    public boolean search(int[] nums, int target) {
        return search(nums, target, 0, nums.length-1);
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值