Conversation
raejun92
approved these changes
Mar 30, 2026
|
|
||
| for (let j = 1; j < strs.length; j++) { | ||
| if (strs[j][i] !== char) { | ||
| return strs[0].slice(0, i); |
doitchuu
approved these changes
Apr 1, 2026
|
|
||
| for (let j = 1; j < strs.length; j++) { | ||
| if (strs[j][i] !== char) { | ||
| return strs[0].slice(0, i); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
이렇게 풀었어요
1. Single Number
1) 복잡도 계산
시간 복잡도: O(n)
공간 복잡도: O(n)
2) 접근 아이디어
이 문제는 배열에서 하나의 숫자만 한 번 등장하고, 나머지 숫자들은 모두 두 번 등장하는 상황에서 한 번만 등장하는 숫자를 찾는 문제이다. 처음에는 배열을 정렬해서 인접한 값을 비교하는 방법도 떠올릴 수 있었지만, 가장 직관적인 방법은 각 숫자의 등장 횟수를 세는 것이라고 생각했다.
그래서 Map을 사용해 숫자별 등장 횟수를 저장했다. 먼저 배열을 순회하면서 각 숫자가 몇 번 나왔는지 카운트하고, 그 다음 Map을 다시 순회하면서 값이 1인 숫자를 찾아 반환하도록 구현했다. 문제 조건상 한 번만 등장하는 숫자는 반드시 하나 존재하므로, count === 1인 값을 찾으면 바로 반환하면 된다.
3) 회고
이후에는 XOR 연산으로도 더 효율적으로 풀 수 있다는 점을 알게 되었다.
XOR의 성질:
a ^ a = 0
a ^ 0 = a
그래서 같은 숫자끼리는 다 지워지고, 마지막에 한 번만 나온 숫자만 남게 된다.
2. Longest Common Prefix
1) 복잡도 계산
시간 복잡도: O(n * m)
공간 복잡도: O(1)
2) 접근 아이디어
이 문제는 문자열 배열에서 모든 문자열이 공통으로 가지는 가장 긴 접두사를 찾는 문제이다. 처음에는 문자열들을 정렬하거나 모든 문자열을 하나씩 잘라가며 비교하는 방법도 생각할 수 있었지만, 가장 직관적인 방법은 첫 번째 문자열을 기준으로 각 위치의 문자를 비교하는 것이라고 생각했다.
그래서 첫 번째 문자열의 각 문자를 앞에서부터 순회하면서, 같은 위치의 문자가 나머지 문자열에서도 모두 동일한지 확인하도록 구현했다. 만약 하나라도 다른 문자가 나오면, 그 직전까지가 공통 접두사이므로 strs[0].slice(0, i)를 반환했다. 끝까지 모두 같다면 첫 번째 문자열 전체가 공통 접두사가 되므로 그대로 반환하도록 했다.
3) 회고
이 문제는 문자열 비교 문제이지만, 결국 첫 번째 문자열을 기준으로 한 글자씩 확인하면 된다는 점을 알게 되니 훨씬 단순하게 느껴졌다. 공통 접두사를 찾는 문제에서는 특정 문자열을 기준으로 잡고 다른 문자열들과 비교하는 방식이 직관적이고 구현도 깔끔하다는 점을 배울 수 있었다.