LeetCode----Remove Element
2015-09-10 20:04
197 查看
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.
分析:
移除数组中给定的元素,返回之后数组的长度。简单的遍历+交换。
代码:
class Solution(object):
def removeElement(self, nums, val):
"""
:type nums: List[int]
:type val: int
:rtype: int
"""
right = len(nums) - 1
i = 0
while i <= right:
if nums[i] == val:
nums[i], nums[right] = nums[right], nums[i]
right -= 1
else:
i += 1
return right + 1
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.
分析:
移除数组中给定的元素,返回之后数组的长度。简单的遍历+交换。
代码:
class Solution(object):
def removeElement(self, nums, val):
"""
:type nums: List[int]
:type val: int
:rtype: int
"""
right = len(nums) - 1
i = 0
while i <= right:
if nums[i] == val:
nums[i], nums[right] = nums[right], nums[i]
right -= 1
else:
i += 1
return right + 1
相关文章推荐
- 文件遍历排序函数
- C#选择排序法实例分析
- C#插入法排序算法实例分析
- C#实现Datatable排序的方法
- SQLSERVER的排序问题结果不是想要的
- Windows Powershell排序和分组管道结果
- C#通过IComparable实现ListT.sort()排序
- C#选择法排序实例分析
- SQL学习笔记四 聚合函数、排序方法
- C#对list列表进行随机排序的方法
- 一根网线内的8根线哪4根是传输数据的,哪四根是防干扰的
- C#折半插入排序算法实现方法
- SQL进行排序、分组、统计的10个新技巧分享
- C++实现位图排序实例
- 基于C++实现的各种内部排序算法汇总
- C++线性时间的排序算法分析
- SQL行号排序和分页(SQL查询中插入行号 自定义分页的另类实现)
- PHP下对数组进行排序的函数
- PHP数组排序之sort、asort与ksort用法实例
- php通过asort()给关联数组按照值排序的方法