
[문제]
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.
https://leetcode.com/problems/two-sum/?envType=study-plan-v2&envId=top-interview-150
class Solution {
public int[] twoSum(int[] nums, int target) {
// int l = 0;
// int r = l + 1;
// while (r < nums.length) {
// int sum = nums[l] + nums[r];
// if (sum == target) {
// return new int[] {l, r};
// } else {
// if (r < nums.length - 1) {
// r++;
// } else {
// l++;
// r = l + 1;
// }
// }
// }
// return null;
HashMap<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < nums.length; i++) {
if (map.containsKey(target - nums[i])) {
return new int[] {map.get(target - nums[i]), i};
}
map.put(nums[i], i);
}
return null;
}
}
// 100,000,000
주어진 배열의 두 요소의 합이 target이 되는 인덱스의 값을 찾는 문제이다.
투 포인터나 HashMap을 활용하여 해결할 수 있다.