1. 程式人生 > >Leetcode|Find Minimum in Rotated Sorted Array[二分查詢]

Leetcode|Find Minimum in Rotated Sorted Array[二分查詢]

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

Find the minimum element.

You may assume no duplicate exists in the array.

參考leetcode solution;
對於陣列A,AL代表最左邊的元素,AR代表最右邊的元素;
如果沒旋轉,AL

int findMin(vector<int
>
& nums) { int n=nums.size(); if(n==1) return nums[0]; int first=0,last=n-1; //consider special conditions //if(nums[first]<nums[last]) return nums[first]; while(first<last){ int mid=(first+last)/2; if(nums[last]<nums[mid]) first=mid+1
; else last=mid; } return nums[last]; }

如果有重複元素呢?
最壞情況時間複雜度O(n);
直接去除陣列初始的重複元素(nums[first]==nums[last]),後面和沒重複的一樣了!見下一篇部落格分析!