꿀잠마스터
2026. 7. 21. 21:16
https://leetcode.com/problems/two-sum/description/
Two Sum - LeetCode
Can you solve this real interview question? Two Sum - 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
leetcode.com
두 값의 합이 Target과 일치하는 인덱스를 배열로 반환하는 문제이다.
알고리즘이 필요하기보다. 배열을 다룰 수 있는 지에 가까운 문제였다.
class Solution {
public int[] twoSum(int[] nums, int target){
for(int i = 0; i < nums.length; i++){
for(int j = i + 1; j < nums.length; j++){
if(nums[i] + nums[j] == target){
return new int[]{i, j};
}
}
}
return null;
}
문제에서 반드시 하나의 답이 존재한다고 조건을 주어서 순회가 끝난 경우 null 로 처리하였다.
Exception으로 처리하려 하였으나 리트코드에서는 문제에서 별도의 익셉션 처리를 할 수 없는 듯 하였다. throws Exception 메세지를 추가하자 아래와 같은 오류가 발생하였다.
Line 7: error: unreported exception Exception; must be caught or declared to be thrown [in __Driver__.java] int[] ret = new Solution().twoSum(param_1, param_2); ^
로드맵의 첫 문제라서 그런지 굉장히 쉬웠다.