LeetCode笔记:27. Remove Element
来源:互联网 发布:双系统mac升级到win10 编辑:程序博客网 时间:2024/06/05 11:47
问题:
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.
大意:
给出一个数组和一个数,移除数组中所有等于该数的值并返回新长度。
不要使用额外的空间来创建另一个数组,你必须在恒定的内存中做。
元素的顺序可以改变。新长度以外的内容无所谓是什么样子。
思路:
这道题的要求在于不创建新数组,而是在原有的数组内容来进行操作,按题目的意思就是将所有不等于那个值的数放到数组前面,然后返回这些数的数量,也就是数组的一个长度,这个长度后面的数是什么样子的都没有关系。
按照这个思路很明显就是检测如果不一样就放到前面来了。我们弄两个指针,一个遍历数组中的数,一个记录不一样的数的数量,那么记录数量的数一定是小于等于遍历的那个指针数的,所以每当遍历到不一样的数时,就放在数组中记录不一样的数的位置,因为第二个指针一定是不会大于第一个数的,所以不会存在覆盖一些没遍历到的数的问题,这相当于是把不一样的数都集中到数组前面了,等遍历完了,后面的数其实还是保持原样的,跟题目要求的很契合。
代码(Java):
public class Solution { public int removeElement(int[] nums, int val) { int position = 0; for (int i = 0; i < nums.length; i++) { if (nums[i] != val) { nums[position] = nums[i]; position++; } } return position; }}
合集:https://github.com/Cloudox/LeetCode-Record
版权所有:http://blog.csdn.net/cloudox_
- LeetCode笔记:27. Remove Element
- leetcode笔记:Remove Element
- 27. Remove Element ---leetcode算法笔记
- [LeetCode]27.Remove Element
- LeetCode --- 27. Remove Element
- LeetCode 27.Remove Element
- [Leetcode] 27. Remove Element
- [Leetcode] 27.Remove Element
- 【leetcode】27. Remove Element
- 【leetcode】27. Remove Element
- Leetcode 27. Remove Element
- LeetCode 27. Remove Element
- 27. Remove Element LeetCode
- 【LeetCode】27. Remove Element
- leetcode 27. Remove Element
- leetcode 27. Remove Element
- [LeetCode]27. Remove Element
- LeetCode 27. Remove Element
- java异常处理机制
- 内存泄露查找方法总结
- 编码剖析Spring装配基本属性的原理
- 机器学习是深度学习之母
- 动态 Web 校验码图片生成 XVcode
- LeetCode笔记:27. Remove Element
- linux 中 安装vmware
- 谈谈json和jsonp和jsonp的跨域问题。
- 理解本真的REST架构风格
- python 矩阵运算
- android文件管理器开发中遇到的一些问题
- 认识android系统服务
- 下载apk,并将进度显示在通知栏
- chrom开发者工具不完全指南(笔记一)