• 81. Search in Rotated Sorted Array II


        /*
         * 81. Search in Rotated Sorted Array II 
         * 2016-5-13 by Mingyang
         * 这就是I的升级版,所有思路一模一样
         * 1.如果右边sort,并且target比中间小,那么肯定在左边,
         * 如果A[mid] == A[high],那么high--,因为不能判断哪边是sorted
         * 如果A[mid]>A[high]那么左边sort,那么只需要看最左边和target的关系
         * 这里还需要注意的就是while (low <= high)一定需要等于符号
         */
        public boolean search2(int[] A, int target) {
            if (A == null || A.length == 0)
                return false;
            int low = 0;
            int high = A.length - 1;
            while (low <= high) {
                int mid = (low + high) / 2;
                if (target < A[mid]) {
                    if (A[mid] < A[high])// right side is sorted
                        high = mid - 1;// target must in left side
                    else if (A[mid] == A[high])
    // cannot tell right is sorted, move pointer high----这一部分就是多加出来的
                        high--;
                    else // left side is sorted
                      if (target < A[low])
                        low = mid + 1;
                      else
                        high = mid - 1;
                } else if (target > A[mid]) {
                    if (A[low] < A[mid])// left side is sorted
                        low = mid + 1;// target must in right side
                    else if (A[low] == A[mid])
    // cannot tell left is sorted, move pointer low----这一部分就是多加出来的
                        low++;
                    else // right side is sorted
                      if (target > A[high])
                        high = mid - 1;
                      else
                        low = mid + 1;
                } else
                    return true;
            }
            return false;
        }
  • 相关阅读:
    jQuery 基础一 样式篇
    javaJavaScript DOM
    linux 实用命令
    Linux下修改.bash_profile 文件改变PATH变量的值
    java 字符串截取的方法
    Telnet命令参考手册
    linux下dubbo调试 ---telnet命令
    【Spring Task】定时任务详解实例-@Scheduled
    Spring定时任务的几种实现
    SQL之case when then用法
  • 原文地址:https://www.cnblogs.com/zmyvszk/p/5494400.html
Copyright © 2020-2023  润新知