Loading... <span class="label bg-warning">中等</span> ## 题目 假设按照升序排序的数组在预先未知的某个点上进行了旋转。 ( 例如,数组 `[0,1,2,4,5,6,7]` 可能变为 `[4,5,6,7,0,1,2]`)。 搜索一个给定的目标值,如果数组中存在这个目标值,则返回它的索引,否则返回 `-1` 。 你可以假设数组中不存在重复的元素。 你的算法时间复杂度必须是 O(log<sup>n</sup>) 级别。 示例 1: ```text 输入: nums = [4,5,6,7,0,1,2], target = 0 输出: 4 ``` 示例 2: ```text 输入: nums = [4,5,6,7,0,1,2], target = 3 输出: -1 ``` ## 思路 ## 代码 ```C++ int result = -1; void binarySearch(vector<int> &nums, int left, int right, int target) { if (left >= right) { if (target == nums[left]) { result = left; } return; } int middle = left + (right - left) / 2; binarySearch(nums, left, middle, target); binarySearch(nums, middle + 1, right, target); } int search(vector<int> &nums, int target) { if(nums.size()==0) return -1; binarySearch(nums, 0, nums.size() - 1, target); return result; } ``` ![leetcode-CN-33-binarySearch.png][1] [1]: http://alomerry.com/usr/uploads/2020/08/3232021104.png<hr class="content-copyright" style="margin-top:50px" /><blockquote class="content-copyright" style="font-style:normal"><p class="content-copyright">版权属于:清欢</p><p class="content-copyright">本文链接:<a class="content-copyright" href="http://alomerry.com/archives/408/">http://alomerry.com/archives/408/</a></p><p class="content-copyright">转载时须注明出处及本声明</p></blockquote> Last modification:August 18th, 2020 at 07:12 pm © 允许规范转载 Support 觉得我的文章有帮助吗,欢迎赞赏呀(๑• . •๑) ×Close Appreciate the author Sweeping payments Pay by AliPay Pay by WeChat