이유's Programming/Java

Two Sum - LeetCode

살아가는 이유_EU 2021. 10. 12. 14:14
728x90
반응형

투 썸 구하는 방법 

우선 이중 for 문으로 구하는 방법...

간단하게...

 

nums 안에 들어가는 i 와 j 를 구분해서 하기. 

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

    public static void main(String[] args) {
        System.out.println("넌 정말 멋져 ");
        Solution solution = new Solution();
        int arr[] = {2,7,11,15};
        solution.twoSum(arr,9);
    }
}

 

728x90
반응형