-
Notifications
You must be signed in to change notification settings - Fork 125
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
[윤태권] Week3 문제 풀이 #395
[윤태권] Week3 문제 풀이 #395
Conversation
map.put(nums[idx], idx); | ||
} | ||
|
||
return new int[]{-1, -1}; |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
저는 js를 사용하여 이와 비슷한 방식으로 풀이를 했는데요,
마지막에 return new int[]{-1, -1}; 의 역할이 궁금합니다!
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
@seona926 안녕하세요! 질문 감사합니다.
우선 결론부터 말씀드리면 해당 코드는 풀이와 관련한 의미를 가지진 않습니다! Java 문법상 어쩔 수 없이 추가한 부분이라고 보시면 좋은데요. 우선 문제 조건에 유일한 정답 케이스
가 있다고 안내가 되어 있었어요. 근데 제가 푼 방향이 루프 속에서 중간에 정답 케이스를 찾으면 early return 하는 방식이었고요.
public int[] twoSum(int[] nums, int target) {
Map<Integer, Integer> map = new HashMap<>();
for (int idx = 0; idx < nums.length; idx++) {
int complement = target - nums[idx];
if (map.containsKey(complement)) {
// 문제 제한 조건 상 중간에 반드시 이 리턴문이 실행돼서, 마지막 리턴문 실행 안됨.
return new int[]{map.get(complement), idx};
}
map.put(nums[idx], idx);
}
// 이 부분은 실행되지 않지만, 문법적으로 반드시 이 메서드는 int[] 를 리턴해야 함
return new int[]{-1, -1};
}
사실 위 코드에서 중간에 early return 이 반드시 되기 때문에 마지막 줄에 있는 return 문이 실행되지는 않습니다. 그런데 만약에 early return 부분만 있다면, 문법상 해당 메서드가 특정 조건에는 int[]
를 반환하지만 반대로 조건에 부합하지 못한 경우에는 결국 메서드에 정의한 리턴 타입인 int[]
를 반환하지 못하기 때문에 마지막 줄과 같이 리턴문을 보충해야 메서드 정의에 맞게 동작하기 때문에 위와 같이 추가한 상황입니다.!
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
고생하셨습니다!
* 시간 복잡도: O(n) | ||
* - n = 5 경우를 가정하고 생각해보기 | ||
* - 3층 계단 -> 2층, 1층 계산 (이 경우는 이미 메모되어 있어서 별도로 계산하진 않음) | ||
* - 4층 계단 -> 3층, 2층 계산 (2층은 메모에 있는 것 활용) | ||
* - 5층 계단 -> 4층, 3층 계산 (3층은 메모에 있는 것 활용) | ||
* - ... | ||
* - 각 단계 별로 (메모를 활용해) 아직 계산되지 않은 것을 한 번씩 호출하게 되므로 O(n) | ||
* - 근데 만약 메모를 사용하지 않으면? (중복 호출이 많이 일어남 ... O(n^2)) |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
풀이를 따라갈 수 있어 이해하기 좋았습니다! 고생하셨습니다!
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
풀이와 설명이 깔끔해서 좋았습니다!
@taekwon-dev 다음 PR부터 프로젝트 주차 설정이 누락되지 않도록 부탁드리겠습니다! |
답안 제출 문제
체크 리스트
In Review
로 설정해주세요.