阵列怪癖中最小的数字

use*_*144 3 java arrays

我试图解决CodeWars上的一个问题,我发现数组中的数字最小.这是我目前的代码:

public class SmallestIntegerFinder {
public int findSmallestInt(int[] args){
    int smallest = args[0];
    for(int i=1; i < args.length; ++i){
        if(args[i] < args[0]){
            smallest = args[i];
        }
    }
    return smallest;
 }
}
Run Code Online (Sandbox Code Playgroud)

为什么这不起作用?但是,当我改变[0] ARGS,如果声明变量最小它的工作原理.这两者有什么区别?他们都指向args [0]不是吗?

public class SmallestIntegerFinder {
public int findSmallestInt(int[] args){
    int smallest = args[0];
    for(int i=1; i < args.length; ++i){
        if(args[i] < smallest){
            smallest = args[i];
        }
    }
    return smallest;
 }
}
Run Code Online (Sandbox Code Playgroud)

我正在使用的测试数组是:{78,56,232,12,11,43}

Ell*_*sch 6

因为args[0]是数组中的第一个元素,所以smallest 第一个元素开始 ; 它更新为下一个最小值(考虑3,1,2; 2小于3但1小于2).你也可以使用Math.min(int, int)

public int findSmallestInt(int[] args) {
    int smallest = args[0];
    for (int i = 1; i < args.length; ++i) {
        smallest = Math.min(smallest, args[i]);
    }
    return smallest;
}
Run Code Online (Sandbox Code Playgroud)