双指针问题应用之二

来源:互联网 发布:淘宝钱柜数码怎么样 编辑:程序博客网 时间:2024/05/24 02:39

leetcode27题

问题描述

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.

代码

有两种方式,一种方式是类似快排那样,两个指针同时向中间移动。代码如下:
class Solution {public:    int removeElement(vector<int>& nums, int val) {        if(nums.size()==0)            return 0;        int i=0;        int j=nums.size()-1;        while(true){            while(i<nums.size()&&nums[i]!=val)                i++;            while(j>=0&&nums[j]==val)                j--;            if(i<j){                int temp=nums[i];                nums[i]=nums[j];                nums[j]=temp;            }            else if(i>=nums.size()){                return nums.size();            }            else if(j<0){                return 0;            }            else return j+1;        }    }};
另一种是一个指针进行扫描,另一个指针记录当前不等于target值。代码如下:
class Solution {public:    int removeElement(vector<int>& nums, int val) {        int p=0;        int i;        for(i=0;i<nums.size();i++){            if(nums[i]!=val)                nums[p++]=nums[i];        }        return p;    }};



0 0