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;
        }
    }
  • 相关阅读:
    dfadfas
    Sqlserver修改文件目录,包括系统数据库
    VS2013 产品密钥所有版本
    win11 取消右键更多选项
    VS2013 产品密钥所有版本
    CronTrigger表达式
    C#语言Windows服务程序测试网站发送HTTP请求超时解决办法
    未能写入输出文件“c:\Windows\Microsoft.NET\Framework\v2.0.50727\Temporary ASP.NET Files\root\705b2e0e\c6ba7a68\App_global.asax.v9
    SQL跨数据库复制表数据<转载>
    “服务器应用程序不可用”解决方法
  • 原文地址:https://www.cnblogs.com/airwindow/p/4205111.html
Copyright © 2011-2022 走看看