#26 Remove Duplicates from Sorted Array

Description

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.

Examples

Example 1:

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.

Example 2:

Given nums = [0,0,1,1,1,2,2,3,3,4],
Your function should return length = 5, with the first five elements of nums being modified to 0, 1, 2, 3, and 4 respectively.
It doesn’t matter what values are set beyond the returned length.

解题思路

首先解决为什么返回一个数字会同时返回不重复数组的问题
很明显
就是在计算length的过程中对数组也进行了操作
最简单的方法就是依次判断相邻的两个数值,如果相同就所有的从后往前挪动一个单位,最后一个单位用-1来填充,直到碰到当前值<之后值,就停下来输出

class Solution {
    public int removeDuplicates(int[] nums) {
        int num = 0;
        int i, j;
        int len = 1;
        i = 1;
        while(len < nums.length){
            if(nums[i] < nums[i - 1])
                break;
            len++;
            if(nums[i] == nums[i - 1]){
                for(j = i; j < nums.length - 1; j++)
                    nums[j] = nums[j + 1];
                nums[j] = 1;
                continue;
            }
            i++;
        }
        return i;
    }
}

当然之后去摸了solution hhhhhh

2-Pointer Method

设置两个pointer
在这里插入图片描述
判断两个pointer i i j j 指的值是否相等
如果相等, j j 向后移动一位
如果不相等就将 i i 后移一位,然后用 n u m [ j ] num[ j ] 的值代替 n u m [ i ] num[i] 的值, j j 向后移动一位
以上图为例,接下来的移动将如下所示
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
此时 j j 已经到了最末,循环结束
i = 5 i = 5
返回修改好的数组以及 i i ++

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

猜你喜欢

转载自blog.csdn.net/YY_Tina/article/details/86755603