删除数组中的最小和Java的值

时间:2017-12-12 16:16:39

标签: java arrays sum minimum

我正在尝试构建一个Java程序,通过取出一个可能重复的元素来找到数组的最小值。以下是我的代码。

// Don't place your source in a package
import java.util.*;
import java.lang.*;
import java.io.*;

// Please name your class Main
class Main {
    public static void main (String[] args) throws java.lang.Exception {
        Scanner in = new Scanner(System.in);
        int N = in.nextInt();
        int[] elements = new int[N];
        for (int i = 0; i < N; i++){
            elements[i] = in.nextInt();
        }
        int counter = 1001;
        for (int c = 0; c < elements.length; c++){
            if (sum(elements, c) <= counter){
                counter = sum(elements, c);
            }
        }
        System.out.print(counter);

    }
    public static int sum (int[] e, int n){
        for (int j = 0; j<e.length; j++){
            if (e[j] == n){
                e[j] = 0;
            }
        }
        int sum = 0;
        for (int x: e){
            sum+=x;
        }
        return sum;
    }
}

我觉得我犯了一个简单的错误,但我花了好几个小时查看代码。感谢

1 个答案:

答案 0 :(得分:0)

假设您只想删除单个元素并且可能有一个元素重复多次,那么您需要将主循环更改为:

int counter = Integer.MAX_VALUE;
for (int c = 0; c < elements.length; c++) {
    counter = Math.min(counter, sum(elements, c));
}

这只为每个元素调用一次。