在二维数组寻找重复INT [英] Finding duplicate INT in 2D array

查看:102
本文介绍了在二维数组寻找重复INT的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我卡在此方法。

public class Duplicate{


   public static boolean extra(int [][] grid)
   {
       for(int i = 0; i < grid.length; i++)
           for(int j = 0; j < grid[i].length-1; j++)
              if(grid[i][j] == grid[i][j+1])
              {
                  System.out.println(grid[i][j]);
                  return true;
              }
    return false;
   }

   public static void main(String[] args){

      int [][] grades = {{3,5,8,7},
                        {2,1,11,4},
                       {13,20,10,6},
                        {7,0,12,15}
                       };

       System.out.print(extra(grades));   
   }
 }

我要寻找是否有数组中的任何重复的整数。如果有,并且被复制的INT返回true。我的方法不断现身FALSE。我究竟做错了什么?任何帮助将是AP preciated。请和谢谢你。

I want to find if there are any duplicated ints in the array. return true if there is and the int that is duplicated. My method keeps coming out FALSE. what am I doing wrong? Any help would be appreciated. Please and thank you.

推荐答案

您所有的方法做的,如果连续两个元素是平等的,不告诉你不相邻重复任何正在检查。这样做的一个方法是有一个地图&LT;整数,整数GT; ,该值映射到它们的频率:

All your method is doing is checking if two consecutive elements are equal, which does not tell you anything about duplicates that are not adjacent. One way to do this would be to have a Map<Integer, Integer> that maps the values to their frequencies:

Map<Integer, Integer> map = new HashMap<>();

for (int[] row : grid) {
    for (int a : row) {
        map.put(a, map.containsKey(a) ? map.get(a) + 1 : 1);
    }
}

可以再循环移到该地图的条目找到元件具有大于或等于2的频率。

You can then loop over the entries of this map to find the elements with a frequency greater than or equal to 2.

这篇关于在二维数组寻找重复INT的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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