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.
Hint:
Subscribe to see which companies asked this question
这道题我真的是。。。
用了传统的双指针,但是如果条件是left < right怎么都不行,换成left <= right就对了。
因为left < right没有考虑[3, 3, 3, 3], 3的情况,这个时候length还是1。所以有没有等号要看一下极端情况。
另外需要注意swap的时候其实也要检查left<=right
public class Solution { public int removeElement(int[] nums, int val) { if (nums == null) { return 0; } int left = 0, right = nums.length - 1; int l = nums.length; while (left <= right) { while (left <= right && nums[left] != val) { left++; } while (left <= right && nums[right] == val) { right--; l--; } if (left <= right) { nums[left] = nums[right]; left++; right--; l--; } } return l; } }
反正做出来了,就是代码很长。。。看完人家的top solution,觉得自己的方法真是笨啊。。
public class Solution { public int removeElement(int[] nums, int val) { if (nums == null) { return 0; } int n = 0; for (int i = 0; i < nums.length; i++) { if (nums[i] != val) { nums[n] = nums[i]; n++; } } return n; } }
原文:http://www.cnblogs.com/aprilyang/p/6305723.html