Skip to content

Commit 6eda6d2

Browse files
committed
add 026
1 parent 810c5c1 commit 6eda6d2

File tree

2 files changed

+75
-0
lines changed

2 files changed

+75
-0
lines changed

note/026/README.md

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
# [Remove Duplicates from Sorted Array][title]
2+
3+
## Description
4+
5+
Given a sorted array, remove the duplicates in-place such that each element appear only once and return the new length.
6+
7+
Do not allocate extra space for another array, you must do this by **modifying the input array** in-place with O(1) extra memory.
8+
9+
**Example:**
10+
11+
```text
12+
Given nums = [1,1,2],
13+
14+
Your function should return length = 2, with the first two elements of nums being 1 and 2 respectively.
15+
It doesn't matter what you leave beyond the new length.
16+
```
17+
18+
## 思路
19+
20+
题意是让你从一个有序的数组中移除重复的元素,并返回之后数组的长度。
21+
此外,特别要注意,需要修改原数组。
22+
23+
判断长度小于等于 1 的话直接返回原长度即可,否则的话遍历一遍数组,用一个 tail 变量指向新的数组尾部,如果后面的元素和前面的元素不同,就让后面的元素写到 tail 所指数组元素,然后 tail 变量加一,最后返回 tail 即可。
24+
25+
## [完整代码][src]
26+
27+
```Java
28+
class Solution {
29+
public int removeDuplicates(int[] nums) {
30+
int len = nums.length;
31+
if (len <= 1) return len;
32+
33+
int tail = 1;
34+
for (int i = 1; i < len; i++) {
35+
if (nums[i] != nums[i - 1]) {
36+
nums[tail++] = nums[i];
37+
}
38+
}
39+
40+
return tail;
41+
}
42+
}
43+
```
44+
45+
[title]: https://leetcode.com/problems/remove-duplicates-from-sorted-array
46+
[src]: https://github.com/andavid/leetcode-java/blob/master/src/com/andavid/leetcode/_026/Solution.java
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
package com.andavid.leetcode._026;
2+
3+
public class Solution {
4+
public int removeDuplicates(int[] nums) {
5+
int len = nums.length;
6+
if (len <= 1) return len;
7+
8+
int tail = 1;
9+
for (int i = 1; i < len; i++) {
10+
if (nums[i] != nums[i - 1]) {
11+
nums[tail++] = nums[i];
12+
}
13+
}
14+
15+
return tail;
16+
}
17+
18+
public static void main(String[] args) {
19+
Solution solution = new Solution();
20+
int[] nums = {1, 1, 2, 3, 3, 3};
21+
22+
int len = solution.removeDuplicates(nums);
23+
System.out.println("length = " + len);
24+
25+
for (int i = 0; i < len; i++) {
26+
System.out.print(nums[i] + (i == len - 1 ? "" : ", "));
27+
}
28+
}
29+
}

0 commit comments

Comments
 (0)