Simple Java Solution O(n) time and O(1) space. Replace 2 at line 12 with k


  • 0
    A
    public class Solution {
        public int removeDuplicates(int[] nums) {
            if (nums ==  null || nums.length == 0){
                return 0;
            }
            int idx = 1;
            for (int i = 0; i < nums.length; i++){
                int count = 1;
                int ref = nums[i];
                int j = i+1;
                while (j <= nums.length - 1 && ref == nums[j]){
                    if (count < 2){
                        nums[idx++] = ref;
                    }
                    count++;
                    j++;
                }
                if(j <= nums.length - 1){
                    nums[idx++] = nums[j];
                }
                i = j - 1;
            }
            return idx;
        }
    }

Log in to reply
 

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