知识库 知识库
首页
  • Hyperskill - Java

    • Java basic
    • Java OOP
    • 应知
    • 扩展
    • IO & Stream
    • Error & Exception
    • Algorithm & Data structure
    • Design pattern
    • Web
    • Spring boot
  • 练习题

    • 选择题 & 填空题
    • 代码题
  • Frank - Java与生活 (OOP)

    • 参考资料
    • Java基础
    • OOP上半部分
    • OOP下半部分
  • Frank - Java API进阶

    • Base API
    • Unit Test and main function
  • 学习笔记
  • 学习笔记

    • 数据库
  • Frank - MySQL删库跑路

    • 安装、连接、配置
    • 基本操作——数据库
    • 基本操作——表
    • 基本操作——数据
    • 数据类型
    • 列属性完整性
    • 数据库设计思维
    • 单表查询
    • 多表查询
  • 学习笔记

    • 其它
  • Frank - Linux现代方法

    • 必知
    • 命令
    • 技巧
  • 技术文档
  • Git
  • GitHub技巧
  • 前端
  • Khan Academy - 语法
  • Monthly
  • 阅读
  • Others
  • 学习
  • 面试
  • 心情杂货
  • 实用技巧
  • 友情链接
收藏
  • 标签
  • 归档
GitHub (opens new window)

Jim FuckPPT

Java小学生
首页
  • Hyperskill - Java

    • Java basic
    • Java OOP
    • 应知
    • 扩展
    • IO & Stream
    • Error & Exception
    • Algorithm & Data structure
    • Design pattern
    • Web
    • Spring boot
  • 练习题

    • 选择题 & 填空题
    • 代码题
  • Frank - Java与生活 (OOP)

    • 参考资料
    • Java基础
    • OOP上半部分
    • OOP下半部分
  • Frank - Java API进阶

    • Base API
    • Unit Test and main function
  • 学习笔记
  • 学习笔记

    • 数据库
  • Frank - MySQL删库跑路

    • 安装、连接、配置
    • 基本操作——数据库
    • 基本操作——表
    • 基本操作——数据
    • 数据类型
    • 列属性完整性
    • 数据库设计思维
    • 单表查询
    • 多表查询
  • 学习笔记

    • 其它
  • Frank - Linux现代方法

    • 必知
    • 命令
    • 技巧
  • 技术文档
  • Git
  • GitHub技巧
  • 前端
  • Khan Academy - 语法
  • Monthly
  • 阅读
  • Others
  • 学习
  • 面试
  • 心情杂货
  • 实用技巧
  • 友情链接
收藏
  • 标签
  • 归档
GitHub (opens new window)
  • Hyperskill - Java

  • 练习题

    • 选择题 & 填空题

    • 代码题

      • Boxes
      • The longest ascending sequence
      • Right Rotation
      • Book
      • Compact strings with AsciiCharSequence
      • Cinema
      • Calculate square
      • Count words
      • Robot control
      • Concat all strings without digits
      • Find the nearest number
        • Topic
        • Problem
        • Hint & Explain
        • Solution
          • My solution
          • Other solution 1
          • Other solution 2
          • Other solution 3
          • Other solution 4
      • Leaderboard
      • Split a list into sublists
      • Arithmetic average
      • Processing strings
  • Frank - Java与生活

  • Frank - Java API进阶

  • 学习笔记

  • Java
  • 练习题
  • 代码题
Jim
2022-10-04
目录

Find the nearest number

# Topic

ArrayList

# Problem

Find the nearest number

Write a program that finds the elements in an array of integers that are closest to a given integer. If you find several integers with the same distance to the N, you should output all of them in the ascending order. If there are several equal numbers, output them all.

Input: a set of integers and a number N.

Output: some number(s) from the given array.

Sample Input 1:

1 2 4 5
3
1
2

Sample Output 1:

2 4
1

Sample Input 2:

1 2 3 4
6
1
2

Sample Output 2:

4
1

Sample Input 3:

5 1 3 3 1 5
4
1
2

Sample Output 3:

3 3 5 5
1

# Hint & Explain

You need to use methods we haven't been taught (in my opinion, this makes this a bad problem), you should use Collections.sort() which sorts a collection, and also Math.abs(a) which returns absolute value of a (if it is positive, it is the same, if it is negative it becomes the positive equivalent).

