在一个整数数组中计算重复元素的个数

5
我有一个整数数组,我想要计算重复出现的元素。首先,我读取数组的大小,并从控制台读取数字进行初始化。在数组中,我存储重复的元素。数组存储元素连续出现的次数。然后,我尝试搜索重复序列并以特定格式打印它们。然而,这并没有起作用。
// Get integer array size
Scanner input = new Scanner(System.in);
System.out.println("Enter array size: ");
int size = input.nextInt();

int[] crr_array = new int[size];
int[] new_array= new int[size];
int[] times = new int[size];

// Read integers from the console
System.out.println("Enter array elements: ");
for (int i = 0; i < crr_array.length; i++) {
    crr_array[i] = input.nextInt();
    times[i] = 1;
}

// Search for repeated elements
for (int j = 0; j < crr_array.length; j++) {
    for (int i = j; i < crr_array.length; i++) {
        if (crr_array[j] == crr_array[i] && j != i) {
            new_array[i] = crr_array[i];
            times[i]++;
        }
    }
}



//Printing output
for (int i = 0; i <  new_array.length; i++) {
    System.out.println("\t" + crr_array[i] + "\t" +  new_array[i] + "\t" + times[i]);

}

我希望输出的结果看起来像这样:
There are <count_of_repeated_element_sequences> repeated numbers 
<repeated_element>: <count> times
...

例如:

There are 3 repeated numbers:
22: 2 times
4: 3 times
1: 2 times

如何找到重复的元素及其计数?如何按照上述所示打印它们?

你的输入数组在哪里? - Makky
13个回答

12

这种问题可以通过使用字典(Java中的HashMap)轻松解决。

  // The solution itself 
  HashMap<Integer, Integer> repetitions = new HashMap<Integer, Integer>();

  for (int i = 0; i < crr_array.length; ++i) {
      int item = crr_array[i];

      if (repetitions.containsKey(item))
          repetitions.put(item, repetitions.get(item) + 1);
      else
          repetitions.put(item, 1);
  }

  // Now let's print the repetitions out
  StringBuilder sb = new StringBuilder();

  int overAllCount = 0;

  for (Map.Entry<Integer, Integer> e : repetitions.entrySet()) {
      if (e.getValue() > 1) {
          overAllCount += 1;

          sb.append("\n");
          sb.append(e.getKey());
          sb.append(": ");
          sb.append(e.getValue());
          sb.append(" times");
      }
  }

  if (overAllCount > 0) {
      sb.insert(0, " repeated numbers:");
      sb.insert(0, overAllCount);
      sb.insert(0, "There are ");
  }

  System.out.print(sb.toString());

1
我想只使用基础知识,如果您可以在不使用Java类的情况下帮助我,这将是帮大忙了。 - Hany Moh.
再次感谢您。我尝试了这样做 //////////请问我该如何发送给您,以便您可以查看代码?由于评论框不允许粘贴代码,我无法将代码直接发送给您。 - Hany Moh.
您真是个天才,那篇文章对我的作业帮助很大。非常感谢您。 - Arpit Patel

6
如果您有一些可能的值集,则可以使用像计数排序这样的东西。
如果没有,那么您必须使用另一种数据结构,比如一个字典,在Java中是一个Map
int[] array
Map<Integer, Integer> 

其中Key = 数组值,例如array[i],而Value = 计数器

示例:

int[] array = new int [50];
Map<Integer,Integer> counterMap = new HashMap<>();

//fill the array

    for(int i=0;i<array.length;i++){
         if(counterMap.containsKey(array[i])){
          counterMap.put(array[i], counterMap.get(array[i])+1 );
         }else{
          counterMap.put(array[i], 1);
         }
    }

我想只使用基础知识,希望你能在不使用Java类的情况下帮助我。 - Hany Moh.

2
public class DuplicationNoInArray {

    /**
     * @param args
     *            the command line arguments
     */
    public static void main(String[] args) throws Exception {
        int[] arr = { 1, 2, 3, 4, 5, 1, 2, 8 };
        int[] result = new int[10];
        int counter = 0, count = 0;
        for (int i = 0; i < arr.length; i++) {
            boolean isDistinct = false;
            for (int j = 0; j < i; j++) {
                if (arr[i] == arr[j]) {
                    isDistinct = true;
                    break;
                }
            }
            if (!isDistinct) {
                result[counter++] = arr[i];
            }
        }
        for (int i = 0; i < counter; i++) {
            count = 0;
            for (int j = 0; j < arr.length; j++) {
                if (result[i] == arr[j]) {
                    count++;
                }

            }
            System.out.println(result[i] + " = " + count);

        }
    }
}

1

私有的静态方法 getRepeatedNumbers() {

    int [] numArray = {2,5,3,8,1,2,8,3,3,1,5,7,8,12,134};
    Set<Integer> nums = new HashSet<Integer>();
    
    for (int i =0; i<numArray.length; i++) {
        if(nums.contains(numArray[i]))
            continue;
            int count =1;
            for (int j = i+1; j < numArray.length; j++) {
                if(numArray[i] == numArray[j]) {
                    count++;
                }
                    
            }
            System.out.println("The "+numArray[i]+ " is repeated "+count+" times.");
            nums.add(numArray[i]);
        }
    }
    

你需要为这段代码运行一个测试,因为continue;之后的代码是无法到达的,所以它似乎没有产生任何结果。 - Nowhere Man

0
package jaa.stu.com.wordgame;

/**
 * Created by AnandG on 3/14/2016.
 */
public final class NumberMath {
    public static boolean isContainDistinct(int[] arr) {

        boolean isDistinct = true;
        for (int i = 0; i < arr.length; i++)

        {

            for (int j = 0; j < arr.length; j++) {
                if (arr[i] == arr[j] && i!=j) {
                    isDistinct = false;
                    break;
                }
            }

        }
        return isDistinct;
    }
    public static boolean isContainDistinct(float[] arr) {

        boolean isDistinct = true;
        for (int i = 0; i < arr.length; i++)

        {

            for (int j = 0; j < arr.length; j++) {
                if (arr[i] == arr[j] && i!=j) {
                    isDistinct = false;
                    break;
                }
            }

        }
        return isDistinct;
    }
    public static boolean isContainDistinct(char[] arr) {

        boolean isDistinct = true;
        for (int i = 0; i < arr.length; i++)

        {

            for (int j = 0; j < arr.length; j++) {
                if (arr[i] == arr[j] && i!=j) {
                    isDistinct = false;
                    break;
                }
            }

        }
        return isDistinct;
    }
    public static boolean isContainDistinct(String[] arr) {

        boolean isDistinct = true;
        for (int i = 0; i < arr.length; i++)

        {

            for (int j = 0; j < arr.length; j++) {
                if (arr[i] == arr[j] && i!=j) {
                    isDistinct = false;
                    break;
                }
            }

        }
        return isDistinct;
    }
    public static int[] NumberofRepeat(int[] arr) {

        int[] repCount= new int[arr.length];
        for (int i = 0; i < arr.length; i++)

        {

            for (int j = 0; j < arr.length; j++) {
                if (arr[i] == arr[j] ) {
                    repCount[i]+=1;
                }
            }

        }
        return repCount;
    }
}


call  by NumberMath.isContainDistinct(array) for find is it contains repeat or not

调用 int[] repeat=NumberMath.NumberofRepeat(array) 来查找重复次数。每个位置包含数组对应值的重复次数...


0
public static void main(String[] args) {
    Scanner input=new Scanner(System.in);
    int[] numbers=new int[5];
    String x=null;
    System.out.print("enter the number 10:"+"/n");
    for(int i=0;i<5;i++){
        numbers[i] = input.nextInt();
    }
    System.out.print("Numbers  :  count"+"\n");
    int count=1;
    Arrays.sort(numbers);
    for(int z=0;z<5;z++){
        for(int j=0;j<z;j++){
            if(numbers[z]==numbers[j] & j!=z){
                count=count+1;
            }
        }
        System.out.print(numbers[z]+" - "+count+"\n");
        count=1;

    }

0
package com.core_java;

import java.util.Arrays;
import java.util.Scanner;

public class Sim {
    public static void main(String[] args) {

        Scanner input = new Scanner(System.in);
        System.out.println("Enter array size: ");
        int size = input.nextInt();

        int[] array = new int[size];

        // Read integers from the console
        System.out.println("Enter array elements: ");
        for (int i = 0; i < array.length; i++) {
            array[i] = input.nextInt();
        }
        Sim s = new Sim();
        s.find(array);
    }

    public void find(int[] arr) {
        int count = 1;
        Arrays.sort(arr);

        for (int i = 0; i < arr.length; i++) {

            for (int j = i + 1; j < arr.length; j++) {
                if (arr[i] == arr[j]) {
                    count++;
                }
            }
            if (count > 1) {
                System.out.println();
                System.out.println("repeated element in array " + arr[i] + ": " + count + " time(s)");
                i = i + count - 1;
            }
            count = 1;
        }
    }

}

我能找到的最简单的方法是在整数数组中查找重复元素的计数。 - Manas

0
for (int i = 0; i < x.length; i++) {

    for (int j = i + 1; j < x.length; j++) {

        if (x[i] == x[j]) {
            y[i] = x[i];
            times[i]++;
        }

    }

}

0

with O(n log(n))

int[] arr1; // your given array
int[] arr2 = new int[arr1.length];
Arrays.sort(arr1);

for (int i = 0; i < arr1.length; i++) {
    arr2[i]++;
    if (i+1 < arr1.length) 
    {
        if (arr1[i] == arr1[i + 1]) {
            arr2[i]++;
            i++;
        }
    }
}

for (int i = 0; i < arr1.length; i++) {
    if(arr2[i]>0)
    System.out.println(arr1[i] + ":" + arr2[i]);
}

这是O(nlog(n)),不是O(N)。 - andre_lamothe
嗯,我再仔细想了一下,似乎是O(n),我没能想出O(log(n))。 - Onur A.
在进行处理之前,您正在对数组进行排序。平均情况下的总体复杂度(取决于Java中的排序类型)为O(N*LogN) + O(N),用于处理数组。 - andre_lamothe

0

你必须使用或了解关联数组、映射等。将重复元素出现次数存储在数组中,并另外再开一个数组来保存这些重复元素本身并不是很有意义。

你代码中的问题在于内部循环。

 for (int j = i + 1; j < x.length; j++) {

        if (x[i] == x[j]) {
            y[i] = x[i];
            times[i]++;
        }

    }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接