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

leetcode:Search in Rotated Sorted Array II(duplicated)

时间:2015-03-09 20:36:53      阅读:163      评论:0      收藏:0      [点我收藏+]

标签:

题目要求:

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.

题目地址:https://leetcode.com/problems/search-in-rotated-sorted-array-ii/

public class Solution {
    public static boolean search(int[] A, int target) {
        int first=0,last=A.length-1,mid;
        while(first<=last){
            mid=(first+last)/2;
            System.out.println("当前搜索范围"+A[first]+"--"+A[last]+",mid="+A[mid]);
            if(A[mid]==target)return true;
            else if(A[first]<A[mid]){//左有序
                
                if(target>=A[first]&&target<A[mid]){            
                    last=mid-1;
                }else{
                    first=mid+1;
                }
            }else if(A[first]>A[mid]){//右有序
                if(target>A[mid]&&target<=A[last]){        
                    first=mid+1;
                }else{
                    last=mid-1;
                }
                
            }else{//A[first]==A[mid]
                if(A[last]>A[mid]){//右有序
                    if(target>A[mid]&&target<=A[last]){
                        first=mid+1;
                    }else{
                        last=mid-1;
                    }        
                }else if(A[last]<A[mid]){//左有序,且左范围为同一数字
                    first=mid+1;
                    
                }else{//无法确定
                    first++;
                    last--;
                }
            }
        }
        return false;
    }
}

分析思路:

首先参照原题没重复项的思路,仅仅是first==mid的时候处理不同,分为下列情况:

在first==mid时:

a.当last>mid,则必有右有序;

b.当last<mid,则翻转奇异点在右范围,则必有左有序,且左范围均为同一个数字。

b.当last=mid时,无法确定奇异点分布,则last,mid,first3个相同均不等于target,则可以last--,first++再看下一步。

leetcode:Search in Rotated Sorted Array II(duplicated)

标签:

原文地址:http://www.cnblogs.com/charlesdoit/p/4324374.html

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