1. 선택정렬 (오름차순)
*내림차순도 같은 원리임. 부등호 방향만 반대로 해주면 된다.
package algorithm;
import java.util.Scanner;
public class Selection_sort001 {
/*
가장 큰 수를 잡아 제일 끝 A[last]로 보내고
배열 A의 두번째 인덱스까지 오게 하는 것이다.
생각해줘야하는 배열 크기가 점점 줄어든다.
*/
public static void swap(int a[], int x, int y) {
int tmp = a[x];
a[x] = a[y];
a[y] = tmp;
}
public static void selection_sort(int a[], int N, int K) {
for(int i = N - 1; i > 0; i--) {
int max_index = i;
for(int k = i - 1; k >= 0; k--) {
if(a[k] > a[max_index]) max_index = k;
}
swap(a, max_index , i);
}
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int N = sc.nextInt();
int K = sc.nextInt();
int arr[] = new int[N];
for(int i = 0; i < N; i++)
arr[i] = sc.nextInt();
selection_sort(arr,N,K);
for(int i = 0; i < N; i++)
System.out.printf(arr[i] + " ");
}
}
- 백준 23881 / 23882
이클립스에서는 답이 알맞게 나오는데 사이트에서는 fail;;; 빡친다
package algorithm;
import java.util.Scanner;
public class Selection_sort001 {
/*
가장 큰 수를 잡아 제일 끝 A[last]로 보내고
배열 A의 두번째 인덱스까지 오게 하는 것이다.
생각해줘야하는 배열 크기가 점점 줄어든다.
*/
public static void swap(int a[], int x, int y) {
int tmp = a[x];
a[x] = a[y];
a[y] = tmp;
}
public static void selection_sort(int a[], int N, int K) {
int count = 0;
for(int i = N - 1; i > 0; i--) {
int max_index = i;
for(int k = i - 1; k >= 0; k--) {
if(a[k] > a[max_index]) {
max_index = k;
swap(a, max_index , i);
count++;
if(count == K) {
for(int j = 0; j < N; j++)
System.out.printf(a[j] + " ");
}
//System.out.printf("%d %d" , a[max_index] , a[i]);
}
}
}
if(count < K) System.out.println(-1);
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int N = sc.nextInt();
int K = sc.nextInt();
int arr[] = new int[N];
for(int i = 0; i < N; i++)
arr[i] = sc.nextInt();
selection_sort(arr,N,K);
}
}
2. b 2675 문자열 반복
bufferedReader로 읽는 연습하기.
이 문제에서는 입력 값이 3 ABC <-이런 형식이므로 String형 배열로 한줄씩 읽어주고 공백을 기준으로 나누어준다.
import java.io.*;
import java.util.*;
public class b2675 {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int T = Integer.parseInt(br.readLine());
int R;
String[] input;
String S;
for(int i = 0; i < T; i++) {
input = br.readLine().split(" ");
R = Integer.parseInt(input[0]);
S = input[1];
for(int k = 0; k < S.length(); k++) {
for(int j = 0; j < R; j++) {
System.out.print(S.charAt(k));
}
}
System.out.println();
}
}
}
3. b1152 단어 개수 세기
*앞 뒤 공백 존재 가능함
(1) bufferedReader 사용 (20078KB, 276ms)
-실패 코드
처음에 toCharArray를 이용해서 모두 문자열로 바꾸고, 공백의 개수를 카운트 한 다음에 예외처리를 하나하나 해줌.
예외 처리할 때 골치아픔, 그리고 미처 발견하지 못 한 예외가 있음. fail
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class b1152_2 {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
char input[] = br.readLine().toCharArray();
int count = 0;
for(int i = 0; i < input.length; i++) {
if (input[i] == ' ') count++;
}
if(input.length != 0) {
int last = input.length-1;
if(input[0] == ' ' || input[last] == ' ') count -= 0;
if (input[0] == ' ' && input[last] == ' ') count -= 1;
else count+=1;
}
System.out.println(count);
}
}
-성공 코드
버퍼리더 이용해서 한 문장 전체를 읽어준 다음에 간단하게 StringTokenizer 사용
StringTokenizer는 긴 문자열을 원하는 구분자를 기준으로 슬라이싱 할 때 사용된다.
따라서 분리된 문자열, 즉 토큰(Token)의 개수를 세어주면 끝임. 겁나 간단함
import java.io.*;
import java.util.*;
public class b1152 {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String input = br.readLine();
StringTokenizer st = new StringTokenizer(input, " ");
int count = st.countTokens();
System.out.println(count);
}
}
(2) BufferedReader 사용 X (39508KB, 544ms)
trim() 메소드 사용해서 앞뒤 공백 제거한 후 " " 공백 문자 기준으로 분리한 나머지의 길이를 구한다
비교적 간단하나 차지하는 메모리 크기가 크고 속도가 느리다.
import java.util.*;
public class Main{
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String st= sc.nextLine().trim();
int howlong = st.split(" ").length;
if (st.isEmpty())
System.out.println("0");
else System.out.println(howlong);
}
}
3. b2908 상수
(1) StringBuilder + reverse() 사용 (14188KB , 124ms)
StringBuilder : String과 문자열을 더할 때 새로운 객체 생성하지 않고 기존의 데이터에 더하는 방식 사용
append() -> 문자열 더하는 용도toString() -> 문자열로 불러오는 용도. 보통 출력할 때나 값을 사용해야 할 때 많이 쓴다.
입력 형태가 123 456 과 같이 공백으로 구분되어있으면 아래와 같은 방법을 쓰자.
int num = Integer.parseInt(new StringBuilder(st.nextToken()).reverse().toString());
import java.io.*;
import java.util.StringTokenizer;
public class b2908 {
public static int compare(int a, int b) {
if(a > b) return a;
return b;
}
public static void main(String[] args) throws NumberFormatException, IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine(), " ");
int num = Integer.parseInt(new StringBuilder(st.nextToken()).reverse().toString());
int num2 = Integer.parseInt(new StringBuilder(st.nextToken()).reverse().toString());
System.out.println(compare(num,num2));
}
}
4. b2941 문자열 포함 여부
(1) BufferedReader 사용 (14268KB, 128ms)
1. contain 메소드로 문자 포함 여부 간단하게 확인
2. 하나의 문자로 취급하므로 replace 메소드 이용해서 아무 문자로 변경
import java.io.*;
public class Main {
public static void main(String[] args) throws IOException {
String croAlpha[] = {"c=", "c-", "dz=", "d-", "lj", "nj", "s=", "z="};
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String input = br.readLine();
for(int i = 0; i < croAlpha.length; i++) {
if(input.contains(croAlpha[i]))
input = input.replace(croAlpha[i], "@");
}
System.out.println(input.length());
}
}
(2) Scanner 사용 (17712KB, 208ms)
import java.util.Scanner;
public class Main {
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
String croAlpha[] = {"c=", "c-", "dz=", "d-", "lj", "nj", "s=", "z="};
String input = sc.nextLine();
for(int i = 0; i < croAlpha.length; i++) {
if(input.contains(croAlpha[i]))
input = input.replace(croAlpha[i], "@");
}
System.out.println(input.length());
}
}
'Problems & Solutions' 카테고리의 다른 글
11441 합 구하기 (0) | 2022.07.26 |
---|---|
1058 친구 (0) | 2022.07.25 |
1244 스위치 켜고 끄기 (0) | 2022.07.25 |
23881 알고리즘 수업 - 선택 정렬 1 (0) | 2022.07.02 |
[1월 11일] 숫자 각 자릿수 활용 (0) | 2022.01.15 |