Skip to content
Merged
Show file tree
Hide file tree
Changes from 9 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
37 changes: 37 additions & 0 deletions contains-duplicate/YeomChaeeun.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
function containsDuplicate(nums: number[]): boolean {

// 접근 (1) - 시간 복잡도가 매우 커서 실패
// const uniqueArr = nums.filter((item, index) => { return nums.indexOf(item) === index })
// console.log(uniqueArr)
//
// return nums.length !== uniqueArr.length;

// 접근 (2) - 양 옆의 값을 비교 =============
// if(nums.length === 1)
// return false;
//
// // 정렬
// nums.sort()
//
// // 양 옆의 값을 비교
// for(let i = 0; i < nums.length; i++){
// console.log(nums[i], nums[i+1])
// if(nums[i] === nums[i+1]){
// return true;
// }
// }
// return false;

// 접근 (3) - obj를 이용 ================
let obj={}

for(let i = 0; i < nums.length; i++) {
console.log('nums >>', nums[i], 'obj >>', obj)
Copy link
Contributor

@HC-kang HC-kang Dec 14, 2024

Choose a reason for hiding this comment

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

제출시에는 지워주시는 편이 좋을 것 같아요~🧹
아마 다른 부분은 해주신걸로 보아 이부분만 놓치신것 같네요!

Copy link
Contributor Author

Choose a reason for hiding this comment

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

앗 수정하겠습니다! 감사합니다!

if(obj[nums[i]]) {
return true;
}
obj[nums[i]] = 1;
}
return false;

};
43 changes: 43 additions & 0 deletions house-robber/YeomChaeeun.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
/**
* 하나 이상 건너 뛴 값을 더한 것중 가장 높은 값의 합을 구하기
* @param nums
*/
function rob(nums: number[]): number {

if(nums.length === 1) return nums[0];

// 0 + 2 ...
// 1 + 3 ...
// Max(인덱스 0부터 더한 것, 인덱스 1부터 더한 것)

// 접근 (1) - 양 옆의 값을 제외하고 홀수/짝수 인덱스 값들을 더했음
// [2, 1, 1, 2] 일 때, 답이 4가 나와야 함
// let max = 0
// let odd = 0
// let even = 0
// for(let i = 0; i < nums.length; i++) {
// if(i % 2 == 0) {
// console.log(nums[i], 'even >>>', even);
// even += nums[i];
// } else {
// console.log(nums[i], 'odd >>>', odd);
// odd += nums[i];
// }
// }
// console.log(even, '===', odd);
// max = Math.max(even, odd);

// 접근 (2) - max 값을 저장해두고 Math.max(하나 이상 건너뛴 값 + 현재 값 더한 것, max) 를 구함
let prev = 0
let max = 0
let temp = 0
for(let i = 0; i < nums.length; i++) {
temp = max
max = Math.max(prev + nums[i], max) // 이전의 값과 하나 이상 건너뛰고 더한 값 중 최대 값을 구함
prev = temp

// console.log(temp, " - ", max, " - ", prev)
};
// console.log(max);
return max;
};
50 changes: 50 additions & 0 deletions longest-consecutive-sequence/YeomChaeeun.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
/**
* 가장 긴 연속의 시퀀스 구하기
* @param nums
*/
function longestConsecutive(nums: number[]): number {

// length 가 0, 1 인 경우
if(nums.length < 2)
return nums.length; // 0, 1

// 정렬
nums = nums.sort((a, b) => a - b)

// 접근 (1) 처음 연속된 count만 리턴함 =============
// let count = 1
// for(let i = 0; i < nums.length-1; i++) {
// if(nums[i] === nums[i+1]) {
// continue;
// } else if(nums[i] - nums[i+1] === 1) {
// count++;
// } else {
// break;
// }
// };
// console.log(count);
// return count;

// =========

let longest = 0;
let temp = 1;
Copy link
Contributor

Choose a reason for hiding this comment

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

중요하진 않은 내용이지만, 변수명에 의미를 담아주시면 가독성에 도움이 될 것 같아요.
여기서는 현재까지 연속된 수를 의미하니까, currentSequence 혹은 longest 와 맞추어 current 등은 어떨까요?


for(let i = 0; i < nums.length-1; i++) {
if(nums[i] === nums[i + 1]) {
// console.log(nums[i], '===', nums[i+1])
continue;
} else if(nums[i] + 1 === nums[i + 1] ) {
// console.log(nums[i], '+ 1 =', nums[i+1])
temp += 1;
} else {
// console.log(longest, ' - ', temp)
longest = Math.max(temp, longest);
temp = 1;
}
}

// i가 마지막인 경우 for문의 else문을 타지 않으므로 다시 한번 체크함
Copy link
Contributor

Choose a reason for hiding this comment

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

for (let i = 1; i < nums.length; i++) {
        if (nums[i] === nums[i - 1]) {
            continue;
...

위와 같은 형태로 +1이 아니라 -1로 접근한다면 아래의 추가적인 확인 로직이 필요없지 않을까요?

longest = Math.max(temp, longest);
return longest;
};
29 changes: 29 additions & 0 deletions top-k-frequent-elements/YeomChaeeun.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
/**
*
* @param nums
* @param k
*/
function topKFrequent(nums: number[], k: number): number[] {
let obj = {}

for(const num of nums) {
if(!obj[num])
obj[num] = 0
++obj[num]
}

// 배열로 변경
let entries = Object.entries(obj)
// 정렬
let sort_arr = entries.sort((a, b) => Number(b[1]) - Number(a[1]));

let result = [];
let l = 0;
for(const item of sort_arr) {
if(l == k) break;
result.push(Number(item[0]));
l++;
}

return result;
Copy link
Contributor

Choose a reason for hiding this comment

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

불필요한 순회를 막기 위해 l을 사용하신것 같아, 최적화도 고려하신것 같아 좋네요!
이 부분은 취향의 문제이지만 아래와 같은 함수형 풀이는 어떻게 생각하시나요?

return Object.entries(frequencyMap)
        .sort((a, b) => b[1] - a[1])
        .slice(0, k)
        .map(entry => Number(entry[0]));

Copy link
Contributor Author

Choose a reason for hiding this comment

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

함수형 풀이로 소스를 더 간략하게 작성할 수 있겠네요!
좋은 의견 감사합니다! ☺️

};
17 changes: 17 additions & 0 deletions valid-palindrome/YeomChaeeun.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
/**
* palindrom: 회문, 거꾸로 읽어도 제대로 읽는 것과 같은 문장
* @param s
*/
function isPalindrome(s: string): boolean {
let word = s.toLowerCase();
const reg = /[\{\}\[\]\/?.,;:|\)*~`!^\-_+<>@\#$%&\\\=\(\'\" ]/g;
Copy link
Contributor

Choose a reason for hiding this comment

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

음.. 모든 아스키 코드를 고려하신 것 같은데요,
문제의 본문에서 ...removing all non-alphanumeric characters...라는 부분이 있습니다.
따라서 위 조건과 6 line을 통해, 아래와 같이 간소화 하실 수 있지 않을까요?

const reg = /[^a-z0-9]/g;

Copy link
Contributor Author

Choose a reason for hiding this comment

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

모든 특수문자를 지워야한다고 생각했던거 같습니다 😅
꼼꼼히 봐주셔서 감사합니다. 간소화 해보겠습니다 ^^


word = word.replace(reg, '');
for(let i = 0; i < word.length; i++) {
for(let j = word.length-i-1; j >= word.length-i-1; j--) {
Copy link
Contributor

Choose a reason for hiding this comment

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

이 루프는 사실상 한번밖에 돌지 않는것같은데, 혹시 이렇게 작성하신 이유가 있을까요?

// console.log(word[i], '===', word[j])
if(word[i] !== word[j]) return false;
}
}
return true;
};
Loading