[LeetCode] 162. Find Peak Element
Problem
A peak element is an element that is strictly greater than its neighbors.
Given a 0-indexed integer array nums
, find a peak element, and return its index. If the array contains multiple peaks, return the index to any of the peaks
.
You may imagine that nums[-1] = nums[n] = -∞
. In other words, an element is always considered to be strictly greater than a neighbor that is outside the array.
You must write an algorithm that runs in O(log n)
time.
Example 1:
Input: nums = [1,2,3,1]
Output: 2
Explanation: 3 is a peak element and your function should return the index number 2.
Example 2:
Input: nums = [1,2,1,3,5,6,4]
Output: 5
Explanation: Your function can return either index number 1 where the peak element is 2, or index number 5 where the peak element is 6.
Constraints:
1 <= nums.length <= 1000
-2^31 <= nums[i] <= 2^31 - 1
nums[i] != nums[i + 1]
for all validi
.
Solution
class Solution {
public int findPeakElement(int[] nums) {
if (nums.length == 1 || nums[1] < nums[0])
return 0;
else if (nums[nums.length - 2] < nums[nums.length - 1])
return nums.length - 1;
for (int i = 1; i < nums.length / 2 + 1; i++) {
if (nums[i - 1] < nums[i] && nums[i + 1] < nums[i])
return i;
else if (nums[nums.length - 2 - i] < nums[nums.length - 1 -i] && nums[nums.length - i] < nums[nums.length - 1 - i])
return nums.length - 1 -i;
}
return 99;
}
}
Explanation
- 배열 속 한 요소와 양 옆의 요소끼리의 비교를 하기 위해 for 반복문을 작성한다.
for (int i = 1; i < nums.length - 1; i++) { if (nums[i - 1] < nums[i] && nums[i + 1] < nums[i]) return i;
- 문제는 다음과 같은 조건을 제시하고 있다.
- 위의 for 반복문은 O(log n)의 시간복잡도를 만족할 수 없으므로, for 반복문의 반복을 줄일 방법이 필요하다.
You must write an algorithm that runs in `O(log n)` time.
- 배열의 두 번째 요소부터의 반복을 배열의 마지막 이전 요소부터의 반복과 함께 진행하면 시간 복잡도를 줄일 수 있다.
- 배열의 마지막 이전 요소부터의 반복을 추가하기 위해 if 조건문을 for 반복문 속에 추가한다.
- for 반복문의 조건식은 배열 속 요소의 개수가 짝수 일 때, 정 가운데 요소까지 진행할 수 있도록 작성한다.
for (int i = 1; i < nums.length / 2 + 1; i++) { if (nums[i - 1] < nums[i] && nums[i + 1] < nums[i]) return i; else if (nums[nums.length - 2 - i] < nums[nums.length - 1 -i] && nums[nums.length - i] < nums[nums.length - 1 - i]) return nums.length - 1 -i;
- 위의 for 반복문을 실행하면 배열의 첫 번째 요소와 마지막 요소가 조건에 만족하는지 확인할 수 없으므로 이를 위한 if 조건문을 작성한다.
if (nums[1] < nums[0]) return 0; else if (nums[nums.length - 2] < nums[nums.length - 1]) return nums.length - 1;
- 배열의 길이가 1일 때는 0을 반환해야 하는데, if 조건문이나 for 반복문이 실행될 수 없으므로 0을 반환하는 if 조건문의 조건식에 배열의 길이가 1인 상황을 추가한다.
for (int i = 1; i < nums.length / 2 + 1; i++) { if (nums[i - 1] < nums[i] && nums[i + 1] < nums[i]) return i; else if (nums[nums.length - 2 - i] < nums[nums.length - 1 -i] && nums[nums.length - i] < nums[nums.length - 1 - i]) return nums.length - 1 -i; }
- 반환문이 필요없을 것 같지만, 반환문이 필요하다는 에러가 나타나서 반환문을 추가하여 임의의 값을 반환하도록 한다.
return 99;
Leave a comment