如何在一个阵列中检查多个重复项? [ReadyJava]

时间:2016-11-08 02:57:47

标签: java arrays loops integer

该程序接收100个输入,然后输出最低值。我需要帮助检查输入的所有重复值。

有5个输入的示例: 5,1,1,5,4

最小值:1

重复值的数量:4

import java.awt.*;
import hsa.Console;
public class ArrayNumbers
{
static Console c;           

public static void main (String[] args)
 {
    c = new Console ();
    int number[] = new int [100], i = 1, output = 0;
    c.print ("Enter number #1:");
    number [0] = c.readInt ();
    output = number [0];

    for (int count = 0 ; count < 99 ; count++)
    {
        c.print ("Enter number #" + (count + 2)+ ":");
        number [i] = c.readInt ();
        if (number [i] < output)
        {
            output = number [i];
        }
        i++;
    }
c.print(output);
 } // main method
} // ArrayNumbers class

3 个答案:

答案 0 :(得分:1)

可以使用map完成。请在下面找到相同的代码:

import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;

public class MinAndDuplicates {

    public static void main(String[] args) {

        int number, totalDupCount=0;
        Scanner stdin = new Scanner(System.in);
        Map<Integer, Integer> map = new HashMap<Integer,Integer>();

        //Prepare map with duplicate count for each number
        for (int i = 0; i < 5; i++) {
            number=stdin.nextInt();
            if(map.containsKey(number)){
                map.put(number, ((Integer)map.get(number)+1));
            }else{
                map.put(number, 1);
            }
        }

         for (Map.Entry<Integer, Integer> entry : map.entrySet()) {
                int numberCount= entry.getValue();
                if (numberCount> 1) {
                    totalDupCount+= numberCount;
                }
            }

        System.out.println(totalDupCount);
    }

}

希望这有帮助!

答案 1 :(得分:1)

以下是在O(n)时间和O(1)额外空间中执行duplicate count的逻辑。

试试这个

// Function to find counts of all elements present in
// arr[0..n-1]. The array elements must be range from
// 1 to n
// Traverse all array elements
int[] arr = {5,1,1,5,4};
int i = 0,n=arr.length;
int totalDupCount = 0;
while (i < n) {
    // If this element is already processed,
    // then nothing to do
    if (arr[i] <= 0) {
        i++;
        continue;
    }

    // Find index corresponding to this element

    int elementIndex = arr[i] - 1;

    // If the elementIndex has an element that is not
    // processed yet, then first store that element
    // to arr[i] so that we don't loose anything.
    if (arr[elementIndex] > 0) {
        arr[i] = arr[elementIndex];

        // After storing arr[elementIndex], change it
        // to store initial count of 'arr[i]'
        arr[elementIndex] = -1;
    } else {
        // If this is NOT first occurrence of arr[i],
        // then increment its count.
        arr[elementIndex]--;

        // And initialize arr[i] as 0 means the element
        // 'i+1' is not seen so far
        arr[i] = 0;
        i++;
    }
}

System.out.println("Below are counts of all elements");
for (int j = 0; j < n; j++){
        if(Math.abs(arr[j]) >= 2){
            System.out.println(j + 1 + "->" + Math.abs(arr[j]));
            totalDupCount +=Math.abs(arr[j]);
        }
}
System.out.println("Total Duplicate Count in Array is : "+totalDupCount);

}

输出

Below are counts of all elements
1->2
5->2
Total Duplicate Count in Array is : 4

答案 2 :(得分:0)

(这篇文章比我的第一篇文章略显丑陋,但它以他们喜欢的方式解决了海报的问题。我已经决定将其作为一个单独的答案。)

  

如果要多次计算重复数字的数量   根据他们出现的频率,你可以用一个   HashMap

方法

  • 创建一个HashMap来计算每个数字出现的频率。
  • 读取输入时,请增加该数字的出现次数。
  • 要查找&#34;重复项&#34;的数量,请遍历HashMap并将所有多次出现的事件相加。

实施例

import java.util.Scanner;
import java.util.Map;
import java.util.HashMap;

public class DuplicateCounter {

    static int[] numbers = new int[100];
    static HashMap<Integer, Integer> occurrences = new HashMap<>();

    public static void main(String[] args) {
        readInput();
        int duplicates = countDuplicates();
        System.out.printf("%d numbers appeared multiple times.\n", duplicates);
    }

    public static void readInput() {
        Scanner stdin = new Scanner(System.in);
        for (int i = 0; i < numbers.length; i++) {
            int number = stdin.nextInt();
            numbers[i] = number;
            incrementCount(number);
        }
        stdin.close();
    }

    public static int countDuplicates() {
        int duplicates = 0;
        for (Map.Entry<Integer, Integer> entry : occurrences.entrySet()) {
            int numOfOccurrences = entry.getValue();
            if (numOfOccurrences > 1) {
                duplicates += numOfOccurrences;
            }
        }
        return duplicates;
    }

    public static void incrementCount(int number) {
        if (occurrences.get(number) != null) {
            int previous = occurrences.get(number);
            occurrences.put(number, previous + 1);
        } else {
            occurrences.put(number, 1);
        }
    }   
}