How do I find the largest negative value in an array with both positive and negative values?

前端 未结 7 1239
無奈伤痛
無奈伤痛 2021-01-29 15:43

I need to return the greatest negative value, and if there are no negative values, I need to return zero. Here is what I have:

public int greatestNegative(int[]          


        
7条回答
  •  遇见更好的自我
    2021-01-29 16:14

    Start by setting your "maxNegative" value to 0. Then assign the first negative number you come across. After that, only assign negative numbers that are higher. If there are no negative numbers, then your "maxNegative" will still be zero.

    public static void main(String[] args) {
        int arr[] = {2, -1, 4, 1, 0, 7, 2, -3, 5, 9, -4, 5, -9};
        int maxNegative = 0;
        for (int i = 0; i < arr.length; i++) {
            if (maxNegative == 0 && arr[i] < maxNegative) {
                // Set the first negative number you come across
                maxNegative = arr[i];
            } else if (maxNegative < arr[i] && arr[i] < 0) {
                // Set greater negative numbers
                maxNegative = arr[i];
            }
        }
        System.out.println(maxNegative);
    }
    

    Results:

    -1
    

    Java 8

    Then there are streams, that allow you to do this with one line of code.

    public static void main(String[] args) {
        int arr[] = {2, 4, 1, 0, 7, 2, -3, 5, 9, -4, 5, -9};
        int maxNegative = Arrays.stream(arr).filter(a -> a < 0).max().orElse(0);
        System.out.println(maxNegative);
    }
    

    Results:

    -3
    

提交回复
热议问题