LeetCode 30 days Challenge - Day 19
本系列将对LeetCode新推出的30天算法挑战进行总结记录,旨在记录学习成果、方便未来查阅,同时望为广大网友提供帮助。
Search in Rotated Sorted Array
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
.
You may assume no duplicate exists in the array.
Your algorithm’s runtime complexity must be in the order of O(log n).
Example 1:
1 | Input: nums = [4,5,6,7,0,1,2], target = 0 |
Example 2:
1 | Input: nums = [4,5,6,7,0,1,2], target = 3 |
Solution
题目要求分析:给定一个经过“旋转”的升序排列数组,在其中查找target
,若不存在返回-1
。
解法:
本题有多种解法,作者选用的是一种比较直观的方法,其他更为“tricky”的题解可参考原题讨论区。
思路大体上分为两步:
- 二分搜索,找到原升序排列数组第一个元素在给定数组中的位置
sep
。 - 通过映射,将给定数组的元素位置“映射”到实际位置:
true_pos = (pos + sep) % nums.size()
- 在此基础上,进行二分搜索。
1 | int search(vector<int>& nums, int target) { |
传送门:Search in Rotated Sorted Array
Karl