Algorithm

Two Sum

후니우니 2020. 8. 20. 14:39
반응형

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]

 

class 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");
   }
}

주어진 int 배열의 요소의 합이 Target을 만족할때 해당하는 요소의 인덱스 값을 출력하는 문제

i+1을 초기값으로 갖는 이중 for문을 돌리면서 target - nums[i] 의 값이 nums[j]의 값과 일치할 경우

해당 요소의 합이 target을 만족하므로 그에 맞는 인덱스 값이 정답!

 

출처 : https://leetcode.com/

반응형