#154 Find Minimum in Rotated Sorted Array II
2021/9/7 23:08:43
本文主要是介绍#154 Find Minimum in Rotated Sorted Array II,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
Description
Suppose an array of length n sorted in ascending order is rotated between 1 and n times. For example, the array nums = [0,1,4,4,5,6,7] might become:
- [4,5,6,7,0,1,4] if it was rotated 4 times.
- [0,1,4,4,5,6,7] if it was rotated 7 times.
Notice that rotating an array [a[0], a[1], a[2], …, a[n-1]] 1 time results in the array [a[n-1], a[0], a[1], a[2], …, a[n-2]].
Given the sorted rotated array nums that may contain duplicates, return the minimum element of this array.
You must decrease the overall operation steps as much as possible.
Examples
Example 1:
Input: nums = [1,3,5]
Output: 1
Example 2:
Input: nums = [2,2,2,0,1]
Output: 0
Constraints:
n == nums.length
1 <= n <= 5000
-5000 <= nums[i] <= 5000
nums is sorted and rotated between 1 and n times.
思路
大体上和 #153 是一样的思路,区别在于增加了一个step++步骤
也就是当nums[start] == nums[end]的时候,将start向右移动,直到nums[start] != nums[end],再执行原来的递归操作
代码
class Solution { public int min(int[] nums, int start, int end){ int end_num = nums[end]; int i; for(i = start; i < end; i++) if(nums[i] != end_num) break; start = i; if(start >= end) return nums[start]; int mid = (start + end) / 2; if(nums[start] < nums[end] || nums[start] > nums[mid]) return min(nums, start, mid); else return min(nums, mid + 1, end); } public int findMin(int[] nums) { int len = nums.length - 1; return min(nums, 0, len); } }
这篇关于#154 Find Minimum in Rotated Sorted Array II的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-11-29RocketMQ底层原理资料详解:新手入门教程
- 2024-11-29RocketMQ源码资料解析与入门教程
- 2024-11-29[开源]6.1K star!这款电视直播源神器真的太赞啦!
- 2024-11-29HTTP压缩入门教程:轻松提升网页加载速度
- 2024-11-29JWT开发入门指南
- 2024-11-28知识管理革命:文档软件的新玩法了解一下!
- 2024-11-28低代码应用课程:新手入门全攻略
- 2024-11-28哪些办公软件适合团队协作,且能够清晰记录每个阶段的工作进展?
- 2024-11-28全栈低代码开发课程:零基础入门到初级实战
- 2024-11-28拖动排序课程:轻松掌握课程拖动排序功能