【问题标题】:Sort array of negative integers and find pair of Larger integer irrespective of sign对负整数数组进行排序并找到一对较大的整数,而不考虑符号
【发布时间】:2017-10-27 08:09:12
【问题描述】:

我有一个整数数组,如下面的代码所示。我必须在数组中找到一对最大的数字。但有一个小转折。

请看下面的代码和输出。

public class ArraySort {

public static void main(String[] args) {
    // TODO Auto-generated method stub

    int[] a = { -9, -2, -10, -1, -4 };
    int[] b = null;
    int n = a.length;
    int temp = 0;
    int k = 0;
    for (int i = 0; i < n; i++) {
        for (int j = i + 1; j < n; j++) {
            if (a[i] > a[j]) {
                temp = a[i];
                a[i] = a[j];
                a[j] = temp;
            }
        }
    }
    System.out.println("Ascending Order:");
    for (int i = 0; i < n; i++) {
        System.out.print(a[i] + ",");
    }

    System.out.println("\nPair of larger numbers");

    for (int i = 0; i < n; i++) {
        if (k < 2) {
            if (a[i] > a[n - 1 - i]) {
                System.out.println(a[i]);

            } else {
                System.out.println(a[n-1-i]);
            }
        }
        k++;
    }
  }

}

其输出显示为

Ascending Order:

-10,-9,-4,-2,-1, 一对更大的数字 -1 -2

但不是将最大的数字显示为-1,-2。我必须显示-10和-9。即使数组包含负值,比较也应该没有减号。

【问题讨论】:

  • 使用Math.abs(...)获取绝对值
  • 不使用 Math.abs() 方法有什么办法吗?
  • 然后取较小的值......你说你只有负值。 我投票结束,因为这个问题不太可能在未来帮助某人
  • 请解释一下你对Math.abs()的看法。
  • a[i] = a[i] &lt; 0 ? -a[i] : a[i];

标签: java arrays core


【解决方案1】:

只需添加:

for(int i = 0; i < a.length; i++){
   a[i] = Math.abs(a[i]);
}

这会将数字转换为正数。或者您可以按照 JF 所说的进行。但如果其中一些是积极的,这种方法就行不通。

【讨论】:

    【解决方案2】:

    如果你所有的整数都是负数,为什么不只显示最小的两个整数?

    【讨论】:

    • 实际上我可能会在同一个数组中包含一些正数。那个时候它也应该无缝地工作......
    【解决方案3】:

    为了使任务有意义(“困难”),数组应该同时包含负数和正数。

    绝对个最大数的候选者位于数组的开头或结尾:

    -13a, -7, -3, -2, -1, 9, 10b
    -10b, -7, -3, -2, -1, 9, 13a
    -13a, -11b, -3, -2, -1, 9, 10
    -8, -7, -3, -2, -1, 9b, 13a
    

    所以你可能在一个循环中有两个索引,一个从开始,一个从结束。没有重叠(对于 -2、4)。

    因为这是家庭作业,祝你好运。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-04-11
      • 1970-01-01
      • 1970-01-01
      • 2018-06-06
      • 1970-01-01
      • 1970-01-01
      • 2021-06-23
      相关资源
      最近更新 更多