[Leetcode][python]Remove Element
2017-08-27 12:41
253 查看
题目大意
去掉数组中等于elem的元素,返回新的数组长度,数组中的元素不必保持原来的顺序。解题思路
双指针使用头尾指针,头指针碰到elem时,与尾指针指向的元素交换,将elem都换到数组的末尾去。
代码
判断与指定目标相同
class Solution(object): def removeElement(self, nums, val): """ :type nums: List[int] :type val: int :rtype: int """ front = len(nums)-1 behind = len(nums)-1 number = 0 while front >= 0: print 'now:', front, behind if nums[front] == val: print front, behind number += 1 nums[front], nums[behind] = nums[behind], nums[front] behind -= 1 front -= 1 print number return len(nums) - number
判断与指定目标不同
class Solution(object): def removeElement(self, nums, val): """ :type nums: List[int] :type val: int :rtype: int """ size = 0 length = len(nums) for i in range(length): if nums[i] != val: nums[size] = nums[i] size += 1 return size
总结
相关文章推荐
- 【LeetCode with Python】 Remove Element
- LeetCode 27 — Remove Element(C++ Java Python)
- [leetcode:python]27.Remove Element
- [LeetCode]题解(python):027-Remove Element
- 【LeetCode 27】Remove Element(Python)
- Leetcode-Remove element-Python
- LeetCode 27 Remove Element (C,C++,Java,Python)
- leetcode 日经贴,python code -Remove Element
- leetcode 日经贴,python code -Remove Element
- leetcode 【 Remove Element 】python 实现
- LeetCode--Group Anagrams(Python)
- [LeetCode]题解(python):065-Valid Number
- [leetcode]Minimum Depth of Binary Tree @ Python
- 【LEETCODE】73-Set Matrix Zeroes [Python]
- Leetcode_Problem27_Remove Element
- [LeetCode] Maximum Depth Of Binary Tree Python 题解
- python爬虫抓取LeetCode题目
- LeetCode 60 Permutation Sequence (Python实现及详解)
- 【LEETCODE】129-Sum Root to Leaf Numbers [Python]
- [Leetcode]@python 105. Construct Binary Tree from Preorder and Inorder Traversal