forked from dnshi/Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRemoveDuplicatesFromSortedArray_II.js
More file actions
35 lines (33 loc) · 1.06 KB
/
RemoveDuplicatesFromSortedArray_II.js
File metadata and controls
35 lines (33 loc) · 1.06 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
// Source : https://leetcode.com/problems/remove-duplicates-from-sorted-array-ii
// Author : Dean Shi
// Date : 2017-03-04
/***************************************************************************************
*
* Follow up for "Remove Duplicates":
* What if duplicates are allowed at most twice?
*
* For example,
* Given sorted array 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. It doesn't matter what you leave beyond the new length.
*
*
***************************************************************************************/
/**
* @param {number[]} nums
* @return {number}
*/
var removeDuplicates = function(nums) {
let pointer = 0
for (let i = 1, isRepeated = false; i < nums.length; i++) {
if (nums[pointer] !== nums[i]) {
nums[++pointer] = nums[i]
isRepeated = false
} else if (!isRepeated) {
nums[++pointer] = nums[i]
isRepeated = true
}
}
return nums.length ? pointer + 1 : 0
};