Find Peak Element

2015.1.23 14:28

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.

Note:

Your solution should be in logarithmic complexity.

Solution1:

  Here is the O(n) solution.

Accepted code:

 1 // 1CE, 2WA, 1AC, how to achieve logN with unordered data?
 2 class Solution {
 3 public:
 4     int findPeakElement(const vector<int> &num) {
 5         int n = (int)num.size();
 6 
 7         if (n == 1) {
 8             return 0;
 9         }
10         
11         if (num[0] > num[1]) {
12             return 0;
13         }
14         
15         if (num[n - 1] > num[n - 2]) {
16             return n - 1;
17         }
18         
19         int i;
20         for (i = 1; i < n - 1; ++i) {
21             if (num[i] > num[i - 1] && num[i] > num[i + 1]) {
22                 return i;
23             }
24         }
25     }
26 };

Solution2:

  I came up with the log(n) solution at last. See the code below.

Accepted code:

 1 // 2WA, 1AC, the O(log(n)) solution
 2 class Solution {
 3 public:
 4     int findPeakElement(vector<int> &nums) {
 5         int n = nums.size();
 6         if (n == 1) {
 7             return 0;
 8         }
 9         
10         int ll, rr, mm;
11         
12         ll = 0;
13         rr = n - 1;
14         while (rr - ll >= 2) {
15             mm = (ll + rr) / 2;
16             if (nums[mm] > nums[mm - 1] && nums[mm] > nums[mm + 1]) {
17                 return mm;
18             } else if (nums[mm - 1] < nums[mm]) {
19                 ll = mm;
20             } else {
21                 rr = mm;
22             }
23         }
24         if (nums[0] > nums[1]) {
25             return 0;
26         } else {
27             return n - 1;
28         }
29     }
30 };

 

 posted on 2015-01-23 14:38  zhuli19901106  阅读(250)  评论(0编辑  收藏  举报