[LeetCode] 80. Remove Duplicates from Sorted Array II

Remove duplicates in sorted array II. Given a sorted array, you need to delete the repeated elements in place, so that each element appears at most twice , and return the new length of the array after removal. Don't use extra array space, you must modify the input array in place and do it with O (1) extra space. example,

Example 1:

Given nums = [1,1,1,2,2,3],

Your function should return length = 5, with the first five elements of nums being 1, 1, 2, 2 and 3 respectively.

It doesn't matter what you leave beyond the returned length.

Example 2:

Given nums = [0,0,1,1,1,1,2,3,3],

Your function should return length = 7, with the first seven elements of nums being modified to 0, 0, 1, 1, 2, 3 and 3 respectively.

It doesn't matter what values are set beyond the returned length.

The idea is similar to version one, but it needs to be separated from the two positions. Create a res pointer to point to the first invalid position. For example, in the first example, res initially points to the third one, because the number at this position must be invalid and needs to be replaced. Because the title requires elements that can be repeated twice, the first two elements do not need to be changed. Then every time res is compared with the number before 2 positions to see if there is any repetition, and put it into the array without repetition.

Time O (n)

Space O (1)

Java implementation

 1 class Solution {
 2     public int removeDuplicates(int[] nums) {
 3         // corner case
 4         if (nums.length <= 2)
 5             return nums.length;
 6 
 7         // normal case
 8         int res = 2;
 9         for (int i = 2; i < nums.length; i++) {
10             if (nums[i] != nums[res - 2]) {
11                 nums[res] = nums[i];
12                 res++;
13             }
14         }
15         return res;
16     }
17 }

 

JavaScript implementation

 1 /**
 2  * @param {number[]} nums
 3  * @return {number}
 4  */
 5 var removeDuplicates = function(nums) {
 6     // corner case
 7     if (nums.length <= 2) return nums.length;
 8 
 9     // normal case
10     let res = 2;
11     for (let i = 2; i < nums.length; i++) {
12         if (nums[i] !== nums[res - 2]) {
13             nums[res] = nums[i];
14             res++;
15         }
16     }
17     return res;
18 };

 

Guess you like

Origin www.cnblogs.com/aaronliu1991/p/12749299.html