Two pointer easy Java solution


  • 0
    X

    The j is used to traverse each element in the array.
    The i is used to indicate the max element index of NOT duplicated sorted array.

    public class Solution {
        public int removeDuplicates(int[] nums) {
            if(nums.length == 0)return 0;
            if(nums.length == 1)return 1;
            
            int i = 0;
            int j = 1;
            
            for(; j < nums.length; j ++) {
                if(nums[j] != nums[i]) {
                    i ++;
                    nums[i] = nums[j];
                }
            }
            return i + 1;
        }
    }
    

Log in to reply
 

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