您的位置:首页 > 其它

leetcode解题方案--027--Remove Element

2017-11-05 17:07 393 查看

题目

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 by modifying the input array in-place with O(1) extra memory.

The order of elements can be changed. It doesn’t matter what you leave beyond the new length.

Example:

Given nums = [3,2,2,3], val = 3,

Your function should return length = 2, with the first two elements of nums being 2.

分析

从前向后遍历数组,如果遇到相同的就将后面的元素复制过来。因此需要维持一个尾指针。

class Solution {
public int removeElement(int[] nums, int val) {
int end = nums.length-1;
int ans = 0;

for (int i = 0; i<=end;i++) {
if (nums[i] != val) {
ans++;
} else {
while (end>i&&nums[end]==val) {
end--;
}
if (nums[end]!=val) {
nums[i] = nums[end];
end--;
ans++;
}
}
}
return ans;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: