Skip to content

Commit 9dced72

Browse files
committed
two sum
1 parent a7072f6 commit 9dced72

File tree

1 file changed

+24
-0
lines changed

1 file changed

+24
-0
lines changed

two-sum/se6816.java

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
/**
2+
Problem 1 : Two Sum
3+
Summary :
4+
- for문으로 순회하면서, target에서 뺀 값을 저장한다.
5+
- 저장된 값과 일치하는 인덱스를 만나면 해당 값을 리턴한다.
6+
- 기본 For문이 O(N^2)이라면, 해당 방법의 경우 O(N)이 가능하다.
7+
8+
*/
9+
10+
class Solution {
11+
12+
public int[] twoSum(int[] nums, int target) {
13+
Map<Integer, Integer> indexMap = new HashMap<>();
14+
int[] result = null;
15+
for(int idx=0; idx<nums.length; idx++) {
16+
if(indexMap.containsKey(nums[idx])) {
17+
result = new int[]{ indexMap.get(nums[idx]), idx };
18+
break;
19+
}
20+
indexMap.put(target-nums[idx], idx);
21+
}
22+
return result;
23+
}
24+
}

0 commit comments

Comments
 (0)