[LeetCode] 1. Two Sum (Java)

2022. 12. 22. 14:50알고리즘/LeetCode

Description

Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target.

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

You can return the answer in any order.

---

정수의 array와 정수로 된 목표 숫자가 주어지고 목표 숫자로 더해지는 두 숫자를 반환해라. 같은 요소를 두 번 사용하면 안된다.

 

Example 1.

Input: nums = [2,7,11,15], target = 9
Output: [0,1]
Explanation: Because nums[0] + nums[1] == 9, we return [0, 1].

Example 2.

Input: nums = [3,2,4], target = 6
Output: [1,2]

Example 3.

Input: nums = [3,3], target = 6
Output: [0,1]

Follow-up: Can you come up with an algorithm that is less than O(n2) time complexity?

 

Solution

class Solution {
    public int[] twoSum(int[] nums, int target) {
        int a = 0;
        int b = 0;
        for(int i=0;i<nums.length;i++){
            for(int j=0;j<nums.length;j++){
                if(nums[i] + nums[j] == target && i!=j){
                    a=j;
                    b=i;
                }
            }
        }
        return new int[]{a,b};
    }
}

직관적인 문제라 배열의 수만큼 반복해서 배열을 순회하는 이중for문을 사용하고 자기 요소를 반복해서 사용하지 않게 예외처리를 두었다.