WUSTOJ 1247: 递增或递减排序(Java)
2024-08-27 12:29:46
1247: 递增或递减排序
题目
有n个整数,求它的递增排序序列或递减排序序列。更多内容点击标题。
分析
- 统一升序排序,输出的时候做区分。
- 先区分是升序还是降序,调用库函数。
代码
方法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();
}
}
最新文章
- Solr 排除查询
- border边框的宽度/样式/颜色 全部值
- Entity Framework 第十篇 条件查询
- My Package
- TCP : two different sockets sharing a port?
- js设计模式-建造者模式
- Spring 3 整合Apache CXF WebService[转]
- CSS中的 REM PX EM
- android开发中防止刚进入activity时edittext获取焦点,自动弹出软键盘
- C_数据结构
- Pycharm直接连接Github
- XMPP(三)-安卓即时通讯客户端
- attr 和 prop的使用区别
- 百度GIS API使用
- CLR寄宿和AppDomain
- 大型运输行业实战_day07_2_数据字典实现
- CentOS 6.5 配置IP地址的三种方法
- git command cheat sheet
- so模块加载后数据问题
- python入门(四):标准输出和文件读写