LeetCode算法笔记–Day37
31. Next Permutation
题目:
Suppose an array sorted in ascending order 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]).
You are given a target value to search. If found in the array return its index, otherwise return -1.
Your algorithm’s runtime complexity must be in the order of O(log n).
example
input: nums = [4,5,6,7,0,1,2], target = 0
output: 4
My Answer:
方法一:二分法
题目要求算法时间复杂度必须是O(logn) 的级别,提示可以使用二分搜索的方法。
我们将数组从中间分开成左右两部分的时候,一定有一部分的数组是有序的。
如果 [l, mid - 1] 是有序数组,且 target 的大小满足 [\textit{nums}[l],\textit{nums}[mid])[nums[l],nums[mid]),则我们应该将搜索范围缩小至 [l, mid - 1],否则在 [mid + 1, r] 中寻找。
如果 [mid, r] 是有序数组,且 target 的大小满足 (\textit{nums}[mid+1],\textit{nums}[r]](nums[mid+1],nums[r]],则我们应该将搜索范围缩小至 [mid + 1, r],否则在 [l, mid - 1] 中寻找。
Runtime complexity : O(logn)
Space complexity : O(1)
1 | /** |