码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode 154 Find Minimum in Rotated Sorted Array II

时间:2014-10-22 12:56:43      阅读:223      评论:0      收藏:0      [点我收藏+]

标签:java   leetcode   

Follow up for "Find Minimum in Rotated Sorted Array":
What if duplicates are allowed?

Would this affect the run-time complexity? How and why?

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.

The array may contain duplicates.

思路1:采用排序(jdk中的快排),时间复杂度为O(nlogn),代码如下
public class Solution {
	public int findMin(int[] num) {
		Arrays.sort(num);
		return num[0];
	}
}

思路2:采用一次性遍历,时间复杂度为O(n),代码如下
public class Solution {
    public int findMin(int[] num) {
        int  min=Integer.MAX_VALUE;
        for(int i=0;i<num.length;i++){
        	if(min>num[i])
        		min=num[i];
        }
        return min;
    }
}
思路3:采用折半查找,时间复杂度为O(logn),代码如下
public class Solution {
	public int findMin(int[] num) {
		return minFind(num, 0, num.length - 1);
	}

	private int minFind(int[] num, int begin, int end) {
		int middle = (begin + end) / 2;
		if (begin == end) {
			return num[begin];
		} else if (end == begin + 1) {
			return Math.min(num[begin], num[end]);
		} else if (end == begin + 2) {
			return Math.min(Math.min(num[begin], num[begin + 1]), num[end]);
		}
		if (num[begin] == num[end]) {
			return Math.min(minFind(num, begin, middle),minFind(num, middle, end));
		}
		if (num[middle] < num[begin] && num[middle] <= num[end]) {
			return minFind(num, begin, middle);
		} else if (num[begin] <= num[middle] && num[end] < num[middle]) {
			return minFind(num, middle, end);
		} else if (num[begin] < num[middle] && num[middle] <= num[end]) {
			return minFind(num, begin, middle);
		}else if (num[begin] <= num[middle] && num[middle] < num[end]) {
			return minFind(num, begin, middle);
		}
		return 0;
	}
}


LeetCode 154 Find Minimum in Rotated Sorted Array II

标签:java   leetcode   

原文地址:http://blog.csdn.net/mlweixiao/article/details/40373683

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