Leetcode NO.27 Remove Element

来源:互联网 发布:grub安装ubuntu 编辑:程序博客网 时间:2024/06/06 20:46

本题要求如下:

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(int A[], int n, int elem) {        int ptr_i = 0;        int ptr_j = n - 1;        int len = n;        while (ptr_i < len) {            if (A[ptr_i] == elem) {                swap(A[ptr_i], A[ptr_j--]);                --len;            }            else                ++ptr_i;        }        return len;    }};
用的是two pointer的方法,思路就是一个前指针,一个后指针,

对前指针遍历,如果遇到了elem,则和后指针指向的元素交换,同时,后指针往前移动,len减1

此时,需要对该元素再次检测,以防其也等于elem。


由于Leetcode改了function的接口,更新下代码

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



0 0
原创粉丝点击