【问题标题】:Is it possible to check this way, that all elements in 2d Array are the same?是否可以通过这种方式检查 2d 数组中的所有元素是否相同?
【发布时间】:2020-05-05 06:13:43
【问题描述】:

所以我用谷歌搜索了这个问题。只有这个来自 StackOF 的链接出现了。 The question is ~4 years old.

我发现我的解决方案相当简单,但没有人写过,这有意义吗?

代码如下:

public boolean areAllTheSame(int[][] image) {

    // Create a new set, so we can store our unique elems there.
    Set<Integer> set = new HashSet<>();

    //Iterate through all elements, add to our HashSet set
    for (int[] ints : image) {
        for (int anInt : ints) {
            set.add(anInt);
        }
    }
    // Because set has only unique elements, if all are the same => size should be 1

    return set.size() == 1;
} // end of areAllTheSame

【问题讨论】:

    标签: java arrays multidimensional-array 2d


    【解决方案1】:

    怎么样:

    public boolean areAllTheSame(int[][] image) {
      // assuming `image` >= 1x1 pixels
    
      int expectedPixel = image[0][0];
    
      for (int[] pixels: image)
        for (int pixel: pixels)
          if(pixel != expectedPixel)
            return false;
    
      return true;
    }
    

    一旦知道数组不统一,它就会停止循环,并且不需要分配HashSet&lt;Integer&gt;

    【讨论】:

      【解决方案2】:

      我认为还有更多方法,其中之一是使用 java 流:

      public boolean areAllTheSame(int[][] image) {
          return Arrays.stream(image)
                  .flatMapToInt(Arrays::stream)
                  .distinct()
                  .count() == 1;
      }
      

      【讨论】:

      • 第二个和第三个例子不对,因为它们只检查是否相等,而不是单个像素。
      • @Louis-JacobLebel 完全没有,我使用的是Arrays.equals(first, a),它采用两个数组并比较它们是否相等
      • 如果我没记错的话,Arrays.equals(a, b) 会同时遍历两个数组并检查是否有a[0] == b[0]a[1] == b[1] 等等,但a[0] 可能与b[1] 不同.
      • @Louis-JacobLebel 对于第二种解决方案,您也可以像这样解决它public static boolean areAllTheSame2(int[][] image) { int[] first = image[0]; return new HashSet&lt;&gt;(Arrays.asList(first)).size() == 1 &amp;&amp; Arrays.stream(image).allMatch(a -&gt; Arrays.equals(first, a)); }
      • @Louis-JacobLebel 是的,您可以使用 !Arrays.stream(image).anyMatch(a -&gt; !Arrays.equals(first, a));
      【解决方案3】:

      看起来效率很低,如果你想检查一个多维数组是否只包含一个元素,你可以只取第一个元素,然后将它与所有其他数字进行比较,如果一个不匹配,则返回 false

      【讨论】:

      • @LostPuppy 你真的认为我是在他发表评论后写的吗?当我回答时没有 cmets
      猜你喜欢
      • 1970-01-01
      • 2011-01-19
      • 2015-02-12
      • 2018-05-13
      • 2011-04-20
      • 2012-05-04
      • 2014-12-27
      • 2022-06-23
      • 1970-01-01
      相关资源
      最近更新 更多