Code & Func
2017-12-08

第72天。

今天的题目是Find Peak Element:

A peak element is an element that is greater than its neighbors.

Given an input array where num[i] ≠ num[i+1], find a peak element and return its index.

The array may contain multiple peaks, in that case return the index to any one of the peaks is fine.

You may imagine that num[-1] = num[n] = -∞.

For example, in array [1, 2, 3, 1], 3 is a peak element and your function should return the index number 2.

显然这道题写出一个O(n)的解法很简单。

这里的用二分法去求解,可以用O(logn)解出,两个步骤都是O(1)的时间复杂度。

1
int findPeakElement(vector<int>& nums) {
2
return findPeakElement(nums,0,nums.size() - 1);
3
}
4
int findPeakElement1(vector<int> &nums,int first,int last) {
5
if (first > last) return -1;
6
int mid = (first + last)/2;
7
int a = 0;
8
if ( (mid+1 == nums.size() || nums[mid] > nums[mid + 1]) &&
9
(mid-1 < 0 || nums[mid] > nums[mid-1]) )
10
return mid;
11
int left = findPeakElement(nums,first,mid-1);
12
if (left != -1) return left;
13
return findPeakElement(nums,mid+1,last);
14
}

当然这不是最好的解法,这里其实是用二分查找去做的:

1
int findPeakElement(const vector<int> &num) {
2
return Helper(num, 0, num.size()-1);
3
}
4
int Helper(const vector<int> &num, int low, int high){
5
if(low == high)
6
return low;
7
else
8
{
9
int mid1 = (low+high)/2;
10
int mid2 = mid1+1;
11
if(num[mid1] > num[mid2])
12
return Helper(num, low, mid1);
13
else
14
return Helper(num, mid2, high);
15
}
1 collapsed line
16
}

或者

1
int findPeakElement(const vector<int> &num)
2
{
3
int low = 0;
4
int high = num.size()-1;
5
6
while(low < high)
7
{
8
int mid1 = (low+high)/2;
9
int mid2 = mid1+1;
10
if(num[mid1] < num[mid2])
11
low = mid2;
12
else
13
high = mid1;
14
}
15
return low;
1 collapsed line
16
}
上一条动态