Grind75{: target="_blank"}
문제로{: target="_blank"}
0초로 푼 이들의 답이 궁금하다
풀이1#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
| class Solution {
public int[] twoSum(int[] nums, int target) {
if(nums == null || nums.length == 0) return null;
for(int i = 0; i < nums.length -1; i++) {
for(int j = i+1; j < nums.length; j++) {
if(nums[i] + nums[j] == target){
int[] arr = {i, j};
return arr;
}
}
}
return null;
}
}
|

풀이2#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
| class Solution {
public int[] twoSum(int[] nums, int target) {
Map<Integer, Integer> numMap = new HashMap<>();
for(int i = 0; i < nums.length; i++) {
numMap.put(nums[i], i); // key: 값, value: 인덱스
}
for(int i = 0; i < nums.length; i++) {
int complement = target - nums[i];
if(numMap.containsKey(complement) && numMap.get(complement) != i) {
return new int[] {i, numMap.get(complement)};
}
}
return new int[] {};
}
}
|

풀이3#
1
2
3
4
5
6
7
8
9
10
11
12
13
| class Solution {
public int[] twoSum(int[] nums, int target) {
Map<Integer, Integer> numMap = new HashMap<>();
for(int i = 0; i < nums.length; i++) {
int complement = target - nums[i];
if(numMap.containsKey(complement)) return new int[] {numMap.get(complement), i};
else numMap.put(nums[i], i);
}
return new int[]{};
}
}
|
