检查int [] Java中的重复数字

时间:2011-06-05 06:04:27

标签: java sorting

我希望能够判断int []中的任何数字是否出现3次或更多次?我怎么能这样做?

拥有方法

会很棒
boolean hasTriples(int[] numbers) {

//some code

}

3 个答案:

答案 0 :(得分:7)

创建一个Map<Integer, Integer>,让整数 n 映射到 n 的出现次数。

循环遍历数组以填充地图,然后遍历地图中的键以检查哪些键映射到值> = 3。

以下是一些可以帮助您入门的代码:

int[] arr = { 1, 3, 2, 3, 3, 4, 2, 2 };
Map<Integer, Integer> counts = new HashMap<Integer, Integer>();

// Count occurrencies
for (int i : arr) {
    if (!counts.containsKey(i))
        counts.put(i, 0);
    counts.put(i, 1 + counts.get(i));
}

// Print how many times each number occurs in arr.
for (int i : counts.keySet())
    System.out.printf("i: %d, count: %d%n", i, counts.get(i));

答案 1 :(得分:4)

   public boolean anyRepeatThreeTimes( int [] array ) {
      Map<Integer, Integer > map = new HashMap<Integer, Integer>();
      for ( int index = 0; index < array.length; index++ ) {
         Integer total = map.get(array[ index ]);
         int count;
         if ( total == null ) {
            count = 1;
         }
         else {
            count = total + 1;
            if ( count >= 3 ) {
               return true;
            }
         }
         map.put( array[ index ], count );
      }

      return false;
   }

这是发生了什么:

  1. 您传入了一系列整数。
  2. 您可以将数组值的映射设置为值的计数。
  3. 你走了数组。对于数组中的每个整数:

    一个。检索该数组值的当前计数

    湾如果不存在值,则以值1

    开头

    ℃。如果地图中确实存在给定值的值,请向其中添加一个

    d。如果从地图+ 1中检索到的值超过了您的限制3,那么您已经证明数组中的值至少重复了三次。

  4. 如果你在循环结束时没有返回true,则返回false,因为没有值重复3次。

答案 2 :(得分:2)

这是一种不使用任何额外类(如Map类)的方法。它可能会更慢,但希望更容易理解。

public boolean hasTriples(int[] list) {
    for (int i = 0; i < list.length; i++){
        int duplicates = 0;

        for (int j = i+1; j < list.length; j++){
            if (list[i] == list[j]) {
                duplicates++;
                if (duplicates >= 3) return true;
            }
        }
    }
    return false;
}

以下是此代码的用途。外部for循环正在列表中运行,以确保检查每个值是否有重复项。内部循环遍历列表的记录,以检查有多少重复值。如果找到三个或更多重复项,则该函数将返回true,而不处理列表的其余部分。如果外部for循环完成而没有返回true的方法,则返回false,因为不能有任何三个重复。

希望这有帮助!