[LeetCode] 81. Search in Rotated Sorted Array II

Posted aaronliu1991

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[LeetCode] 81. Search in Rotated Sorted Array II相关的知识,希望对你有一定的参考价值。

在旋转有序数组中搜索二。这题跟[LeetCode] 33. Search in Rotated Sorted Array求的一样,多一个条件是input里面有重复数字。依然是用二分法做,但是worst case很可能会到O(n);而且其中还会多一个case的判断,就是nums[mid]和nums[start],nums[end]的大小关系。因为在重复数字的数量超过数组一半的情况下,nums[mid]是有可能跟后两者相等的,此时需要将左右指针都分别往中间靠近。

时间O(logn), worst case O(n)

空间O(1)

 1 /**
 2  * @param {number[]} nums
 3  * @param {number} target
 4  * @return {boolean}
 5  */
 6 var search = function(nums, target) {
 7     // corner case
 8     if (nums === null || nums.length === 0) {
 9         return false;
10     }
11 
12     // normal case
13     let start = 0;
14     let end = nums.length - 1;
15     while (start + 1 < end) {
16         let mid = Math.floor(start + (end - start) / 2);
17         if (nums[mid] === target) return true;
18         if (nums[start] === nums[mid] && nums[mid] === nums[end]) {
19             start++;
20             end--;
21         } else if (nums[start] <= nums[mid]) {
22             if (nums[start] <= target && target <= nums[mid]) {
23                 end = mid;
24             } else {
25                 start = mid;
26             }
27         } else if (nums[mid] <= nums[end]) {
28             if (nums[mid] <= target && target <= nums[end]) {
29                 start = mid;
30             } else {
31                 end = mid;
32             }
33         }
34     }
35     if (nums[start] === target) return true;
36     if (nums[end] === target) return true;
37     return false;
38 };

 

以上是关于[LeetCode] 81. Search in Rotated Sorted Array II的主要内容,如果未能解决你的问题,请参考以下文章

leetcode 81. Search in Rotated Sorted Array II 搜索旋转排序数组 II(中等)

LeetCode 81. Search in Rotated Sorted Array II

LeetCode:81. Search in Rotated Sorted Array II

LeetCode-81-Search in Rotated Sorted Array II

LeetCode81. Search in Rotated Sorted Array II

[LeetCode] 81. Search in Rotated Sorted Array II