码迷,mamicode.com
首页 > 其他好文 > 详细

Search in Rotated Sorted Array II

时间:2014-09-18 11:26:23      阅读:167      评论:0      收藏:0      [点我收藏+]

标签:style   color   io   java   ar   for   div   sp   cti   

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[] A, int target) {
        if(A==null)
        {
            return false;
        }
        int left=0;
        int right=A.length-1;
        int middle;
        while(left<=right)
        {
            middle=left+(right-left)/2;
            if(A[middle]==target)
            {
                return true;
            }
            if(A[left]==A[right])
            {
                left++;
                continue;
            }
            if(A[left]<=A[middle])
            {
                if(A[left]<=target&&target<=A[middle])
                {
                    right=middle-1;
                }
                else
                {
                    left=middle+1;
                }
            }
            else
            {
                if(A[middle]<target&&target<=A[right])
                {
                    left=middle+1;
                }
                else
                {
                    right=middle-1;
                }
            }
        }
        return false;
    }
}


Search in Rotated Sorted Array II

标签:style   color   io   java   ar   for   div   sp   cti   

原文地址:http://blog.csdn.net/jiewuyou/article/details/39369539

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!