33. Search in Rotated Sorted Array

来源:互联网 发布:名片地图生成软件 编辑:程序博客网 时间:2024/06/06 12:52

题目

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.


翻译

假设以升序排列的数组在您预先知道的枢轴上旋转。

(即0 1 2 4 5 6 7可能成为4 5 6 7 0 1 2)。

您将获得一个目标值进行搜索。如果在数组中找到返回其索引,否则返回-1。

您可以假定数组中不存在重复。



分析

对于这种旋转的排序数组,他是可以分成两个有序数组的

所以首先通过二分法,在分成两个有序数组的情况下进行讨论


有两种情况,中位数(mid)大于最左边的数(l),如4,5,6,7,0,1,2

mid小于l,如5,6,7,0,1,2,4

情况1中,target在左边的数组中,r=m-1;右边的数组中则l=m+1

情况2中,target在左边的数组中,r=m-1;右边的数组中则l=m+1

以mid的尾后为分界线的话,左边可以分成两种数组,即4,5,6,7和5,6,7,0

情况1和2的处理是一样的,但是条件不一样,所以分别是&&和||

时间复杂度为O(logN)

class Solution {public:    int search(vector<int>& nums, int target) {        int l =0, r = nums.size()-1;          while(l<=r){              int m = (l+r)/2;              if(nums[m] == target) return m;              if(nums[m]>= nums[l]){                  if(nums[l]<=target && target<= nums[m]) r = m-1;                  else l = m+1;              }else{                  if(target>=nums[l] || target<=nums[m]) r = m-1;                  else l = m+1;              }          }          return -1;      }};


原创粉丝点击