Reputation: 49
class Solution {
public int removeDuplicates(int[] nums) {
int [] arr = new int[nums.length];
for(int i=0; i<nums.length; i++){
if(nums[i] != nums[i+1]){
arr[i] = nums[i];
}
}
return arr;
}
}
this is my code and I am having error :: incompatible conversion from int[] to int.
Upvotes: 0
Views: 94
Reputation: 46
The above solutions are right but i noticed another problem in your solution. Let's say that the array has 10 numbers. You start from i = 0; and you continue until the i < array.legth. But in your comparison you compare num[i] and num [i+1]. So when i = 9 that is the last index of the array, the comparison will be if num[9] == num[10],so you will have a runtime error, because there is not index 10. one think you can do is this:
class Solution {
public int[] removeDuplicates(int[] nums) {
int [] arr = new int[nums.length];
for(int i=0; i<nums.length-1; i++){
if(nums[i] != nums[i+1]){
arr[i] = nums[i];
}
}
return arr;
}
You got to change the array.length to array.length-1. And if you still stuck that's an existed soltion for youe problem. remove dublicates
Upvotes: 2
Reputation: 109532
Already said the return type must be int[]
too.
public int[] removeDuplicates(int[] nums) {
if (nums.length == 0) {
return nums;
}
int[] arr = nums.clone();
int j = 0;
for (int i = 1; i < arr.length; i++) {
if (arr[i] != arr[j]) {
++j;
arr[j] = arr[i];
}
}
return Arrays.copy(arr, j + 1);
}
The removal of consecutive duplicates must be done a bit different. Above a not so elegant solution. Not tested.
Upvotes: 1
Reputation: 46
Your return statement is returning the int
array, but your declared return type is an int
primitive. You should return the int
array instead:
public int[] removeDuplicates(int[] nums)
Upvotes: 3