码迷,mamicode.com
首页 > 其他好文 > 详细

LC.33. Search in Rotated Sorted Array

时间:2018-02-25 11:18:12      阅读:155      评论:0      收藏:0      [点我收藏+]

标签:ota   分享   tco   div   ted   class   gpo   log   otherwise   

 

https://leetcode.com/problems/search-in-rotated-sorted-array/description/
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.

time: o(logn) space: o(1)


 1 public int search(int[] nums, int target) {
 2         if (nums == null || nums.length ==0 ) return -1 ;
 3         int left = 0, right = nums.length -1 ;
 4         while(left + 1 < right){
 5             int mid = left + (right-left)/2;
 6             if (nums[mid] == target) return mid ;
 7             //break into two parts: note, there is no duplicate
 8             //first half
 9             if (nums[left]< nums[mid] ){
10                 if (target<=nums[mid] && nums[left] <=target){
11                     right = mid ;
12                 }else {
13                     left = mid ;
14                 }
15             }
16             //second half: 注意判断顺序变化: 考虑单调的,避开非单调的!
17             else {
18                 if (nums[mid]<=target && target <= nums[right]){
19                     left = mid ;
20                 }else {
21                     right = mid;
22                 }
23             }
24         }
25         //post processing for the left and right
26         if (nums[left] == target){
27             return left ;
28         }
29         if(nums[right] == target){
30             return right;
31         }
32         return -1 ;
33     }

 

技术分享图片

 

 

技术分享图片

 

LC.33. Search in Rotated Sorted Array

标签:ota   分享   tco   div   ted   class   gpo   log   otherwise   

原文地址:https://www.cnblogs.com/davidnyc/p/8468655.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!