题目链接:https://leetcode.com/problems/remove-element/description/
难度:Easy
题目描述:
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.
给一个数组,和一个数,要求删除数组中与该数相等的元素并返回新数组的长度。不能用额外的数组,in-palce即不允许移动元素,原位操作。
我的解答虽然AC,但是没有达到要求in-place,而且时间复杂度O(n2)
Java:
class Solution {
public static int removeElement(int[] nums, int val) {
int n=nums.length;
for(int i=0;i<n;i++)
{
if(nums[i]==val)
{
for(int j=i+1;j<n;j++)
{
nums[j-1]=nums[j];
}
n--;
i--;
}
}
return n;
}
}
双指针法
复杂度
时间 O(N) 空间 O(1)
思路
用一个指针记录不含给定数字的数组边界,另一个指针记录当前遍历到的数组位置。只有不等于给定数字的数,才会被拷贝到子数组的边界上。
代码
public class Solution {
public int removeElement(int[] nums, int val) {
int pos = 0;
for(int i = 0; i < nums.length; i++){
// 只拷贝非给定数字的元素
if(nums[i] != val){
nums[pos] = nums[i];
pos++;
}
}
return pos;
}
}
交换法
复杂度
时间 O(N) 空间 O(1)
思路
因为题目中并不要求相对顺序保持一致,所以有进一步优化的空间。我们遍历数组时,每遇到一个目标数,就和当前数组结尾交换,并把数组大小减1,如果不是目标数,则检查下一个数字。这样可以减少很多赋值操作。
代码
public class Solution {
public int removeElement(int[] nums, int val) {
int size = nums.length, i = 0;
while(i < size){
if(nums[i] == val){
nums[i]=nums[size-1];
size--;
} else {
i++;
}
}
return size;
}
}
日期:2018/2/23-16:56