algorithm

큰 수 출력하기

juuuuuuun 2024. 4. 29. 02:12

설명

N개의 정수를 입력받아, 자신의 바로 앞 수보다 큰 수만 출력하는 프로그램을 작성하세요.

(첫 번째 수는 무조건 출력한다)

 

입력

첫 줄에 자연수 N(1<=N<=100)이 주어지고, 그 다음 줄에 N개의 정수가 입력된다.

 

출력

자신의 바로 앞 수보다 큰 수만 한 줄로 출력한다.

예시 입력 1 

6
7 3 9 5 6 12

 

예시 출력 1

7 9 6 12

 

소스 코드 1

import java.util.Scanner;

public class Main {
    public static int[] solution(int[] nums) {
        int[] ans = new int[nums.length];
        ans[0] = nums[0];
        int cnt = 0;
        for (int i = 1; i < nums.length; i++) {
            if (nums[i] > nums[i - 1]) {
                cnt++;
                ans[cnt] = nums[i];
            }
        }

        return ans;
    }

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int N = sc.nextInt();
        int[] nums = new int[N];
        
//        for (int num : nums) { 향상된 for문은 읽기만 가능하고 수정불가
//            num = sc.nextInt();
//        }

        for (int i = 0; i < nums.length; i++) {
            nums[i] = sc.nextInt();
        }
        for (int num : solution(nums)) {
            if (num != 0) {
                System.out.print(num + " ");
            }
        }
    }
}

 

소스 코드 2

 

import java.util.ArrayList;
import java.util.Scanner;

public class Main {
    public static ArrayList<Integer> solution(int n, int[] nums) {
        ArrayList<Integer> ans = new ArrayList<>();
        ans.add(nums[0]);
        for (int i = 1; i < n; i++) {
            if (nums[i] > nums[i - 1]) {
                ans.add(nums[i]);
            }
        }
        return ans;
    }

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int N = sc.nextInt();
        int[] nums = new int[N];
        for (int i = 0; i < nums.length; i++) {
            nums[i] = sc.nextInt();
        }

        for (int num : solution(N,nums)) {
            System.out.print(num + " ");

        }
    }
}

'algorithm' 카테고리의 다른 글

가위 바위 보  (0) 2024.04.29
보이는 학생  (0) 2024.04.29
암호  (0) 2024.04.29
문자열 압축  (0) 2024.04.29
가장 짧은 문자거리  (0) 2024.04.28