LeetCode Remove Element

来源:互联网 发布:软件微电子 综合信息 编辑:程序博客网 时间:2024/06/05 21:07

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.

题意:给出一个数组和一个数,删除数据组中的这个数,返回新的数组的长度

思路:用一个下标cnt,遍历数组,如果当前的数等于要删除的数就继续,否则就将当前数赋值给a[cnt],同时将cnt加1

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



0 0
原创粉丝点击