Skip to content

[SunaDu] Week 1 #628

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

Merged
merged 12 commits into from
Dec 9, 2024
Merged

[SunaDu] Week 1 #628

merged 12 commits into from
Dec 9, 2024

Conversation

dusunax
Copy link
Member

@dusunax dusunax commented Dec 4, 2024

답안 제출 문제

체크 리스트

  • PR을 프로젝트에 추가하고 Week를 현재 주차로 설정해주세요.
  • 바로 앞에 PR을 열어주신 분을 코드 검토자로 지정해주세요.
  • 문제를 모두 푸시면 프로젝트에서 Status를 In Review로 설정해주세요.
  • 코드 검토자 1분 이상으로부터 승인을 받으셨다면 PR을 병합해주세요.

TIL Blog Post

@dusunax dusunax self-assigned this Dec 4, 2024
@dusunax dusunax requested a review from a team as a code owner December 4, 2024 06:31
@github-actions github-actions bot added the py label Dec 4, 2024
@dusunax dusunax changed the title add solution: contains duplicate [SunaDu] Week 1 Dec 4, 2024
Copy link
Contributor

@changchanghwang changchanghwang left a comment

Choose a reason for hiding this comment

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

js가 아니라 python으로 푸시는군요ㅎㅎ


class Solution:
def isPalindrome(self, s: str) -> bool:
if s is " ":
Copy link
Contributor

Choose a reason for hiding this comment

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

python에서 is의 경우 짧은 문자열일 경우에는 같은 객체로 취급하기때문에 equal이지만 긴 문자열일때는 ==를 사용해야 한다고 하네요. 몰랐던 사실이라 공유해봅니다!

Copy link
Member Author

Choose a reason for hiding this comment

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

감사합니다~! 아직 python에 익숙하지 않아서 실수했습니다

Copy link
Contributor

Choose a reason for hiding this comment

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

지금도 사실 짧은 문자열이라 사실 결과값은 같으니까 문제 없는 코드라고 생각됩니다!

Comment on lines 25 to 26
reg = "[^a-z0-9]"
converted_s = re.sub(reg, "", s.lower())
Copy link
Contributor

Choose a reason for hiding this comment

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

regex가 간편해서 저도 사용하긴 했는데 사실 regex보단 내장함수들이 성능이 좋을거라 gpt한테 물어봤더니 이런 코드를 제안해주네요! (코드가 그렇게 가독성이 좋진 않은 것 같아서 좋은진 잘 모르겠습니다... ㅎ..)

class Solution:
    def isPalindrome(self, s: str) -> bool:
        # 문자열을 소문자로 변환하고 알파벳과 숫자만 남김
        converted_s = ''.join(c for c in s.lower() if c.isalnum())
        # 회문 여부 판단
        return converted_s == converted_s[::-1]

Copy link
Member Author

@dusunax dusunax Dec 4, 2024

Choose a reason for hiding this comment

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

코멘트 잘 봤어요!

말씀하신 대로 내장함수 기반 접근이 regex보다 성능상 유리할 것 같습니다😀

그리고 제너레이터 표현식을 사용하는 것도 효율성 면에서 좋은 것 같습니다.
약간의 가독성을 향상을 위해서 s.lower만 분리해서 적용해봤어요

s = s.lower()
converted_s = ''.join(c for c in s if c.isalnum())

Comment on lines +24 to +33
class Solution:
def topKFrequent(self, nums: List[int], k: int) -> List[int]:
frequency_map = Counter(nums) # TC: O(n), SC: O(n)
sorted_frequencies = sorted(frequency_map.items(), key=lambda x: x[1], reverse=True) # TC: O(n log n), SC: O(n)

result = [] # SC: O(k)
for e in sorted_frequencies: # TC: O(k)
result.append(e[0])

return result[0:k]
Copy link
Contributor

@changchanghwang changchanghwang Dec 5, 2024

Choose a reason for hiding this comment

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

저도 이런식으로 풀었는데
기본적으로 보통 언어들에서는 Quick sort를 기반으로한 정렬을 하기 때문에 O(nlogn) 입니다.

Bucket sort를 이용하면 시간적으로 조금 더 효율적으로 풀 수 있을 것 같습니다!

제가 python을 잘 모르겠어서 js로 풀이 공유드립니다!

const input = [1, 1, 1, 2, 2, 3];

function topKFrequent(nums, k) {
  const count = new Map();
  nums.forEach((num) => {
    count.set(num, (count.get(num) || 0) + 1);
  }); // { 1 => 3, 2 => 2, 3 => 1 }

  const frequent = Array.from({ length: nums.length + 1 }, () => []); // [[], [], [], [], ...] 처럼 0부터 nums.length까지 빈 배열을 생성

  for (const [num, freq] of count) {
    frequent[freq].push(num);
  } // [[], [3], [2], [1], ...] 처럼 빈 배열에 빈도수에 해당하는 숫자를 넣음

  const result = [];

  // index가 빈도수, value가 숫자이기 때문에 뒤부터 돌아야 빈도수가 높은 숫자부터 result를 넣을 수 있다.
  for (let i = frequent.length - 1; i >= 0; i--) {
    // 빈도수가 높은 숫자부터 result에 넣음
    for (const num of frequent[i]) {
      result.push(num);
      // k개만큼 result에 넣으면 종료
      if (result.length === k) {
        return result;
      }
    }
  }

  return result;
}
console.log(topKFrequent(input, 2));

가독성은 좀 구리지만... 성능적으로는 아주 큰수로 갈때 이득을 볼 수 있습니다!

Copy link
Member Author

Choose a reason for hiding this comment

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

코멘트 감사합니다!
bucket sort 방식을 추가했어요 👉 3dff920

Copy link
Contributor

Choose a reason for hiding this comment

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

파이썬 라이브러리와 문법은 정말.. 알고리즘 풀기에 행복한 수준이네요 ㅎㅎ

Copy link
Contributor

Choose a reason for hiding this comment

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

ㅎㅎㅎㅎ 공감합니다

@dusunax dusunax merged commit 7165f94 into DaleStudy:main Dec 9, 2024
1 check passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
No open projects
Status: Completed
Development

Successfully merging this pull request may close these issues.

4 participants