标签:style color io ar java for strong 数据 sp
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.
Solution1:
public class Solution { public int removeElement(int[] A, int elem) { int length=0, ptr=0; for(int i=0; i<A.length;i++){ if(A[i]!=elem){ A[ptr]=A[i]; ptr++; length++; } } return length; } }Solution2:不要的用数组尾的数据填充,改变数组长度即可。
public class Solution { public int removeElement(int[] A, int elem) { int length=A.length; for(int i=0; i<length;i++){ if(A[i]==elem){ A[i]=A[length-1]; length--; i--; } } return length; } }
标签:style color io ar java for strong 数据 sp
原文地址:http://blog.csdn.net/amberfeb/article/details/39993921