您的位置:首页 > 其它

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 = 3

Your 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,应该能启发出新解法
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  数组