简体   繁体   中英

incompatible conversion from int[] to int

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.

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)

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM