leetcode之 Remove Element

来源:互联网 发布:淘宝待售宝贝在哪里 编辑:程序博客网 时间:2024/04/29 15:52

题目:

Given an array and a value, remove all instances of that value in place and return the new length.

The order of elements can be changed. It doesn't matter what you leave beyond the new length.

解答:

就是两个指针,遇见这个value的时候和后面进行交换,同时移动指针即可

class Solution {
public:
    int removeElement(vector<int>& nums, int val) {
        int size = nums.size();
        if(size == 0)
            return 0;
        int start = 0;
        int end = size - 1;
        while(start <= end)
        {
            if(nums[start] == val)
            {
                nums[start] = nums[end];
                nums[end] = val;
                end--;
            }
            else
                start++;
        }
        return start;
    }
};

0 0
原创粉丝点击