[LeetCode] Two Sum

dhjo ㅣ 2021. 4. 27. 22:46

 

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

 

  1. 2중 for문 통해서 배열의 값을 비교 두 값을 더했을때 target과 값이 동일할 시 answer에 담아서 리턴