博客
关于我
杭电oj 2020 绝对值排序 (Java)(注意换行符在oj上的特别要求)
阅读量:377 次
发布时间:2019-03-05

本文共 1045 字,大约阅读时间需要 3 分钟。

为了解决这个问题,我们需要对给定的整数按照绝对值从大到小进行排序。每个测试实例的输入包括一个整数n,接着是n个整数。当n为0时,输入结束。

方法思路

  • 读取输入:使用Scanner读取输入数据。每行的第一个数字是n,接着是n个整数。当n为0时,输入结束。
  • 排序:对每组数据进行排序,按照绝对值从大到小的顺序排列。可以使用Java的Arrays.sort()方法,并提供一个自定义的比较器来比较两个数的绝对值。
  • 输出结果:输出排序后的结果,每个数之间用空格隔开,每行一组。
  • 解决代码

    import java.util.Scanner;import java.util.Arrays;public class Main {    public static void main(String[] args) {        Scanner input = new Scanner(System.in);        int n;        while (true) {            n = input.nextInt();            if (n == 0) break;            int[] arr = new int[n];            for (int i = 0; i < n; i++) {                arr[i] = input.nextInt();            }            Arrays.sort(arr, (a, b) -> Integer.compare(Math.abs(b), Math.abs(a)));            for (int num : arr) {                System.out.print(num + " ");            }            System.out.println();        }    }}

    代码解释

  • 读取输入:使用Scanner读取输入数据。循环读取每行的数据,直到n为0时结束输入。
  • 存储输入数据:将读取的整数存储到数组arr中。
  • 排序:使用Arrays.sort()方法对数组进行排序,自定义比较器确保按绝对值从大到小排序。
  • 输出结果:遍历排序后的数组,将每个数打印出来,元素之间用空格隔开,每行输出一组数据。
  • 这种方法确保了我们能够高效地读取输入、排序和输出结果,满足题目要求。

    转载地址:http://crpg.baihongyu.com/

    你可能感兴趣的文章
    Notadd —— 基于 nest.js 的微服务开发框架
    查看>>
    NOTE:rfc5766-turn-server
    查看>>
    Notepad ++ 安装与配置教程(非常详细)从零基础入门到精通,看完这一篇就够了
    查看>>
    Notepad++在线和离线安装JSON格式化插件
    查看>>
    notepad++最详情汇总
    查看>>
    notepad++正则表达式替换字符串详解
    查看>>
    notepad如何自动对齐_notepad++怎么自动排版
    查看>>
    Notes on Paul Irish's "Things I learned from the jQuery source" casts
    查看>>
    Notification 使用详解(很全
    查看>>
    NotImplementedError: Cannot copy out of meta tensor; no data! Please use torch.nn.Module.to_empty()
    查看>>
    NotImplementedError: Could not run torchvision::nms
    查看>>
    nova基于ubs机制扩展scheduler-filter
    查看>>
    Now trying to drop the old temporary tablespace, the session hangs.
    查看>>
    nowcoder—Beauty of Trees
    查看>>
    np.arange()和np.linspace()绘制logistic回归图像时得到不同的结果?
    查看>>
    np.power的使用
    查看>>
    NPM 2FA双重认证的设置方法
    查看>>
    npm build报错Cannot find module ‘webpack/lib/rules/BasicEffectRulePlugin‘解决方法
    查看>>
    npm build报错Cannot find module ‘webpack‘解决方法
    查看>>
    npm ERR! ERESOLVE could not resolve报错
    查看>>