簡體   English   中英

創建一個與舊編號相同但沒有重復的數組

[英]Creating an Array with the same numbers from an old one but without repetitions

所以我創建了一個帶有隨機數的數組,我打印並計算了重復的數字,現在我只需要創建一個新數組,該數組具有與第一個數組相同的數字,但沒有重復。 不能使用ArrayList。

我有的是。

public static void main(String[] args) {

    Random generator = new Random();
    int aR[]= new int[20];

    for(int i=0;i<aR.length;i++){
        int number=generator.nextInt(51);
        aR[i]=number;
        System.out.print(aR[i]+" ");

    }
    System.out.println();
    System.out.println();
    int countRep=0;
    for(int i=0;i<aR.length;i++){
        for(int j=i+1;j<aR.length-1;j++){
            if(aR[i]==aR[j]){
                countRep++;
                System.out.println(aR[i]+" "+aR[j]);
                break;
            }
        }
    }   
    System.out.println();
    System.out.println("Repeated numbers:  "+countRep);

    int newaR[]= new int[aR.length - countRep];




}

有人可以幫忙嗎?

編輯:也不能真正使用HashSet。 另外,新陣列需要具有正確的大小。

使用Java 8和流,您可以執行以下操作:

int[] array = new int[1024];
//fill array
int[] arrayWithoutDuplicates = Arrays.stream(array)
        .distinct()
        .toArray();

這將:

  1. 將您的int[]轉換為IntStream
  2. 過濾掉所有重復項,從而保留不同的元素。
  3. 將其保存在int[]類型的新數組中。

嘗試:

Set<Integer> insertedNumbers = new HashSet<>(newaR.length);
int index = 0;
for(int i = 0 ; i < aR.length ; ++i) {
    if(!insertedNumbers.contains(aR[i])) {
        newaR[index++] = aR[i];
    }
    insertedNumbers.add(aR[i]);
}

一種可能的方法是遍歷數組,並為每個值計算在數組中再次出現的索引(如果數字不再出現,則為-1)。 不再出現的值的數量是唯一值的數量。 然后從數組中收集所有值,其對應索引為-1。

import java.util.Arrays;
import java.util.Random;

public class UniqueIntTest
{
    public static void main(String[] args)
    {
        int array[] = createRandomArray(20, 0, 51);
        System.out.println("Array " + Arrays.toString(array));

        int result[] = computeUnique(array);
        System.out.println("Result " + Arrays.toString(result));
    }

    private static int[] createRandomArray(int size, int min, int max)
    {
        Random random = new Random(1);
        int array[] = new int[size];
        for (int i = 0; i < size; i++)
        {
            array[i] = min + random.nextInt(max - min);
        }
        return array;
    }

    private static int[] computeUnique(int array[])
    {
        int indices[] = new int[array.length];
        int unique = computeIndices(array, indices);
        int result[] = new int[unique];
        int index = 0;
        for (int i = 0; i < array.length; i++)
        {
            if (indices[i] == -1)
            {
                result[index] = array[i];
                index++;
            }
        }
        return result;
    }

    private static int computeIndices(int array[], int indices[])
    {
        int unique = 0;
        for (int i = 0; i < array.length; i++)
        {
            int value = array[i];
            int index = indexOf(array, value, i + 1);
            if (index == -1)
            {
                unique++;
            }
            indices[i] = index;
        }
        return unique;
    }

    private static int indexOf(int array[], int value, int offset)
    {
        for (int i = offset; i < array.length; i++)
        {
            if (array[i] == value)
            {
                return i;
            }
        }
        return -1;
    }
}

這聽起來像是一個作業問題,如果是,那么您應該采用的技術是首先對數組進行排序。

數組排序后,重復的條目將彼此相鄰,因此很難找到它們:

int[] numbers = //obtain this however you normally would
java.util.Arrays.sort(numbers);

//find out how big the array is
int sizeWithoutDuplicates = 1; //there will be at least one entry
int lastValue = numbers[0];

//a number in the array is unique (or a first duplicate)
//if it's not equal to the number before it
for(int i = 1; i < numbers.length; i++) {
    if (numbers[i] != lastValue) {
        lastValue = i;
        sizeWithoutDuplicates++;
    }
}

//now we know how many results we have, and we can allocate the result array
int[] result = new int[sizeWithoutDuplicates];

//fill the result array
int positionInResult = 1; //there will be at least one entry
result[0] = numbers[0];
lastValue = numbers[0];

for(int i = 1; i < numbers.length; i++) {
    if (numbers[i] != lastValue) {
        lastValue = i;
        result[positionInResult] = i;
        positionInResult++;
    }
}

//result contains the unique numbers

無法使用列表意味着我們必須弄清楚該數組在一次單獨傳遞中的大小—如果我們可以使用ArrayList來收集結果,則只需要對數字數組進行一次循環。

這種方法比遍歷數組的雙嵌套循環更快(O(n log n)vs O(n ^ 2))。 在H(n)處使用HashSet會更快。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM