【问题标题】:How can I remove duplicate elements from a given array in java without using collectionsjava - 如何在不使用集合的情况下从java中的给定数组中删除重复元素
【发布时间】:2021-05-09 19:18:23
【问题描述】:

我有一个这样的数组元素:

int arr[] = {1,1,2,2,3,3,4,4};

我想从中删除重复的元素。在互联网上搜索并了解 ArrayUtil 类。您能否告诉我它的用法 - 这就是我如何在输出中获得这样的数组:

arr[] = {1,2,3,4};

【问题讨论】:

  • List是一个集合,也没有Sets?
  • 检查这个帖子有一个类似的问题[删除重复][1][1]:stackoverflow.com/questions/17967114/…
  • 您使用的是 Java 8 吗?
  • @ChetanKinger - 我正在使用 java 7

标签: java arrays


【解决方案1】:

这是Element Distinctness Problem 的下一步,在此线程中进行了彻底讨论:Find duplicates in an array,包括问题的下限(如果不涉及哈希集,不能比O(nlogn) 做得更好)。

如果您不愿意使用哈希集来检查您已经看到的所有元素,最好的办法是对数组进行排序,然后对其进行迭代 - 所有重复的元素将彼此相邻。

public static int[] justUniques(int[] arr) { 
    if (arr == null || arr.length == 0) return arr;
    Arrays.sort(arr);
    int n = 1;
    for (int i = 1; i < arr.length; i++) {
        if (arr[i] != arr[i-1]) n++;
    }
    int[] res = new int[n];
    res[0] = arr[0];
    n = 1;
    for (int i = 1; i < arr.length; i++) {
        if (arr[i] != arr[i-1]) res[n++] = arr[i];
    }
    return res;

}

请注意,上面的一个简单变体也可以在原地完成,而无需创建新数组。

这个解决方案是O(nlogn),因此是最优的。如果您不愿意使用Arrays.sort(),您可以实现自己的排序算法(这很容易)。

另一个提出类似问题但有附加限制的相关主题:Removing the duplicates from an array without disturbing the order of elements without using Sets

【讨论】:

    【解决方案2】:

    为这个问题找到了一个很好的解决方案:而且效果很好。对于那些仍在寻找这个问题的答案的人,您可以使用下面的代码。

    import java.io.BufferedReader;
    import java.io.InputStreamReader;
    
    public class DuplicatesRemove {
    
    public static void main(String[] args) throws Exception {
    
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    
        System.out.print("Enter the array size :");
        int size = Integer.parseInt(br.readLine());
    
        int[] arr = new int[size];
    
        // Creating the array
        for (int i = 0; i < size; i++) {
            System.out.print("Enter the element arr[" + i + "] = ");
            arr[i] = Integer.parseInt(br.readLine());
            System.out.println();
        }
    
        // displaying the array - it may contain elements in unsorted manner
        System.out.println("Before Sorting :");
        for (int i = 0; i < size; i++) {
            System.out.println("Element arr[" + i + "] = " + arr[i]);
        }
        System.out
                .println("*****************************************************");
    
        // Logic for sorting the elements in the array
        for (int i = 0; i < size; i++) {
            for (int j = 1; j < size - i; j++) {
                if (arr[j - 1] > arr[j]) {
                    int temp = arr[j];
                    arr[j] = arr[j - 1];
                    arr[j - 1] = temp;
                }
            }
        }
    
        // Printing the sorted elements - it may contain duplicate elements
        System.out.println("After Sorting :");
        for (int i = 0; i < size; i++) {
            System.out.println("Element arr[" + i + "] = " + arr[i]);
        }
    
        System.out
                .println("*****************************************************");
        // Logic for removing the duplicate elements
        int compare = 0;
        arr[compare] = arr[0];
    
        for (int i = 1; i < size; i++) {
            if (arr[compare] != arr[i]) {
                compare++;
                arr[compare] = arr[i];
            }
        }
    
        System.out.println("Array After removing duplicate elements is :");
        for (int i = 0; i <= compare; i++) {
            System.out.println("Element arr[" + i + "] = " + arr[i]);
          }
       }
    }
    

    【讨论】:

    • 好吧,您不需要编写您自己的算法来对数组进行排序! Java 内置的排序能力远胜于此。
    【解决方案3】:
    public class UniqueElementinAnArray 
    {
    
    public static void main(String[] args) 
    {
        int[] a = {10,10,10,10,10,100};
        int[] output = new int[a.length];
        int count = 0;
        int num = 0;
    
        //Iterate over an array
        for(int i=0; i<a.length; i++)
        {
            num=a[i];
            boolean flag = check(output,num);
            if(flag==false)
            {
                output[count]=num;
                ++count;
            }
    
        }
    
        //print the all the elements from an array except zero's (0)
        for (int i : output) 
        {
            if(i!=0 )
                System.out.print(i+"  ");
        }
    
    }
    
    /***
     * If a next number from an array is already exists in unique array then return true else false
     * @param arr   Unique number array. Initially this array is an empty.
     * @param num   Number to be search in unique array. Whether it is duplicate or unique.
     * @return  true: If a number is already exists in an array else false 
     */
    public static boolean check(int[] arr, int num)
    {
        boolean flag = false;
        for(int i=0;i<arr.length; i++)
        {
            if(arr[i]==num)
            {
                flag = true;
                break;
            }
        }
        return flag;
    }
    

    }

    【讨论】:

      【解决方案4】:
      public int[] removeDuplicates(int[] arr) {
          int[] res = new int[arr.length];
          int index = 0;
          for (int num : arr) {
              if (res.indexOf(num) == -1)
                  res[index++] = num;
          }
          return res;
      }
      

      这是一个次优的解决方案,但是它不需要对数组进行任何排序。我创建了一个新数组,遍历原始数组中的项目,如果这些项目不存在,则将它们添加到新数组中。

      【讨论】:

      • 请补充说明
      • 这在 O(n^2) 时间内运行,这是次优的
      【解决方案5】:
      public static int[] removeDuplicates(int[] input){
      
          int j = 0;
          int i = 1;
          //return if the array length is less than 2
          if(input.length < 2){
              return input;
          }
          while(i < input.length){
              if(input[i] == input[j]){
                  i++;
              }else{
                  input[++j] = input[i++];
              }   
          }
          int[] output = new int[j+1];
          for(int k=0; k<output.length; k++){
              output[k] = input[k];
          }
      
          return output;
      }
      

      来源:http://java2novice.com/java-interview-programs/remove-duplicates-sorted-array/

      【讨论】:

        【解决方案6】:
            int flag = 0, k = 0;
            for (int i = 0; i < arr.length; i++) {
                for (int j = 0; j < arrAns.length; j++) {
                    if (arr[i] == arrAns[j]) {
                        flag = 0;
                        break;
                    }
                    flag=1;
                }
                if (flag == 1) {
                    arrAns[k] = arr[i];
                    k++;
                }
                flag = 0;
            }
        

        【讨论】:

          【解决方案7】:
          package practice1;
          
          import java.util.Scanner;
          
          public class RemoveArrayDuplicatesElements {
          
          
              public static void main(String[] args) {
          
                  int i, j, k, size,same = 0;
          
                  System.out.println("\nEnter array size : ");
                  @SuppressWarnings("resource")
                  Scanner sc = new Scanner(System.in);
                  size = sc.nextInt();
                  int[] arr = new int[size+1];
                  System.out.println("\nAccept Numbers : ");
                  for (i = 0; i < size; i++)
                      arr[i] = sc.nextInt();
          
                  System.out.println("\nArray with Unique list  : ");
          
                  for (i = 0; i < size; i++) {
                        for (j = i + 1; j < size;) {
                           if (arr[j] == arr[i]) {
                               same++;
                              for (k = j; k < size; k++) {
                                 arr[k] = arr[k + 1];
                              }
                              size--;
                           } else
                              j++;
                        }
                     }
          
          
          
          
                  for (int g = 0; g < arr.length; g++) {
                      System.out.println(arr[g]);
                  }
          
              }
          
          }
          

          【讨论】:

            【解决方案8】:

            使用以下方法:

            /*
             * Method to remove duplicates from array in Java, without using
             * Collection classes e.g. Set or ArrayList. Algorithm for this
             * method is simple, it first sort the array and then compare adjacent
             * objects, leaving out duplicates, which is already in the result.
             */
            public static int[] removeDuplicates(int[] numbersWithDuplicates) {
            
                // Sorting array to bring duplicates together      
                Arrays.sort(numbersWithDuplicates);     
            
                int[] result = new int[numbersWithDuplicates.length];
                int previous = numbersWithDuplicates[0];
                result[0] = previous;
            
                for (int i = 1; i < numbersWithDuplicates.length; i++) {
                    int ch = numbersWithDuplicates[i];
            
                    if (previous != ch) {
                        result[i] = ch;
                    }
                    previous = ch;
                }
                return result;
            
            }
            

            【讨论】:

              【解决方案9】:

              这是在不应用排序和集合的情况下删除重复元素的最佳解决方案。

              public static int[] removeElm(int arr[]) {
                  int[] tempArr = new int[arr.length];
                  int j = 0;
                  tempArr[j] = arr[0];
                  for (int i = 1; i < arr.length; i++) {
                      boolean check = false;
                      for (int k = 0; k < j + 1; k++) {
                          if (tempArr[k] != arr[i]) {
                              check = true;
                          } else {
                              check = false;
                              break;
                          }
                      }
                      if (check) {
                          tempArr[++j] = arr[i];
                      }
                  }
                  return tempArr;
              }
              

              【讨论】:

                【解决方案10】:
                package com.array;
                import java.util.*;
                
                class RemoveDuplicatesInArray{
                
                    public static void main(String[] args) {
                        Integer[] array = new Integer[10];
                
                        array[0] = 1;
                        array[1] = 2;
                        array[2] = 3;
                        array[3] = 3;
                        array[4] = 3;
                        array[5] = 3;
                        array[6] = 7;
                        array[7] = 7;
                        array[8] = 9;
                        array[9] = 9;
                        removeDuplicatesFromArray(array);
                
                    }
                
                
                    private static void removeDuplicatesFromArray(Integer[] array){
                        StringBuffer stringBuffer = new StringBuffer();
                         String arrayString =  Arrays.toString(array);
                         for(int index =0 ; index <= arrayString.length(); index++){
                          try{
                              int number = Integer.parseInt(arrayString.charAt(index)+"");
                              if(!stringBuffer.toString().contains(number+"")){
                              if(stringBuffer.length()!=0)
                                  stringBuffer.append(",");
                                 stringBuffer.append(number);
                              }
                
                          }catch(Exception e){
                
                          }
                         }
                         String[] stringArray = stringBuffer.toString().split(",");
                         array = new Integer[stringArray.length];
                         for(int index = 0 ; index < stringArray.length ; index++){
                           array[index] = Integer.parseInt(stringArray[index]); 
                         }
                         System.out.println(Arrays.toString(array));
                      }
                
                }
                

                【讨论】:

                  猜你喜欢
                  • 1970-01-01
                  • 1970-01-01
                  • 1970-01-01
                  • 2010-10-13
                  • 2013-10-23
                  • 1970-01-01
                  • 2021-05-21
                  • 1970-01-01
                  相关资源
                  最近更新 更多