Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Leetcode - Easy] Third Maximum Number #12

Merged
merged 1 commit into from
Dec 5, 2024

Conversation

BangDori
Copy link
Contributor

문제

Type Info
Platform Leetcode
Level Easy
Link https://leetcode.com/problems/third-maximum-number/description/

풀이

  • 문제에서 주어진 nums 배열을 set으로 변환한다.
  • set을 다시 배열(uniqueNums)로 변환한다.
  • uniqueNums를 내림차순으로 정렬한다.
  • uniqueNums의 원소의 갯수가 3개 이하라면 첫 번째 인덱스의 값을 반환하고, 그렇지 않다면 세 번째 인덱스의 값을 반환한다.

어려웠던 점

  • 없음.

알게된 점

사실 이 문제를 알고리즘에 작성한 이유가 문제 풀이가 어려워서라기 보다는 알게된 점이 커서 작성하게 되었다.

1. Set 내장 메서드 사용이 기억이 안난다면 Array로 변환하기

const mySet = new Set([1, 1, 2, 2, 3, 3]);

// 방법 1
const myArray = [...mySet];
console.log(myArray); // [1, 2, 3]

// 방법 2
const myArray = Array.from(mySet);
console.log(myArray); // [1, 2, 3]

Set 내장 메서드를 단순히 Array로 변환할 수 있는 이유는 자바스크립트의 Set, Map, 배열, 문자열이 모두 이터러블 객체이기 때문.

2. 자바스크립트의 Set은 순서를 보장한다

const nums = [5,3,6,71,1,78453,32,1,9,23,67,7,94,23,6,1,5,3,2,6,4,7,8,0,658,475,43526423,7452724];

const sortedNums = nums.sort((a, b) => a - b); // 오름차순 정렬
console.log(sortedNums); //  [0, 1, 1, 1, 2, 3, 3, 4, 5, 5, 6, 6, 6, 7, 7, 8, 9, 23, 23, 32, 67, 71, 94, 475, 658, 78453, 7452724, 43526423]

const uniqueNums = [...new Set(sortedNums)]; // 고유한 원소를 가진 sortedNums로 변환
console.log(uniqueNums); // [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 23, 32, 67, 71, 94, 475, 658, 78453, 7452724, 43526423]

@asuan99
Copy link
Contributor

asuan99 commented Nov 29, 2024

LGTM!!👍

@github-actions github-actions bot merged commit f17a05a into main Dec 5, 2024
2 checks passed
@github-actions github-actions bot deleted the bangdori/third-maximum-number branch December 5, 2024 01:40
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants