zoukankan      html  css  js  c++  java
  • 【leetcode】Search in Rotated Sorted Array (hard)

    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.

    思路:二分搜索,每次去掉一半的错误选项。

    注意,每次 l = m + 1, r = m - 1 防止无限循环。

    int search(int A[], int n, int target) {
        int l = 0, r = n - 1;
        while(l <= r)  //注意有等号
        {
            int m = (l + r) / 2;
            if(A[m] == target)
                return m;
            if(A[l] <= A[m] && A[m] <= A[r]) //顺序的
            {
                if(A[m] > target)
                    r = m - 1;
                else
                    l = m + 1;
            }
            else if(A[l] >= A[m] && A[m] <= A[r]) //开头转到了左半部分
            {
                if(A[m] < target && target <= A[r]) //在右半部分
                    l = m + 1;
                else
                    r = m - 1;
            }
            else //开头转到了右半部分
            {
                if(A[l] <= target && target <= A[m]) //在左半部分
                    r = m - 1;
                else
                    l = m + 1;
            }
        }
        return -1;
    }

    大神简约版写法:去掉一半选项时的思路不同

    int search(int A[], int n,int target) {
        int lo = 0;
        int hi = n - 1;
        while (lo <= hi) {
            int mid = (lo + hi) / 2;
            if (A[mid] == target) return mid;
    
            if (A[lo] <= A[mid]) {
                if (target >= A[lo] && target < A[mid]) {
                    hi = mid - 1;
                } else {
                    lo = mid + 1;
                }
            } else {
                if (target > A[mid] && target <= A[hi]) {
                    lo = mid + 1;
                } else {
                    hi = mid - 1;
                }
            }
        }
        return -1;
    }
  • 相关阅读:
    gns3 接口说明 转
    Java二进制指令代码解析
    java大神RednaxelaFX
    深入理解Java虚拟机
    java环境变量设置
    openjdk
    JAVA call graphs JAVA调用图
    Java虚拟机原理图解
    JAVA --BYTECODE
    利用hsdis和JITWatch查看分析HotSpot JIT compiler生成的汇编代码
  • 原文地址:https://www.cnblogs.com/dplearning/p/4353985.html
Copyright © 2011-2022 走看看