LeetCode - Algorithms - 162. Find Peak Element

Problem

162. Find Peak Element

Java

eager approach - O(n)

1
2
3
4
5
6
7
8
9
10
11
class Solution {
public int findPeakElement(int[] nums) {
final int len = nums.length;
for (int i = 1; i < len - 1; i++) {
if (nums[i] > nums[i - 1] && nums[i] > nums[i + 1]) {
return i;
}
}
return nums[0] < nums[len - 1] ? len - 1 : 0;
}
}

Submission Detail

  • 63 / 63 test cases passed.
  • Runtime: 0 ms, faster than 100.00% of Java online submissions for Find Peak Element.
  • Memory Usage: 41.3 MB, less than 66.17% of Java online submissions for Find Peak Element.

JavaScript

eager approach

1
2
3
4
5
6
7
8
9
10
11
12
13
/**
* @param {number[]} nums
* @return {number}
*/
var findPeakElement = function(nums) {
const len = nums.length;
for (let i = 1; i < len - 1; i++) {
if (nums[i] > nums[i - 1] && nums[i] > nums[i + 1]) {
return i;
}
}
return nums[0] < nums[len - 1] ? len - 1 : 0;
};

Submission Detail

  • 63 / 63 test cases passed.
  • Runtime: 123 ms, faster than 5.43% of JavaScript online submissions for Find Peak Element.
  • Memory Usage: 42 MB, less than 73.96% of JavaScript online submissions for Find Peak Element.