LeetCode @ Remove Element D1F4

来源:互联网 发布:8月经济数据 编辑:程序博客网 时间:2024/05/17 22:01

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.

关键在于通过不同元素新建array,而不是找到相同来补位改造array。

遇到相同元素时候,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;    }}

【注意1】返回index还是index+1,遇到不同题目要用最简单case验证,别忘记index++过。

【后记】和之前的去重题目总结一下。

0 0