Leetcode26 Remove Duplicates from Sorted Array

来源:互联网 发布:sftp 修改制定端口号 编辑:程序博客网 时间:2024/06/05 19:26

Remove Duplicates from Sorted Array

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 nums = [1,1,2],

Your function should return length = 2, with the first two elements of nums being 1 and 2 respectively. It doesn’t matter what you leave beyond the new length.

Solution

  • 直接看代码如下:
public class Solution {    public int removeDuplicates(int[] nums) {        int len = 0;//既是新加数的指针也是新数组的长度        for(int num:nums) if(len==0||num!=nums[len-1]) nums[len++] = num;//如果目前还没有加入数或者将要加入的数和上一个数不一样,则加入该数        return len;            }}
0 0