algorithm notes: leetcode#27 remove element

Problem


Solution


Analysis

Python implementation

1
2
3
4
5
6
7
8
9
10
11
12
13
class :
def removeElement(self, nums, val):
"""
:type nums: List[int]
:type val: int
:rtype: int
"""
i = 0
for j in range(len(nums)):
if nums[j] != val:
nums[i] = nums[j]
i += 1
return i

Java implementation

1
2
3
4
5
6
7
8
9
10
11
12
class {
public int removeElement(int[] nums, int val) {
int i = 0;
for(int j = 0; j < nums.length; j++){
if(nums[j] != val){
nums[i] = nums[j];
i++;
}
}
return i;
}
}

Time complexity

O(n).

Space complexity

O(1).


27. Remove Element
(中文版) 算法笔记: 力扣#27 移除元素