Symple Accepted Java solution.


  • 2
    P
    public int removeDuplicates(int[] A) {
    	if (A.length == 0) return 0;
        int i = 0;
        for (int j=0; j<A.length; j++) {
        	if (A[i] != A[j]) i++;
        	A[i] = A[j];
        }
        return i+1;
    }

  • 0
    J

    better to put together

    if(A[j]!=A[i]){
        i++;
        A[i]=A[j];
    }

  • 0
    L

    I made two updates for your code.

    public int removeDuplicates(int[] A) {
      if (A == null || A.length == 0) return 0;
      int i = 0;
      for (int j=1; j<A.length; j++) {
         if (A[i] != A[j]) A[++i] = A[j];
      }
    
      return i+1;
    }
    
    1. it's better for j started from 1 instead of 0 as i = 0;
    2. if A[i] is not equal with A[j], it's not necessary to do A[i] = A[j].

  • 0
    L

    and better to put together ?
    if(A[i] != A[j]) A[++i] = A[j];


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.