Java clean code extended to at most k duplicates are allowed


  • 1

    In case there is another follow up for at most k duplicates, just replace k = 2 in the code

      public class Solution {
            public int removeDuplicates(int[] nums) {
                if (nums == null || nums.length == 0)
                    return 0;
                int count = 0;
                int k = 2;
                int i = 0;
                for (int j = 1; j < nums.length; j++) {
                    if (nums[j] == nums[i]) {
                        if (++count == k - 1) {
                            nums[++i] = nums[j];
                        } 
                    } else { 
                        nums[++i] = nums[j];
                        count = 0; //reset count 
                    }
                }
                return i + 1;
            }
        }

  • 0
    I

    You have a small bug though. The condition in the nested if should be ++count < k.


Log in to reply
 

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