算法笔记: 力扣#27 移除元素

问题描述


解法


分析

Python 实现

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 实现

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;
}
}

时间复杂度

O(n).

空间复杂度

O(1).

链接


27. Remove Element
27. 移除元素
(English version) Algorithm Notes: Leetcode#27 Remove Element