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

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

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

简单使用Comparator

import java.util.*;

public class Main {

    public Main() {
    }

    public void sortIntegerArray(Integer[] pIntegerArray, int iSortFlag) {
        // 按升序
        if (iSortFlag == 0) {
            Arrays.sort(pIntegerArray, new Comparator<Integer>() {
                public int compare(Integer o1, Integer o2) {
                    return o1 - o2;
                }
            });
        }
        // 按降序
        else {
            Arrays.sort(pIntegerArray, new Comparator<Integer>() {
                public int compare(Integer o1, Integer o2) {
                    return o2 - o1;
                }
            });
        }
    }

    public void output(Integer[] array) {
        for (Integer i : array) {
            System.out.print(i + " ");
        }
        System.out.println();
    }

    public static void main(String[] args) {
        Main solution = new Main();
        Scanner in = new Scanner(System.in);
        while (in.hasNextInt()) {
            int n = in.nextInt();
            Integer[] array = new Integer[n];
            for (int i = 0; i < n; i++) {
                array[i] = in.nextInt();
            }
            int flag = in.nextInt();
            solution.sortIntegerArray(array, flag);
            solution.output(array);
        }

    } 
}
全部评论
升序直接sort就可以 干嘛非要自定义Comparator
点赞 回复 分享
发布于 2024-04-15 18:38 陕西
写法很好,就是写复杂了。眼睛花了(◎﹏◎)
点赞 回复 分享
发布于 2022-09-19 21:55 江苏

相关推荐

06-17 00:26
门头沟学院 Java
程序员小白条:建议换下项目,智能 AI 旅游推荐平台:https://github.com/luoye6/vue3_tourism_frontend 智能 AI 校园二手交易平台:https://github.com/luoye6/vue3_trade_frontend GPT 智能图书馆:https://github.com/luoye6/Vue_BookManageSystem 选项目要选自己能掌握的,然后最好能自己拓展的,分布式这种尽量别去写,不然你只能背八股文了,另外实习的话要多投,尤其是学历不利的情况下,多找几段实习,最好公司title大一点的
无实习如何秋招上岸
点赞 评论 收藏
分享
风中翠竹:真的真的真的没有kpi。。。面试官是没有任何kpi的,捞是真的想试试看这个行不行,碰碰运气,或者是面试官比较闲现在,没事捞个人看看。kpi算HR那边,但是只有你入职了,kpi才作数,面试是没有的。
双非有机会进大厂吗
点赞 评论 收藏
分享
不愿透露姓名的神秘牛友
07-08 12:10
点赞 评论 收藏
分享
评论
28
6
分享

创作者周榜

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