## 1411
기초 5-1 1차원 배열
빠진 카드
- 총 카드 수 N 입력받음 (1~N까지 있는 카드 묶음)
- 하지만 한 장 잃어버림. 그 한장 빼고 다 입력받음.
- 잃어버린 카드 찾기
import java.util.Scanner;
public class CodeUp1411 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int N = sc.nextInt();
int[] arr = new int[N - 1];
for (int i = 0; i < N - 1; i++) {
arr[i] = sc.nextInt();
}
sc.close();
//
outer: for (int cmp = 1; cmp <= N; cmp++) {
boolean flag = false;
for (int j = 0; j < N - 1; j++) {
if (arr[j] == cmp) {
flag = true;
continue outer;
}
}
if (flag == false) {
System.out.println(cmp);
break;
}
}
}
}
- 험 생각보다 오래 걸렸다.
- label까지 쓰는게 맞나.. 싶었는데 그냥 썼다.
- 와 근데 머지 그냥 다 더하면 잃어버린 카드 구할 수 있네... 허망한 시간이었구나
// 2안 - (잃어버리기 전의 합-지금 합)
// int sum=0;
// for(int i =0;i<N-1;i++) {
// sum+=arr[i];
// }
// System.out.println(N*(N+1)/2-sum);
- 이렇게 추가했다.
## 1492
1차원 누적 합 배열 만들기
1 2 3 4 5 -> 1 3 6 10 15로 만들기 (각 자리에 a_n대신 S_n 넣기)
import java.util.Scanner;
public class CodeUp1492 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int[] arr = new int[n];
int[] arrO = new int[n];
for (int i = 0; i < n; i++) {
arr[i] = sc.nextInt();
}
for (int i = 0; i < n; i++) {
for (int j = 0; j <= i; j++) {
arrO[i]+=arr[j];
}
}
for (int i = 0; i < n; i++) {
System.out.printf("%d ",arrO[i]);
}
}
}
- 난 진짜 바보다...
- 위 코드는 똑같은 길이의 빈 배열을 새로 생성해서, 각 자리마다 원래 배열로 돌아가서 for로 반복해서 합산하고 넣어주는 답답한 코드
- 배열 두개 만들 필요 없이 개간단한 알고리즘이 떠올라서 다시 짰다
import java.util.Scanner;
public class CodeUp1492 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int[] arr = new int[n];
for (int i = 0; i < n; i++) {
arr[i] = sc.nextInt();
}
for (int i = 1; i < n; i++) {
arr[i] += arr[i - 1];
}
for (int i = 0; i < n; i++) {
System.out.printf("%d ", arr[i]);
}
}
}
- 그냥... 각 자리는 그 앞자리와 더하면 되는거였다.
'PS - CodeUp' 카테고리의 다른 글
1501, 1502 - 2차원 배열 채우기1&2, 1507, 1512 - 4개의 직사각형 넓이, 숫자 등고선 (0) | 2022.01.20 |
---|---|
3011 - 버블 정렬 + (0) | 2022.01.20 |
1096, 1097, 1098 - 바둑판에 흰 돌 놓기, 바둑알 십자 뒤집기, 설탕과자 뽑기 (0) | 2022.01.20 |
1093, 1094, 1095 - 이상한 출석 번호 부르기 1, 2, 3 (0) | 2022.01.20 |
1441, 1442, 1443 - 버블 정렬, 선택 정렬, 삽입 정렬 (0) | 2022.01.20 |