Leetcode:Search in Rotated Sorted Array
来源:互联网 发布:金融网络销售违法吗 编辑:程序博客网 时间:2024/06/01 10:33
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.
思路:先遍历一遍数组,找出分割点,将数组分成low1~high1,low2~high2两个有序子数组,其中A[high2]<A[low1]。
如果A[low1]<=target,则在low1~high1区间二分查找;
如果A[low1]>target,则在low2~high2区间二分查找。
时间复杂度为O(logn + n)。
代码如下:
class Solution {public: int binSearch(int A[],int begin,int end,int target) { while(begin <= end) { int mid = begin + (end - begin) >> 1; if(A[mid] > target) end = mid - 1; else if(A[mid] < target) begin = mid + 1; else return mid; } return -1; } int search(int A[], int n, int target) { if(n == 0)return -1; int i = 0; while(i < n - 1 && A[i] < A[i + 1]) i++; if(i == n - 1) return binSearch(A,0,n - 1,target); if(i < n - 1) { int low1 = 0; int high1 = i; int low2 = i + 1; int high2 = n - 1; if(A[low1] <= target) { int idx = binSearch(A,low1,high1,target); if(idx >= 0)return idx; else return -1; } else { int idx = binSearch(A,low2,high2,target); if(idx >= 0)return idx; else return -1; } } }};
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
- WSGI 简介(使用python描述)
- 使用Vitamio打造自己的Android万能播放器(8)——细节优化
- 计算阶乘n!末尾的0的个数
- SIPp web frontend(1)
- SSH基本原理和免密码登录
- Leetcode:Search in Rotated Sorted Array
- MySQL 数据库优化
- 5.4链接
- Java中的Callable和Future
- 第一年的年终奖
- 利用Mock测试Spring中Databinder
- 利用commons-fileupload 实现文件上传终极版及commons-fileupload和commons-io包关系
- 1016. 部分A+B (15)
- Linux Shell 脚本应用 ——shell命令的组合运用