从整数数组中删除重复项。

13

我在编写下面的代码时遇到了问题:

编写一个名为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

5
简单的方法是将元素添加到一个集合中(这样可以自动为您去除重复项),然后再将数字放回数组中。 - assylias
2
可能是重复的问题:什么是在Java中删除数组中重复项的最佳方法?,还有其他类似的问题... - Brian Roach
你没有说明你的实现约束条件,我敢打赌有很多,否则解决方案就是微不足道的。 - Marko Topolnik
1
实际上我不能使用Set或HashSet,必须使用循环和简单数组来完成。 - Ali-J8
23个回答

8
为了保留整数数组的顺序并去除重复项,您可以尝试以下方法:
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);
}

希望这能帮到您。

6

试试这个 -

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

1
看起来这里有一个错误。应该是if(!isExists(result, i))而不是if(isExists(result, i))。 - nakosspy
3
唯一能够拯救秩序的解决方案。但有两个问题:1)会跳过0;2)如果有重复,最后会有0。这两个问题都很容易解决。 - RiaD

3

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

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

3
尝试一下。
 int numbers[] = {1,2,3,4,1,2,3,4,5,1,2,3,4};

 numbers =  java.util.stream.IntStream.of(numbers).distinct().toArray();

2
也许您可以使用lambdaj (下载,官网),这个库非常强大,用于管理集合(..列表、数组)。以下代码非常简单,而且完美运行:
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添加到你的项目中。希望这对你有用。
注意:假设你的代码有替代方案,这将会对你有所帮助。

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

}

1
这是一个面试问题。 问题:原地删除数组中的重复元素。
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中:使用enumerate的列表推导式。
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]

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

    }

}

1
您可以使用不允许重复元素的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]


1

你也可以将数组元素放入一个Set中,其语义精确地表示它不包含重复元素。


2
Set set = new HashSet( Arrays.asList( s ) ) 这段代码无法编译。 - Subhrajyoti Majumder
-1 Set是一个原始类型。对泛型类型Set<E>的引用应该进行参数化。 - dogbane
你的编辑并没有解决问题,你不能使用Arrays.asList()int[]转换为Integer[] - assylias

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接