Remove duplicates from integer array

前端 未结 23 2366
执念已碎
执念已碎 2020-12-01 18:52

I having a problem with coding this:

Write a static method named removeDuplicates that takes as input an array of integers and returns as a result a new

相关标签:
23条回答
  • 2020-12-01 19:35

    You can also use Google's Guava library and use ImmutableSet do

    ImmutableSet.copyOf(myArray).asList();
    
    0 讨论(0)
  • 2020-12-01 19:35
    int[] arrayRemoveDuplicates= Arrays.stream("integerArray").distinct().toArray();
        // print the unique array
        for (int i = 0; i < arrayRemoveDuplicates.length; i++) {
            System.out.println(arrayRemoveDuplicates[i]);
        }
    

    Java.util.streamapi introduced in java 8

    0 讨论(0)
  • 2020-12-01 19:35

    import java.util.*;

    public class Duplicates {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
    
        int [] myArray  = {1,3,2,4,3,2,3,4,5,6,7,6,5,4,3,4,5,6,76,5,4,3,4,4,5};
        List <Integer> myList = new ArrayList <Integer>();
        myList = removeDuplicates(myArray);
    
        //Printing Output   
        for (int k=0; k<myList.size();k++)
            System.out.print(" "+ myList.get(k));
    
    }
    
    private static List<Integer> removeDuplicates(int[] myArray) {
        // TODO Auto-generated method stub
        Arrays.sort(myArray);
        List <Integer> myList = new ArrayList <Integer>();
        for (int i=0; i<myArray.length-1; i++){
    
             if (myArray[i]!= myArray[i+1]){    
    
                        myList.add(myArray[i]);
                }
    
        }
        myList.add(myArray[myArray.length-1]);
    
        return myList;
    }
    

    }

    0 讨论(0)
  • 2020-12-01 19:36

    try this.

     int numbers[] = {1,2,3,4,1,2,3,4,5,1,2,3,4};
    
     numbers =  java.util.stream.IntStream.of(numbers).distinct().toArray();
    
    0 讨论(0)
  • 2020-12-01 19:36

    You can do something like this

      public class MyClass {
    
        public static void main(String args[]) {
    
            int[] man = {4,56,98,89,78,45,78, 79, 56};
    
            for (int i = 0; i < man.length; i++)
            {
                for (int j = i+1; j < man.length; j++)
                {
                    //check if it is equal
                   if (man[i] == man[j])
                    {
    
                         man[j] = man[j] -1;
    
                   //Decrementing size
    
                       j--;
                    }
                }
            }
    
             //Array without duplicates
    
            for(int k=0; k<man.length; k++)
            {
    
                System.out.print(" " + man[k]);
            } 
        }
    }
    
    0 讨论(0)
提交回复
热议问题