指针滑动-LeetCode26:Remove Duplicates from Sorted Array

一、问题描述
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.
Example
Given 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 returned length.

二、解决思路
方法一:使用一个指针循环遍历数组,数据相同,遍历下一个元素,数据不同,数据复制并向后滑动,O(n)

三、算法实现

public int removeDuplicates(int[] nums) {
        if(nums == null) return 0;
        if(nums.length == 1) return 1;
        if(nums.length == 0) return 0;
        int idx = 1;
        int pre = nums[0];
        for(int i = 1, lens = nums.length; i < lens; i++){
            if(nums[i] == pre){
                continue;
            } else{
                nums[idx++] = nums[i];
                pre = nums[i];
            }
        }
        return idx;
}

你可能感兴趣的:(指针滑动-LeetCode26:Remove Duplicates from Sorted Array)