Two Sum - LeetCode
Can you solve this real interview question? 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
leetcode.com
ํ์ด์ฌ ์ฝ๋
class Solution(object):
def twoSum(self, nums, target):
dic = {}
for i in range(len(nums)):
search = target - nums[i]
if search in dic:
return [dic[search],i]
else:
dic[nums[i]] = i
return []
nums ๋ผ๋ ๋ฐฐ์ด์ด ์ฃผ์ด์ง๊ณ nums์ ์์๋ฅผ ๊ณจ๋ผ target ๊ฐ์ ๋ง๋ค ์ ์๋ index๋ฅผ ๊ตฌํ๋ ๋ฌธ์ ์๋ค.
๋์ ๋๋ฆฌ ์๋ฃ ๊ตฌ์กฐ๋ฅผ ์ฌ์ฉํด์ ํ์๋ค.
์ฐพ์์ผ ํ๋ ๊ฐ์ด dic์ ์์ผ๋ฉด ์ถ๊ฐํ๊ณ , ์๋ค๋ฉด ๋ต์ ๋ฐํํ๋ ๋ฐฉ์์ด๋ค.
์๋ฐ ์ฝ๋
import java.util.*;
class Solution {
public int[] twoSum(int[] nums, int target) {
Map<Integer,Integer> map = new HashMap<>();
for(int i=0;i<nums.length;i++){
int search = target-nums[i];
if(map.containsKey(search)){
return new int[]{map.get(search),i};
}else{
map.put(nums[i],i);
}
}
return new int[]{};
}
}
์๋ฐ ์ฝ๋๋ ๊ฐ์ ๋ฐฉ์์ผ๋ก ์ง๋ฉด ๋๋ค.