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;
        }
    }
  • 相关阅读:
    JS中的原型规则与原型链
    JS中的“==”与强制类型转换
    协作开发中常用的Git命令小结
    JavaScript变量类型检测总结
    IDEA IntelliJ常用设置以及快捷键(转)
    Spring 发送 Email
    SSM框架的整合思路&功能实现
    使用Eclipse把java文件打包成jar 含有第三方jar库的jar包
    基于CDH5.x 下面使用eclipse 操作hive 。使用java通过jdbc连接HIVESERVICE 创建表
    Volley源码学习笔记
  • 原文地址:https://www.cnblogs.com/airwindow/p/4205111.html
Copyright © 2011-2022 走看看