Skip to content

Commit 1558690

Browse files
committed
Add Solution 027[Java]
1 parent 5a844f3 commit 1558690

File tree

2 files changed

+75
-0
lines changed

2 files changed

+75
-0
lines changed

solution/027.Remove Element/README.md

+54
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
## 移除元素
2+
### 题目描述
3+
4+
给定一个数组 nums 和一个值 val,你需要原地移除所有数值等于 val 的元素,返回移除后数组的新长度。
5+
6+
不要使用额外的数组空间,你必须在原地修改输入数组并在使用 O(1) 额外空间的条件下完成。
7+
8+
元素的顺序可以改变。你不需要考虑数组中超出新长度后面的元素。
9+
10+
示例 1:
11+
12+
给定 nums = [3,2,2,3], val = 3,
13+
14+
函数应该返回新的长度 2, 并且 nums 中的前两个元素均为 2。
15+
16+
你不需要考虑数组中超出新长度后面的元素。
17+
示例 2:
18+
19+
给定 nums = [0,1,2,2,3,0,4,2], val = 2,
20+
21+
函数应该返回新的长度 5, 并且 nums 中的前五个元素为 0, 1, 3, 0, 4。
22+
23+
注意这五个元素可为任意顺序。
24+
25+
你不需要考虑数组中超出新长度后面的元素。
26+
27+
### 解法
28+
1. 维护 i 和 end 两个指针,end 指向数组尾部,i 从左向右遍历数组,
29+
2. 若 nums[i] == val, 则把数组尾部的值 nums[end] 拷贝至 i 的位置,然后将 end 指针向左移动;否则,i 向右移动,继续遍历数组。
30+
3. 这样当两个 i 与 end 相遇时,end 左边的所以 val 元素都被 end 右边的非 val 元素替换。
31+
32+
```java
33+
class Solution {
34+
public int removeElement(int[] nums, int val) {
35+
if(nums == null || nums.length == 0) {
36+
return 0;
37+
}
38+
39+
int end = nums.length - 1;
40+
int i = 0;
41+
while(i <= end) {
42+
if(nums[i] == val) {
43+
nums[i] = nums[end];
44+
end--;
45+
}
46+
else {
47+
i++;
48+
}
49+
}
50+
return end + 1;
51+
52+
}
53+
}
54+
```
+21
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
class Solution {
2+
public int removeElement(int[] nums, int val) {
3+
if(nums == null || nums.length == 0) {
4+
return 0;
5+
}
6+
7+
int end = nums.length - 1;
8+
int i = 0;
9+
while(i <= end) {
10+
if(nums[i] == val) {
11+
nums[i] = nums[end];
12+
end--;
13+
}
14+
else {
15+
i++;
16+
}
17+
}
18+
return end + 1;
19+
20+
}
21+
}

0 commit comments

Comments
 (0)