数组|leetcode27.移除元素
給你一個數(shù)組 nums 和一個值 val,你需要 原地 移除所有數(shù)值等于 val 的元素,并返回移除后數(shù)組的新長度。
不要使用額外的數(shù)組空間,你必須僅使用 O(1) 額外空間并 原地 修改輸入數(shù)組。
元素的順序可以改變。你不需要考慮數(shù)組中超出新長度后面的元素。
示例 1:
輸入:nums = [3,2,2,3], val = 3
輸出:2, nums = [2,2]
解釋:函數(shù)應(yīng)該返回新的長度 2, 并且nums 中的前兩個元素均為 2。你不需要考慮數(shù)組中超出新長度后面的元素。例如,函數(shù)返回的新長度為 2 ,而 nums =[2,2,3,3] 或 nums = [2,2,0,0],也會被視作正確答案。
示例 2:
輸入:nums = [0,1,2,2,3,0,4,2], val = 2
輸出:5, nums = [0,1,4,0,3]
解釋:函數(shù)應(yīng)該返回新的長度 5, 并且 nums 中的前五個元素為 0, 1, 3, 0, 4。注意這五個元素可為任意順序。你不需要考慮數(shù)組中超出新長度后面的元素。
提示:
0 <= nums.length <= 100
0 <= nums[i] <= 50
0 <= val <= 100
來源:力扣(LeetCode) 鏈接:https://leetcode-cn.com/problems/remove-element
方法1:暴力遍歷
class Solution {public int removeElement(int[] nums, int val) {int len = nums.length;for(int i = 0 ;i < len;i++){if(nums[i] == val){for(int j = i;j < len -1;j++){nums[j] = nums[j+1];}i--;len--;}}return len;} }方法2:快慢指針方法
class Solution {public int removeElement(int[] nums, int val) {int first = 0;int second = 0;for(first = 0;first < nums.length;first++){if(nums[first] != val){nums[second++] = nums[first];}}return second;} }總結(jié)
以上是生活随笔為你收集整理的数组|leetcode27.移除元素的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 苹果xr充满电会自动断电吗
- 下一篇: Mybatis快速入门的代码实现及报错处