Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
43 changes: 43 additions & 0 deletions raejun/LongestCommonPrefix.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
/**
* @param {string[]} strs
* @return {string}
*/
var longestCommonPrefix = function (strs) {
const checkChar = (strs, c, index) => {
Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

조건 검사를 분리 작성해서 가독성이 좋네요

return strs.every((str) => str[index] === c);
Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

공통 접두사 여부도 every로 표현해서 의도가 잘 드러난 것 같아요! 👍

};

if (strs.length === 1) {
return strs[0];
}

let answer = "";

for (let i = 0; i < strs[0].length; i++) {
const char = strs[0][i];

if (checkChar(strs, char, i)) {
answer += char;
} else {
break;
Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

break말고 바로 answer를 반환해줘도 좋을 것 같아요.
checkChar로 따로 빼니 조건문 확인을 따로 안해도 되서 좋았어요!

}
}

return answer;
};

/*
14분 걸림.

시간 복잡도는 O(N x M) N은 문자열의 개수, M은 공통 접두사를 확인하기 위해 보는 문자 수이다.
공간 복잡도는 O(1)이다. answer 문자열의 길이는 공통 접두사의 길이까지 될 수 있기 때문이다.

strs 배열의 첫 번째 문자열을 기준으로 공통 접두사를 확인하는 방식으로 풀이했다.
checkChar 함수를 만들어서, strs 배열의 모든 문자열이 index 위치에서 char와 같은지 확인하는 방식으로 풀이했다.
strs 배열의 첫 번째 문자열을 순회하면서, checkChar 함수를 이용해서 공통 접두사를 확인했다.
공통 접두사가 맞으면 answer에 char를 더해주고, 공통 접두사가 아니면 반복문을 종료했다.


복쟙하게 생각하지 않고 주어진 조건에 대해 풀이했다.
strs 배열의 첫 번째 문자열을 기준으로 공통 접두사를 확인하는 방식이 가장 직관적인 풀이인 것 같다.
*/
32 changes: 32 additions & 0 deletions raejun/SingleNumber.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
/**
* @param {number[]} nums
* @return {number}
*/
var singleNumber = function (nums) {
if (nums.length === 1) return nums[0];

const map = new Map();

nums.forEach((num) => {
map.set(num, map.has(num) ? map.get(num) + 1 : 1);
});

for (const [k, v] of map) {
if (v === 1) {
return k;
}
}
};

/*
8분 걸림.

시간 복잡도는 O(n)이다. n은 입력 배열의 길이이다.
공간 복잡도는 O(n)이다. Map 자료구조에 최대 n개의 요소가 저장될 수 있기 때문이다.

Map 자료구조를 이용하여 풀이했다.
배열을 순회하면서, Map에 요소가 있는지 확인하고, 있으면 요소의 값을 1 증가시키고, 없으면 요소를 추가하고 값을 1로 설정했다.
Map을 순회하면서, 값이 1인 요소의 키를 반환했다.

Map을 이용해서 풀이를 했지만, 뭔가 for문을 한 번만 돌리는 풀이가 있을 것 같은 느낌이 들었다.
*/
Loading