【LeetCode从零单刷】Search in Rotated Sorted Array I & II

来源:转载

I 题目:

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.

解答:

直接遍历是可以的,但是不够快。再想想,已经 sorted 了,能不能用 O(log n) 时间复杂度的方法?二分搜索?

二分搜索需要探究 mid 处的值与 target 的关系,因此将原数组分为head~mid、mid~tail 两个区间继续二分。

但是对于 rotated 的特殊排序数组,可能有以下两种特殊情况:

  • [4,5,6,7,8,1,2],中间值是 7,大于 tail=2。但是 head~mid 区间内必然是有序的,如果 [head] < target < [mid],可以正常二分;如果不在,就继续对特殊区间 mid~tail 特殊二分处理
  • [4,5,6,0,1,2,3],中间值是 0,小于 head=4,但是 mid~tail 区间内必然是有序的,如果 [mid] < target < [tail],可以正常二分;如果不在,就继续对特殊区间 head~mid 特殊二分处理

关于二分搜索的实现,有一个细节需要注意:每次必然移动一位

例如:head = mid +1,tail = mid- 1。只是这样实现,需要在循环中单独预先判断 head,tail,mid 处的值。

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

II 题目:

What if duplicates are allowed?

Would this affect the run-time complexity? How and why?

解答:

如果有重复元素,例如 [1,2,1,1]。那么中间值是大于 tail 时, head~mid 区间内未必是有序的;同理中间值是小于 head 时, mid~tail 区间内未必是有序的。

但是,如果我跳过重复元素呢?就变成了上一道问题了。因此,这道题仅仅需要一些预处理过程。

class Solution {public: bool search(vector<int>& nums, int target) { int size = nums.size(); int mid; int head = 0; int tail = size - 1; while (head <= tail) { if (nums[head] == target) return true; if (nums[tail] == target) return true; mid = (head + tail) / 2; if (nums[mid] == target) return true; if (nums[mid] == nums[head]) { int i = head; for(; i <= mid; i++) { if (nums[i] != nums[mid]) { head = i; break; } } } if (nums[mid] == nums[tail]) { int i = tail; for(; i >= mid; i--) { if (nums[i] != nums[mid]) { tail = i; break; } } } if (nums[mid] < nums[head]) { if (nums[mid] < target && target < nums[tail]) head = mid + 1; else tail = mid - 1; } else if (nums[mid] > nums[tail]) { if (nums[head] < target && target < nums[mid]) tail = mid - 1; else head = mid + 1; } else { if (target < nums[mid]) tail = mid - 1; else head = mid + 1; } } return false; }};

版权声明:本文为博主原创文章,转载请联系我的新浪微博 @iamironyoung



分享给朋友:
您可能感兴趣的文章:
随机阅读: