Leetcode NO.153 Find Minimum in Rotated Sorted Array

题目要求如下:

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.

本题就是寻找轴,或者说最小值。。也有其他几道涉及rotated array的问题应该都跟找到pivot有关。。

本题最直观的方法就是brute force,直接遍历一遍array,看看哪个num[i] < num[i-1],就是解。。很神奇的是,即便这样,也能通过测试。。。不过这么丧心病狂的方法显然不能跟面试官讲。。。而且并没有用到sorted array的性质。。。

本题我用类似二分查找的方式解决的,代码如下所示:

class Solution {
public:
    int findMin(vector<int> &num) {
  		/* find the pivot */
  		int low = 0;
  		int high = num.size()-1;
  		while (num[low] > num[high]) {
  			int mid = (low + high) / 2;
  			if (num[mid] >= num[low]) {
  				low = mid + 1;
  			}
  			else {
  				/* can't discard mid val, so test again in the next iteration */
  				high = mid;
  			}
  		}
  		return num[low];
    }
};

基本思路:

1,最外层循环,如果num[low]>num[high],说明pivot还没有找到,继续循环,如果num[low] <= num[high]说明已经找到,跳出循环,返回num[low]

2,循环内:设一个中点,如果num[mid]>=num[low],则说明pivot必然不在其中,需要寻找array的后半段;反之,则需要寻找array的前一半。这样每次把寻找范围缩小一半,故时间复杂度是O(log(n))。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值