标签:leetcode
题意:从一个平移过的数组中找到最小的元素思路1:最简单的思路莫过于排序然后取第一个元素,复杂度O(N*log(N))
代码1:
public class Solution { public int findMin(int[] num) { Arrays.sort(num); return num[0]; } }
思路2: 遍历,比较两段升序数字的第一个就可以了, 4 5 6 7
0 1 2复杂度O(N)
代码2:
public int findMin(int[] num) {//解法1 遍历 int min = num[0], currMin = num[0]; int i = 0; while (++ i < num.length){ currMin = Math.min(num[i],currMin); if(i + 1 < num.length && num[i + 1] < currMin){ currMin = num[i + 1]; break; } } min = Math.min(min, currMin); return min; }思路3:二分法, 时间复杂度 O(log(N))
public int findMin(int[] num) {//解法3 二分 int min = 0; int l = 0, r = num.length -1, mid; while (l < r){ mid = l + (r - l) / 2; if(num[mid] > num[r]){ l = mid + 1; }else { r = mid; } } min = num[l]; return min; }
[LeetCode]Find Minimum in Rotated Sorted Array
标签:leetcode
原文地址:http://blog.csdn.net/youmengjiuzhuiba/article/details/44888087