如何在具有正值和负值的数组中找到最大的负值? [英] How do I find the largest negative value in an array with both positive and negative values?

查看:114
本文介绍了如何在具有正值和负值的数组中找到最大的负值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要返回最大的负值,如果没有负值,我需要返回零。
以下是我所拥有的:

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[] list) {


    for (int i = 0; i < list.length; i++) {


       if (list[i] < 0)
           negativeNumbers ++;
    }

    int j = list.length - 1;

    while (j >= 0) {
       if (list[j - negativeNumbers] < 0) {
        list[j] = 0;
        list[j - 1] = list[j - negativeNumbers];
        negativeNumbers--;
        j--;
       }
       else{
        list[j] = list[j - negativeNumbers];
        j--;
     }
  }

}


推荐答案

您只需要将此问题视为两个步骤:

You just need to think of this problem as 2 steps:


  1. 仅考虑list []中的负值。

  2. 在负值内的循环中,更新当前结果if(result == 0)或(value> result)。

代码:

public int greatestNegative(int[] list) {
    int result = 0;
    for (int i = 0; i < list.length; i++) {
        if (list[i] < 0) {
            if (result == 0 || list[i] > result) {
                result = list[i];
            }
        }
    }
    return result;
}

这篇关于如何在具有正值和负值的数组中找到最大的负值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