您的位置:首页 > 其它

leetcode -- Remove Element

2013-07-24 08:50 211 查看
Given an array and a value, remove all instances of that value in place and return the new length.

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

思路:

两层循环,注意删除元素时指针要回溯,此方法的时间复杂度为O(n^2)

public class Solution {
public int removeElement(int[] A, int elem) {
// Start typing your Java solution below
// DO NOT write main() function
int len = A.length;
for(int i = 0; i < len;){
if(A[i] == elem){
for(int j = i + 1; j < len; j++){
A[j - 1] = A[j];
}
len --;
continue;
}
i++;
}
return len;
}
}


双指针,时间复杂度为O(n)

public int removeElement(int[] A, int elem) {
int len = A.length;
int cur = 0;
for(int i = 0; i < len; i ++){
if(A[i] == elem)
continue;

A[cur] = A[i];
cur ++;
}
return cur;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: