Skip to content

[JustHm] Week 01 Solutions #1133

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 8 commits into from
Apr 3, 2025
Merged

[JustHm] Week 01 Solutions #1133

merged 8 commits into from
Apr 3, 2025

Conversation

JustHm
Copy link
Contributor

@JustHm JustHm commented Mar 30, 2025

답안 제출 문제

작성자 체크 리스트

  • 우측 메뉴에서 PR을 Projects에 추가해주세요.
  • Projects의 오른쪽 버튼(▼)을 눌러 확장한 뒤, Week를 현재 주차로 설정해주세요.
  • 문제를 모두 푸시면 프로젝트에서 StatusIn Review로 설정해주세요.
  • 코드 검토자 1분 이상으로부터 승인을 받으셨다면 PR을 병합해주세요.

검토자 체크 리스트

Important

본인 답안 제출 뿐만 아니라 다른 분 PR 하나 이상을 반드시 검토를 해주셔야 합니다!

  • 바로 이전에 올라온 PR에 본인을 코드 리뷰어로 추가해주세요.
  • 본인이 검토해야하는 PR의 답안 코드에 피드백을 주세요.
  • 토요일 전까지 PR을 병합할 수 있도록 승인해주세요.

@JustHm JustHm requested a review from a team March 30, 2025 12:35
@seungriyou seungriyou self-requested a review March 30, 2025 13:35
@JustHm JustHm moved this from Solving to In Review in 리트코드 스터디 4기 Apr 1, 2025
Copy link
Contributor

@seungriyou seungriyou left a comment

Choose a reason for hiding this comment

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

고생하셨습니다~! 🍀


// var dp = [nums[0], max(nums[0], nums[1])]
var twoStepPrev = nums[0]
var oneStepPrev = max(nums[0], nums[1])
Copy link
Contributor

Choose a reason for hiding this comment

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

DP 문제를 O(n) space로 푸신 다음 O(1) space로 최적화하셨군요! 사용하신 변수명이 직관적이어서 코드 이해가 잘 되는 것 같습니다 😄

Copy link
Contributor Author

Choose a reason for hiding this comment

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

정말 꼼꼼히 리뷰해주셔서 감사합니다!
DP 풀이는 피보나치만 해봐서 그런지 너무 생소해서 기초부터 열심히 공부해봐야겠습니다.. 초보풀이지만 좋은점 짚어주셔서 감사합니다!

