728x90
[leetcode] 1. Two Sum
[문제]
Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target.
You may assume that each input would have exactly one solution, and you may not use the same element twice.
You can return the answer in any order.
[입출력]
Input: nums = [2,7,11,15], target = 9
Output: [0,1]
[코드]
1. 이중 for문 돌리기
class Solution {
public int[] twoSum(int[] nums, int target) {
int len = nums.length;
int idx1 = -1;
int idx2 = -1;
for (int i = 0; i < len - 1; i++) {
for (int j = i+1; j < len; j++) {
if(target == nums[i]+nums[j]) {
idx1 = i;
idx2 = j;
}
}
}
int[] arr = {idx1,idx2};
return arr;
}
}
2. HashMap에 차 저장하여 알맞은 차 채우기
class Solution {
public int[] twoSum(int[] nums, int target) {
int len = nums.length;
int idx1 = -1;
int idx2 = -1;
Map<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < nums.length; i++) {
if(map.containsKey(nums[i])) {
idx1 = map.get(nums[i]);
idx2 = i;
}else {
map.put(target - nums[i], i);
}
}
int[] arr = {idx1,idx2};
return arr;
}
}
'programming > 알고리즘 풀이' 카테고리의 다른 글
[leetcode] 42. Trapping Rain Water (0) | 2021.10.06 |
---|---|
[leetcode] 49. Group Anagrams (0) | 2021.10.06 |
[백준(Baekjoon)] 14235. 크리스마스 선물 (0) | 2021.08.27 |
[백준(Baekjoon)] 1260. DFS와 BFS (0) | 2021.08.26 |
[백준(Baekjoon)] 2257. 화학식량 (0) | 2021.08.25 |
댓글