반응형
문제
내 답
- 1시간 제한
- 인터넷 사용 안함
Overview
- input : int[] nums, int target
- output : int[]
My code
class Solution {
public int[] twoSum(int[] nums, int target) {
int temp[] = new int[nums.length];
int rtn[] = new int[2];
for (int i = 0; i < nums.length; i++) {
temp[i] = target - nums[i];
for (int j = 0; j < i; j++) {
if (temp[j] == nums[i]) {
rtn[0] = j;
rtn[1] = i;
return rtn;
}
}
}
rtn[0] = 0;
rtn[1] = 0;
return rtn;
}
}
- Time complexity: $O(n^2)$
- Space complexity $O(1)$
최선의 답
인터넷과 책에서 찾아본 답
class Solution {
public int[] twoSum(int[] nums, int target) {
Map<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < nums.length; i++) {
int tempkey = target - nums[i];
if (map.containsKey(tempkey)) {
return new int[] { map.get(tempkey), i };
}
map.put(nums[i], i);
}
throw new IllegalArgumentException("No solution");
}
}
- Time complexity: $O(n)$
- Space complexity $O(n)$
반성 할 점
- Brute Force 방법으로 문제를 풀었다. 이 방법 자체가 틀린것은 아니지만 매우 비효율적인 답이였다. 효율적인 방법을 찾는 연습이 필요함.
필요한 공부
- IllegalArgumentException (exceptions)
- hash
반응형
'old > Algorithm Solving' 카테고리의 다른 글
Wave Array문제의 자바 해결 방법: 효율적인 알고리즘 (0) | 2023.04.24 |
---|---|
Geekina Loves Order 문제의 자바 솔루션 (0) | 2023.04.05 |
Add Strings 문제풀이 (0) | 2021.09.11 |
Remove Duplicates from Sorted Array 문제풀이 (0) | 2021.09.11 |
Count Binary Substrings문제 풀이 (0) | 2021.09.09 |