LeetCode-remove-element

来源:互联网 发布:第一次欧洲旅游知乎 编辑:程序博客网 时间:2024/06/13 14:38

题目描述


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++记录最终留下元素的位置!!!切记!切记!

0 0