반응형
같은수를 두번 사용하지 않고
입력받은 int형 배열에서 두개의 합이 target과 같은 배열의 인덱스를 찾는 알고리즘 문제이다.
ex)
Given nums = [2, 7, 11, 15], target = 9, Because nums[0] + nums[1] = 2 + 7 = 9, return [0, 1].
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
|
class Solution {
public int[] twoSum(int[] nums, int target) {
int[] result = new int[2];
for(int i = 0; i < nums.length; i++){
for(int j = 0; j < nums.length; j++){
if(nums[i] + nums[j] == target && i != j){
result[0] = j;
result[1] = i;
}
}
}
return result;
}
public int[] twoSum1(int[] nums, int target) {
Map<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < nums.length; i++) {
map.put(nums[i], i);
}
for (int i = 0; i < nums.length; i++) {
int complement = target - nums[i];
if (map.containsKey(complement) && map.get(complement) != i) {
return new int[] { i, map.get(complement) };
}
}
throw new IllegalArgumentException("No two sum solution");
}
public int[] twoSum2(int[] nums, int target) {
Map<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < nums.length; i++) {
int complement = target - nums[i];
if (map.containsKey(complement)) {
return new int[] { map.get(complement), i };
}
map.put(nums[i], i);
}
throw new IllegalArgumentException("No two sum solution");
}
}
|
cs |
twoSum(int[] nums, int target)
- 반복문을 두번 중첩해서 하나하나 모두 확인하는 알고리즘이다.
- BigO 표현법에 의해 배열의 길이 만큼 반복문을 두번 실행하기 때문에 n^2이 된다.
twoSum1(int[] nums, int target)
- Hashmap에 key와 value로 int[]배열값을 하나씩 put한다.
- map.containsKey(complement) 값을 이용하여 원하는 값이 있는지 확인한다.
- value값이 i와 같지 않도록 하여 두수를 중복해서 사용하는 것을 방지한다.
twoSum2(int[] nums, int target)
- Hashmap을 선언해 두고 원하는 값이 존재하지 않으면 현재 순서의 nums[i]를 put한다.(초기 Hashmap은 비어있다.)
- 두번째 부터는 Hashmap에 값이 존재하기 때문에 Hashmap에 존재하는 값과 현재nums[i] 값을 계산하여 판단한다.(EX: complement = target - nums[2] , map에 complement key를 가지고 있는지 비교)
- nums[i]의 값과 Hashmap 내부의 값은 서로 중복되지 않으므로 같은 두개의 값을 사용하지 않는다.
반응형
'알고리즘 > 코드 연습' 카테고리의 다른 글
[백준 - 1924] 2007년 (0) | 2020.07.29 |
---|---|
[백준 - 2798] 블랙잭 (0) | 2020.07.24 |
[LeetCode] Roman to Integer (0) | 2020.07.21 |
[LeetCode] Palindrome Number (0) | 2020.07.20 |
[LeetCode] Reverse Integer (0) | 2020.07.20 |