Post

Array_큰 수 출력하기

✅ N개의 정수를 입력받아, 자기 바로 앞의 수보다 자신이 크면 출력하는 프로그램

단, 첫 번째 수는 무조건 출력한다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
class Main {
    public ArrayList<Integer> solution(int n, int[] arr){
        ArrayList<Integer> answer= new ArrayList<>();
        answer.add(arr[0]); //첫 번째 수는 무조건 출력

        for(int i=1; i<n; i++){  //0부터 시작하면 i-1을 못하니까 1부터 시작
            if(arr[i]> arr[i-1]){
                    answer.add(arr[i]);

            }
        }
        return answer;

}
    public static void main(String[] args) {
        Main T = new Main();
        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 x: T.solution(n, arr)){
            System.out.print(x+ " ");
        }
    }
}


//⭐️input:
//6
//7 3 9 5 6 12
//⭐️output:
//7 9 6 12

🟢 index [i+1]이 배열 넘어가지 않니 ? 그러면 [i+1] : 아니면 0

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
class Main {
    public ArrayList<Integer> solution(int n, int[] arr){
        ArrayList<Integer> answer= new ArrayList<>();
        answer.add(arr[0]);

        for(int i=0; i<n; i++){
            int nextValue= (i+1 != n) ? arr[i+1] : 0; //배열 벗어나니? if문
            if(arr[i]<nextValue){
                    answer.add(arr[i+1]);

            }
        }
        return answer;

}
    public static void main(String[] args) {
        Main T = new Main();
        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 x: T.solution(n, arr)){
            System.out.print(x+ " ");
        }
    }
}


🔵 ThingsILearned

✔️ 조건이 왜 있는지 살펴보자.

왜 하필 첫 번째 수는 무조건 출력한다는 조건이 있었을까?
인덱스를 1로부터 시작해서 arr[i]arr[i-1]을 비교하기 위함이었을 것이다.
만약 인덱스가 0에서 시작하면 arr[i-1]arr[-1]이 되니까~
for문을 돌 때 반드시 인덱스를 0에서 시작해야 한다는 둥, i가 꼭 1씩 증가해야 한다는 생각을 버리자!
인덱스 i는 1에서 시작할 수도 있고, i += 7처럼 7씩 증가할 수도 있는 것이다!

This post is licensed under CC BY 4.0 by the author.