LeetCode-remove-element

题目描述


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.


这个题目还要求将数组变为最后的样子,光计算出个数是不行的!

对于这种数组需要以为的题目,index!index!index!

public class Solution {
    public int removeElement(int[] A, int elem) {
        int index = 0;
        for(int i=0; i<A.length; i++) {
            if(A[i] != elem){
                A[index++] = A[i];
            }
        }
        
        return index;
    }
}

用index++记录最终留下元素的位置!!!切记!切记!
发布了120 篇原创文章 · 获赞 25 · 访问量 12万+

猜你喜欢

转载自blog.csdn.net/yearningseeker/article/details/52372334