1247: 递增或递减排序

题目

  有n个整数,求它的递增排序序列或递减排序序列。更多内容点击标题。

分析

  1. 统一升序排序,输出的时候做区分。
  2. 先区分是升序还是降序,调用库函数。

代码

  方法1,将数组升序排序,输出的时候,再看是升序还是降序。用Arrays.sort(int[],int,int)进行升序排序。

/**
* time 814ms
* @author wowpH
* @version A1.0
* @date 2019-05-10 上午10:09:02
* Environment: Windows 10
* IDE Version: Eclipse 2019-3
* JDK Version: JDK1.8.0_112
*/ import java.io.BufferedInputStream;
import java.util.Arrays;
import java.util.Scanner; public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(new BufferedInputStream(System.in));
int n, k, i;
int[] a = new int[100];
while (sc.hasNext()) {
n = sc.nextInt();
k = sc.nextInt();
for (i = 0; i < n; i++) {
a[i] = sc.nextInt();
}
Arrays.sort(a, 0, n); // 注意后面两个参数
if (1 == k) { // 升序
for (i = 0; i < n - 1; i++) {
System.out.print(a[i] + " ");
}
System.out.println(a[n - 1]);
} else { // 降序
for (i = n - 1; i > 0; i--) {
System.out.print(a[i] + " ");
}
System.out.println(a[0]);
}
}
sc.close();
}
}

  方法2,用Collections.reverseOrder()进行降序排序。

/**
* time 979ms
* @author wowpH
* @version A2.0
* @date 2019-05-10 上午11:19:49
* Environment: Windows 10
* IDE Version: Eclipse 2019-3
* JDK Version: JDK1.8.0_112
*/ import java.io.BufferedInputStream;
import java.util.Arrays;
import java.util.Collections;
import java.util.Scanner; public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(new BufferedInputStream(System.in));
int n, k;
Integer[] a = new Integer[100];
while (sc.hasNext()) {
n = sc.nextInt();
k = sc.nextInt();
for (int i = 0; i < n; i++) {
a[i] = sc.nextInt();
}
if (1 == k) { // 升序
Arrays.sort(a, 0, n);
} else { // 降序
Arrays.sort(a, 0, n, Collections.reverseOrder());
}
for (int i = 0; i < n - 1; i++) {
System.out.print(a[i] + " ");
}
System.out.println(a[n - 1]);
}
sc.close();
}
}

最新文章

  1. Solr 排除查询
  2. border边框的宽度/样式/颜色 全部值
  3. Entity Framework 第十篇 条件查询
  4. My Package
  5. TCP : two different sockets sharing a port?
  6. js设计模式-建造者模式
  7. Spring 3 整合Apache CXF WebService[转]
  8. CSS中的 REM PX EM
  9. android开发中防止刚进入activity时edittext获取焦点,自动弹出软键盘
  10. C_数据结构
  11. Pycharm直接连接Github
  12. XMPP(三)-安卓即时通讯客户端
  13. attr 和 prop的使用区别
  14. 百度GIS API使用
  15. CLR寄宿和AppDomain
  16. 大型运输行业实战_day07_2_数据字典实现
  17. CentOS 6.5 配置IP地址的三种方法
  18. git command cheat sheet
  19. so模块加载后数据问题
  20. python入门(四):标准输出和文件读写

热门文章

  1. Maven私服使用经验总结
  2. vue tab嵌入iframe切换不刷新,相对完整的方案
  3. 面试题小议---BY gremount
  4. Redis客户端多线程跟多个连接不是一回事
  5. 常用的xml头文件
  6. 制作A4纸打印的网页像素大小设置(转)
  7. python 设计模式之备忘录模式
  8. nginx里面的location 规则匹配
  9. 通过Redis的list来实现 Server - Client 的同步通信
  10. Expression: __acrt_first_block == header