설명
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 + " ");
}
}
}