如何检测整数数组中的重复值并在java中用它们创建一个新值?

时间:2015-04-01 11:29:02

标签: java arrays

大家,如果你能在这个问题上帮助我,我将非常感激。关键是我有初始阵列" a"一堆数字,其中一些可以重复多次,其中一些 - 一次。任务是创建一个新阵列" b"它由重复的数字组成。如果数组中有任何数字" a"不止一次重复 - 在阵列" b"它必须只反映一次。新数组中的元素序列应与初始元素中的元素序列相同。 例如:

*initial array "a": 2 3 3 4 5 6 9 2 7 3 3  
new array "b": 2 3* 

我决定生成阵列" a"它每次都是随机的,没有任何困难,但是在定义代表方面存在一些问题。我唯一做的就是找到所有重复的数字。我现在的结果是

*initial array "a": 2 3 3 4 5 6 9 2 7 3 3        
new array "b": 2 3 3 3* 

我的代码:

import java.util.*;

public class ProcessingTool  {

public static int[] arrayCreatingMethod(){

    Random rand = new Random();

    int myArrayDim = rand.nextInt(50);

    int [] myArray  = new int [myArrayDim]; 

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

        myArray[i] = (int)(Math.random()*(100)); 

    }

return myArray;

}

public static int[] newArrayCreatingMethod(int[] a) {

    int[] d = new int [a.length];

    int k = 0;
    int repetitions = 0;


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

         int j = i;
         int current = a[i];             

         while (j<a.length-1) { 


             if (current == a[j+1]) {

                 d[k] = current;    
                 k++;
                 repetitions++;
                 break;

             }


             else {

                 k=k-1+1;

             }

             j++;

         }

    }

    System.out.print("\n"+repetitions+"\n");

   System.out.println("\nArray d: ");

   for (int ww = 0; ww<d.length; ww++){

        System.out.print(d[ww]+" ");

    }

4 个答案:

答案 0 :(得分:2)

使用适当的类简化了这一点:

import java.util.Arrays;
import java.util.LinkedHashSet;
import java.util.Set;
import java.util.TreeSet;

import org.junit.Assert;

public class Reducing {

  public int[] reduce(int[] input) {
    Set<Integer> vals = new LinkedHashSet<Integer>();
    Set<Integer> recurrences = new LinkedHashSet<Integer>();
    for (Integer i : input) {
      if (vals.contains(i)) {
        recurrences.add(i);
      }
      vals.add(i);
    }
    vals.retainAll(recurrences);
    int index = 0;
    Integer[] recurs = new Integer[vals.size()];
    for (Integer i : vals)  {
      recurs[index++] = i;
    }
    return recurs;
  }

  @org.junit.Test
  public void test() {
    Integer[] input = {2, 3, 3, 4, 5, 6, 9, 2, 7, 3, 3};
    System.out.println(Arrays.toString(reduce(input)));
  }
}

答案 1 :(得分:1)

public static int[] findRecurringNumbers(int[] array){
    Map<Integer, Boolean> map = new HashMap<>();

    for(Integer i : array){

        Boolean recurred = map.get(i);
        //if current number is unknown ==> recurred = null
        //if current number occurred once ==> recurred = false
        //if current number occurred more than once ==> recurred = true

        map.put(i, recurred != null);
    }
    // as result, filter all entries' keys, where the corresponding value is TRUE
    return map.entrySet().stream()
              .filter(entry->entry.getValue())
              .mapToInt(entry->entry.getKey()).toArray();
}

使用以下Junit测试用例测试上述解决方案:

@Test
public void testFind(){
    int[] a = {2,3,5,3,2,3};
    int[] expectedResult = {2,3};

    int[] recurrence = findRecurringNumbers(a);

    System.out.println("Recurrence: " + Arrays.toString(recurrence));

    assertTrue(Arrays.equals(expectedResult, recurrence));
}

控制台声明:

  

复发:[2,3]

答案 2 :(得分:0)

public static void main(String[] args) {
    // TODO code application logic here
    int[] a = {1,2,3,4,2,2,3,3,1,2};
    int[] b = new int[a.length];
    int bcount = 0;
    for(int i=0; i<a.length; i++){            
        for(int j=i; j<a.length;j++){
            if(a[i] == a[j] && i!=j){
                boolean flag = true;
                for(int q=0; q<bcount && flag; q++){
                    if(a[i] == b[q]){
                        flag = false;
                    }
                }
                if(flag){
                    b[bcount] = a[i];
                    bcount++;
                }
            }
        }
    }

    //display
    for(int i=0; i<bcount; i++){
        System.out.print(b[i]+" ");
    }        
}

我认为您的问题是打印出已打印出的号码。所以,只需要包含一个循环来测试它。
我希望它对你有帮助。

答案 3 :(得分:0)

这是一个快速的解决方案。它遍历数组a中的每个元素,以检查它是否出现多次,如果出现,则将其添加到HashSet。

import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;


public class IntCount {

    int [] a = new int [] {2,3,3,4,5,6,9,2,7,3,3};

    public IntCount()
    {
        Set<Integer> b = new HashSet<Integer>();
        for (int i : a)
        {
            if (containsTwice(i))
                b.add(i);
        }
        System.out.println(Arrays.toString(b.toArray()));
    }

    boolean containsTwice(int i)
    {
        int count = 0;
        for (int j : a)
        {
            if (j == i)
                count++;
        }
        return (count > 1);
    }

    public static void main(String [] args)
    {
        new IntCount();
    }
}

输出:[2,3]