Remove Element
2016-12-07 22:33
239 查看
Description:
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.
问题描述:
给一个数组和一个值。将数组中的所有与给定值相等的元素删除,返回新数组的长度。限定条件是对数组进行原地操作,不能额外分配内存空间。注意:在操作的过程中数组中的元素的相对顺序可以改变。
Ex:
Given input array nums = [3,2,2,3], val = 3Your function should return length = 2, with the first two elements of nums being 2.
解法一:
思路:
处理数组需要拿到数组的长度,用一个索引变量begin,当遍历数组时,数组的值不等于给定的值时,赋值给构造数组nums[begin],并将begin++,处理完返回begin的值,即新数组长度。Code:
public class Solution { public int removeElement(int[] nums, int val) { int n = nums.length; int begin = 0; for(int i =0 ; i < n; i++){ if(nums[i] != val){ nums[begin++] = nums[i]; } } return begin; } }
彩蛋:
Hint:Try two pointers.
Did you use the property of “the order of elements can be changed”?
What happens when the elements to remove are rare?
leetcode给出的hint,应该能启发出新解法
相关文章推荐
- ruby 数组使用教程
- Ruby中的数组和散列表的使用详解
- C#实现AddRange为数组添加多个元素的方法
- C#比较二个数组并找出相同或不同元素的方法
- 快速解决C# android base-64 字符数组的无效长度问题
- C#中数组、ArrayList和List三者的区别详解
- C# 拷贝数组的几种方法(总结)
- C#动态调整数组大小的方法
- 详解Lua中的数组概念知识
- Perl中的列表和数组学习笔记
- jQuery 判断是否包含在数组中Array[]的方法
- 浅谈C#各种数组直接的数据复制/转换
- 探索PowerShell (八) 数组、哈希表(附:复制粘贴技巧)
- C#中数组初始化与数组元素复制的方法
- C#交错数组用法实例
- Linux Shell 数组建立及使用技巧
- PowerShell数组的一些操作技巧
- C#通过yield实现数组全排列的方法
- C#不重复输出一个数组中所有元素的方法
- C#实现将数组内元素打乱顺序的方法