美文网首页
26 Remove Duplicates from Sorte

26 Remove Duplicates from Sorte

作者: Mree111 | 来源:发表于2019-04-20 00:25 被阅读0次

Given a sorted array nums, 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 by modifying the input array in-place with O(1) extra memory.
和之前MoveZeroToEnd很像,只需记录重复的次数及需要replace即可

Solution

class Solution {
    public int removeDuplicates(int[] nums) {
        int moveCount=0;
        for(int i =0;i<nums.length-1;i++){
            if(nums[i]==nums[i+1]){
                moveCount+=1;
            }
            else{
                replace(nums,i+1,i+1-moveCount);
                      
            }
        }
        return nums.length-moveCount;
    }
    public void repalce(int[] nums,int i,int j){
        // int tmp=nums[i];
        // nums[i]=nums[j];
        nums[j]=nums[i];
    }
}

相关文章

网友评论

      本文标题:26 Remove Duplicates from Sorte

      本文链接:https://www.haomeiwen.com/subject/mpcfgqtx.html