Find Minimum in Rotated Sorted Array

来源:互联网 发布:阿里云学生服务器续费 编辑:程序博客网 时间:2024/05/07 20:03

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.

思路:简单二分法即可

class Solution {public:    int findMin(vector<int> &num) {                if(num.size()==1) {            return num[0];        }                return findMinUtil(num, 0, num.size()-1);    }        int findMinUtil(vector<int> &num, int low, int high) {        int mid;                if (num[low] < num[high]) {            return num[low];        }                if (low == high) {            return num[low];        }                if (num[low] > num[high]) {            mid = low + (high - low)/2;            if (num[mid] >= num[low]) {                low = mid + 1;                return findMinUtil(num, low, high);            }            else {                high = mid;                return findMinUtil(num, low, high);            }        }    }}; 

2015-01-13

简化了一下上面的代码,序列在rotate后,在pivot前面的一段是升序序列,pivot后也是升序序列,但是pivot前的升序序列的值都大于pivot后的升序序列的值,最小值是后面那段小的升序序列里面的第一个值。判断num[mid]和num[high],如果num[mid] > num[high],说明mid还在rotate前面那段大的里面,最小值是在rotate后面那段小的里面,所以low往后移动;相反如果num[mid] < num[high]说明,mid已经在rotate后面那段小的升序序列里面,就要把high的范围往前提。一直到low == high或者num[low] < num[high]的时候退出循环,num[low]即为最小值。

class Solution {public:    int findMin(vector<int> &num) {        int low = 0, high = num.size() - 1;        while (low < high && num[low] > num[high]) {            int mid = low + (high - low) / 2;            if (num[mid] > num[high]) {                low = mid + 1;            }            else {                high = mid;            }        }                return num[low];    }};


0 0
原创粉丝点击