【问题标题】:Remove duplicates from integer array从整数数组中删除重复项
【发布时间】:2012-12-04 10:07:08
【问题描述】:

我在编码时遇到问题:

编写一个名为removeDuplicates 的静态方法,该方法将一个整数数组作为输入,并作为结果返回一个新的整数数组,其中删除了所有重复项。 例如,如果输入数组具有元素 {4, 3, 3, 4, 5, 2, 4},则结果数组 应该是 {4, 3, 5, 2}

这是我到目前为止所做的事情

public static int[] removeDuplicates(int []s){
    int [] k = new int[s.length];
    k[0]=s[0];
    int m =1;
    for(int i=1;i<s.length;++i){
        if(s[i]!=s[i-1]){
            k[m]=s[i];
            ++m;
        }//endIF
    }//endFori
    return k;
}//endMethod

【问题讨论】:

  • 简单的方法是将元素添加到集合中(这会自动为您删除重复项)并将数字放回数组中。
  • 你没有说明你的实施的限制,我敢打赌有很多,否则解决方案是微不足道的。
  • 其实我不能使用 Set 或 HashSet ,它必须用循环和简单的数组来完成

标签: java arrays


【解决方案1】:

我找到了这个问题的解决方案。使用 HashSet 是一种对整数数组进行过滤和排序的强大方法。它也非常快。

我写了这个简短的代码来展示这个功能的强大。 从整数数组中,它创建两个列表。一个是有序整数,没有重复项,另一个只显示重复项和它们在初始数组中的次数。

public class DuplicatesFromArray {

    public static void main(String args[]) {
        int[] withDuplicates = { 1, 2, 3, 1, 2, 3, 4, 5, 3, 6 };
        
        
        // complexity of this solution is O[n]

        duplicates(withDuplicates);

        
    }

//Complexity of this method is O(n)
    
    public static void duplicates(int[] input) {

        HashSet<Integer> nums = new HashSet<Integer>();

        List<Integer> results = new ArrayList<Integer>();
        List<Integer> orderedFiltered = new ArrayList<Integer>();

        for (int in : input) {

            if (nums.add(in) == false) {
                results.add(in);
            } else {
                orderedFiltered.add(in);
            }
        }
        out.println(
                "Ordered and filtered elements found in the array are : " + Arrays.toString(orderedFiltered.toArray()));
        out.println("Duplicate elements found in the array are : " + Arrays.toString(results.toArray()));
    }

    
    /**
     * Generic method to find duplicates in array. Complexity of this method is O(n)
     * because we are using HashSet data structure.
     * 
     * @param array
     * @return
     */
    public static <T extends Comparable<T>> void getDuplicates(T[] array) {
        Set<T> dupes = new HashSet<T>();
        for (T i : array) {
            if (!dupes.add(i)) {
                System.out.println("Duplicate element in array is : " + i);
            }
        }

    }

}

