난이도: EASY
문제
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.
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]
Constraints:
2 <= nums.length <= 104
-109 <= nums[i] <= 109
-109 <= target <= 109
Only one valid answer exists.
Follow-up: Can you come up with an algorithm that is less than O(n2) time complexity?
시도 1
class Solution {
public int[] twoSum(int[] nums, int target) {
int[] answer = new int[2];
try{
for(int i=0; i < nums.length; i++) {
int sum = nums[i] + nums[i+1];
if(sum == target) {
answer[0] = i;
answer[1] = i+1;
return answer;
}
}
} catch(Exception e) {
throw new Exception("No Match: " + e.getMessage());
}
// 예외가 발생하지 않았지만 정답을 못 찾았을 때 => 빈 배열 반환
return new int[] {};
}
}
사실 try-catch 안써도되는데 그냥 자바를 너무 오래안써서 재활(?)겸 넣어본건데,
Line 17: error: unreported exception Exception; must be caught or declared to be thrown throw new Exception("No Match: " + e.getMessage());
이런 에러가 나는 것임(넣어보길잘했디 휴). 에러들고 챗지선생 찾아감.
chatGPT:
이 오류는 일반 예외(Checked Exception)인 Exception을 던졌기 때문에 발생합니다. 자바에서는 Exception을 던질 경우, 반드시 해당 메서드에 throws Exception을 선언해야 합니다.
ㅋㅋㅋㅋㅋㅋㅋㅋㅋㅋㅋㅋㅋㅋㅋ 아 이런 멍청한.... 하.... 맨날 기본적으로 써서 복붙수정만했더니 생각도 못했네, 그런게 있었찌 ㅋㅋㅋㅋㅋㅋㅋㅋㅋㅋㅋㅋㅋㅋㅋㅋㅋ 암튼 수정방법은 두 개 인데,
1. 메소드 선언부에 throws Exception 추가 (비추)
public class Solution {
public int[] twoSum(int[] nums, int target) throws Exception { // throws 추가
int[] answer = new int[2];
try {
for (int i = 0; i < nums.length - 1; i++) {
int sum = nums[i] + nums[i + 1];
if (sum == target) {
answer[0] = i;
answer[1] = i + 1;
return answer;
}
}
} catch (Exception e) {
throw new Exception("Error: " + e.getMessage());
}
// 예외가 발생하지 않았지만 정답을 못 찾았을 때 => 빈 배열 반환
return new int[] {};
}
}
chatGPT:
⚠️ throws Exception을 추가하면, twoSum을 호출하는 곳에서도 반드시 try-catch로 예외를 처리해야 합니다.
이 방법은 코드의 복잡성을 증가시키므로, RuntimeException을 사용하는 방법이 더 좋습니다.
2. 기본 익셉션 대신 다른 익셉션 추가(내가 선택한 방법)
class Solution {
public int[] twoSum(int[] nums, int target) {
int[] answer = new int[2];
try{
for(int i=0; i < nums.length; i++) {
int sum = nums[i] + nums[i+1];
if(sum == target) {
answer[0] = i;
answer[1] = i+1;
return answer;
}
}
} catch(Exception e) {
// 기본 익셉션 대신 RuntimeException으로 변경
throw new RuntimeException("Error: " + e.getMessage());
}
// 예외가 발생하지 않았지만 정답을 못 찾았을 때 => 빈 배열 반환
return new int[] {};
}
}
나의 최종 제출 답안:
public class Solution {
public int[] twoSum(int[] nums, int target) {
int[] answer = new int[2];
for (int i = 0; i < nums.length - 1; i++) {
int sum = nums[i] + nums[i + 1];
if (sum == target) {
answer[0] = i;
answer[1] = i + 1;
return answer;
}
}
// 정답을 찾지 못한 경우 => 빈 배열 반환
return new int[] {};
}
}
chatGPT에게 더 간단하고 효율적이게 수정해달라고 요청한 답안:
public class Solution {
public int[] twoSum(int[] nums, int target) {
for (int i = 0; i < nums.length - 1; i++) {
if (nums[i] + nums[i + 1] == target) { // sum 변수 없이 직접 계산
return new int[]{i, i + 1};
}
}
return new int[] {}; // 정답을 찾지 못한 경우 빈 배열 반환
}
}
✅ sum을 변수로 선언할 필요 없이 바로 조건문에서 계산하는 것이 좋습니다.
(변수 선언 없이 직접 계산하면 불필요한 메모리 사용을 줄일 수 있음)
✅ 메모리를 절약할 수 있고, 불필요한 코드가 줄어들어 가독성이 좋아집니다.
✅ 성능 차이는 거의 없지만, 최적화된 코드 스타일을 유지하는 것이 중요합니다.
'Coding Challenges > LeetCode' 카테고리의 다른 글
[SQL50] 1757. Recyclable and Low Fat Products (0) | 2025.02.06 |
---|---|
[Java] 20. Valid Parentheses (0) | 2025.02.06 |
[Java] 14. Longest Common Prefix (2) | 2025.02.05 |
[Java] 13. Roman to Integer (0) | 2025.02.04 |
[Java] 9. Palindrome Number (1) | 2025.02.03 |