[LeetCode] Find Minimum in Rotated Sorted Array II

简介: 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 pi

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.

  • 解题思路
    与上一题相比,比较过程多了中间元素和首尾元素相同的情况,在这种情况下需要分别对前半部分和后半部分求最小值。在最坏情况下,时间复杂度为O(n)

  • 实现代码

/*************************************************************
    *  @Author   : 楚兴
    *  @Date     : 2015/2/8 18:33
    *  @Status   : Accepted
    *  @Runtime  : 13 ms
*************************************************************/
#include <iostream>
#include <vector>
using namespace std;

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

    int find(vector<int> &num, int begin, int end)
    {
        int mid;
        while (begin < end)
        {
            if (num[begin] < num[end]) //表示没有翻转
            {
                return num[begin];
            }

            mid = (begin + end) / 2;
            if (num[mid] > num[end])
            {
                begin = mid + 1;
            }
            else if (num[mid] < num[end])
            {
                end = mid;
            }
            else
            {
                //分别查找两边
                return min(find(num, begin, mid), find(num, mid + 1, end));
            }
        }
        return num[begin];
    }
};
目录
相关文章
|
11月前
|
Java
Leetcode 295. Find Median from Data Stream
在一个有序数组中找中位数,但需要支持再数组中添加新的元素。本来是有序里的,可以很轻易就查到中位数,但如果添加新数字后,不一定有序。如果先对数组排序,那代价就比较大了,每次排序时间复杂度O(n*log(n)),看discuss发现了一种很巧妙的解法,可以把添加数据的时间复杂度降低到O(log(n)) ,查询中位数O(1)。
45 0
|
11月前
Leetcode 4. Median of Two Sorted Arrays
题目描述很简单,就是找到两个有序数组合并后的中位数,要求时间复杂度O(log (m+n))。 如果不要去时间复杂度,很容易就想到了归并排序,归并排序的时间复杂度是O(m+n),空间复杂度也是O(m+n),不满足题目要求,其实我开始也不知道怎么做,后来看了别人的博客才知道有个二分法求两个有序数组中第k大数的方法。
32 0
|
11月前
Leetcode Find Minimum in Rotated Sorted Array 题解
对一个有序数组翻转, 就是随机取前K个数,移动到数组的后面,然后让你找出最小的那个数,注意,K有可能是0,也就是没有翻转。
41 0
|
机器学习/深度学习 人工智能 算法
CF1550A Find The Array(贪心算法)
CF1550A Find The Array(贪心算法)
32 0
|
JavaScript 前端开发 索引
Array类型【find】
Array类型【find】
90 0
|
Shell Linux 索引
Linux- 转换 find 命令的返回值为 shell array
本文示例了如何在Linux系统下转换 find 命令的返回值为一个 shell array
191 0
Search in Rotated Sorted Array - 循环有序数组查找问题
Search in Rotated Sorted Array - 循环有序数组查找问题
66 0
|
5月前
|
Python
使用array()函数创建数组
使用array()函数创建数组。
86 3
|
1月前
|
Go
Golang语言之数组(array)快速入门篇
这篇文章是关于Go语言中数组的详细教程,包括数组的定义、遍历、注意事项、多维数组的使用以及相关练习题。
21 5
|
2月前
|
Python
PyCharm View as Array 查看数组
PyCharm View as Array 查看数组
51 1