27. 移除元素 27. 移除元素 - 力扣(Leetcode) 1234567891011121314151617181920212223242526272829303132333435363738394041import 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:文件名要和类名保持一致。