LeetCode:Remove Element

来源:互联网 发布:mac safari打不开页面 编辑:程序博客网 时间:2024/06/05 15:09
/**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.题目大意:给一个数组一个数字,从数组里删掉这个数字,返回剩下的数组长度**/public class Solution {    public int removeElement(int[] A, int elem) {        return solve1(A, elem);        //return solve2(A, elem); //错误答案    }        //====================== solve1 ==========================    //O(n)    //双指针,index记录新指针的长度,i则一直遍历,同时将数组元素前移,最后index指向的位置就是新数组的长度    //    private int solve1(int[] A, int elem) {        int index = -1;        int i= -1;                for(i=0, index=0; i<A.length; i++)            if(A[i] != elem)                A[index++] = A[i];                return index;    }        //====================== solve2 ==========================    //这个是错误答案,在这一题里,原本的那个数组是必须要修改的,不能纯粹是算个数    private int solve2(int[] A, int elem){        int result = 0;        for(int a : A)            if(a != elem)                result++;                return result;    }}

原创粉丝点击