본문 바로가기

Algorithm

Two Sum

반응형

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/

반응형

'Algorithm' 카테고리의 다른 글

Simple Array Sum  (0) 2020.10.10
K번째  (0) 2020.08.22
더 맵게  (0) 2020.08.22
주식가격  (0) 2020.08.21
완주하지 못한 선수  (0) 2020.08.21