정보
분류 : 1차원 배열
문제
풀이
- 풀이 1 ( Scanner + println() ) → 696ms
import java.util.*;
public class Main {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
int a = sc.nextInt();
int x = sc.nextInt();
int n[] = new int[a];
for(int i = 0 ; i < a ; i++) {
n[i] = sc.nextInt();
if(n[i] < x) {
System.out.print(n[i] + " ");
}
}
}
}
- 풀이 2 ( Scanner + println() + List ) → 580ms
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt(); //배열이 될 숫자
int x = sc.nextInt(); //x보다 작은 숫자를 찾는 것
int[] arr = new int[n]; //배열의 길이
List<Integer> arr2 = new ArrayList<Integer>();
for(int i = 0 ; i < n ; i++) {
int num = sc.nextInt(); //입력할 숫자
if(x > num) {
arr2.add(num);
}
};
for(Integer j : arr2) {
System.out.print(j + " ");
}
}
}
- 풀이 3 ( BufferedReader + BufferedWriter + StringTokenizer )→ 212ms
import java.io.*;
import java.util.StringTokenizer;
public class Main {
public static void main(String[] args) throws IOException {
// InputStream : 자바의 가장 기본이 되는 입력 스트림
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
// OutputStreamWriter : 자바의 가장 기본이 되는 출력 스트림
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
StringTokenizer st = new StringTokenizer(br.readLine(), " ");
int n = Integer.parseInt(st.nextToken());
int x = Integer.parseInt(st.nextToken());
int[] arr = new int[n];
st = new StringTokenizer(br.readLine(), " ");
for(int i = 0 ; i < arr.length ; i++) {
arr[i] = Integer.parseInt(st.nextToken());
// 배열 안에 들어있는 숫자가 x 보다 작으면 순서대로 출력하기
if(arr[i] < x) {
bw.write(arr[i] + " ");
}
}
br.close();
bw.flush();
bw.close();
}
}
풀이 후기
입력 행 | 내용 |
1 | 입력 받고자 하는 숫자 개수와 찾고자 하는 숫자를 입력 |
2 | 1행에 지정한 개수만큼 숫자를 공백 기준으로 나열 |
출력은 찾고자 하는 숫자보다 작은 숫자를 순서대로 출력하면 된다. 해당 조건은 for문 안에서 if문을 통해 진행하였다. 블로그를 이리저리 돌아다녀보니 내가 푼 방법 외에도 다양한 풀이가 있는 것 같았다. 보아하니 배열을 사용하지 않고 푸는 방법도 있던데 신기하다🤔
Scanner로 푼 방법은 예전에 푼 방법이라 최근에 푼 BufferedReader 방식과 같이 보여주고 있다. 슬슬 Scanner 방식으로 푼 문제가 많지 않아서 BufferedReader 방식으로만 풀이를 진행할 것 같다. 두 가지 방법을 비교하면서 풀어보니 확실히 성능 차이가 나서 시간이 단축되는 점을 확인할 수 있었다.
'💡문제 풀이 > 백준 - JAVA' 카테고리의 다른 글
최댓값 / 2562 (1) | 2023.11.20 |
---|---|
최소, 최대 / 10818 (0) | 2023.11.20 |
개수 세기 / 10807 (0) | 2023.11.20 |
A+B - 4 / 10951 (1) | 2023.11.17 |
A+B - 5 / 10952 (1) | 2023.11.17 |