leetcode Two Sum(HashMap사용)

이기현·2020년 8월 5일

코딩테스트 준비

목록 보기
9/20

합쳐서 특정 값이되는 array안에 있는 두 값의 index를 구하는 문제였다.
나는 brute force를 이용해서 풀었는데, 이것을 hashmap을 이용해서 풀면 훨씬 쉽게 풀 수 있는 문제였다.
map의 특성상 중복된 값이 들어 올 수 없기 때문에, 주어진 값에서 array에 있는 한 수를 뺀 뒤 그 빼고 남은 수가 array에 존재하는지 찾으면 되는 문제이다. 이것을 hash를 통해 구현하였기 때문에, 찾는데 걸리는 시간이 거의 O(1)이 걸리는 빠른 탐색시간을 가진다

내코드

		class Solution {
		    public int[] twoSum(int[] nums, int target) {
		        int[] ans = new int[2];
		        for(int i = 0; i < nums.length-1; i++){
		            for(int j = i+1; j < nums.length; j++){
		                if(nums[i] + nums[j] == target){
		                    ans[0] = i;
		                    ans[1] = j;
		                }
		            }
		        }
		        return ans;
		    }
		}

hashMap사용

public int[] twoSum(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");
}
    
profile
실력을 쌓아가는 하루하루

0개의 댓글