Advertisement
exmkg

2-5

Jan 14th, 2025
33
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 0.85 KB | None | 0 0
  1. class Solution {
  2.     public int removeDuplicates(int[] nums) {
  3.         // [1, 1, 1, 1, 2, 2, 3, 4, 4, 4]
  4.         //  n  d  d  d  n  d  n  n  d  d
  5.         // n – non-duplicate.
  6.         // d – duplicate.
  7.  
  8.         // We will put non-duplicated numbers at positions
  9.         // 0, 1, 2, 3, 4, ..., etc. one-by-one.
  10.  
  11.         // Number nums[0] should stay at position 0.
  12.         // We will start filling non-duplicated numbers
  13.         // from position 1.
  14.         int j = 1;
  15.  
  16.         // Iterate starting from i = 1.
  17.         for (int i = 1; i < nums.length; i++) {
  18.             // If it's a duplicate (d), skip it.
  19.             if (nums[i] == nums[i - 1]) {
  20.                 continue;
  21.             }
  22.  
  23.             // Otherwise (n), put it at index j,
  24.             // and then increment j.
  25.             nums[j++] = nums[i];
  26.         }
  27.         return j;
  28.     }
  29. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement