3

Why this code is not accepted by Leetcode compiler? My program is running in netbeans. but leetcode compiler is not accepting 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 mathod:

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.

Melchia
  • 16,699
  • 16
  • 70
  • 93
salma209
  • 179
  • 2
  • 6

2 Answers2

3

I expect leetcode is having trouble with this line:

int new_nums[] = removeDuplicates(nums);

This isn't the typical way to define an integer array (this is the C style). Java does support the syntax, but it's a little arcane. See this answer for more detail.

Try this instead:

int[] new_nums = removeDuplicates(nums);

Just tried this on LeetCode, seems to work: OP's code running on LeetCode

Michael Powers
  • 1,800
  • 1
  • 4
  • 12
  • Tried the code you provided on LeetCode, everything seems ok. Can you provide more information about the error you're getting? – Michael Powers Aug 10 '18 at 18:49
0

I would do it a bit like this myself:

import java.util.ArrayList;
import java.util.List;

public class Main {
    public static void main(String[] args) {

        int[] nums = new int[]{1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 5, 6, 7, 7, 7, 8, 9, 0, 0, 0, 0}; 
        System.out.println("nums lenght: " + nums.length);

        int[] new_nums = removeDuplicates(nums);

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

    }
    public static int[] removeDuplicates(int[] nums) {
        List<Integer> found = new ArrayList();
        for (int i = 1; i < nums.length; i++) {
            if (!found.contains(nums[i])) {
                found.add(nums[i]);
            }
        }
        int[] ret = new int[found.size()];
        for(int i = 0; i < found.size(); i++){
            ret[i] = found.get(i);
        }
        return ret;
    }
}