We were also not taught how to approach a complicated problem like this, it is not good to just throw us into this with only the advanced users already understanding what they need to do, lastly there was some poor wording in the question, especially with the word "distance". I would recommend either avoiding problems like this or teaching us everything we need to understand before giving it to us, it took me a long time to figure out a lot of this because I had to learn on my own, go scrambling around the internet to understand the necessary information when it could have been taught in a topic.

That is relatively complex task, not trivial at least. Good thing is however you can split it to several trivial task and implement them one after another.

  • input data: you've got a line of integers and yet another one in a separate line. Get the first line as a string, split it by spaces to array, get from each sub-string an integer and put it in int[] array or ArrayList or any storage of your preference. Just get the number N on the next line.
  • distance: means you need to find a minimal distance between N and numbers in array. It could be 0 or anything. Trick here if you just get the difference between number in array and N it could be positive or negative, depends from what side number is closer to N. Somehow you need to get rid off the sign, the absolute value you are interested in.
  • find all nearest numbers: you have your distance, find all numbers in array with exactly this distance from N and store them some were, ArrayList wouldn't be overkill here.
  • sort and output: task requires output in ascending order, just sort and print your favorite way

Neither of this sub task requires you to know what you haven't taught yet till that point. If you lazy enough to write your own abs() function here, use Math.abs() instead - it is proven to work since Java's childhood )

Useful link: https://stackoverflow.com/questions/1187352/find-closest-value-in-an-ordered-list

# Solution

# My solution

// I don't even have the capacity to solve this problem
1

# Other solution 1

import java.util.*;

public class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        String[] items = scanner.nextLine().split("\\s+");
        List<Integer> numbers = new ArrayList<>();

        for (String item : items) {
            numbers.add(Integer.parseInt(item));
        }

        int n = scanner.nextInt();
        ArrayList<Integer> result = new ArrayList<>();

        int delta = Integer.MAX_VALUE;
        for (int i : numbers) {
            if (Math.abs(i - n) < delta) {
                delta = Math.abs(i - n);
                result.clear();
                result.add(i);
            } else if (Math.abs(i - n) == delta) {
                result.add(i);
            }
        }

        Collections.sort(result);

        for (int item : result) {
            System.out.print(item + " ");
        }
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34

# Other solution 2

import java.util.ArrayList;
import java.util.Collections;
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        var list = new ArrayList<Integer>();
        while (scanner.hasNextInt()) {
            list.add(scanner.nextInt());
        }
        var n = list.remove(list.size() - 1);
        Collections.sort(list);
        var closest = Integer.MAX_VALUE;
        for (Integer element : list) {
            if (Math.abs(n - element) < closest) {
                closest = Math.abs(n - element);
            }
        }
        for (Integer element : list) {
            if (Math.abs(n - element) == closest) {
                System.out.print(element + " ");
            }
        }
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26

# Other solution 3

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

public class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        String line = scanner.nextLine();
        String[] numbers = line.split("\\s+");
        List<Integer> nums = Arrays.stream(numbers).map(Integer::parseInt).sorted().collect(Collectors.toList());
        int minimumDistance = Integer.MAX_VALUE;
        int reference = scanner.nextInt();
        for (int num: nums) {
            int distance = Math.abs(num - reference);
            if (distance < minimumDistance) {
                minimumDistance = distance;
            }
        }
        for (int num: nums) {
            if (Math.abs(num - reference) == minimumDistance) {
                System.out.print(num + " ");
            }
        }

    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25

# Other solution 4

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

public class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        List<Integer> arrayNumber = Arrays.stream(scanner.nextLine().split(" "))
                .map(Integer::parseInt)
                .sorted()
                .collect(Collectors.toList());

        int n = scanner.nextInt();
        int minDistance = arrayNumber.stream().mapToInt(e -> Math.abs(n - e)).min().orElseThrow();

        arrayNumber.stream()
            .filter(e -> Math.abs(n - e) == minDistance)
            .forEach(e -> System.out.printf("%d ", e));
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
编辑 (opens new window)
上次更新: 2022/10/04, 21:45:45
Concat all strings without digits
Leaderboard

← Concat all strings without digits Leaderboard→

最近更新
01
《挪威的森林》
04-14
02
青钢影
04-14
03
Processing strings
02-18
更多文章>
Theme by Vdoing | Copyright © 2022-2023 Jim Frank | MIT License
  • 跟随系统
  • 浅色模式
  • 深色模式
  • 阅读模式