简体   繁体   中英

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. 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.

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));
    }

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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