//給你一個數組 nums 和一個值 val,你需要 原地 移除所有數值等於 val 的元素,並返回移除後數組的新長度。 // 不要使用額外的數組空間,你必須僅使用 O(1) 額外空間並 原地 修改輸入數組。// 元素的順序可以改變。你不需要考慮數組中超出新長度後面的元素。// 示例 1:// 給定 nums = [3,2,2,3], val = 3,//函數應該返回新的長度 2, 並且 nums 中的前兩個元素均為 2。//你不需要考慮數組中超出新長度後面的元素。// 示例 2:// 給定 nums = [0,1,2,2,3,0,4,2], val = 2,//函數應該返回新的長度 5, 並且 nums 中的前五個元素為 0, 1, 3, 0, 4。//注意這五個元素可為任意順序。//你不需要考慮數組中超出新長度後面的元素。// 說明:// 為什麼返回數值是整數,但輸出的答案是數組呢?// 請注意,輸入數組是以「引用」方式傳遞的,這意味著在函數裡修改輸入數組對於調用者是可見的。// 你可以想像內部操作如下:// nums 是以「引用」方式傳遞的。也就是說,不對實參作任何拷貝//int len = removeElement(nums, val);// 在函數裡修改輸入數組對於調用者是可見的。// 根據你的函數返回的長度, 它會列印出數組中 該長度範圍內 的所有元素。//for (int i = 0; i < len; i++) {// print(nums[i]);//}// Related Topics 數組 雙指針// 597 0package com.zqh.leetcode.editor.cn;//Java:移除元素//j 是為了記錄最後相等的索引值,遇到不相等的時候,j就不會加了,然後又遇到相等的。就會覆蓋最後一個j的索引位置的值,所以j索引前面的值與對比值肯定不相等的public class P27RemoveElement { public static void main(String[] args) { Solution solution = new P27RemoveElement().new Solution(); // TO TEST int[] nums = new int[]{0, 1, 2, 2, 3, 0, 4, 2}; int var = 2; nums = new int[]{3, 2, 2, 3}; var = 3; System.out.println(solution.removeElement(nums, var)); } //leetcode submit region begin(Prohibit modification and deletion) class Solution { public int removeElement(int[] nums, int val) { int j = 0; for (int i = 0; i < nums.length; i++) { if (nums[i] != val) { nums[j] = nums[i]; j++; } } return j; } }//leetcode submit region end(Prohibit modification and deletion)}