27.Remove Element

xiaoxiao2021-02-28  46

Description

Given an array and a value, remove all instances of that value in-place and return the new length. Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory. The order of elements can be changed. It doesn’t matter what you leave beyond the new length. Example: Given nums = [3,2,2,3], val = 3, Your function should return length = 2, with the first two elements of nums being 2.

Solution

class Solution { public: int removeElement(vector<int>& nums,int val) { int i = 0; int j = 0; for(i = 0; i < nums.size(); i++) { if(nums[i] == val) { continue; } nums[j++] = nums[i]; } return j; } };

Analysis

这道题的大意是在一个数组中移除指定的val,结果返回新的数组长度。解题的思路是设置两个浮标i与j,刚开始i与j都指向第一个元素。执行循环,当遇到val时,使用j记录位置,i递增,直到遇到非val时,将i对应的非val值复制到j的位置上,j加1。重复上述过程直到循环结束。

转载请注明原文地址: https://www.6miu.com/read-2621628.html

最新回复(0)