LeetCode 27. Remove Element(移除给定值元素)

题目描述:

    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.

例子:

Given nums = [3,2,2,3], val = 3,

Your function should return length = 2, with the first two elements of nums being 2.

分析:
    题意:给定一个有序数组,一个目标值,移除所有和目标值相等的元素,并且返回新的数组长度。空间复杂度要求为O(1)。
    思路:此题是LeetCode 26的简化版本。不需要采用双指针法,只需要单指针即可。我们先初始化指针left=0,并且用cnt表示每个和目标值不相等的元素在数组中的新位置,初始化为0。我们先查找第一个和目标值不同的元素位置,更新该元素到cnt位置,cnt加一,然后继续重复该操作(与此同时,每一步查找指针left都加一,顺序向右遍历),直到更新完成所有元素。cnt的最终值就是新数组的长度。
    假设原数组总共有n个元素,那么时间复杂度为O(n),空间复杂度为O(1)。

代码:

#include <bits/stdc++.h>

using namespace std;

class Solution {
public:
    int removeElement(vector<int>& nums, int val) {
        int n = nums.size();
		// Exceptional Case: 
		if(n == 0){
			return 0;
		}
		int left = 0, cnt = 0;
		while(left <= n - 1){
			if(nums[left] != val){
				nums[cnt++] = nums[left];
			}
			left++;
		}
		return cnt;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值