|
| 1 | +package leetCode.DailyChallenge._2022.FEB; |
| 2 | + |
| 3 | +/** |
| 4 | + * @docs https://leetcode.com/problems/remove-duplicates-from-sorted-array-ii/ |
| 5 | + * |
| 6 | + * Given an integer array nums sorted in non-decreasing order, |
| 7 | + * remove some duplicates in-place such that each unique element appears at most twice. |
| 8 | + * The relative order of the elements should be kept the same. |
| 9 | + * |
| 10 | + * Since it is impossible to change the length of the array in some languages, |
| 11 | + * you must instead have the result be placed in the first part of the array nums. More formally, |
| 12 | + * if there are k elements after removing the duplicates, then the first k elements of nums should hold the final result. |
| 13 | + * It does not matter what you leave beyond the first k elements. |
| 14 | + * |
| 15 | + * Return k after placing the final result in the first k slots of nums. |
| 16 | + * |
| 17 | + * Do not allocate extra space for another array. |
| 18 | + * You must do this by modifying the input array in-place with O(1) extra memory. |
| 19 | + * |
| 20 | + * Custom Judge: |
| 21 | + * |
| 22 | + * The judge will test your solution with the following code: |
| 23 | + * |
| 24 | + * int[] nums = [...]; // Input array |
| 25 | + * int[] expectedNums = [...]; // The expected answer with correct length |
| 26 | + * |
| 27 | + * int k = removeDuplicates(nums); // Calls your implementation |
| 28 | + * |
| 29 | + * assert k == expectedNums.length; |
| 30 | + * for (int i = 0; i < k; i++) { |
| 31 | + * assert nums[i] == expectedNums[i]; |
| 32 | + * } |
| 33 | + * If all assertions pass, then your solution will be accepted. |
| 34 | + * |
| 35 | + * |
| 36 | + * |
| 37 | + * Example 1: |
| 38 | + * |
| 39 | + * Input: nums = [1,1,1,2,2,3] |
| 40 | + * Output: 5, nums = [1,1,2,2,3,_] |
| 41 | + * Explanation: Your function should return k = 5, with the first five elements of nums being 1, 1, 2, 2 and 3 respectively. |
| 42 | + * It does not matter what you leave beyond the returned k (hence they are underscores). |
| 43 | + * Example 2: |
| 44 | + * |
| 45 | + * Input: nums = [0,0,1,1,1,1,2,3,3] |
| 46 | + * Output: 7, nums = [0,0,1,1,2,3,3,_,_] |
| 47 | + * Explanation: Your function should return k = 7, with the first seven elements of nums being 0, 0, 1, 1, 2, 3 and 3 respectively. |
| 48 | + * It does not matter what you leave beyond the returned k (hence they are underscores). |
| 49 | + * |
| 50 | + * |
| 51 | + * Constraints: |
| 52 | + * |
| 53 | + * 1 <= nums.length <= 3 * 10^4 |
| 54 | + * -104 <= nums[i] <= 10^4 |
| 55 | + * nums is sorted in non-decreasing order. |
| 56 | + */ |
| 57 | +public class _06FEB2022_RemoveDuplicatesfromSortedArrayII { |
| 58 | + public int removeDuplicates(int[] nums) { |
| 59 | + int i = 0; |
| 60 | + for (int n : nums) |
| 61 | + if (i < 2 || n > nums[i-2]) |
| 62 | + nums[i++] = n; |
| 63 | + return i; |
| 64 | + } |
| 65 | +} |
0 commit comments