본문 바로가기

study_IT/알고리즘 노트

[leetcode] two-sum

728x90
반응형

문제 출처 : https://leetcode.com/problems/two-sum/

 

LeetCode - The World's Leading Online Programming Learning Platform

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

 

주력 언어(?)인 JAVA로 문제를 풀어보았다.

class Solution {
    public int[] twoSum(int[] nums, int target) {
        int[] result = new int[2];   // result 배열을 초기화
        for(int i = 0; i<nums.length; i++){
           int num1 = nums[i];
            for(int j = i+1; j<nums.length; j++){  // j를 i + 1로 설정하여 중복 방지
               int num2 = nums[j];
                if(num1 + num2 == target){
                    result[0] = i;
                    result[1] = j;                  
                }
            }

        } 
         return result;
    }
}

Accepted 가 될 때까지 총 2번의 에러가 났다.

 

1. int[] result = null; 를 int[] result = new int[2]; 로 수정

 

: 오랜만에 배열을 사용했더니..기본적인 배열 생성 및 초기화 작업을 잊고 있었다. 항상 기본에 충실하자!

 

2. for(int j = 0; j < nums.length; j++) 를 for(int j = i + 1; j < nums.length; j++) 로 수정

: 문제의 조건에 따르면 두 수를 더해서 target을 만들어야 하기 때문에 두 수의 인덱스가 서로 다르다는 조건이 필요하다. 따라서 중복을 방지하기 위해 j 는 i 보다 1 큰 index를 사용해야 한다.

728x90
반응형