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;
        }
    }
  • 相关阅读:
    collections工具类 排序
    API text|lang
    异常处理
    extends继承
    接口
    static修饰符
    多态与find关键词
    Markdown语法
    Hexo | (五)Yilia主题优化
    Hexo | (四)多机同步更新博客
  • 原文地址:https://www.cnblogs.com/airwindow/p/4205111.html
Copyright © 2011-2022 走看看