java,如何找到4个相同的数字?

时间:2014-08-07 20:02:19

标签: java arrays

我需要一个代码,它会找到四个相同的num并告诉给定数组中有多少个。

int tnum =0;
    int q = 0;
    int[] spot = {689, 690, 690, 689, 689, 690, 689, 688, 688};
    int[] arr = new int[4];
    for(int i= 0; i < spot.length; i++ ){
        for (int j = 0; j < spot.length; ++j){
            if (spot[i] == spot[j]){
                tnum++;
// i tried to make a new array here instead of "tnum" but it become even worse.   
            }
        }

    }
    if (tnum % 4 == 0 ){
        q = (tnum / 4);
    }
    System.out.print(q);

所以,这是我的代码,我知道什么不起作用,但我不知道如何让它工作, 我需要得到多少给定数字重复4次 在这种情况下,输出将是&#34; 1&#34;因为689重复4次并且存在1个相同数字的组合。  请谁能帮助我等你,谢谢!

2 个答案:

答案 0 :(得分:1)

如果我理解正确,您正在寻找重复四次的项目数量。

// Initial data
int[] spot =
{
    689, 690, 690, 689, 689, 690, 689, 688, 688
};

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

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

    // Build a map of number=>duplicates
    if (mapOfDuplicates.containsKey(spot[i]))
    {
        int n = mapOfDuplicates.get(spot[i]);
        mapOfDuplicates.put(spot[i], ++n);
    }
    else
    {
        mapOfDuplicates.put(spot[i], 1);
    }

}

int duplicateCount = 0;
for (int i : mapOfDuplicates.keySet())
{
    // Check if there are exactly four duplicates
    if (mapOfDuplicates.get(i) == 4)
    {
        duplicateCount++;
    }
}

System.out.println(duplicateCount); // Outputs "1"

我已使用number =&gt;重复的地图替换了您的第二个数组。然后,您可以遍历地图,检查重复项== 4。

答案 1 :(得分:0)

在尝试计算元素实例之前,请先保存自己的麻烦世界并对数组进行排序。这会将所有相同的值聚集在一起,避免大量不必要的混淆。只要在已排序的数组中引入新数字,只需重新启动“出现计数器”。

第1步:排序 对不起,我不打算详细说明,有数百万本书和链接可用于教授各种排序方法和算法。 http://www.sorting-algorithms.com/

第2步:迭代并记录 按照首选顺序对数组进行排序后,创建 for循环以查看每个元素,并在当前元素与前一个元素相同时进行计数。如果是这样,请添加到柜台:

int myCounter = 0;
int logIndex = 0;
int[] mySORTEDArray = { 688, 688, 689, 689, 689, 689, 690, 690, 690};
int[] log = new int[mySORTEDArray.length/4];  //it only makes sense that this logger 
                                              //is 4 times shorter because we're
                                              //looking for 4 instances
for(int i=0; i < mySORTEDArray.length();i++) {
    if(myCounter == 4) {
        log[logIndex] = mySORTEDArray[i];    //this element has be spotted 4 times, log it
        logIndex ++;
    }
    if(mySORTEDArray[i-1] == NULL) {
        myCounter ++;                     //start the counter on the first element
        return;                           //jump out if we're working with first
    }

    if(mySORTEDArray[i] == mySORTEDArray[i-1]) {
        myCounter ++;
    }
    else {
        myCounter = 0;
    }
}

这主要是出于逻辑目的,而不是仅仅提供答案。我希望这有点帮助。试着记住,当涉及像Java这样的面向对象编程时,“分而治之”是最好的意识形态。