반응형
1. 문제

- 정수 배열 nums가 주어질 때, 고유한 값 중 3번 째로 큰 요소를 반환하라.
2. 해결
function thirdMax(nums: number[]): number {
let firstMax = -Infinity, secondMax = -Infinity, thirdMax = -Infinity;
new Set(nums).forEach(num => {
if (num > firstMax) {
thirdMax = secondMax;
secondMax = firstMax;
firstMax = num;
} else if (num > secondMax) {
thirdMax = secondMax;
secondMax = num;
} else if (num > thirdMax) {
thirdMax = num;
}
});
console.log(firstMax, secondMax, thirdMax);
return thirdMax === -Infinity ? firstMax : thirdMax;
}
- 처음 풀 때 사용한 방법. 초기화를 -Infinity로 안하면 테스트 케이스 중에 통과못하는 경우가 있다.
function thirdMax(nums: number[]): number {
const set = new Set(nums);
const first = Math.max(...set);
if(set.size < 3) return first;
set.delete(first);
set.delete(Math.max(...set));
return Math.max(...set);
}
- Set을 이용해 중복을 제거하면서 찾는 방법. 더 깔끔한 것 같다.