Arrays.asList() of an array

后端 未结 9 829
我寻月下人不归
我寻月下人不归 2020-11-27 15:41

What is wrong with this conversion?

public int getTheNumber(int[] factors) {
    ArrayList f = new ArrayList(Arrays.asList(factors));  
    Co         


        
9条回答
  •  没有蜡笔的小新
    2020-11-27 16:33

    Use java.utils.Arrays:

    public int getTheNumber(int[] factors) {
        int[] f = (int[])factors.clone();
        Arrays.sort(f);
        return f[0]*f[(f.length-1];
    }
    

    Or if you want to be efficient avoid all the object allocation just actually do the work:

    public static int getTheNumber(int[] array) {
        if (array.length == 0)
            throw new IllegalArgumentException();
        int min = array[0];
        int max = array[0];
        for (int i = 1; i< array.length;++i) {
            int v = array[i];
            if (v < min) {
                min = v;
            } else if (v > max) {
                max = v;
            }
        }
        return min * max;
    }
    

提交回复
热议问题