TypechoJoeTheme

IT技术分享

统计

[LeetCode 81] Search in Rotated Sorted Array II [Java]

2018-03-17
/
0 评论
/
938 阅读
/
正在检测是否收录...
03/17

1. Description

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

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

Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand.

i.e., 0 1 2 4 5 6 7 might become 4 5 6 7 0 1 2

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

The array may contain duplicates.

2. Example

given 4 5 6 7 0 1 2, find 6
return true

3. Code

public class LeetCode0081 {

    public boolean search(int[] nums, int target) {
        if (nums == null || nums.length == 0) {
            return false;
        }
        int left = 0;
        int right = nums.length - 1;
        while (left <= right) {
            int mid = left + ((right - left) >> 1);
            if (nums[mid] == target) {
                return true;
            } else if (nums[left] <= nums[mid]) {
                if (nums[left] <= target && target < nums[mid]) {
                    right = mid - 1;
                } else {
                    left++;
                }
            } else {
                if (nums[mid] < target && target <= nums[right]) {
                    left = mid + 1;
                } else {
                    right--;
                }
            }
        }
        return false;
    }

    public static void main(String[] args) {
        LeetCode0081 leetcode = new LeetCode0081();
        System.out.println(leetcode.search(new int[] { 4, 5, 6, 7, 0, 1, 2 }, 0));
    }
}
Array
朗读
赞 · 0
版权属于:

IT技术分享

本文链接:

https://idunso.com/archives/1478/(转载时请注明本文出处及文章链接)