【leetcode】Find Minimum in Rotated Sorted Array

来源:互联网 发布:java ee eclipse教程 编辑:程序博客网 时间:2024/05/17 22:56

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.
这道题目我没有找到合适的方法,开始就是暴力搜索的方式,竟然也通过了leetcode的测试。。。

class Solution {public:    int findMin(vector<int> &num) {        int min;        min=num[0];        for (int i=1;i<num.size();i++)        {            if(num[i]<=min)            {                min=num[i];            }        }        return min;    }};

网上的思路
主要思想是二分查找,对于num[beg .. end]数组,命mid=(beg+end)/2(有序的情况下),那么存在一下三种情况:

  • num[beg] < num[end]:这时,整个数组是有序的,因此直接返回num[beg]即可;
  • num[beg] >=num[end] && num[beg]>num[mid]:这时,num[mid..end]有序,那么最小值一定出现在num[beg..mid]之中,抛弃num[mid+1..end];
  • num[mid] >=num[end] && num[beg]<=num[mid] : 这时,num[beg..mid]是有序的,所以最小值一点个出现在num[mid+1..end]中,因为至少num[end]是小于num[beg]的,抛弃num[beg..mid];

    public class Solution {  public int findMin(int[] num){      int len = num.length;      int beg = 0;      int end = len-1;      while(beg<end){          //all sorted          if(num[end]>=num[beg]){              break;          }          int mid = (beg+end)/2;          //Sorted from mid to end          //The smallest must in num[beg..mid]           if(num[mid]<num[beg]){              end = mid;          }          else{              //Sorted from beg to mid              //The smallest must in num[mid+1..end]              beg = mid+1;          }      }      return num[beg];  }  }  
0 0