LeetCode 27. Remove Element

来源:互联网 发布:玛祖铭立 知乎 编辑:程序博客网 时间:2024/06/03 18:30

27. Remove Element

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 in place with constant memory.
The order of elements can be changed. It doesn’t matter what you leave beyond the new length.

 Example:Given input array nums = [3,2,2,3], val = 3Your function should return length = 2, with the first two elements of nums being 2.

Solution

  • 题意即给定一个数组和一个数字,要求你将其中和这个数字相同的数删除并返回剩下的数组,不论顺序。
  • 我们换一个角度来想,就是寻找该数组中和给定数字不同的数字组成的数字,文字不便描述,详见代码:
// C/C++class Solution {public:    int removeElement(vector<int>& nums, int val) {        int j = 0;        for (int i = 0;i < nums.size();i++) {            if (val != nums[i])                nums[j++] = nums[i];        }        return j;    }};
# pythonclass Solution(object):    def removeElement(self, nums, val):        rnt = 0        for i in range(len(nums)):            if nums[i] != val:                nums[rnt] = nums[i]                rnt += 1        return rnt
原创粉丝点击