美文网首页
Search in Rotated Sorted Array I

Search in Rotated Sorted Array I

作者: 无为无悔 | 来源:发表于2016-09-09 20:02 被阅读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.

    
    public class Solution {
        public static int search(int[] arr, int key) {
            if(arr == null || arr.length == 0)
                return -1;
            int low = 0, high = arr.length;
            while(low != high) {
                int mid  = low + (high - low) / 2;
                // 主要针对第一个和最后一个元素重复,直接返回第一个
                if(arr[low] == key)
                    return low;
                if(arr[mid] == key)
                    return mid;
                if(arr[low] <= arr[mid]) {
                    if(key >= low && key < arr[mid]) {
                        high = mid;
                    }
                    else {
                        low = mid + 1;
                    }
                }
                else {
                    if(key > arr[mid] && key <= arr[high-1] ) {
                        low = mid + 1;
                    }
                    else {
                        high = mid;
                    }
                }
            }
            return -1;
        }
    }
    
    

    相关文章

      网友评论

          本文标题:Search in Rotated Sorted Array I

          本文链接:https://www.haomeiwen.com/subject/vntyettx.html