简体   繁体   English

输入4个数字时如何求和3个最高数字

[英]How can I sum 3 highest numbers when entered 4 numbers

I'm still learning how to use java, and I was wondering if there was a way to add the 3 highest numbers when a user inputs 4 numbers?我还在学习如何使用 java,我想知道是否有办法在用户输入 4 个数字时添加 3 个最高数字?

For Ex.对于前。 the user enters 5 6 7 6, they would add 6 7 6 which would be 19.用户输入 5 6 7 6,他们将添加 6 7 6,即 19。

The only idea I got was using and if else statement?我得到的唯一想法是使用 if else 语句? But I feel like that wouldn't be efficient in my code.但我觉得这在我的代码中效率不高。

Thanks in advanced提前致谢

Assuming an int array and there'll only ever be 4 numbers entered, the problem can actually be rephrased as getting a sum with the minimum element of the array removed.假设一个 int 数组并且只会输入 4 个数字,这个问题实际上可以重新表述为在删除数组的最小元素的情况下获得一个总和。 Not that it matters much at this size, sorting incurs an O(nlogn) cost.并不是说在这个大小上很重要,排序会产生 O(nlogn) 成本。 Instead, just do it linearly in one loop by finding the min and removing it at the end.相反,只需通过查找最小值并在最后将其删除,就可以在一个循环中线性地执行此操作。

int[] nums = { 5, 6, 7, 6 };
int min = Integer.MAX_VALUE;
int sum = 0;

for (int num : nums) {
    if (num < min) {
        min = num;
    }
    sum += num;
}

sum -= min;

System.out.println(sum);

use Array.sort使用 Array.sort

    int arr[] = {5,6,7,6};
    Arrays.sort(arr);
    int total = 0;
    for (int i = 3; i > 0; i--) // what a fool, it was the wrong way around
        total += arr[i];

    System.out.println(total);

Or you could use或者你可以使用

    Integer arr[] = {5,10, 10, 10};
    Arrays.sort(arr, Collections.reverseOrder());

and loop normally from 0 to 3并通常从 0 到 3 循环

I'd suggest you to first create a set and then sort.我建议你先创建一个集合,然后排序。 If you sort and sum, a test case such as如果你排序和求和,一个测试用例,比如

9, 5, 9, 7, 6, 2 will fail as the largest numbers in the array are 9,5,7 and after sorting you will only get 9,9,9 at the first three indices 9, 5, 9, 7, 6, 2 将失败,因为数组中的最大数字是 9,5,7 并且排序后你只会在前三个索引处得到 9,9,9

by creating a set (no repetition)通过创建一个集合(不重复)

The array would be 9,5,7,6,2 you can then sort it and sum the first three.该数组将是 9,5,7,6,2 然后您可以对其进行排序并对前三个求和。

store them in array.将它们存储在数组中。 sort the array.对数组进行排序。 sum up the last 3 elements i,e总结最后 3 个元素 i,e

int[] arr={7,8,5,2,1,4,5};
Arrays.sort(arr);
int sum = 0;
        for(int i=arr.length-1;i>=arr.length-3;i--) {
            sum += arr[i];
        }
        System.out.println(sum);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM