zoukankan      html  css  js  c++  java
  • Find Minimum in Rotated Sorted Array

    Find Minimum in Rotated Sorted Array

    问题:

    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).

    Find the minimum element.

    You may assume no duplicate exists in the array.

    思路:

      变形后的二分查找

    我的代码:

    public class Solution {
     public int findMin(int[] num) {
            if(num == null || num.length == 0) return -1;
            int left = 0;
            int right = num.length - 1;
            while(left + 1 < right)
            {
                int mid = (left + right)/2;
                int leftVal = num[left];
                int rightVal = num[right];
                int midVal = num[mid];
                if(leftVal <= midVal && midVal < rightVal)   return num[left];
                else if(midVal > rightVal)  left = mid;
                else right = mid;
            }
            if(num[left] <= num[right]) return num[left];
            else return num[right];
        }
    }
    View Code

    学习之处;

      此种方法是改种后的二分查找,常规二分查找 left <= right left = mid - 1 or right = mid + 1,而此时变形为left = mid, right = mid,这样的话,如果判断条件还是left<=right,则无法跳出循环了,所以只能是left + 1 < right 

  • 相关阅读:
    less的安装使用
    bootStrap
    响应式布局——媒体查询
    发光渐变器
    好看的按钮
    CSS3:2D、3D属性
    CSS3渐变
    background
    过渡transition、opacity的兼容性
    【未完成】【java异常】java.lang.IllegalStateException: No suitable default RequestUpgradeStrategy
  • 原文地址:https://www.cnblogs.com/sunshisonghit/p/4321363.html
Copyright © 2011-2022 走看看