27. Remove Element

https://leetcode.com/problems/remove-element/

/*
    t: O(n), s: O(1)
*/
class Solution {
    public int removeElement(int[] nums, int val) {
        // because this problem only need to know the length of array after removing element
        // so use a index to record the left element
        
        int begin = 0;
        for (int num : nums) {
            if (num != val) {
                nums[begin++] = num;
            }
        }
        return begin;
    }
}

Last updated