> For the complete documentation index, see [llms.txt](https://emmaguo100.gitbook.io/leetcode/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://emmaguo100.gitbook.io/leetcode/01-17-2022-27.md).

# 01/17/2022 27

When we encounter nums\[i] = valnums\[i]=val, we can swap the current element out with the last element and dispose the last one, else increment the i, finally return n.

Time O(n)

Space O(1)

class Solution {&#x20;

public int removeElement(int\[] nums, int val) {&#x20;

int i = 0;&#x20;

int n = nums.length;&#x20;

while (i < n){ if(nums\[i] == val){&#x20;

nums\[i] = nums\[n-1];

&#x20;n--;&#x20;

}else{&#x20;

i++; }&#x20;

} return n; }

![](/files/4gkp1Hoxw0fVaDGNkuLa)
