码迷,mamicode.com
首页 > 编程语言 > 详细

Search in Rotated Sorted Array leetcode java

时间:2018-06-11 17:05:32      阅读:173      评论:0      收藏:0      [点我收藏+]

标签:int   duplicate   难度   sea   return   stat   log   bec   solution   

描述
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 // LeetCode, Search in Rotated Sorted Array
 2 // 时间复杂度 O(log n),空间复杂度 O(1)
 3 class Solution {
 4     public static int search(int A[], int n, int target) {
 5        int first = 0, last = n;
 6        while (first != last) {
 7             int mid = (first + last) / 2;
 8             if (A[mid] == target)
 9                   return mid;
10            if (A[first] <= A[mid]) {
11                  if (A[first] <= target && target < A[mid])
12                             last = mid;
13                   else
14                              first = mid + 1;
15            } else {
16                   if (A[mid] < target && target <= A[last-1])
17                              first = mid + 1;
18                   else
19                               last = mid;
20             }
21          }
22              return -1;
23    }
24 }

 

Search in Rotated Sorted Array leetcode java

标签:int   duplicate   难度   sea   return   stat   log   bec   solution   

原文地址:https://www.cnblogs.com/ncznx/p/9167398.html

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