我用的方法是輸入用Bufferedreader,將陣列排序後,toString去掉括號和逗號輸出,然後將陣列去掉重複的,反過來toString去括號逗號輸出
import java.io.*;
import java.util.*;
public class add {
public static void main(String[] args) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(reader.readLine());
String[] s = reader.readLine().split(" ");
int[] num = new int[n];
for (int i = 0; i < n; i++)
num[i] = Integer.parseInt(s[i]);
Arrays.sort(num);
String line1 = Arrays.toString(num);
line1 = line1.replace("[", "").replace("]", "").replace(",", "");
System.out.println(line1);
String[] words = line1.split(" ");
Set<String> uniqueWords=new LinkedHashSet<>(Arrays.asList(words));
line1 = String.join(" ", uniqueWords);
s=line1.split(" ");
for (int i = 0; i < s.length / 2; i++) {
String k=s[i];
s[i]=s[s.length-i-1];
s[s.length-i-1]=k;
}
line1 = Arrays.toString(s).replace("[", "").replace("]", "").replace(",", "");
System.out.println(line1);
}
}
StreamTokenizer st = new StreamTokenizer(new java.io.BufferedReader(new java.io.InputStreamReader(System.in)));
st.nextToken();
int N = (int) st.nval;
int[] num = new int[N];
for(int i=0; i<N; i++) {
st.nextToken();
num[i] = (int) st.nval;
}
Arrays.sort(num);
StringBuilder ans = new StringBuilder();
for(int i=0; i<N; i++) {
ans.append(Integer.toString(num[i]));
ans.append(' ');
}
System.out.println(ans);
ans = new StringBuilder();
int keep = -1;
for(int i=N-1; i>=0; i--) {
if(num[i] != keep) {
keep = num[i];
ans.append(Integer.toString(num[i]));
ans.append(' ');
}
}
System.out.println(ans);
BufferedWriter bw = new BufferedWriter(new java.io.OutputStreamWriter(System.out));
for(int i=0; i<N; i++) {
bw.append(Integer.toString(num[i]));
bw.append(' ');
}
bw.append('\n');
int keep = -1;
for(int i=N-1; i>=0; i--) {
if(num[i] != keep) {
keep = num[i];
bw.append(Integer.toString(num[i]));
bw.append(' ');
}
}
bw.flush();