js 154. Find Minimum in Rotated Sorted Array II 二分查找

Follow up for "Find Minimum in Rotated Sorted Array":
What if duplicates are allowed?

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

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).

Find the minimum element.

The array may contain duplicates.

思路:

寻找有序重复数组的最小值是对上一道题目的延伸,当数组中存在大量重复数字的时候,就会破坏二分查找的机制,就无法取得O(lgn)的事件复杂度。比如:{2, 2, 2, 2, 2, 2, 2, 2, 0, 1, 1, 2} 和 {2, 2, 2, 0, 2, 2, 2, 2, 2, 2, 2, 2}。可以发现,当第一个数字、最后一个数字和中间数组全部相等的时候,二分查找就崩溃了,因为他无法判断该去左半边还是右半边,这中情况下,只需要将左指针右移一位,略过相同的数字,这对结果不会产生坏的影响,因为知识去掉了一个相同的,然后对剩余部分继续用二分查找,在最坏的情况下,比如所有元素都相同,时间复杂度会升到O(n)

 var findMin = function(nums) {
            var l = 0;
            var r = nums.length - 1;
            var res=nums[0];
            if (nums[l] < nums[r]) {
                return nums[l];
            } else{
                var m;
                while (l + 1 < r) {
                    m = Math.floor((l + r) / 2);
                    if (nums[l] < nums[m]) {
                        res=Math.min(res,nums[l]);//注意存储最小的值,因为后边很可能都相等,最小值就是这一个。
                        l = m;
                    } else if (nums[l] > nums[m]) {
                        res=Math.min(res,nums[m]);
                        r = m;
                    } else {
                        l++;
                    }
                }
              res=Math.min(nums[l], res);
              res=Math.min(nums[r], res);
              return res;
            }

        };

你可能感兴趣的:(js 154. Find Minimum in Rotated Sorted Array II 二分查找)