-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathremove-duplicates-from-sorted-array.js
More file actions
96 lines (85 loc) · 1.92 KB
/
remove-duplicates-from-sorted-array.js
File metadata and controls
96 lines (85 loc) · 1.92 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
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
/**
* Source: https://leetcode.com/problems/remove-duplicates-from-sorted-array/
* Tags: [Array,Two Pointers]
* Level: Easy
* Title: Remove Duplicates from Sorted Array
* Auther: @imcoddy
* Content: Given a sorted array, remove the duplicates in place such that each element appear only once and return the new length.
*
*
* Do not allocate extra space for another array, you must do this in place with constant memory.
*
*
*
* For example,
* Given input array A = [1,1,2],
*
*
* Your function should return length = 2, and A is now [1,2].
*/
/**
* @param {number[]} A
* @return {number}
*/
/**
* Memo:
* Runtime: 189ms
* Rank: S
*/
var removeDuplicates = function(A) {
if (!A || A.length === 0) {
return 0;
}
if (A.length === 1) {
return 1;
}
var length = A.length;
var i = 0;
var j = 1;
while (i < length) {
while (A[i] === A[j] && j < length) {
A[j] = NaN;
j++;
}
i = j;
j = i + 1;
}
var count = 0;
for (var i = 0; i < length; i++) {
if (!isNaN(A[i])) {
A[count++] = A[i];
}
}
console.log(A);
return count;
};
/**
* @param {number[]} nums
* @return {number}
*/
/**
* Memo: Add unique elements to a new array, and put them back to nums.
* Complex: O(n)
* Runtime: 164ms
* Tests: 161 test cases passed
* Rank: S
* Updated: 2015-06-15
*/
var removeDuplicates = function(nums) {
var array = [];
var i = 0;
while (i < nums.length) {
if (nums[i] !== array[array.length - 1]) {
array.push(nums[i]);
}
i++;
}
for (var i = 0; i < array.length; i++) {
nums[i] = array[i];
}
return array.length;
};
console.log(removeDuplicates([1]));
console.log(removeDuplicates([1, 1, 1, 1]));
console.log(removeDuplicates([1, 1, 1, 2]));
console.log(removeDuplicates([1, 1, 1, 2, 2, 2, 2, 2]));