我是靠谱客的博主 酷炫可乐,这篇文章主要介绍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 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 = 3

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

这道题要收去除指定的元素,和上一道题类似,但是不一样,我这里直接使用一个尾部指针,不断的把要删除的元素交换到末尾即可完成本题。

代码如下:


/*
 * 这道题的想法就是设置一个end指针,然后
 * 
 * */
public class Solution 
{
    public int removeElement(int[] nums, int val) 
    {
        if(nums==null || nums.length<=0)
            return 0;
        int end=nums.length-1;
        for(int i=nums.length-1;i>=0;i--)
        {
            if(nums[i]==val)
            {
                int tmp=nums[i];
                nums[i]=nums[end];
                nums[end]=tmp;
                end--;
            }
        }
        return end+1;
    }

} 

下面是C++的做法

代码如下:

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

class Solution 
{
public:
    int removeElement(vector<int>& nums, int val) 
    {
        if (nums.size() <= 0)
            return 0;

        int end = nums.size() - 1;
        for (int i = nums.size() - 1; i >= 0; i--)
        {
            if (nums[i] == val)
            {
                int tmp = nums[i];
                nums[i] = nums[end];
                nums[end] = tmp;
                end--;
            }
        }
        return end + 1;
    }
};

最后

以上就是酷炫可乐最近收集整理的关于leetcode 27. Remove Element 尾部双指针的全部内容,更多相关leetcode内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(133)

评论列表共有 0 条评论

立即
投稿
返回
顶部