Leetcode 题目解析之 Search in Rotated Sorted Array II

2022-01-10 20:05:16 浏览数 (1)

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.

代码语言:txt复制
    public boolean search(int[] nums, int target) {
        int l = 0, r = nums.length - 1;
        while (l <= r) {
            int m = (l   r) / 2;
            if (nums[m] == target)
                return true;
            if (nums[l] < nums[m]) {
                if (target <= nums[m] && target >= nums[l])
                    r = m - 1;
                else
                    l = m   1;
            } else if (nums[l] > nums[m]) {
                if (target >= nums[l] || target <= nums[m])
                    r = m - 1;
                else
                    l = m   1;
            } else
                l  ;
        }
        return false;
    }

0 人点赞