문제

I am trying to have a method (duplicates) return true if a given array called x (entered by user in another method), contains duplicate values. Otherwise it would return false. Rather then checking the entire array, which is initialized to 100, it will check only the amount of values entered, which is kept track of with a global counter: numElementsInX.

What is the best way to accomplish this?

public static boolean duplicates (int [] x)

I am prompting for user data like so:

public static void readData (int [] x, int i){

    Scanner input = new Scanner(System.in);
    System.out.println("Please enter integers, enter -999 to stop");

    while (i <= 99) {
        int temp = input.nextInt();
            if(temp == -999){
                break;
            }
            else {
                x[i++]=temp;
            }

    // else

}//end while
        printArray(x,i);


}//end readData

public static void printArray(int [] x, int numElementsInX){

int n = numElementsInX;

for (int i = 0; i < n; i++){
    System.out.print(x[i] + " ");


}//end for
        System.out.println();
}//end printArray

I am sure there is a better way to do this, but this is how I have been taught so far.

도움이 되었습니까?

해결책

Here is a solution that:

  • Compiles and executes without throwing.
  • Uses numElementsInX as you requested.
  • Returns as soon as it finds a duplicate.

This approach tests whether each member of the array has been seen before. If it has, the method can return immediately. If it hasn't, then the member is added to the set seen before.

public static boolean duplicates (int [] x, int numElementsInX ) {
    Set<Integer> set = new HashSet<Integer>();
    for ( int i = 0; i < numElementsInX; ++i ) {
        if ( set.contains( x[i])) {
            return true;
        }
        else {
            set.add(x[i]);
        }
    }
    return false;
}

Here's a sample program containing the above code.

다른 팁

this should do it.

public boolean containsDuplicates(Integer[] x) {
   return new HashSet<Integer>(Arrays.asList(x)).size() != x.length
}

You dont need numElementsInX as this is the same as x.length

edit after comment from Louis. Arrays.asList does not work with int arrays.

To convert int[] to Integer try this question How to convert int[] to Integer[] in Java?

or do soemthing like this (not tested but from memory)

Integer[] newArray = new Integer[a.length];
System.arraycopy(a, 0, newArray, 0, a.length);

This certainly isn't the most efficient way, but since you don't know about Sets yet, you can use two loops:

public static boolean duplicates (int [] x){
    for (int i=0; i<numElementsInX; i++){
        for (int j=i+1; j<numElementsInX; j++){
            if (x[j]==x[i]) return true;
        }
    }
    return false;
}

"set.add()" returns true if the element is not already present in the set and false otherwise. We could make use of that and get rid of "set.contains()" as in the above solution.

public static boolean duplicates (int[] x, int numElementsInX) {
    Set<Integer> myset = new HashSet<>();
    for (int i = 0; i < numElementsInX; i++) {
        if (!myset.add(x[i])) {
            return true;
        }
    }
    return false;
}

For java, return true if the array contains a duplicate value,


boolean containsDuplicates(int[] a) {
    
    HashSet<Integer> hs = new HashSet<>();
    
    for(int i = 0; i<a.length; i++) {
        if(!hs.add(a[i])){
            return true;
        }  
    }   
    return false;
}

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top