简体   繁体   English

如何消除此 Java 代码中的重复项?

[英]How can I get rid of duplicates in this Java code?

How can I make this code not have any repeating numbers in it?如何使此代码中没有任何重复数字?
All I would like to do is make it so that it doesn't output any duplicates in this little block.我想要做的就是让它不会在这个小块中输出任何重复项。

int[] arr = {5,10,44,2, 44,44,5,10,44,2, 44,44};
int startScan;
int index;
int minindex; 
int minValue;

for (startScan=0;startScan<(arr.length-1);startScan++){
    minindex=startScan; 
    minValue =arr[startScan]; 

    for (index=startScan+1; index<arr.length;index++){
        if (arr[index]<minValue){
            minValue=arr[index]; 
            minindex=index; 
            }
        } 
        arr[minindex]=arr[startScan];
        arr[startScan]=minValue;
    }

for(int x=0; x<arr.length;x++)
    System.out.println(arr[x]); 

Your code sorted the int array in ascending order.您的代码按升序对 int 数组进行排序。 It would have been nice if you had mentioned that in your question, and not left it for someone else to spend time figuring out.如果您在问题中提到了这一点,而不是让其他人花时间去弄清楚,那就太好了。

Removing the duplicates required some extra code.删除重复项需要一些额外的代码。

Here is the results of a test run.这是测试运行的结果。

[2, 5, 10, 44]

Here's the revised version of your code.这是您的代码的修订版。 It's runnable, so you can copy the code and paste it into your IDE.它是可运行的,因此您可以复制代码并将其粘贴到您的 IDE 中。

package com.ggl.testing;

import java.util.Arrays;

public class RemoveDuplicates {

    public static void main(String[] args) {
        int[] arr = { 5, 10, 44, 2, 44, 44, 5, 10, 44, 2, 44, 44 };
        int masterIndex = 0;

        for (int startScan = 0; startScan < (arr.length - 1); startScan++) {
            int minindex = startScan;
            int minValue = arr[startScan];

            for (int index = startScan + 1; index < arr.length; index++) {
                if (arr[index] < minValue) {
                    minValue = arr[index];
                    minindex = index;
                }
            }

            arr[minindex] = arr[startScan];
            arr[startScan] = minValue;

            if (arr[masterIndex] < minValue) {
                arr[++masterIndex] = minValue;
            }
        }

        int[] newarr = Arrays.copyOf(arr, masterIndex + 1);
        System.out.println(Arrays.toString(newarr));
    }

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM