LeetCode26. Remove Duplicates from Sorted Array

来源:互联网 发布:上传歌曲到网络qq音乐 编辑:程序博客网 时间:2024/05/22 08:06

题目

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.


思路

取两个变量,i从1开始遍历,j从0开始表示计数,也表示不重复的最后一位,因为数组已经是排列好的,所以当i与j位的数字重复时,j不变,不重复时j自增并且复制为新的不重复数,问题解决。


代码

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


原创粉丝点击