[Leetcode] Search in Rotated Sorted Array II

来源:互联网 发布:淘宝图 编辑:程序博客网 时间:2024/06/18 16:20

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 {    public boolean search(int[] nums, int target) {        int start = 0;        int end = nums.length - 1;        while(start <= end) {            int mid = (start + end) / 2;            if(nums[mid] == target) {                return true;            }            else if(nums[start] < nums[mid]) {                if(target > nums[mid]) {                    start = mid +1;                }                else if(target < nums[mid] && target >= nums[start]) {                    end = mid -1;                }                else if(target < nums[mid] && target < nums[start]){                    start = mid + 1;                }            }            else if(nums[start] > nums[mid]) {                if(target < nums[mid]) {                    end = mid - 1;                }                else if(target > nums[mid] && target > nums[end]) {                    end = mid - 1;                }                else if(target > nums[mid] && target <= nums[end]) {                    start = mid + 1;                }            }            // when nums[start] == nums[mid], it can either be because pivot is on the right of mid or because of duplicates            else {                start++;            }        }        return false;    }}

0 0
原创粉丝点击