LeetCode - Algorithms - 26. Remove Duplicates from Sorted Array

Java

The size of a Java array is fixed when you allocate it, and cannot be changed.

You’ve to provide a fixed size for that Array, You can neither EXPAND or SHRINK that array.

1

26.[圖解]Remove Duplicates from Sorted Array

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class Solution {
public int removeDuplicates(int[] nums) {
if (nums.length<2) return nums.length;
int x=0,y=1;
while (y<nums.length) {
if (nums[x]==nums[y]) {
y+=1;
}
else {
x+=1;
nums[x]=nums[y];
y+=1;
}
}
return x+1;
}
}

Submission Detail

  • 161 / 161 test cases passed.
  • Runtime: 6 ms
  • Memory Usage: 39.8 MB
  • Your runtime beats 97.51 % of java submissions.

2

5 lines Java solution

1
2
3
4
5
6
7
8
9
10
11
class Solution {
public int removeDuplicates(int[] nums) {
if (nums.length==0) return 0;
int j=0;
for(int i=0;i<nums.length;i++) {
if (nums[i]!=nums[j])
nums[++j]=nums[i];
}
return ++j;
}
}

Submission Detail

  • 161 / 161 test cases passed.
  • Runtime: 7 ms
  • Memory Usage: 42 MB
  • Your runtime beats 61.11 % of java submissions.

JavaScript

1
2
3
4
5
6
7
8
9
10
11
12
/**
* @param {number[]} nums
* @return {number}
*/
var removeDuplicates = function(nums) {
if (nums.length < 2) return nums.length;
for (var i = 0; i < nums.length; i++) {
while (nums[i] === nums[i-1])
nums.splice(i, 1);
}
return nums.length;
};

Submission Detail

  • 161 / 161 test cases passed.
  • Runtime: 84 ms, faster than 42.35% of JavaScript online submissions for Remove Duplicates from Sorted Array.
  • Memory Usage: 37.7 MB, less than 22.92% of JavaScript online submissions for Remove Duplicates from Sorted Array.

Resources