WUSTOJ 1247: 递增或递减排序(Java)

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();
	}
}
原文地址:https://www.cnblogs.com/wowpH/p/11060792.html