华为机试-HJ3 明明的随机数

274 阅读1分钟

题目

image.png

www.nowcoder.com/practice/32…

我的题解

import java.util.*;
import java.util.stream.*;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int length = sc.nextInt();
        Set<Integer> set = new HashSet();
        for (int i = 0; i < length; i++) {
            set.add( sc.nextInt());
        }
        set.stream().sorted(Comparator.naturalOrder()).forEach(a ->
                System.out.println(a));
    }
}

image.png

我的题解-改进版

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Comparator;
import java.util.HashSet;
import java.util.Set;

public class Main {
    public static void main(String[] args) throws IOException {
        BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
        int count = Integer.parseInt(bf.readLine());
        Set<Integer> set = new HashSet();
        for (int i = 0; i < count; i++) {
            set.add(Integer.parseInt(bf.readLine()));
        }
        set.stream().sorted(Comparator.naturalOrder()).forEach(a ->
            System.out.println(a));
    }
}

image.png

高效题解

public static void main(String[] args) throws IOException {
    BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
    String str;
    while ((str = bf.readLine()) != null) {
        int totalTime = Integer.parseInt(str);
        boolean[] stu = new boolean[1001];
        for (int i = 0; i < totalTime; i++) {
            stu[Integer.parseInt(bf.readLine())] = true;
        }
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < 1001; i++) {
            if (stu[i]) {
                sb.append(i).append("\n");
            }
        }
        sb.deleteCharAt(sb.length() - 1);
        System.out.println(sb);
    }
}

image.png

总结:

1、while ((str = bf.readLine()) != null)

if ((str = bf.readLine()) != null) 都可以、只不过一直死循环、一个执行一次、而且执行完要记得执行br.close();

2、(str = bf.readLine()) != null 控制台好像永远无法读到null

3、这个思路很厉害、和map的key、set的用法异曲同工、但是效率高很、而且自动排好序了、去重排序合二为一了

boolean[] stu = new boolean[1001];
for (int i = 0; i < totalTime; i++) {
    stu[Integer.parseInt(bf.readLine())] = true;
}

image.png

4、注意要求1000个数、boolean[] stu = new boolean[1001];定义为1001个,因为按照下标方式的话为1-1000、下标1000就对应这第1001这个元素;

5、拼接字符串时去掉最后多余连接符的经典操作

StringBuilder sb = new StringBuilder();
for (int i = 0; i < 1001; i++) {
    if (stu[i]) {
        sb.append(i).append("\n");
    }
}
sb.deleteCharAt(sb.length() - 1);

image.png

image.png