Java – Buckle: Remove Duplicates from Sorted Array

Buckle: Remove Duplicates from Sorted Array… here is a solution to the problem.

Buckle: Remove Duplicates from Sorted Array

Why doesn’t the Leetcode compiler accept this code?
My program runs in netbeans. But the leetcode compiler does not accept it.

Here is my code :

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;
}

Here is my main method:

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 + " ");
}

}

The error is:

incompatible types: int[] cannot be converted to int.

Solution

I expect leetcode has a problem with this line :

int new_nums[] = removeDuplicates(nums);

This is not the typical way to define arrays of integers (this is C style). Java does support syntax, but it’s a bit mysterious. See also this answer for more detail

Try this :

int[] new_nums = removeDuplicates(nums);

Just tried it on LeetCode and it seems to work:
OP's code running on LeetCode

Related Problems and Solutions