Java solution,


  • 0

    O(n) solution

    public class Solution {
        public int removeDuplicates(int[] nums) {
            if(nums.length <= 2) {
                return nums.length;
            }
            int index = 1;
            int count = 0; //count of dup, same with preceding element
            for(int i = 1; i < nums.length; i++) {
                if(nums[i] != nums[i-1]) {
                    nums[index++] = nums[i];
                    count = 0;
                } else if(count < 1) {
                    count++;
                    nums[index++] = nums[i];
                }
            }
            return index;
        }
    }
    

Log in to reply
 

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