https://leetcode.com/problems/two-sum/description/?envType=study-plan-v2&envId=top-interview-150
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
📌 - 풀이
처음엔 브루트 포스를 이용해서 풀려고 생각을 했으나, nums의 length가 10^4여서 시간복잡도로 생각하면 너무 많은 시간을 소요할 것 같아서, HashMap으로 생각을 바꿈
- nums를 처음부터 끝까지 for문을 수행함
- target - nums[i]를 하면서 해당하는 숫자가 map에 있으면 현재 i 값과 map의 value값 출력
- 리트코드에서 메모리 관련 부분은 그렇게 중요하지 않다고 생각한게, 같은 코드인데 여러번 제출 할 때마다 시간이 너무 다르게 나와서 신뢰도는 딱히 없다고 생각함.
- 이번 문제에서도 Beats가 아래 처럼 88.66%인 경우도 있고, 10% 근처로 나올 때도 있음
🔥 - Java 코드
class Solution {
public int[] twoSum(int[] nums, int target) {
Map<Integer,Integer> map = new HashMap<>();
for(int i =0;i<nums.length;i++){
int number = target - nums[i];
if(map.get(number) != null ){
return new int[]{map.get(number),i};
}
map.put(nums[i],i);
}
return new int[]{1,2};
}
}