Leetcode 153. Find Minimum in Rotated Sorted Array & Leetcode 154. Find Minimum in Rotated Sorted Ar

153题目:
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.


这个题不知道O(n)能不能过,但既然出出来了,那就肯定不是那种暴力的方法。
因为只有一次rotate,(假设rotate后不是单调升),所以除了某两个数之间其他都是有序的。
所以,相当于有两段上升的序列,且前一段的最小值比后一段的最大值要大。
然后依据这个特点二分求解即可。
这里写图片描述

class Solution {
public:
    int findMin(vector<int>& nums) {
        return find(nums, 0, nums.size() - 1);
    }

    int find(vector<int>& nums, int lt, int rt) {
        if (lt == rt) return nums[lt];
        if (lt + 1 == rt) return min(nums[lt], nums[rt]);
        int mid = (lt + rt) >> 1;
        if (nums[lt] > nums[rt]) {
            if (nums[mid] > nums[rt]) return find(nums, mid, rt);
            else return find(nums, lt, mid);
        }
        else return nums[lt];
    }
};

154题目:
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.


这个题允许重复数字。
所以,我认为这个题是做不到logn复杂度的,比如说:1,1,1……1,2,-1,1,1,1…..1
最小的数字是-1,但是两侧有很多很多1,所以二分的时候mid的值也是1,所以无法判断是在哪个区间。
所以只能将左边界右移一位(或者右边界左移一位),这样,算法就是O(N)复杂度了。
但是呢,这样写也是能过的。
总而言之,个人认为这个题没有任何意义。
这里写图片描述

class Solution {
public:
    int findMin(vector<int>& nums) {
        return find(nums, 0, nums.size() - 1);
    }

    int find(vector<int>& nums, int lt, int rt) {
        if (lt == rt) return nums[lt];
        if (lt + 1 == rt) return min(nums[lt], nums[rt]);
        int mid = (lt + rt) >> 1;
        if (nums[lt] > nums[rt]) {
            if (nums[mid] > nums[rt]) return find(nums, mid, rt);
            else return find(nums, lt, mid);
        }
        else if (nums[lt] < nums[rt]) return nums[lt];
        else return find(nums, lt + 1, rt);
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值