rlxo9529   3년 전

제가 생각한 알고리즘은

앞에서부터 연속된 숫자 3개가 있으면 3개씩 해서

1 2 3 4 5 6 7 이면

1 3 2 / 4 6 5 / 7 이런식으로 하는 것인데 어떤 예외가 있는지 잘 모르겠습니다.


import java.io.PrintStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Scanner;
 
public class Main {
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
PrintStream ps = System.out;
 
while(sc.hasNextInt()){
int N=sc.nextInt();
HashMap<Integer, Integer> map= new HashMap<>();
ArrayList<Integer> arr = new ArrayList<>();
HashSet hs=new HashSet();
int count=1;
for(int i=0; i<N ; i++){
arr.add(sc.nextInt());
}
arr.sort(null);
for(int i=0; i<N-1; i++){
if(arr.get(i)==arr.get(i+1)){
count++;
}else{
map.put(arr.get(i), count);
count=1;
}
}
map.put(arr.get(arr.size()-1), count);
hs.addAll(arr);
arr.clear();
arr.addAll(hs);
count = 0;
for(int i=0; i<arr.size()-1; i++){
if(arr.get(i)+1==arr.get(i+1)){
count++;
}else {
if(count==1){
Collections.swap(arr, i-1, i);
}
count=0;
}
if(count==2){
Collections.swap(arr, i, i+1);
count=0;
}
}
if(count==1){
Collections.swap(arr, arr.size()-2, arr.size()-1);
}
for(int i=0; i<arr.size()-1;i++){
for(int k=0; k<map.get(arr.get(i)); k++)
ps.print(arr.get(i)+" ");
}
for(int k=0; k<map.get(arr.get(arr.size()-1))-1; k++)
ps.print(arr.get(arr.size()-1)+" ");
ps.print(arr.get(arr.size()-1));
ps.println();
}
sc.close();
ps.close();
}
}


댓글을 작성하려면 로그인해야 합니다.