如何找到数组中最大的负整数?

问题描述 投票:0回答:6

令 test12 = [-1, -2, -3];

我被这个问题困住了。 我在正整数上使用了下面的内容,但我不确定对负数要改变什么。

let test = [1 , 2, 3];

var largest= 0;

for (i=0; i<=test.length;i++){
    if (test[i]>largest) {
        largest=test[i];
    }
}
console.log(largest);

javascript arrays
6个回答
2
投票

数组中最大的负整数

您的问题可以有 3 种解释:

  1. 距离
    0
  2. 最远的负整数
  3. 最接近
    0
  4. 的负整数
  5. 一般最大的数字(如果出现全负整数数组,你可能会很困难,因为你将 min 初始化为 0)

澄清一下,最小是“离零最远”。但这是所有三种方法:) :

const ints = [-3, -2, -1, 0, 1, 2]

const negativeInts = ints.filter(i => i < 0)

const smallestNegative = Math.min(...negativeInts)
const largestNegative = Math.max(...negativeInts)
const largestOverall = Math.max(...ints)
console.log({smallestNegative, largestNegative, largestOverall}) // -3, -1, 2

希望这有帮助。干杯。


0
投票

只需将

largest
初始化为
-Infinity
而不是
0
。您还需要迭代输入数组的长度,而不是
0
largest
:

let test12 = [-1, -2, -3];
var largest = -Infinity;
for (i = 0; i < test12.length; i++) {
  if (test12[i] > largest) {
    var largest = test12[i];
  }
}
console.log(largest);

另一种方法是传播到

Math.max

let test12 = [-1, -2, -3];
console.log(
  Math.max(...test12)
);


0
投票

最大的负数是

-244
,因此您可以排序并获得第一个索引。

let arr = [-1, -2, -244, -7],
    [largets] = arr.slice().sort((a, b) => a - b);
console.log(largets);


0
投票

试试这个..

var array = [-155,3, 6, 2, 56, 32, 5, -89, -32,115,-150];
array.sort(function(a, b) {
  return a - b;
});
console.log(array[0]);


0
投票

如果您想要一个编程解决方案,例如即使给出全负数组,您的程序也需要执行编辑,那么请尝试以下操作:

let test = [-10, -1, -2, -3];
// just Assign largest to the first element in test.
// the largest int might not be greater than zero,
// but will definitely be larger that any other element in the array. 
var largest= test[0];

for (i=0; i<=test.length;i++){
    if (test[i]>largest) {
        largest=test[i];
    }
}
console.log(largest);


0
投票

public static void main(String[] args) {

    int[] arr = {1, 2, -7, 4, 62, 2, 5};
    System.out.println(maxAbs(arr));
}
public static int maxAbs(int[] arr) {

  //  public int greatestNegative(int[] list) {
        int max = 0;
        for (int i = 0; i < arr.length; i++) {
            if (arr[i] < 0) {
                if (max == 0 || arr[i] > max) {
                    max = arr[i];
                }
            }
        }
        return max;
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.