[Leetcode] Search in Rotated Sorted Array
来源:互联网 发布:网络招聘平台对比 编辑:程序博客网 时间:2024/05/21 12:42
题目:
Suppose a sorted array 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.
思路:二分法,不过需要加一层判断条件。首先判断哪边是连续的,然后向左走还是向右走通过连续的那一部分去判断。
class Solution {public: int search(int A[], int n, int target) { int lower_bound = 0; int upper_bound = n - 1; while (lower_bound <= upper_bound) { int mid = (lower_bound + upper_bound) / 2; if (A[mid] == target) { return mid; } else if (A[mid] >= A[lower_bound]) { //left part consistent if (A[lower_bound] <= target && A[mid] > target) { //go left upper_bound = mid - 1; } else { //go right lower_bound = mid + 1; } } else { //right part consistent if (A[upper_bound] >= target && A[mid] < target) { //go right lower_bound = mid + 1; } else { //go left upper_bound = mid - 1; } } } return -1; }};
总结:复杂度为O(log n).
0 0
- [leetcode][search] Search in Rotated Sorted Array
- LeetCode: Search in Rotated Sorted Array
- LeetCode: Search in Rotated Sorted Array II
- LeetCode Search in Rotated Sorted Array
- LeetCode Search in Rotated Sorted Array II
- [Leetcode] Search in Rotated Sorted Array
- LeetCode : Search in Rotated Sorted Array
- LeetCode : Search in Rotated Sorted Array II
- [LeetCode] Search in Rotated Sorted Array II
- [LeetCode] Search in Rotated Sorted Array
- [Leetcode] Search in a Rotated Sorted Array
- [Leetcode] Search in Rotated Sorted Array II
- leetcode 97: Search in Rotated Sorted Array
- [LeetCode] Search in Rotated Sorted Array
- [leetcode] Search in Rotated Sorted Array
- [leetcode] Search in Rotated Sorted Array II
- Leetcode Search in Rotated Sorted Array
- [LeetCode]Search in Rotated Sorted Array
- Java基本概念:集合类(Collection)List/Set/Map... 的区别和联系
- 网上无法找到的教程,LZMA教程,欢迎大家指正
- lu 初始化设置步骤
- 发了个快递是法国
- Java程序员的JavaScript学习笔记(5——prototype和Object内置方法)
- [Leetcode] Search in Rotated Sorted Array
- PHP中的定界符 EOT
- JAVA数据类型转换
- 初探java内存机制
- 再谈Java数据类型
- LINUX挂载光驱
- 游戏并购再创高峰,第三季度高达122亿美金,是去年总额的两倍
- BFS时间复杂度问题
- [Leetcode] Search for a Range