您的位置:首页 > 其它

LeetCode 081 Search in Rotated Sorted Array II

2015-10-24 08:38 267 查看

题目描述

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.

代码

[code]    public boolean search(int[] nums, int target) {

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

        while (left <= right) {

            int mid = (left + right) / 2;

            if (nums[mid] == target)
                return true;

            if (nums[left] < nums[mid]) {
                if (target <= nums[mid] && target >= nums[left])
                    right = mid - 1;
                else
                    left = mid + 1;
            } else if (nums[left] > nums[mid]) {
                if (target >= nums[left] || target <= nums[mid])
                    right = mid - 1;
                else
                    left = mid + 1;
            } else
                left++;
        }

        return false;
    }
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: