在 Core Java 中从数组中删除重复元素

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16102696/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 21:55:30  来源:igfitidea点击:

Removing duplicate elements from Array in Core Java

java

提问by Deepak

Without using collections,i have written a java program to remove duplicate integer element from an integer array,however the program is removing only one integer element and other integer element is left over.

在不使用集合的情况下,我编写了一个 Java 程序来从整数数组中删除重复的整数元素,但是该程序只删除了一个整数元素,而剩下的其他整数元素。

Could you let me know how should i remove duplicate integer elements in the below core java program.In the below core java program i have to remove the duplicate integer element 5

你能让我知道我应该如何在下面的核心 java 程序中删除重复的整数元素。在下面的核心 java 程序中,我必须删除重复的整数元素 5

Help provided will be appreciated.

提供的帮助将不胜感激。

Below is the Java code.

下面是Java代码。

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class DeleteElementFromArray {

    static int[] a = {5,1,2,3,4,5,7,8,9,10};
    static int[] b = new int[10];
    static int i, k, f, j = 0;
    static int l = a.length;

    void DeletElementInt() {
         for (i = 0; i < l; i++) {
             if (i != k) {
                   if (i < k) {
                       b[i] = a[i];
                   } else{                    
                         b[i - 1] = a[i];
                   }  
             }
         }
     }       



    public static void main(String[] args) {
          DeleteElementFromArray d = new DeleteElementFromArray();
          System.out.println("Array Elements are ");
          for (i = 0; i < l; i++){
            System.out.println(a[i]); 
          }
          InputStreamReader is = new InputStreamReader(System.in);
          BufferedReader br = new BufferedReader(is);
          System.out.println("Enter the Element for Delete");
          try {
             String s = br.readLine();
             f = Integer.parseInt(s);
              for (i = 0; i < l; i++) {
                if (f == a[i]) {
                  System.out.println("Delete Element found from given array");
                  k = i;
                  j++;
                  d.DeletElementInt();
                }
              }
                 l = l - 1;
                 System.out.println("New Array ");
                 for (i = 0; i < l; i++) 
                 {
                      System.out.println(b[i]);
                 }
                 if (j == 0) {
                   System.out.println("Entered Element does not found from given array");
                 }
          } catch (IOException e) {
                System.out.println(e);
          }
    }
}


//output
/*
Array Elements are 
5
1
2
3
4
5
7
8
9
10
Enter the Element for Delete
5
Delete Element found from given array
New Array 
1
2
3
4
5
7
8
9
10
*/

回答by izogfif

Here is the fixed code:

这是固定代码:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class DelElem {

    static int[] a = {5,1,2,3,4,5,7,8,9,10};
    static int[] b = new int[10];
    static int f, i, k, j = 0;
    static int l = a.length;

    static void DeleteElementInt(int elementToDelete) {
        j = 0;
        for (int i = 0; i < l; i++)
            if (a[i] != elementToDelete)
                b[i - j] = a[i];
            else
                ++j;
    }



    public static void main(String[] args) {
        System.out.println("Array elements are:");
        for (i = 0; i < a.length; i++)
            System.out.println(a[i]);
        InputStreamReader is = new InputStreamReader(System.in);
        BufferedReader br = new BufferedReader(is);
        System.out.print("Enter the element to be deleted: ");
        try {
            String s = br.readLine();
            f = Integer.parseInt(s);
            DeleteElementInt(f);
            System.out.println("New array:");
            for (i = 0; i < l - j; i++)
                System.out.println(b[i]);
            if (j == 0)
                System.out.println("Entered element was not found in the given array");
        } catch (IOException e) {
            System.out.println(e);
        }
    }
}


//output
/*
Array elements are:
5
1
2
3
4
5
7
8
9
10
Enter the element to be deleted: 5
New array:
1
2
3
4
7
8
9
10
*/

回答by Nicolas

First you have to sort your array. It will be much easier for you to remove the duplicates if you do. The Arrays class contains various methods (most of them are static) to manipulate arrays. Use Arrays.sort(array). If you're not allowed to, you have to use one of the many existing sorting algorithm. The simplest being Bubble sort.

首先,您必须对数组进行排序。如果这样做,您将更容易删除重复项。Arrays 类包含各种操作数组的方法(其中大部分是静态的)。使用Arrays.sort(array). 如果不允许,则必须使用许多现有排序算法中的一种。最简单的是冒泡排序

Insert the first integer in your result array, and in a temporary variable which will contain the last inserted value. Parse the source array: if the current value is different than the temporary var, insert it in the result array (and update the temp var).

在结果数组中插入第一个整​​数,并在包含最后插入值的临时变量中插入。解析源数组:如果当前值与临时变量不同,则将其插入结果数组(并更新临时变量)。

Be careful with the size of your return array.

注意返回数组的大小。

回答by Marco Forberg

is Arrays.sort()okay?

Arrays.sort()好吗?

static int[] a = {5,1,2,3,4,5,7,8,9,10};
static int[] b = new int[a.length];

Arrays.sort(a);

b[0]=a[0];
int bIndex = 1;
for(int aIndex = 1; aIndex < a.length; aIndex++) {
    if(b[bIndex-1] != a[aIndex]) {
        b[bIndex] = a[aIndex];
        bIndex++;
    }
}

int[] result = Arrays.copyOfRange(b, 0, bIndex);

if this is for educational purposes another interesting approach could be to construct a tree structure with the numbers and flatten the tree to an array when all inserts are done.

如果这是出于教育目的,另一种有趣的方法可能是构建一个带有数字的树结构,并在所有插入完成后将树展平为数组。

回答by Damian Leszczyński - Vash

The first question when some one ask you to work with arrays should be. Do the order is important ?

当有人要求您使用数组时,第一个问题应该是。顺序重要吗?

Most problem with arrays can be solved by sorting it first and then the problem is reduced to trivial from complex as you always work on the same type of data. As Archimedes sad once "Give me a place to stand on, and I will move the Earth". The sort operation is that stand place.

数组的大多数问题都可以通过先对它进行排序来解决,然后问题从复杂减少到微不足道,因为您总是在处理相同类型的数据。正如阿基米德曾经悲伤过的“给我一个站立的地方,我将推动地球”。排序操作是站位。

When you sort your array, then you just need to traverse it and find that next item is equal to previous. This is trivial.

当您对数组进行排序时,您只需要遍历它并找到下一项等于前一项。这是微不足道的。

How ever if the order is important then we have a little bit harder task.

但是,如果订单很重要,那么我们的任务就有点难了。

So first solution that pop i my mind is to create new point to stand. The rules are that array has items grater or equal then zero.

因此,我想到的第一个解决方案是创建新的站立点。规则是数组的项目大于或等于零。

In this case we could do something like this.

在这种情况下,我们可以做这样的事情。

  1. We find the grates element in our source array.
  2. We create a boolean array with size of grates item.
  3. We move through each item of source list and
  4. We check that boolean arrays position of value has false if so then we set it to true an print the result else we go to next item of source array.
  1. 我们在源数组中找到了 grates 元素。
  2. 我们创建一个布尔数组,其大小为炉排项目。
  3. 我们遍历源列表的每个项目和
  4. 我们检查布尔数组值的位置是否为假,如果是,则将其设置为真并打印结果,否则我们将转到源数组的下一项。

The step 4 was simplified as we want to print the list. The technical aspect of returning new one with distinct values is trivial to.

由于我们要打印列表,因此简化了步骤 4。返回具有不同值的新值的技术方面是微不足道的。

So good luck.

所以祝你好运。

回答by pradyumna kaushik

import java.util.Scanner;

public class RemoveAllOccurences{

    static int[] removeAll(int[] a,int n){
        int[] dupl = new int[a.length];
        for(int i = 0;i < dupl.length;i++){
            dupl[i] = -999;
        }
        int index = 0;
        //looping over,finding all occurrences of n and creating new array that does not contain n.
        for(int i = 0;i < a.length;i++){
            if(a[i] != n){
                dupl[index++] = a[i];
            }
        }

        //returning array with all duplicates removed.
        return dupl;
    }

    public static void main(String[] args) {

        int[] a = {3,5,5,5,3,6,5,3,3};
        int numberToRemove;

        System.out.println("the array values are:");
        for(int i:a){
            System.out.print(a[i]+"\t");
        }

        Scanner sc = new Scanner(System.in);
        System.out.println("\nenter the number for which all occurences need to be deleted:");

        numberToRemove = sc.nextInt();

        int[] b = removeAll(a,numberToRemove);

        System.out.println("After removing all occurences of "+numberToRemove);
        for(int i:b){
            if(i != -999)
                System.out.print(i+"\t");
        }

    }
}

回答by Rahul Kale

Below is my solution:

以下是我的解决方案:

First step:- Iterate through array with nested loops to find duplicates Second step:- If found duplicates copy all elements in new array except duplicate element.

第一步:- 使用嵌套循环遍历数组以查找重复项 第二步:- 如果找到重复项,则复制新数组中除重复元素外的所有元素。

Please find below code, any improvement would be appreciated.

请找到下面的代码,任何改进将不胜感激。

public class DuplicateElements {

公共类重复元素{

private static int[] arr = new int[]{3,2,4,4,5,3,8,2,4,9,10};

public static void main(String[] args) {
    for(int i=0;i<arr.length;i++){
        int arr_i = arr[i];
        for(int j=0;j<arr.length;j++){
            if(arr_i == arr[j] && i != j){
                removeElement(j);
            }
        }
    }

    for(int i=0;i<arr.length;i++){
        System.out.print(arr[i]+", ");
    }
}

public static void removeElement(int position){
    int[] intArr = new int[arr.length - 1];
    for(int i=0;i<position;i++){
        intArr[i] = arr[i];
    }
    for(int i=position+1;i<arr.length;i++){
        intArr[i-1] = arr[i];
    }
    arr = intArr;
}

}

}

回答by Deepak Singhal

public static void main(String[] args) {
    int a[]={1,4,3,2,6,5,7,3,5,4,2};
    int b[]=new int[a.length];
    Arrays.sort(a);
    int j=0;
    for(int i=0;i<a.length;i++){
        while(i<a.length-1 && a[i]==a[i+1]){
            a[i]=999;  // This can be any tag which you are not going to have in your array
            i++;
        }
        if(a[i]!=999)
            b[j++]=a[i];
    }

    System.out.println(b);
}