Skip to content

[JooKangsan] 2025.02.13#42

Merged
JooKangsan merged 25 commits intomainfrom
JooKangsan
Feb 20, 2025
Merged

[JooKangsan] 2025.02.13#42
JooKangsan merged 25 commits intomainfrom
JooKangsan

Conversation

@JooKangsan
Copy link
Collaborator

집합

md 파일로 추가했습니다!

📌 푼 문제

문제이름 문제링크
중복된 문자 제거 https://school.programmers.co.kr/learn/courses/30/lessons/120888
한 번만 등장한 문자 https://school.programmers.co.kr/learn/courses/30/lessons/120896
무작위로 K개의 수 뽑기 https://school.programmers.co.kr/learn/courses/30/lessons/181858
Contains Duplicate https://leetcode.com/problems/contains-duplicate
소인수분해 https://school.programmers.co.kr/learn/courses/30/lessons/120852
Longest Consecutive Sequence https://leetcode.com/problems/longest-consecutive-sequence
Repeated DNA Sequences https://leetcode.com/problems/repeated-dna-sequences


📝 간단한 풀이 과정

중복된 문자 제거

  • 중복된 요소는 삭제되는 Set 으로 풀었습니다.
function solution(my_string) {
  var answer = [...new Set(my_string)].join('');
  return answer;
}

한 번만 등장한 문자

  • filter를 통해서 앞뒤 요소를 확인하고 앞요소와 뒷요소랑 같지 않은 것들만 남겼습니다.
function solution(s) {
  return s
      .split('')
      .sort()
      .filter((char, idx, arr) => 
          char !== arr[idx-1] && char !== arr[idx+1]
      )
      .join('');
}

무작위로 K개의 수 뽑기

  • 중복된 요소들을 Set으로 지우고 k보다 적을 경우 -1로 채워넣었습니다.
function solution(arr, k) {
  var answer = [...new Set(arr)];
    return [...answer.slice(0, k), ...Array(Math.max(0, k - answer.length)).fill(-1)];
}

Contains Duplicate

  • Set을 통해 반복 요소를 지우것과 지우지 않은것을 비교했습니다.
var containsDuplicate = function (nums) {
  const uniqueNums = [...new Set(nums)];
  return uniqueNums.length != nums.length;
};

소인수분해

  • Set을 사용하여 중복된 소인수를 제거후, 2로 나눌 수 있을 때까지 나눈 후, 홀수로 나누면서 소인수를 탐색했습니다.
  • 마지막으로 남은 수가 2보다 크면 소인수이므로 추가하여 오름차순으로 정렬하여 반환했습니다.
function solution(n) {
  let primeFactors = new Set();
  let num = n;

  while(num % 2 === 0) {
      primeFactors.add(2);
      num = num / 2;
  }
     for(let i = 3; i <= num; i += 2) {
      while(num % i === 0) {
          primeFactors.add(i);
          num = num / i;
      }
  }
  if(num > 2) {
      primeFactors.add(num);
  }

  return [...primeFactors].sort((a, b) => a - b);
}

Longest Consecutive Sequence

  • Set에서 각 숫자의 이전 숫자(num-1)가 없는 경우만 검사해서 시작점을 찾고, while문으로 연속된 숫자가 있는지 확인하면서 길이를 계산합니다
var longestConsecutive = function (nums) {
  const numSet = new Set(nums);
  let longestStreak = 0;
  for (const num of numSet) {
    if (!numSet.has(num - 1)) {
      let currentNum = num;
      let currentStreak = 1;
      while (numSet.has(currentNum + 1)) {
        currentNum += 1;
        currentStreak += 1;
      }
      longestStreak = Math.max(longestStreak, currentStreak);
    }
  }
  return longestStreak;
};

Repeated DNA Sequences

  • Set을 두 개 사용하여 처음보는것과 두번째 보는 걸로 나누고, 10개씩 탐색하여 한번이상 나왔다면 두번재 이상 보는데에 추가했습니다.
function findRepeatedDnaSequences(s) {
  const see = new Set();
  const seen = new Set();

  for (let i = 0; i <= s.length - 10; i++) {
    const sequence = s.slice(i, i + 10);
    if (see.has(sequence)) {
      seen.add(sequence);
    }
    see.add(sequence);
  }

  return [...seen];
}

@JooKangsan JooKangsan self-assigned this Feb 13, 2025
Copy link
Collaborator

@bona1122 bona1122 left a comment

Choose a reason for hiding this comment

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

전체적으로 set을 잘 활용하신 것 같습니다. 많이 배우고 갑니다! 한주동안 수고하셨습니다!

Comment on lines +1 to +20
function solution(n) {
let primeFactors = new Set();
let num = n;

while(num % 2 === 0) {
primeFactors.add(2);
num = num / 2;
}
for(let i = 3; i <= num; i += 2) {
while(num % i === 0) {
primeFactors.add(i);
num = num / i;
}
}
if(num > 2) {
primeFactors.add(num);
}

return [...primeFactors].sort((a, b) => a - b);
} No newline at end of file
Copy link
Collaborator

Choose a reason for hiding this comment

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

코드 잘 보았습니다!
현재 i<=num까지 반복하는 방식보다, 모든 합성수 n은 적어도 하나의 소인수를 가지며, 그 소인수는 √n 이하특성을 이용해서 √n까지만 검사하면 더 효율적입니다!
그리고 2를 특별히 처리한 후 홀수만 검사하는 아이디어는 좋지만, 하나의 루프로 통합하면 간결하게 표현할 수 있을 것 같습니다.

function solution(n) {
  const factors = new Set()
  for (let i = 2; i * i <= n; i++) { 
    while (n % i === 0) { // 동일한 소인수로 여러번 나누기 가능
      factors.add(i)
      n /= i
    }
  }
  // 마지막으로 남은 수가 1보다 크면 그 자체가 소수이므로 추가
  if (n > 1) factors.add(n)
  return Array.from(factors)
}

이 방식으로 하면 sort도 필요없어집니다!

@JooKangsan JooKangsan merged commit b9cb8c3 into main Feb 20, 2025
3 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants