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;
        }
    }
  • 相关阅读:
    Uva 11401 数三角形
    Uva 11538 象棋中的皇后
    数学基础——基本计数方法
    八数码问题
    python 爬poj.org的题目
    python 爬图片
    hiho 第135周 九宫
    Uva 11464 偶数矩阵
    BZOJ 1001 [BeiJing2006]狼抓兔子
    LA 3708 墓地雕塑
  • 原文地址:https://www.cnblogs.com/airwindow/p/4205111.html
Copyright © 2011-2022 走看看