|
| 1 | +// Given an integer array nums sorted in non-decreasing order, remove the duplicates in-place such that each unique element appears only once. |
| 2 | + |
| 3 | +// The relative order of the elements should be kept the same. Then return the number of unique elements in nums. |
| 4 | + |
| 5 | +// Consider the number of unique elements of nums to be k, to get accepted, you need to do the following things: |
| 6 | + |
| 7 | +// Change the array nums such that the first k elements of nums contain the unique elements in the order they were present in nums initially. |
| 8 | +// The remaining elements of nums are not important as well as the size of nums. Return k. |
| 9 | + |
| 10 | +// Custom Judge: |
| 11 | +// The judge will test your solution with the following code: |
| 12 | + |
| 13 | +/* |
| 14 | +* int[] nums = [...]; // Input array |
| 15 | +* int[] expectedNums = [...]; // The expected answer with correct length |
| 16 | +* |
| 17 | +* int k = removeDuplicates(nums); // Calls your implementation |
| 18 | +* |
| 19 | +* assert k == expectedNums.length; |
| 20 | +* for (int i = 0; i < k; i++) { |
| 21 | +* assert nums[i] == expectedNums[i]; |
| 22 | +* } |
| 23 | +*/ |
| 24 | + |
| 25 | +// If all assertions pass, then your solution will be accepted. |
| 26 | + |
| 27 | + |
| 28 | + |
| 29 | +// Example 1: |
| 30 | + |
| 31 | +// Input: nums = [1,1,2] |
| 32 | +// Output: 2, nums = [1,2,_] |
| 33 | +// Explanation: Your function should return k = 2, with the first two elements of nums being 1 and 2 respectively. |
| 34 | +// It does not matter what you leave beyond the returned k (hence they are underscores). |
| 35 | + |
| 36 | +// Example 2: |
| 37 | + |
| 38 | + |
| 39 | +// Input: nums = [0,0,1,1,1,2,2,3,3,4] |
| 40 | +// Output: 5, nums = [0,1,2,3,4,_,_,_,_,_] |
| 41 | +// Explanation: Your function should return k = 5, with the first five elements of nums being 0, 1, 2, 3, and 4 respectively. |
| 42 | + |
| 43 | + |
| 44 | +class Solution { |
| 45 | +public: |
| 46 | + int removeDuplicates(vector<int>& nums) { |
| 47 | + int pos = 0; |
| 48 | + for (auto x : nums) |
| 49 | + {if(pos==0) nums[pos++] = x; |
| 50 | + else |
| 51 | + if( x > nums[pos-1]) |
| 52 | + nums[pos++] = x;} |
| 53 | + return pos; |
| 54 | + } |
| 55 | +}; |
0 commit comments