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.
题目标签:Array
这道题目给了我们一个nums array, 让我们把array 里和val 相同的数字都移除,最后return 一个 新的length。题目规定我们要in place。 所以利用two pointers, i 和 res = 0。 让 i 从0 开始遍历,一旦找到和val 不相同的数字,把这个数字和res 位置的数字互换,res++。意思就是,把所有不需要删除的数字,放到前面去。res记录了所有不需要删除的数字。
Java Solution:
Runtime beats 95.05%
完成日期:03/27/2017
关键词:Array
关键点:Two Pointers
public class Solution
{
public int removeElement(int[] nums, int val)
{
int res = 0; // count non-val numbers for(int i=0; i<nums.length; i++)
if(nums[i] != val) // once find the non-val number, swap non-val number with res index
nums[res++] = nums[i]; return res;
}
}
参考资料:
http://www.cnblogs.com/grandyang/p/4606700.html
LeetCode 算法题目列表 - LeetCode Algorithms Questions List