Day1_移除元素(remove element)_leetcode27

前情提要:在养成写一些博客的习惯,同时练习英文表述和分析问题的能力,所以内容均为英文。

Problem statement(leetcode 27):

Given an integer array nums and an integer val, remove all occurrences of val in nums in-place. The order of the elements may be changed. Then return the number of elements in nums which are not equal to val.

Consider the number of elements in nums which are not equal to val be k, to get accepted, you need to do the following things:

  • Change the array nums such that the first k elements of nums contain the elements which are not equal to val. The remaining elements of nums are not important as well as the size of nums.
  • Return k.

Problem Discussion:

The keyword for this problem is "in-place," which means you need to solve it without using extra space. In-place algorithms modify the input data structure directly, without requiring additional memory allocation.

The spirit of my solution is to create two "pointers" (not actual pointers, but rather indices) that point to different indices of the vector, both starting from index 0. The "slow" pointer keeps track of the position where the next non-target element should be placed, while the "fast" pointer iterates through the array to find non-target elements.

How this work:

  1. Initialize two pointers, slow and fast, both pointing to index 0.
  2. Iterate through the array using the fast pointer:
    - Copy the fast element to the position pointed to by the slow pointer, and increment the slow pointer.
    - Increment the fast pointer regardless of whether the element is equal to val or not.

Time: O(n)

Space: O(1)

#include <vector>
#include <iostream>
using namespace std;

class Solution {
public:
    int removeElement(vector<int>& nums, int val) {
        int fast = 0, slow = 0, counter = 0;
        for (int i = 0; i < nums.size(); i++) {
            if (nums[i] != val) {
                nums[slow] = nums[fast];
                slow++;
                counter++;
            }
            fast++;
        }
        return counter;
    }
};
  • 9
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值