-
Notifications
You must be signed in to change notification settings - Fork 0
/
No27RemoveElement.java
52 lines (45 loc) · 1.02 KB
/
No27RemoveElement.java
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
package com.wzx.leetcode;
/**
* @see <a href="https://leetcode.com/problems/remove-element/">https://leetcode.com/problems/remove-element/</a>
* @author wzx
*/
public class No27RemoveElement {
/**
* 双指针,快慢指针
* <p>
* time: O(n)
* space: O(1)
*/
public int removeElement1(int[] nums, int val) {
// 用于存储的索引
int slow = 0;
// 用于遍历检测目标值的索引
int fast = 0;
for (; fast < nums.length; fast++) {
if (nums[fast] != val) {
nums[slow] = nums[fast];
slow++;
}
}
return slow;
}
/**
* 双指针,如果大多数元素不是val则方法二快,如果大多数元素是val则方法一快
* <p>
* time: O(n)
* space: O(1)
*/
public int removeElement2(int[] nums, int val) {
int left = 0;
int right = nums.length - 1;
while (left <= right) {
if (nums[left] == val) {
nums[left] = nums[right];
right--;
} else {
left++;
}
}
return left;
}
}