// var dp = [nums[0], max(nums[0], nums[1])]
var twoStepPrev = nums[0]
var oneStepPrev = max(nums[0], nums[1])
for i in 2..<nums.count {
Copy link
Contributor

Choose a reason for hiding this comment

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

저는 경계값에서 조건을 빠짐없이 판단하거나 배열의 인덱스를 정확하게 다루는 데에 서툴러서 twoStepPrevoneStepPrev를 모두 0으로 초기화해서 풀었습니다. JustHm님처럼 꼼꼼히 케이스를 따져보면서도 풀어봐야겠다는 생각이 드네요!

Copy link
Contributor

Choose a reason for hiding this comment

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

저도 해당 문제를 O(n)으로 푸는 게 어려워서 디스커션과 솔루션을 참고했습니다... 제가 풀 때 도움이 됐던 아이디어를 공유드릴게요! 혹시 참고하시고 싶으시다면 다음 토글을 열어주시면 됩니다 😀

O(n) 풀이 관련 아이디어
  1. 어떤 값 mconsecutive한 값m - 1m + 1이다.
  2. 길이 n 짜리 시퀀스를 순회하면서 consecutive한 값(m - 1, m + 1)이 존재하는지 O(1)에 알 수 있다면, O(1) * n = O(n)에 문제를 해결할 수 있다.
  3. 시퀀스에서 어떤 값을 O(1)에 찾기 위해서는 hash map을 이용할 수 있다.

그리고 저는 문제 요구사항대로 O(n)으로만 풀어야겠다는 것에만 매몰되는 바람에 다른 자료를 참고했는데요, JustHm님처럼 먼저 떠오른 아이디어부터 차근차근 코드로 구현하고 개선해봐야겠습니다!

Copy link
Contributor Author

Choose a reason for hiding this comment

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

저 역시도 O(n)에 집중했다가 결국 실패했어서 가장 원시적인 방법으로 해결하고 복잡도를 줄이는 방식을 사용했는데요..
찾아봐도 O(n) 풀이가 안보여서 포기했었는데 이런 아이디어가 있었군요!! 제가 시간복잡도를 이해 못해서 HashMap을 고려하다가 아닌거 같아서 뒷걸음쳤었는데,,, seungriyou님이 공유해주신 아이디어를 보니 이번주에 다시 한 번 도전해 볼 수 있을거 같네요 ㅎㅎ 감사합니다!!

Copy link
Contributor Author

Choose a reason for hiding this comment

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

제공해주신 아이디어로 Set만 사용해서 O(n) 풀이를 만들어봤는데,, 실제 실행시간은 Sort 해서 해버린게 더 빠르더라구요..
일단 Leetcode에서 분석해준 시간복잡도는 O(n)이 나오긴 했습니다!

Set.contains 메서드를 이용했는데요 O(n)일 줄 알았지만 실제로는 Set이 Hashtable 기반으로 구현되어 있어서 O(1)로 검색이 가능하더라구요!
이걸 몰랐어서 아 안되겠네 했는데 더 간단히 풀이를 할 수 있었습니다!

하지만 실제 실행시간이 더 걸린 이유에 대해서는 확신은 없지만,, contains 할때 들어가는 num을 해시로 변경 -> 버킷 확인 -> 충돌 검사 를 거쳐서 확인하기 때문에 실제실행시간이 조금 더 걸린거 같다.. 라는 생각이 드네요

Copy link
Contributor

Choose a reason for hiding this comment

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

swift 문법은 정말 멋있네요! 🤩

그리고 저 또한 정렬을 이용한 풀이를 먼저 생각했었는데요, follow up에서 O(nlogn) time 보다 개선하라는 조건이 있어서 다시 풀어본 케이스입니다. 저는 heap(우선순위 큐)에서 k번 pop 하는 방법을 통해 O(n + klogn) time으로 줄였으나, 다른 접근법도 여러 가지 있는 것 같더라구요! 혹시나 여유가 되신다면 O(nlogn) 보다 최적화된 접근법을 추가로 떠올려보시는 것도 좋을 것 같습니다~!

Copy link
Contributor Author

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.

heap으로 푸는방식도 생각해보려했지만 Swift에서는 heap이 기본 라이브러리에 없는 관계로.. (다른 라이브러리를 붙여야합니다 ㅠㅠ)

bucket sort라는걸 사용해봤는데요, 결과적으로 time O(n), space O(n)으로 더 줄일 수 있었습니다!

물론 제대로 보자면 공간복잡도가 조금 더 늘어나긴 했지만, 시간복잡도 최적화는 확실히 챙기게되었네요! 다시 한 번 공부하고 새로운걸 알게되어서 기쁘네요 감사합니다!

Copy link
Contributor

Choose a reason for hiding this comment

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

swift는 heap을 기본으로 제공해주지 않는군요..! bucket sort는 나중에 봐야겠다고 미루고 있었는데 저도 찾아봐야겠네요! 알려주셔서 감사합니다 😆 그리고 첫 번째 주 고생 많으셨습니다!!

@JustHm JustHm merged commit 0c50ee3 into DaleStudy:main Apr 3, 2025
1 check passed
@github-project-automation github-project-automation bot moved this from In Review to Completed in 리트코드 스터디 4기 Apr 3, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
Status: Completed
Development

Successfully merging this pull request may close these issues.

2 participants