27. Remove Element
2016-07-26 19:36
357 查看
27. Remove Element
Leetcode link for this questionDiscription:
Given an array and a value, remove all instances of that value in place and return the new length.Do not allocate extra space for another array, you must do this in place with constant memory.
The order of elements can be changed. It doesn’t matter what you leave beyond the new length.
Example:
Given input array nums = [3,2,2,3], val = 3
Your function should return length = 2, with the first two elements of nums being 2.
Analyze:
Code 1 :
class Solution(object): def removeElement(self, nums, val): """ :type nums: List[int] :type val: int :rtype: int """ i=0 while i<len(nums): if nums[i]==val: nums.pop(i) i-=1 i+=1 return len(nums)
Submission Result:
Status: AcceptedRuntime: 72 ms
Ranking: beats 5.50%
Code 2 :
class Solution(object): def removeElement(self, nums, val): """ :type nums: List[int] :type val: int :rtype: int """ p1,p2=0,len(nums)-1 if p2<1 and val in nums: return 0 while p1<=p2: if nums[p2]==val: p2-=1 continue elif nums[p1]!=val: p1+=1 continue else: nums[p1],nums[p2]=nums[p2],nums[p1] return p2+1
Submission Result:
Status: AcceptedRuntime: 64 ms
Ranking: beats 18.83%
相关文章推荐
- 顺序表应用1:多余元素删除之移位算法
- 24. Swap Nodes in Pairs
- 2016夏季练习——类次小生成树
- 51Nod-1183-编辑距离
- Python中的序列相机和相乘
- [SCU4438] Censor [2015 Sichuan Province Contest Final C]
- HDU 3363 Ice-sugar Gourd
- Java实现HTML页面转PDF解决方案
- MyBatis和Hibernate相比,优势在哪里?
- 21. Merge Two Sorted Lists
- quartz动态定时任务
- HDU 2141 Can you find it?(二分)
- 20. Valid Parentheses
- DDR Layout Guide-DDR内存布线指导
- hdu_5761_Rower Bo(xjb猜公式)
- 大数小数的加法
- 【Window编程】Step.1 我的第一个Windows程序
- 14. Longest Common Prefix
- 命令的查看帮助 和 命令行的历史
- Material Design的其他使用