Algorithm & Data Structure/LeetCode
1. Two Sum
Dfree
2025. 4. 22. 11:29
가정 : scanner를 써서 입력을 받는게 아니라 처음 작동시킬 때부터 입력이 들어온다.
문제 ) 배열 입력받아 두개 더했을때 target 이랑 일치하면 그 인덱스를 반환
Q.
incides 인덱스
스캐너 선언 : Scanner sc = new Scanner(System.in);
int 입력 : sc.nextInt();
배열 선언 : 자료형[] 이름;
배열 도는 for 문 : for(배열자료형 변수명 : 배열명)
인텔리제이에서 LeetCode 작동시키기
처음 작성한 잘못된 코드
public class Main {
public static void main(String[] args) {
twoSum m = new twoSum(); //twoSum 이라는 클래스 없음 -> Solution 으로 해야함
int[] result = m([2, 3, 5],6); // 메서드 호출 방식이 잘못됨 → m.twoSum(...)이어야 함
} //int[] 배열을 출력하거나 확인할 코드도 없음
}
class Solution {
public int[] twoSum(int[] nums, int target) {
for (int i = 0; i < nums.length; i++) {
for (int j = 0; j < nums.length; j++) {
if ((nums[i] + nums[j]) == target) {
return new int[]{i, j};
}
}
}
return new int[]{};
}
}
고친 코드
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
Solution m = new Solution();
int[] result = m.twoSum(new int[]{3, 2, 4},6);
System.out.println(Arrays.toString(result));
}
}
class Solution {
public int[] twoSum(int[] nums, int target) {
for (int i = 0; i < nums.length; i++) {
for (int j = 0; j < nums.length; j++) {
if ((nums[i] + nums[j]) == target && i!=j) {
return new int[]{i, j};
}
}
}
return new int[]{};
}
}
오류 난 이유 : 조건문에 i와 j가 다르다는 조건을 안 넣어줬더니 [0,0] 이 출력됨
이렇게 쓰는 방법도 있음
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};
}
}
}