题解 | #输入整型数组和排序标识,对其元素按照升序或降序进行排序#

输入整型数组和排序标识,对其元素按照升序或降序进行排序

http://www.nowcoder.com/practice/dd0c6b26c9e541f5b935047ff4156309

API解法

import java.util.*;

class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        while (sc.hasNext()) {
            int number = Integer.parseInt(sc.nextLine().trim());
            ArrayList<Integer> list = new ArrayList<>();
            String[] line = sc.nextLine().trim().split("\\s");
            for (int i = 0; i < line.length; i++) {
                list.add(Integer.parseInt(line[i]));
            }
            int sortType = Integer.parseInt(sc.nextLine().trim());
            if(sortType==0) {
                Collections.sort(list, new Comparator<Integer>() {
                    @Override
                    public int compare(Integer o1, Integer o2) {
                        return o1.compareTo(o2);
                    }
                });
            }else {
                Collections.sort(list, new Comparator<Integer>() {
                    @Override
                    public int compare(Integer o1, Integer o2) {
                        return 0-o1.compareTo(o2);
                    }
                });
            }
            StringBuffer sb = new StringBuffer();
            for (int i = 0; i < list.size(); i++) {
                sb.append(list.get(i)+" ");
            }
            System.out.println(sb);
        }
    }
}
全部评论

相关推荐

牛客48826091...:哥们胸肌挺好看
点赞 评论 收藏
分享
09-09 16:12
已编辑
成都理工大学 Java
future0210:学java就是好啊,啥都能转
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务