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

19.2.2 [LeetCode 33] Search in Rotated Sorted Array

时间:2019-02-02 23:28:15      阅读:198      评论:0      收藏:0      [点我收藏+]

标签:splay   sea   arch   16px   open   dex   duplicate   index   有序数组   

 

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.

Your algorithm‘s runtime complexity must be in the order of O(log n).

Example 1:

Input: nums = [4,5,6,7,0,1,2], target = 0
Output: 4

Example 2:

Input: nums = [4,5,6,7,0,1,2], target = 3
Output: -1

题意

有序数组截成两段打乱顺序(或者也可能保持原序),以logn的复杂度找数

题解

技术图片
 1 class Solution {
 2 public:
 3     int search(vector<int>& nums, int target) {
 4         if (nums.size() <= 0)return -1;
 5         int pivot = nums[0], size = nums.size(), mididx = size, s=0, e=size-1;
 6         if (nums[size - 1] <= pivot) {
 7             int S = 0,E = size - 1;
 8             while (S <= E) {
 9                 int mid = (S + E) / 2;
10                 if (nums[mid] >= pivot)
11                     S = mid + 1;
12                 else
13                     E = mid - 1;
14             }
15             mididx = S;
16             if (mididx > size - 1)
17                 mididx = 0;
18             if (nums[size - 1] >= target) {
19                 s = mididx, e = max(size - 1,s);
20             }
21             else
22                 s = 0, e = max(mididx - 1,s);
23         }
24         while (s < e) {
25             int mid = (s + e) / 2;
26             if (nums[mid] < target)
27                 s = mid + 1;
28             else
29                 e = mid;
30         }
31         if (s >= size)return -1;
32         if (nums[s] == target)
33             return s;
34         return -1;
35     }
36 };
View Code

先找从哪开始是分界点,然后再找数

19.2.2 [LeetCode 33] Search in Rotated Sorted Array

标签:splay   sea   arch   16px   open   dex   duplicate   index   有序数组   

原文地址:https://www.cnblogs.com/yalphait/p/10349317.html

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