[LeetCode] 27.Remove Element

来源:互联网 发布:macbook彻底删除软件 编辑:程序博客网 时间:2024/06/16 19:09

[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.

Example:

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

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

解题思路

这道题比较容易理解和解决,就是在一个vector中的所有数中将给定的数给去除掉,然后把后面的元素挪到前面,具体解决方法见代码,比较简单。

实验代码

class Solution {public:    int removeElement(vector<int>& nums, int val) {        int t = 0, s = nums.size();        for (int i = 0 ; i < s ; i++) {            if (nums[i] == val)                t++;            else nums[i-t] = nums[i];        }        return s - t;    }};
原创粉丝点击