Search in Rotated Sorted Array
来源:互联网 发布:焊缝截面计算软件 编辑:程序博客网 时间:2024/06/05 19:25
Search in Rotated Sorted Array
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.
1. 0 1 2 4 5 6 7
2. 7 0 1 2 4 5 6
3. 6 7 0 1 2 4 5
4. 5 6 7 0 1 2 4
5. 4 5 6 7 0 1 2
6. 2 4 5 6 7 0 1
7. 1 2 4 5 6 7 0
We can use binary search method to solve this problem. Firstly, let's try to find the regular pattern from the rotated array list above. From list 2,3,4, we can see that the value of the middle element is less that the value of the first element and the right half of every list is in an ascending order. From list 1,5,6,7, we can see that the value of the middle element is larger than the value of the first element and the left half of the list is in an ascending order.
public class Solution { public int search(int[] nums, int target) { if (nums == null || nums.length == 0) return -1; int start = 0; int end = nums.length - 1; while (start < end) { int mid = start + (end - start) / 2; if (nums[mid] == target) return mid; else if (nums[mid] < nums[start]) { if (target <= nums[end] && target > nums[mid]) start = mid + 1; else end = mid - 1; } else { if (target >= nums[start] && target < nums[mid]) end = mid - 1; else start = mid + 1; } } if (target == nums[start]) return start; else return -1; }}
- Search in Rotated Sorted Array
- Search in Rotated Sorted Array
- Search in Rotated Sorted Array
- Search in Rotated Sorted Array
- Search in Rotated Sorted Array
- Search in Rotated Sorted Array
- Search in Rotated Sorted Array
- Search in Rotated Sorted Array
- Search in Rotated Sorted Array
- Search in Rotated Sorted Array
- Search in Rotated Sorted Array
- Search in Rotated Sorted Array
- Search in Rotated Sorted Array
- Search in Rotated Sorted Array
- Search in Rotated Sorted Array
- Search in Rotated Sorted Array
- Search in Rotated Sorted Array
- Search in Rotated Sorted Array
- 查看jdk位数
- android 声音播放,我这里是给软件配的音效
- android 按手机返回键2次退出程序
- Java之线程状态
- HDU--杭电--3572--Task Schedule--最大流
- Search in Rotated Sorted Array
- 纸上谈兵(一)--对产品运营的初步认识
- mysql 的表名和列名设计时应该注意的一个问题
- 5大常用网站推广方法 吸引大流量
- 目标检测的图像特征提取之(一)HOG特征
- 目标检测的图像特征提取之(二)LBP特征
- Android 4.4 中 WebView 使用注意事项
- java基本数据类型
- jQuery开发之jQuery选择器一