• Search in Rotated Sorted Array ||


    Search in Rotated Sorted Array ||

    Suppose a sorted array is rotated at some pivot unknown to you beforehand.

    (i.e., 0 1 2 4 5 6 7 might become 4 5 6 7 0 1 2).

    You are given a target value to search. If found in the array return its index, otherwise return -1.

    You may assume no duplicate exists in the array.

    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.

    ref:http://fisherlei.blogspot.com/2013/01/leetcode-search-in-rotated-sorted-array_3.html

    [解题思路]
    确实有影响。比如,上一题(http://fisherlei.blogspot.com/2013/01/leetcode-search-in-rotated-sorted-array.html)的程序中默认如果A[m]>=A[l],那么[l,m]为递增序列的假设就不能成立了,比如如下数据
    [1,3,1,1,1]
    所以,要是想增强该假设,有两个选择
    1. 对于每一个递增序列,遍历之,确认。
    2. 找到pivot点,然后确定对应序列搜索。


    Update: 3/18/2013. add the implementation
    重新想了一下,其实不需要这么复杂。如果A[m]>=A[l]不能确定递增,那就把它拆分成两个条件
    1. A[m]>A[l]  递增
    2. A[m] ==A[l] 确定不了,那就l++,往下看一步即可。 

    public class Solution {
        public boolean search(int[] A, int target) {
            int len = A.length;
            
            int l = 0;
            int r = len -1;
            
            while(l <= r){
                int m = (l+r)/2;
                
                if(target == A[m]){
                    return true;
                }
                
                if( A[m] < A[l]){ // higher is sorted
                    if(target > A[m] && target <= A[r]){
                        l = m+1;
                    }else{
                        r = m-1;
                    }
                }else if(A[m] > A[l]){
                    if(target >= A[l] && target < A[m]){
                        r = m-1;
                    }else{
                        l = m+1;
                    }
                }else{  // A[m] == A[l]
                        l++;
                }
            }
            
            return false;
        }
    }
  • 相关阅读:
    input 放大镜
    记住密码弹出事件
    thinkphp修改及编写标签库,编辑器的使用
    thinkphp 配合mongodb
    缓存技术
    php面试题目
    pdo 整套类的封装,保存修改查询
    mongodb 的备份恢复导入与导出
    mongodb 分组查询
    smarty 模板的入门使用
  • 原文地址:https://www.cnblogs.com/RazerLu/p/3535770.html
Copyright © 2020-2023  润新知