Leetcode-remove-duplicates-from-sorted-array

来源:互联网 发布:使命召唤14数据不兼容 编辑:程序博客网 时间:2024/05/29 23:46

题目描述


Given a sorted array, remove the duplicates in place such that each element appear only once and return the new length.

Do not allocate extra space for another array, you must do this in place with constant memory.

For example,
Given input array A =[1,1,2],

Your function should return length =2, and A is now[1,2].


这个题目非常具有代表性,数组的元素移位,以后需要记住该方法,定义一个size指针,遇到与上一个数据不同的,size加一个。

代码如下:


public class Solution {    public int removeDuplicates(int[] A) {        int size = 0;        for(int i=0; i<A.length; i++) {            if(A[i] != A[size]) {                A[++size] = A[i];            }        }        return size+1;    }}


0 0
原创粉丝点击