leetcode27-remove element

题目

对于指定的数字val,删除数组nums中包含val的元素

分析

给定数字val,以及数组nums,删除数组中出现的val元素,删除val后的数字元素,排在nums数组的前面,后面的数字无要求。

java代码实现

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

python代码实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class (object):
def removeElement(self, nums, val):
"""
:type nums: List[int]
:type val: int
:rtype: int
"""

j = 0
if(len(nums) == 0):
return 0
else:
for i in range(len(nums)):
if(nums[i] != val):
nums[j] = nums[i]
j += 1
return j