27. 移除元素

27. 移除元素 - 力扣(Leetcode)

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
import java.util.Scanner;

//27 移除元素
class RemoveElement27 {
public static void main (String[] args) {
Scanner myScanner = new Scanner(System.in);
int[] numArray = {0,1,2,3,3,0,4,2};
System.out.print("请输入要去除的元素:");
int removeNum = myScanner.nextInt();
//int newLength = removeElement(numArray,removeNum);
int newLength = removeElement02(numArray,removeNum);
System.out.println("\nThe length of the new numArray is " + newLength);
myScanner.close();
}
//双指针法
public static int removeElement(int[] nums,int val){
int slowIndex = 0;
for (int fastIndex = 0; fastIndex < nums.length; fastIndex++){
if (nums[fastIndex] != val) {
nums[slowIndex] = nums[fastIndex];
slowIndex++;
}
}
return slowIndex;
}
//相向双指针法
public static int removeElement02(int[] nums,int val){
int left = 0;
int right = nums.length - 1;
//找到从右边开始第一个会被交换过来的元素作为第一个交换的
while(right >= 0 && nums[right] == val) right--;
while(left <= right){
if (nums[left] == val) {
nums[left] = nums[right--];
}
left++;
while(right >= 0 && nums[right] == val) right--;
}
return left;
}
}

Bug:

solution:文件名要和类名保持一致。