【讨论】:

    【解决方案2】:
    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 8中引入的Java.util.streamapi

    【讨论】:

      【解决方案3】:

      试试这个 -

      public static int[] removeDuplicates(int []s){
          int result[] = new int[s.length], j=0;
          for (int i : s) {
              if(!isExists(result, i))
                  result[j++] = i;
          }
          return result;
      }
      
      private static boolean isExists(int[] array, int value){
          for (int i : array) {
              if(i==value)
                  return true;
          }
          return false;
      }
      

      【讨论】:

      • 这里好像有错误。而不是 if(isExists(result, i)) 必须是 if(!isExists(result, i))。
      • 唯一应该保存订单的解决方案。但是那里有两个问题:1)会跳过0 2)如果重复,最后会有0。然而,这两个问题都很容易解决
      【解决方案4】:

      试试这个。

       int numbers[] = {1,2,3,4,1,2,3,4,5,1,2,3,4};
      
       numbers =  java.util.stream.IntStream.of(numbers).distinct().toArray();
      

      【讨论】:

        【解决方案5】:
        import java.util.Arrays;
        import java.util.List;
        import java.util.stream.Collectors;
        
        // Remove duplicates from a list of integers
        public class IntegerUtils {
            public static void main(String[] args) {
                int intArray[] = {1, 2, 4, 2, 67, 4, 9};
                List<Integer> uniqueList = removeDuplicates(intArray);
                uniqueList.stream().forEach(p -> System.out.println(p));
            }
        
            public static List<Integer> removeDuplicates(int[] intArray) {
                return Arrays.stream(intArray).boxed().distinct().collect(Collectors.toList());
            }
        }
        

        【讨论】:

          【解决方案6】:

          这是一道面试题。 问题:从数组中删除重复项:

          public class Solution4 {
              public static void main(String[] args) {
          
                     int[] a = {1,1,2,3,4,5,6,6,7,8};
          
                    int countwithoutDuplicates =  lengthofarraywithoutDuplicates(a);
                    for(int i = 0 ; i < countwithoutDuplicates ; i++) {
                        System.out.println(a[i] + " ");
                    }
              }
          
              private static int lengthofarraywithoutDuplicates(int[] a) {
                  int countwithoutDuplicates = 1 ;
                  for (int i = 1; i < a.length; i++) {
                        if( a[i] != a[i-1]      ) {
                           a[countwithoutDuplicates++] = a[i]; 
                        }//if
                  }//for
                  System.out.println("length of array withpout duplicates = >" + countwithoutDuplicates);
                  return countwithoutDuplicates;
          
              }//lengthofarraywithoutDuplicates
          
          
          }
          

          在 Python 中:

          def lengthwithoutduplicates(nums):
              if not nums: return 0
              if len(nums) == 1:return 1
              # moving backwards from last element i.e.len(a) -1 to first element 0 and step is -1
              for i in range(len(nums)-1,0,-1):
                # delete the repeated element
                  if nums[i] == nums[i-1]: del nums[i]
                  # store the new length of the array without the duplicates in a variable
                  # and return the variable
              l = len(a)      
              return l
          
          
          
          a = [1, 1, 2, 3, 4, 5, 6, 6, 7, 8];
          
          l = lengthwithoutduplicates(a)
          for i in range(1,l):print(i)
          

          在 Python 中:使用枚举进行列表推导

          a = [1, 1, 2, 3, 4, 5, 6, 6, 7, 8]
          
          aa = [ ch  for i, ch in enumerate(a) if ch not in a[:i] ]
          print(aa) # output => [1, 2, 3, 4, 5, 6, 7, 8]
          

          【讨论】:

            【解决方案7】:

            你可以这样做

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

            【讨论】:

              【解决方案8】:

              导入 java.util.*;

              公共类重复{

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

              }

              【讨论】:

                【解决方案9】:

                这对我有用:

                import java.util.Arrays;
                import java.util.HashSet;
                
                public class Util {
                
                    public static int[] removeDups(final int[] intArrayWithDups) {
                        final int[] intArrayDupsRemoved = new int[intArrayWithDups.length];
                
                        final HashSet<Integer> alreadyAdded = new HashSet<>();
                        int innerCounter = 0;
                        for (int integer : intArrayWithDups) {
                            if (!alreadyAdded.contains(integer)) {
                                intArrayDupsRemoved[innerCounter] = integer;
                                alreadyAdded.add(intArrayDupsRemoved[innerCounter]);
                                innerCounter++;
                            }
                        }
                
                        return Arrays.copyOf(intArrayDupsRemoved, innerCounter);
                    }
                }
                

                【讨论】:

                  【解决方案10】:

                  嘿,你可以使用我创建的这段代码!!!

                  import java.util.*;
                  
                  public class DistinctNumber {
                      public static void main(String[] args) {
                  
                          int[] nums=  {1,3,2,3,4,3,2,5,4,6}; 
                          int [] T2 = duplicate(nums);
                          for (int i = 0; i < T2.length; i++) {
                              System.out.println(T2[i]);
                  
                          } 
                      }
                      public static boolean exist(int x,int []A){
                          for (int i = 0; i < A.length; i++) {
                              if(x==A[i]){
                                  return true;
                              }
                          }
                          return false;
                      }
                      public static int [] EliminateDuplicate(int [] numbers){
                         int [] B = new int[numbers.length];
                         int i=0,j=0;
                         for(i=0;i<numbers.length;i++){
                             if(!exist(numbers[i], B)){
                                 B[j] = numbers[i];
                                 j++;
                             }
                  
                         }
                         int[] C = new int[j];
                          for (int k = 0; k < C.length; k++) {
                              C[k] = B[k];
                  
                          }
                         return C;
                      }
                  
                  
                  }
                  

                  【讨论】:

                    【解决方案11】:

                    公共类 Foo {

                    public static void main(String[] args) {
                        //example input
                        int input[] = new int[]{1, 6 , 5896, 5896, 9, 100,7, 1000, 8, 9, 0, 10, 90, 4};
                        //use list because the size is dynamical can change
                        List<Integer> result = new ArrayList<Integer>();
                    
                        for(int i=0; i<input.length; i++)
                        {
                            boolean match = false;
                            for(int j=0; j<result.size(); j++)
                            {
                                //if the list contains any input element make match true
                                if(result.get(j) == input[i])
                                    match = true;
                            }
                            //if there is no matching we can add the element to the result list
                            if(!match)
                                result.add(input[i]);
                        }
                        // Print the result
                        for(int i=0; i<result.size(); i++)
                            System.out.print(result.get(i) + ", ");
                    
                    }
                    

                    } 输出:1、6、5896、9、100、7、1000、8、0、10、90、4,

                    【讨论】:

                    • 为你的答案添加一些解释。
                    • 已编辑:您可以在 cmets 中查看说明
                    【解决方案12】:

                    首先,你应该知道没有重复的长度(dups):初始长度减去重复的数量。 然后创建具有正确长度的新数组。 然后检查 list[] 的每个元素是否存在 dups,如果 dup 成立 - 检查下一个元素,如果 dup 未成立 - 将元素复制到新数组。

                    public static int[] eliminateDuplicates(int[] list) {
                        int newLength = list.length;
                        // find length w/o duplicates:
                        for (int i = 1; i < list.length; i++) {
                            for (int j = 0; j < i; j++) {
                                if (list[i] == list[j]) {   // if duplicate founded then decrease length by 1
                                    newLength--;
                                    break;
                                }
                            }
                        }
                    
                        int[] newArray = new int[newLength]; // create new array with new length
                        newArray[0] = list[0];  // 1st element goes to new array
                        int inx = 1;            // index for 2nd element of new array
                        boolean isDuplicate;
                    
                        for (int i = 1; i < list.length; i++) {
                            isDuplicate = false;
                            for (int j = 0; j < i; j++) {
                                if (list[i] == list[j]) {  // if duplicate founded then change boolean variable and break
                                    isDuplicate = true;
                                    break;
                                }
                            }
                            if (!isDuplicate) {     // if it's not duplicate then put it to new array
                                newArray[inx] = list[i];
                                inx++;
                            }
                        }
                        return newArray;
                    }
                    

                    【讨论】:

                      【解决方案13】:
                      public class DistinctNumbers{
                          public static void main(String[] args){
                              java.util.Scanner input = new java.util.Scanner(System.in);
                      
                              System.out.print("Enter ten numbers: ");
                              int[] numbers = new int[10];
                              for(int i = 0; i < numbers.length; ++i){
                                  numbers[i] = input.nextInt();
                              }
                              System.out.println("The distinct numbers are:");
                              System.out.println(java.util.Arrays.toString(eliminateDuplicates(numbers)));
                          }
                      
                          public static int[] eliminateDuplicates(int[] list){
                              int[] distinctList = new int[list.length];
                              boolean isDuplicate = false;
                              int count = list.length-1;
                              for(int i = list.length-1; i >= 0; --i){
                                  isDuplicate = false;
                                  for(int j = i-1; j >= 0 && !isDuplicate; --j){
                                      if(list[j] == list[i]){
                                          isDuplicate = true;
                                      }
                                  }
                                  if(!isDuplicate){
                                      distinctList[count--] = list[i];
                                  }
                              }
                              int[] out = new int[list.length-count-1];
                              System.arraycopy(distinctList, count+1, out, 0, list.length-count-1);
                              return out;
                          }
                      }
                      

                      【讨论】:

                        【解决方案14】:
                        public int[] removeRepetativeInteger(int[] list){
                                if(list.length == 0){
                                    return null;
                                }
                                if(list.length == 1){
                                    return list;
                                }
                        
                            ArrayList<Integer> numbers = new ArrayList<>();
                            for(int i = 0; i< list.length; i++){
                                if (!numbers.contains(list[i])){
                                    numbers.add(list[i]);
                                }
                            }
                            Iterator<Integer> valueIterator = numbers.iterator();
                            int[] resultArray = new int[numbers.size()]; 
                            int i = 0;
                            while (valueIterator.hasNext()) {
                                resultArray[i] = valueIterator.next();
                                i++;
                            }
                            return resultArray;     
                        
                        }
                        

                        【讨论】:

                          【解决方案15】:

                          也许你可以使用 lambdaj (download here,website),这个库对于管理集合(..list,arrays)非常强大,下面的代码非常简单并且完美运行:

                          import static ch.lambdaj.Lambda.selectDistinct;
                          import java.util.Arrays;
                          import java.util.List;
                          
                          public class DistinctList {
                               public static void main(String[] args) {
                                   List<Integer> numbers =  Arrays.asList(1,3,4,2,1,5,6,8,8,3,4,5,13);
                                   System.out.println("List with duplicates: " + numbers);
                                   System.out.println("List without duplicates: " + selectDistinct(numbers));
                               }
                          }
                          

                          这段代码显示:

                          List with duplicates: [1, 3, 4, 2, 1, 5, 6, 8, 8, 3, 4, 5, 13]
                          List without duplicates: [1, 2, 3, 4, 5, 6, 8, 13]
                          

                          您可以在一行中获得一个不同的列表,这是一个简单的示例,但使用此库您可以解决更多问题。

                          selectDistinct(numbers)
                          

                          您必须将 lambdaj-2.4.jar 添加到您的项目中。我希望这会有用。

                          注意:这将帮助您假设您可以有替代代码。

                          【讨论】:

                            【解决方案16】:

                            你可以使用不允许重复元素的HashSet

                            public static void deleteDups(int a []) {
                            
                                HashSet<Integer> numbers = new HashSet<Integer>();
                            
                                    for(int n : a)
                                    {
                                        numbers.add(n);
                                    }
                            
                                    for(int k : numbers)
                                    {
                                        System.out.println(k);
                                    }
                                    System.out.println(numbers);
                                }       
                            
                            public static void main(String[] args) {
                                int a[]={2,3,3,4,4,5,6};
                                        RemoveDuplicate.deleteDups(a);
                            
                            }
                            
                            }
                            o/p is 2
                            3
                            4
                            5
                            6
                            

                            [2, 3, 4, 5, 6]

                            【讨论】:

                              【解决方案17】:

                              不过,你可以天真地做。首先,您需要对数组进行排序。您可以使用任何排序算法来做到这一点。我确实使用了快速排序。然后检查一个位置与它的下一个位置。如果它们不相同,则在新数组中添加值,否则跳过此迭代。

                              示例代码(快速排序):

                               public static void quickSort(int[] array, int low, int high) {
                                  int i = low;
                                  int j = high;
                              
                                  int pivot = array[low + (high - low) / 2];
                              
                                  while (i <= j) {
                                      while (array[i] < pivot) i++;
                                      while (array[j] > pivot) j--;
                                      if (i <= j) {
                                          exchange(array, i, j);
                                          i++;
                                          j--;
                                      }
                                  }
                                  if (0 < j) quickSort(array, 0, j);
                                  if (i < high) quickSort(array, i, high);
                              }
                              
                              public static void exchange(int[] array, int i, int j) {
                                  int temp = array[i];
                                  array[i] = array[j];
                                  array[j] = temp;
                              }
                              

                              删除重复项:

                               public static int[] removeDuplicate(int[] arrays) {
                                  quickSort(arrays, 0, arrays.length - 1);
                              
                                  int[] newArrays = new int[arrays.length];
                                  int count = 0;
                                  for (int i = 0; i < arrays.length - 1; i++) {
                                      if (arrays[i] != arrays[i + 1]) {
                                          newArrays[count] = arrays[i];
                                          count++;
                                      }
                                  }
                                  return newArrays;
                              }
                              

                              【讨论】:

                              • 将“快速排序”投入其中是没有帮助的。如果您要进行排序,正确的(Java)解决方案是使用Arrays.sort(int[])。还有更简单的方法可以解决不涉及排序的问题。
                              • 此外,这会重新排序数组的其余元素,并且问题要求保留顺序。
                              【解决方案18】:

                              要保留顺序并删除整数数组中的重复项,您可以尝试以下操作:

                              public void removeDupInIntArray(int[] ints){
                                  Set<Integer> setString = new LinkedHashSet<Integer>();
                                  for(int i=0;i<ints.length;i++){
                                      setString.add(ints[i]);
                                  }
                                  System.out.println(setString);
                              }
                              

                              希望这会有所帮助。

                              【讨论】:

                                【解决方案19】:

                                您还可以将数组元素放入 Set 中,其语义恰恰是它不包含重复元素。

                                【讨论】:

                                • Set set = new HashSet( Arrays.asList( s ) ) 它不会编译。
                                • -1 Set 是原始类型。对泛型 Set 的引用应该被参数化。
                                • 您的编辑不能解决问题,您无法将 int[] 转换为 Integer[]Arrays.asList()
                                【解决方案20】:
                                public class Test 
                                static int[] array = {4, 3, 3, 4, 5, 2, 4};
                                static HashSet list = new HashSet();
                                public static void main(String ar[])
                                {       
                                    for(int i=0;i<array.length;i++)
                                    {         
                                      list.add(array[i]);
                                
                                    }
                                    System.out.println(list);
                                }}
                                

                                输出是:[2, 3, 4, 5]

                                【讨论】:

                                  【解决方案21】:

                                  你也可以使用谷歌的Guava库,使用ImmutableSet

                                  ImmutableSet.copyOf(myArray).asList();
                                  

                                  【讨论】:

                                    【解决方案22】:

                                    试试这个

                                    public static int[] removeDuplicates(int[] s) {     
                                        Integer[] array = new HashSet<Integer>(Arrays.asList(ArrayUtils.toObject(s))).toArray(new Integer[0]);      
                                        return ArrayUtils.toPrimitive(array);
                                    }
                                    

                                    编辑:更新为 Apache Lang 以转换为基元。

                                    【讨论】:

                                    • 不过,这将给出一个 Integer[] 数组。
                                    • 编辑了回复。更新为原始数据类型。
                                    【解决方案23】:

                                    遍历数组并填充集合,因为集合不能包含重复项。然后将集合中的元素复制到一个新数组中并返回它。如下所示:

                                    public static int[] removeDuplicates(int[] array) {
                                        // add the ints into a set
                                        Set<Integer> set = new HashSet<Integer>();
                                        for (int i = 0; i < array.length; i++) {
                                            set.add(array[i]);
                                        }
                                    
                                        // copy the elements from the set into an array
                                        int[] result = new int[set.size()];
                                        int i = 0;
                                        for (Integer u : set) {
                                            result[i++] = u;
                                        }
                                        return result;
                                    }
                                    

                                    【讨论】:

                                      【解决方案24】:

                                      您要做的是,您必须检查第二个数组中的每个元素是否已经存在。

                                      您可以使用更好的方法使用 HashSet 并返回集合。

                                      public static Set removeDuplicates(int []s){
                                        Set<Integer> set = new HashSet<Integer>();       
                                         for(int i=0;i<s.length;++i){
                                                set.add(s[i]);
                                              }//endFori
                                        return set;
                                      }//endMethod
                                      

                                      如果你需要 int Array 比看看这个 java-hashsetinteger-to-int-array链接。

                                      【讨论】:

                                        猜你喜欢
                                        • 2011-04-09
                                        • 2011-06-29
                                        • 2011-01-04
                                        • 2013-08-03
                                        • 2019-08-22
                                        相关资源
                                        最近更新 更多