标签:while 移动 time 没有 val 规律 dup 一个 run
Suppose an array sorted in ascending order 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.
Java Solution:
Runtime beats 70.31%
完成日期:07/14/2017
关键词:Array
关键点:利用Binary Search 结合 rotated sorted array 中必然有一半是有序序列 来搜索
1 public class Solution 2 { 3 public int search(int[] nums, int target) 4 { 5 if(nums == null || nums.length == 0) 6 return -1; 7 8 int left = 0; 9 int right = nums.length - 1; 10 11 while(left <= right) 12 { 13 int mid = left + (right - left) / 2; 14 15 if(nums[mid] == target) // if the middle one is target, return mid index 16 return mid; 17 else if(nums[mid] >= nums[left]) // meaning left half is ascending order 18 { 19 if(target >= nums[left] && target < nums[mid]) // if target is in left half 20 right = mid - 1; // move to left half to search 21 else // target is in right half 22 left = mid + 1; // move to right half to search 23 } 24 else // meaning right half is ascending order 25 { 26 if(target > nums[mid] && target <= nums[right]) // if target is in right half 27 left = mid + 1; 28 else // target is in left half 29 right = mid - 1; 30 31 } 32 33 } 34 35 36 return -1; 37 } 38 }
参考资料:
http://www.cnblogs.com/grandyang/p/4325648.html
LeetCode 算法题目列表 - LeetCode Algorithms Questions List
LeetCode 33. Search in Rotated Sorted Array(在旋转有序序列中搜索)
标签:while 移动 time 没有 val 规律 dup 一个 run
原文地址:http://www.cnblogs.com/jimmycheng/p/7173158.html