zoukankan      html  css  js  c++  java
  • [LeetCode#33]Search in Rotated Sorted Array

    Problem:

    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.

    My analysis:

    The idea behind binary search is beautiful and elegenat: we only search the possible result in the possible part.
    If we stick to this principle, we would finally end up in finding out the right result.
    For this question, even the sorted array was rotated, but we could use extra checking to guarantee we still iterate on the right partion of the array.
    1. we firstly find out the mid element in which partion.
    (either left or right partion is perfectly ordered)
    a. the perfectly ordered partion.
    b. the mixed partion.

    2. we make our decision on iterating which part based on the comparsion in the sorted partion. we could not make the decsion based on the mixed partion, because we do not know the boundary.
    a. iff the target is in the ordered partion, we search the target in it.
    b. otherwise, we search the target in other partion. (which means the target must in this partion)

    Note the checking condition is "if (A[low] <= A[mid])", rather than "if (A[low] < A[mid]) "
    cause we should treat A[low] = A[mid] as the left partion sorted !!!

    My solution: 

    public class Solution {
        public int search(int[] A, int target) {
            
            if (A.length == 0)
                return -1;
            
            int low = 0;
            int high = A.length - 1;
            int mid = -1;
            
            while (low <= high) {
                mid = (low + high) / 2;
                
                if (A[mid] == target)
                    return mid;
                
                if (A[low] <= A[mid]) { //either left partion or right partion is perfectly sorted.
                    
                    if (A[low] <= target && target < A[mid])
                        high = mid - 1;
                    else 
                        low = mid + 1;
                        
                } else{
                    
                    if (A[mid] < target && target <= A[high])
                        low = mid + 1;
                    else 
                        high = mid - 1;
                }
            }
            
            return -1;
        }
    }
  • 相关阅读:
    Web API系列(三)统一异常处理
    Web API系列(二)接口安全和参数校验
    Web API系列(一)设计经验与总结
    文件并发(日志处理)--队列--Redis+Log4Net
    Jquery手机下拉刷新,下拉加载数据
    nginx 几个参数
    op cache config
    历史问题回顾
    第三方服务的使用
    nginx+php-fpm json_encode 到client pages 截断
  • 原文地址:https://www.cnblogs.com/airwindow/p/4205111.html
Copyright © 2011-2022 走看看