LeetCode刷题笔记 33. 搜索旋转排序数组
2019-07-11 17:03
363 查看
题目描述
假设按照升序排序的数组在预先未知的某个点上进行了旋转。
( 例如,数组 [0,1,2,4,5,6,7] 可能变为 [4,5,6,7,0,1,2] )。
搜索一个给定的目标值,如果数组中存在这个目标值,则返回它的索引,否则返回 -1 。
你可以假设数组中不存在重复的元素。
你的算法时间复杂度必须是 O(log n) 级别。
示例:
输入: nums = [4,5,6,7,0,1,2], target = 0
输出: 4
总结
二分查找法,不过再确定下一次循环的start和end值时用nums[start]和nums[end]来判断
Sample Code
public class Solution { //revised bianry search public int search(int[] nums, int target) { int start = 0; int end = nums.length - 1; while (start <= end){ int mid = (start + end) / 2; if (nums[mid] == target) return mid; if (nums[start] <= nums[mid]){ if (target < nums[mid] && target >= nums[start]) end = mid - 1; else start = mid + 1; } if (nums[mid] <= nums[end]){ if (target > nums[mid] && target <= nums[end]) start = mid + 1; else end = mid - 1; } } return -1; } }
相关文章推荐
- Leetcode:33. 搜索旋转排序数组
- 【leetcode】33. 搜索旋转排序数组&&34. 在排序数组中查找元素的第一个和最后一个位置(java实现)
- 【Leetcode】33. 搜索旋转排序数组
- LeetCode33. 搜索旋转排序数组(Java)
- Leetcode 33. 搜索旋转排序数组
- LeetCode c++ 33. 搜索旋转排序数组
- Leetcode 33. 搜索旋转排序数组c++
- LeetCode33.python实现: 搜索旋转排序数组问题☆☆
- Leetcode做题日记:33. 搜索旋转排序数组(PYTHON)
- leetcode 33. 搜索旋转排序数组
- 搜索旋转排序数组 - LeetCode
- LeetCode——旋转排序数组搜索
- leetcode 腾讯精选练习(50 题)33.搜索旋转排序数组
- LeetCode刷题-搜索旋转排序数组
- LeetCode刷题-搜索旋转排序数组 II
- 搜索旋转排序数组(LeetCode)
- 33. 搜索旋转排序数组Leetcode
- leetcode33---搜索旋转排序数组
- 【LeetCode-面试算法经典-Java实现】【081-Search in Rotated Sorted Array II(搜索旋转的排序数组)】
- Leetcode 81 搜索旋转排序数组 II Python C++ 史上最详细题解系列