输入整型数组和排序标识,对其元素按照升序或降序
输入整型数组和排序标识,对其元素按照升序或降序进行排序
https://www.nowcoder.com/practice/dd0c6b26c9e541f5b935047ff4156309
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;
public class Main {
public static void main(String[] args) throws IOException {
Scanner scanner = new Scanner(System.in);
String number=null;
String s=null;
String order=null;
while (scanner.hasNext()){
number= scanner.nextLine();
s = scanner.nextLine();
order=scanner.nextLine();
displayByAscOrDsc(number,s,order);
}
}
private static void displayByAscOrDsc(String next, String s, String order) {
Integer number = Integer.valueOf(next);
List<Integer> objects = new ArrayList<>(number);
String[] s1 = s.split(" ");
for (String ch :s1) {
objects.add(Integer.valueOf(ch));
}
StringBuilder stringBuilder=new StringBuilder();
if ("1".equals(order)) {
Collections.sort(objects, new Comparator<Integer>() {
@Override
public int compare(Integer o1, Integer o2) {
return o2-o1;
}
});
}else {
Collections.sort(objects, new Comparator<Integer>() {
@Override
public int compare(Integer o1, Integer o2) {
return o1-o2;
}
});
}
for (Integer e:objects) {
stringBuilder.append(e).append(" ");
}
System.out.println(stringBuilder);
}
}
#Java求助#
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;
public class Main {
public static void main(String[] args) throws IOException {
Scanner scanner = new Scanner(System.in);
String number=null;
String s=null;
String order=null;
while (scanner.hasNext()){
number= scanner.nextLine();
s = scanner.nextLine();
order=scanner.nextLine();
displayByAscOrDsc(number,s,order);
}
}
private static void displayByAscOrDsc(String next, String s, String order) {
Integer number = Integer.valueOf(next);
List<Integer> objects = new ArrayList<>(number);
String[] s1 = s.split(" ");
for (String ch :s1) {
objects.add(Integer.valueOf(ch));
}
StringBuilder stringBuilder=new StringBuilder();
if ("1".equals(order)) {
Collections.sort(objects, new Comparator<Integer>() {
@Override
public int compare(Integer o1, Integer o2) {
return o2-o1;
}
});
}else {
Collections.sort(objects, new Comparator<Integer>() {
@Override
public int compare(Integer o1, Integer o2) {
return o1-o2;
}
});
}
for (Integer e:objects) {
stringBuilder.append(e).append(" ");
}
System.out.println(stringBuilder);
}
}
#Java求助#