首页 > 代码库 > leetcode------Remove Element

leetcode------Remove Element

标题:Remove Element
通过率:32.6%
难度:简单

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.

也不知道是我理解有问题,还是题目没有说清楚,根据返回的要求,只用返回除去跟elem相同的元素后的数组长度就行那转换成新的数组还有什么意义。。我感觉直接统计跟elem相同的元素有几个然后用A数组的长度减去后就是转换后的长度,但是提交后提示不对。我也没搞清楚。于是我就给转换一遍,两个指针的操作,一个是i,一个是j。i是按照顺序走,如果elem=当前位置的元素,j不走,i继续走,这样就把与elem相同的给覆盖掉,最后j就是新的数组的长度。

 1 public class Solution { 2     public int removeElement(int[] A, int elem) { 3         int len=A.length,j=0; 4         for(int i=0;i<len;i++){ 5             if(A[i]!=elem){ 6                 A[j]=A[i]; 7                 j++; 8             } 9         }10         return j;11     }12 }

 

leetcode------Remove Element