java - 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。
解决方案
我希望 leetcode 在这行有问题:
int new_nums[] = removeDuplicates(nums);
这不是定义整数数组的典型方法(这是 C 风格)。Java 确实支持这种语法,但它有点神秘。有关更多详细信息,请参阅此答案。
试试这个:
int[] new_nums = removeDuplicates(nums);
推荐阅读
- scala - 如何使火花流处理多批次?
- c# - 从已知索引中获取字符串,直到找到 \r\n
- r - 比较矩阵的行并删除项目
- php - 是否可以将成功的登录 cookie 转储到站点并绕过会话?
- java - 如果语句中的 SonarQube Java 'NullPointerException 可能会被抛出'
- asp.net-core - ASP.NET Core SignalR websocket 连接限制
- javascript - 防止空字符串成为数组的一部分
- c# - C# 将共享项目中的类与许多项目集成
- php - 使用 PHP 合并 JSON 数组值
- spring - NoSuchMethodException:org.springframework.boot.autoconfigure.http.HttpMessageConverters