Untitled

mail@pastecode.io avatar
unknown
plain_text
a year ago
982 B
1
Indexable
Never
#include <algorithm>
#include <vector>
#include <cassert>

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

int main() {
    
    vector<int> nums1 = {3, 2, 2, 3};
    int val1 = 3;
    vector<int> expectedNums1 = {2, 2};
    int k1 = removeElement(nums1, val1);
    assert(k1 == expectedNums1.size());
    sort(nums1.begin(), nums1.begin() + k1);
    assert(equal(nums1.begin(), nums1.begin() + k1, expectedNums1.begin()));

    
    vector<int> nums2 = {0, 1, 2, 2, 3, 0, 4, 2};
    int val2 = 2;
    vector<int> expectedNums2 = {0, 0, 1, 3, 4};
    int k2 = removeElement(nums2, val2);
    assert(k2 == expectedNums2.size());
    sort(nums2.begin(), nums2.begin() + k2);
    assert(equal(nums2.begin(), nums2.begin() + k2, expectedNums2.begin()));

    return 0;
}

};