【问题标题】:Java = How to Remove duplicates in int array without using collections or methods like Arrays.copyOf()? [duplicate]Java = 如何在不使用 Arrays.copyOf() 之类的集合或方法的情况下删除 int 数组中的重复项? [复制]
【发布时间】:2021-05-21 18:18:20
【问题描述】:
public static int[] removeSameNumber(int[] input) {
   
   removeSamenumber() takes numbers (int) to array and returns new array with deleted duplicates.
   
   new int[] {2, 2} ==== new int[] {2}
   
   new int[] {1, 2, 1, 3, 2} ==== new int[] {1, 2, 3}

不得使用List、Set 或其他动态集合。你只需要处理数组。

不得使用Arrays.copyOf()等现有函数。

我尝试了很多不同的方法,但都没有奏效

我是初学者,你的帮助对我很有帮助:)

【问题讨论】:

  • 如果您真的不想使用集合,您可以遍历数组,复制新数组中尚未遇到的值。但同样,你为什么不想为此使用集合呢?他们会让工作变得更简单。
  • 你已经尝试了什么?已经看到这个会很有趣

标签: java arrays duplicates


【解决方案1】:

如果您想在没有库方法的情况下对数组进行重复数据删除,可以这样做:

public static void main(String[] args) {
    int[] source = new int[] {1, 2, 1, 3, 2, 1, 4, 3, 2, 1, 11};
    int maxElement = 0;
    int sizeWithoutDouble = source.length;
    //get max int from source array, for getting temp array size
    for (int i = 0; i < source.length; i ++){
        maxElement = Math.max(maxElement, source[i]);
    }
    int temp[] = new int[maxElement + 1];
    //put in temp array uniuque int and decrement total int count
    for (int i = 0; i < source.length; i ++){
        if (temp[source[i]] == 0){
            temp[source[i]] = source[i];
        }else {
            sizeWithoutDouble--;
        }
    }
    //declare result array with size uniuque int
    int result[] = new int[sizeWithoutDouble];
    int currentRes = 0;
    //filling result array
    for (int i = 0; i < temp.length; i ++){
        if (temp[i] != 0){
            result[currentRes++] = temp[i];
        }
    }   
}

输出:

[1, 2, 3, 4, 11]

【讨论】:

    【解决方案2】:
    int[] temp = new int[inputs.length];
            int nUnique = 0;
            for(int i=0;i<inputs.length;i++) {
                boolean dup = false;
                for(int j=i+1;j<inputs.length;j++) {
                    if(inputs[i]==inputs[j]) {
                        dup = true;
                        break;
                    }
                }
                
                if(!dup) {
                    temp[nUnique] = inputs[i];
                    nUnique++;
                }
            }
            int[] result = new int[nUnique];
            for(int i=0;i<nUnique;i++) {
                result[i] = temp[i];
                //System.out.println(result[i]);
            }
    return result;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-04-03
      • 1970-01-01
      • 1970-01-01
      • 2023-02-06
      • 1970-01-01
      相关资源
      最近更新 更多