LeetCode: Remove Element

来源:互联网 发布:运营商云计算 编辑:程序博客网 时间:2024/05/23 10:13

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 start = 0, end = n-1, result = 0;        while(start <= end)        {            if(A[start] != elem)                start++;            else            {                result++;                int temp = A[start];                A[start] = A[end];                A[end] = temp;                end--;            }        }        return start;    }};


Round 3:

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


0 0
原创粉丝点击