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

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

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

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Scanner;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        // 注意 hasNext 和 hasNextLine 的区别
        while (in.hasNext()) {
            int n = in.nextInt();
            Integer[] nums = new Integer[n];
            for (int i = 0 ; i < n ; ++i) {
                nums[i] = in.nextInt();
            }
            int sorts = in.nextInt();
            List<Integer> list = Arrays.asList(nums);
            if (sorts == 0) {
                Collections.sort(list);
            }
            else{
                Collections.sort(list, new Comparator<Integer>(){
                    public int compare(Integer a, Integer b){
                        return b-a;
                    }
                });
            }
            
            for(int i=0 ; i<list.size() ; ++i){
                System.out.print(list.get(i)+" ");
            }

        }
    }
}

全部评论

相关推荐

10-30 16:31
重庆大学 Java
代码飞升:你说你善于学习,大家都会说。你说你是985,985会替你表达一切
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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