Remove Element
题目:
Given an array and a value, remove all instances of that value in place and return the new length.
The order of elements can be changed. It doesn't matter what you leave beyond the new length.
想办法遍历一遍就OK,思想是把前面等于val 的值都移到最后面。贴上自己的代码,已通过检验。
1 def removeElement(self, nums, val): 2 numslen = len(nums) 3 index = 0 4 while index < numslen: 5 if nums[index] == val: 6 if nums[numslen - 1] == val: 7 while nums[numslen - 1] == val and (numslen-1) > index: 8 numslen -= 1 9 if index == numslen-1 : 10 return numslen-1 11 else: 12 temp = nums[numslen - 1] 13 nums[numslen - 1] = nums[index] 14 nums[index] = temp 15 index += 1 16 numslen = numslen - 1 17 else: 18 temp = nums[numslen - 1] 19 nums[numslen - 1] = nums[index] 20 nums[index] = temp 21 index += 1 22 numslen = numslen - 1 23 else: 24 index += 1 25 26 return numslen