본문 바로가기
알고리즘/LeetCode

[LeetCode] Two Sum

by 오이가지아빠 2021. 3. 22.

Two Sum - LeetCode

 

숫자의 배열, 목표 숫자를 입력받고 배열 중 두 수를 골라서 더하면 목표 숫자가 나오는 두 수의 인덱스를 반환하라.

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

        return answer;
    }
}

 

출처: LeetCode 
https://leetcode.com

 

반응형

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

[LeetCode] Reverse Integer  (0) 2021.03.25

댓글