首页 > 解决方案 > Leetcode:从排序数组中删除重复项

问题描述

为什么 Leetcode 编译器不接受这段代码?我的程序在 netbeans 中运行。但 leetcode 编译器不接受它。

这是我的代码:

import  java.util.Arrays;


public class RemoveDuplicateFromArray {

public static int[] removeDuplicates(int[] nums) {

    int temp, count = 0 ,l = 0;
    temp = nums[0];

  for(int i = 1; i < nums.length - (1 + l); i++ ) {

      if(temp == nums[i]) {
          count = count + 1;

          for(int j = i; j < nums.length - count; j++){
              nums[j] = nums[j+1];
            }

          i = i - 1;

      } else {
          temp = nums[i];
          i = i ;

      }
       l = count;
  }

      nums = Arrays.copyOfRange(nums, 0, nums.length-count);

      if(nums.length == 2){
      if(nums[0] == nums[1]){
          nums = Arrays.copyOfRange(nums, 0, nums.length-1);
      }
  } 

    return  nums;
}

这是我的主要方法:

public static void main(String[] args) {

    int[] nums = new int[] {1,1,1}; // showing error here.
    System.err.println("nums lenght: " +nums.length);

    int new_nums[] = removeDuplicates(nums);

   for(int i : new_nums) {
        System.err.print(i + " ");
}

}

}

错误是:

不兼容的类型:int[] 不能转换为 int。

标签: java

解决方案


我希望 leetcode 在这行有问题:

int new_nums[] = removeDuplicates(nums);

这不是定义整数数组的典型方法(这是 C 风格)。Java 确实支持这种语法,但它有点神秘。有关更多详细信息,请参阅此答案

试试这个:

int[] new_nums = removeDuplicates(nums);

刚刚在 LeetCode 上尝试过,似乎有效: 在 LeetCode 上运行的 OP 代码


推荐阅读