Leetcode 之 Find Minimum in Rotated Sorted Array

来源:互联网 发布:简历管理系统 源码 编辑:程序博客网 时间:2024/06/05 20:25

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.

二分查找的思想,找到断口即为最小的数(断口左右两边都是有序的,且比他大)

先做了一个顺序查找,取第一个数为最小数,遍历一遍数组,依次比较,输出最小的,以为会TLE,没想到直接A了。
代码贴一下:

public int findMin(int[] nums) {    int len = nums.length - 1;        int min = nums[0];        for(int i = 0; i <  nums.length;i++){               if(nums[i] < min){                min = nums[i];            }        }        return min;    }

146 / 146 test cases passed.
Status: Accepted
Runtime: 364 ms

然后觉得有点慢,换二分找,这里不需要每次都左右两边分别找一次,只要根据条件找一边就行。研究了半天,发现只要判断middle和left(或者right,一定不能left和right都判断)的关系就行。如果 m > l,说明左边是顺序的,断口在右边,找右边;如果m < l,说明断口在左边,找左边。另外,当左边比右边小的时候递归终止。

这里有一个比较重要的问题,就是=的处理和middle指针的移位要对应。如果middle不移位,会死循环。

不过貌似用二分也没比顺序快很多,

 public int findMin(int[] nums){        return find(nums, 0, nums.length - 1);    }    public int find(int[] nums, int begin, int end){        int key = (begin + end) / 2;        if(nums[begin] <= nums[end])    return nums[begin];        if(nums[key] < nums[begin]){            return find(nums, begin, key);            }        else{            return find(nums, key + 1, end);        }    }

146 / 146 test cases passed.
Status: Accepted
Runtime: 356 ms

0 0
原创粉丝点击