码迷,mamicode.com
首页 > 编程语言 > 详细

LeetCode-Find Minimum in Rotated Sorted Array(找出反转数组中的最小值)

时间:2015-03-07 14:16:09      阅读:150      评论:0      收藏:0      [点我收藏+]

标签:

题1:

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.

题2:如果允许上题的数组有重复数字呢?

解法:最笨的方法,也是最容易想到的方法就是直接遍历数组,找出最小值,时间复杂度O(n),但是对于本题明显会超时。此时,比较容易想到的就是二分查找,因为其有序。但是两者肯定是有不同点的。

第一题的代码如下:

public int findMin(int[] num) {
        int low = 0;
        int high = num.length-1;
        while (low < high-1) {
        	int mid = low + (high-low)/2;
        	if (num[low] < num[high]) {
        		if (num[mid] < num[low]) {
        			low = mid;
        		} else {
        			high = mid;
        		}
        	} else {
        		if (num[mid] < num[high]) {
        			high = mid;
        		} else {
        			low = mid;
        		}
        	}
        }
        return num[low] > num[high] ? num[high] : num[low];
    }

此题一定要区分,这个序列是递增的还是递减的。很多解题方法都没考虑这个问题。显然有了第一题的思路,第二题也就好解了。

public int findMin(int[] num) {
        int low = 0;
        int high = num.length-1;
        while (low < high-1) {
        	int mid = low + (high-low)/2;
        	if (num[low] < num[high]) {
        		if (num[mid] < num[low]) {
        			low = mid;
        		} else if (num[mid] > num[low]){
        			high = mid;
        		} else {
        			low++;
        		}
        	} else {
        		if (num[mid] < num[high]) {
        			high = mid;
        		} else if (num[mid] > num[high]){
        			low = mid;
        		} else {
        			high--;
        		}
        	}
        }
        return num[low] > num[high] ? num[high] : num[low];
    }





LeetCode-Find Minimum in Rotated Sorted Array(找出反转数组中的最小值)

标签:

原文地址:http://blog.csdn.net/my_jobs/article/details/44114951

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!