leetcode 27 Remove Element



Remove Element:题目链接

方法1:双指针之快慢指针

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
import java.util.Arrays;

public class Solution1 {
// 时间复杂度 O(N) 空间复杂度O(1) 双指针
public static int removeElement(int[] nums, int val) {
int slow = 0; // 存放不为val元素 区间[0, slow)
for (int fast = 0; fast < nums.length; ++fast) {
if (val != nums[fast]) {
nums[slow++] = nums[fast];
}
}
return slow;
}

public static void main(String[] args) {
int[] nums = {0, 1, 2, 2, 3, 0, 4, 2};
int val = 2;
System.out.println(removeElement(nums, val));
System.out.println(Arrays.toString(nums));
}
}

方法2:双指针之对撞指针

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19

void swap(int * nums, int i, int j){
int temp = nums[i];
nums[i] = nums[j];
nums[j] = temp;
}

int removeElement(int* nums, int numsSize, int val){
int i = 0, j = numsSize -1;
while (i <= j) {
if (nums[i] == val) {
swap(nums, i, j);
j--;
}else{
i++;
}
}
return i;
}

ps:源代码链接

文章目录
  1. 1. 方法1:双指针之快慢指针
  2. 2. 方法2:双指针之对撞指针
|