27. Remove Element
来源:互联网 发布:nginx ssl 编辑:程序博客网 时间:2024/06/08 20:03
题意: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.
思路:这题思路和 26. Remove Duplicates from Sorted Array 基本差不多。但是现在要去除的不是重复数,而是固定数,思路就很多了,下面方法1是我自己的解法,其他的都是别人,但是他们的思路要明显比我这个简单。
方法一:
class Solution(object): def removeElement(self, nums, val): """ :type nums: List[int] :type val: int :rtype: int """ i = 0 for j in xrange(len(nums)): nums[i] = nums[j] if nums[i] != val: i += 1 else: while nums[j] == val and j<len(nums)-1: j += 1 # print nums return i
这个是基础的方法,利用双指针来求解。
方法二:
class Solution: def removeElement(self, A, elem): i, last = 0, len(A) - 1 while i <= last: if A[i] == elem: A[i], A[last] = A[last], A[i] last -= 1 else: i += 1 return last + 1
这个方法就很巧妙了,题目中说了超出新数组长度的部分不考虑,所以直接把val直接和末端的数调换就好了。
方法三:
int removeElement(int* nums, int numsSize, int val) { int i, j; for(i = j = numsSize - 1; i >= 0; i--) if(nums[i] == val && i != j--) nums[i] = nums[j+1] ; return j+1;}
这是一段C++的代码,但是实在在太厉害了,所以放上来,这个方法从末端开始计算,这里最巧妙的就是&&i!=j–这句话,而i!=j这句话是用来对末端开始的几个val进行忽视的,其他的就需要自己体会了。
- [LeetCode]27.Remove Element
- LeetCode --- 27. Remove Element
- LeetCode 27.Remove Element
- [Leetcode] 27. Remove Element
- 27.Remove Element
- [Leetcode] 27.Remove Element
- 27. Remove Element
- 27. Remove Element
- 【leetcode】27. Remove Element
- 【leetcode】27. Remove Element
- 27. Remove Element
- 27. Remove Element
- 27. Remove Element
- Leetcode 27. Remove Element
- 27. Remove Element
- LeetCode 27. Remove Element
- 27. Remove Element LeetCode
- 27. Remove Element
- C++ 宏定义禁止复制构造函数和赋值函数
- 通讯转换工具开发_webservice储值卡项目总结之XML与对象之间的转换
- C++(10):static、const、mutable、explicit成员
- React native 搭建windows开发环境,目标平台是Android
- zabbix3.2使用sendEmail发送告警邮件
- 27. Remove Element
- “并发用户数”、“系统用户数”和“同时在线用户数”的计算公式
- 方片收集——高效的你必看
- Hdu-1561 The more, The Better(树形依赖背包)
- UE4中动画优化与压缩
- c#实现messsagebox对话框的弹出和对话框选择的操作
- freemarker ftl文件在eclipse高亮显示
- 【12月13日】一道有趣的小题目
- SSH免密码登录(CentOS_6.4)