题解 | #输入整型数组和排序标识,对其元素按照升序或降序进行排序#
输入整型数组和排序标识,对其元素按照升序或降序进行排序
http://www.nowcoder.com/practice/dd0c6b26c9e541f5b935047ff4156309
一开始的思路是使用TreeMap, 有序不允许重复
代码写出来了, 但是有的案例不通过, 估计是案例中重复的输入被自动去重了.
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner ip = new Scanner(System.in);
int length = Integer.valueOf(ip.nextLine());
String in = ip.nextLine();
int id = Integer.valueOf(ip.nextLine());
String[] arr = in.split(" ");
TreeSet<Integer> treeSet = new TreeSet<Integer>();
for (int i = 0; i < (length); i++){
treeSet.add(Integer.valueOf(arr[i]));
}
Iterator<Integer> it =
(id==1?(((TreeSet)treeSet.descendingSet())):treeSet)
.iterator();
while(it.hasNext()){
System.out.print(it.next()+" ");
}
}
}
那我只好使用ArrayList了,简单修改了一下通过了, 就是代码有点丑
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner ip = new Scanner(System.in);
int length = Integer.valueOf(ip.nextLine());
String in = ip.nextLine();
int id = Integer.valueOf(ip.nextLine());
String[] arr = in.split(" ");
List<Integer> list = new ArrayList<>();
for (int i = 0; i < (length); i++){
list.add(Integer.valueOf(arr[i]));
}
list.sort(null);
if (id == 0){
for (Integer e: list){
System.out.print(e+" ");
}
}else {
for (int i = list.size()-1; i>=0; i--){
System.out.print(list.get(i)+" ");
}
}
}
}