LeetCode 영어 문제

 

Given an array of integers, return indices of the two numbers such that they add up to a specific target.

You may assume that each input would have exactly one solution, and you may not use the same element twice.

Example:

Given nums = [2, 7, 11, 15], target = 9, Because nums[0] + nums[1] = 2 + 7 = 9, return [0, 1].

 

번역

 

정수 배열이 주어지면 두 숫자의 인덱스를 반환하여 특정 목표에 합산합니다.

각 입력에 정확히 하나의 솔루션이 있다고 가정하고 동일한 요소를 두 번 사용할 수 없습니다.

예:

주어진 숫자 = [2, 7, 11, 15], target = 9, 숫자 [0] + 숫자 [1] = 2 + 7 = 9이므로 [0, 1]을 반환합니다.

 

다른 사람의 풀이

 

public int[] twoSum(int[] nums, int target) {
    for (int i = 0; i < nums.length; i++) {
        for (int j = i + 1; j < nums.length; j++) {
            if (nums[j] == target - nums[i]) {
                return new int[] { i, j };
            }
        }
    }
    throw new IllegalArgumentException("No two sum solution");
}
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");
}
public int[] twoSum(int[] nums, int target) {
    Map<Integer, Integer> map = new HashMap<>();
    for (int i = 0; i < nums.length; i++) {
        int complement = target - nums[i];
        if (map.containsKey(complement)) {
            return new int[] { map.get(complement), i };
        }
        map.put(nums[i], i);
    }
    throw new IllegalArgumentException("No two sum solution");
}

 

풀이
public int[] twoSum(int[] nums, int target) {
    for (int i = 0; i < nums.length; i++) {
        for (int j = i + 1; j < nums.length; j++) {
            if (nums[j] == target - nums[i]) {
                return new int[] { i, j };
            }
        }
    }
    throw new IllegalArgumentException("No two sum solution");
}

2 + 7 = 9을 예제로 들면, i 가 2 이고 j 가 7 이고 9가 target이라고 가정했을때

i + j = target

j = target - i 가 된다. 그래서 이중포문안에 

if (nums[j] == target - nums[i]) {

 return new int[] { i, j };

} 가 들어간다.

 

출처 sources

'알고리즘 > LeetCode(easy)' 카테고리의 다른 글

53. Maximum Subarray  (0) 2019.12.18
20. Valid Parentheses  (0) 2019.12.18
14. Longest Common Prefix  (0) 2019.12.18
13. Roman to Integer  (0) 2019.12.18
7. Reverse Integer  (0) 2019.12.18

+ Recent posts