Problem 26

Remove Duplicates from Sorted Array

Posted by Ruizhi Ma on December 23, 2019

问题描述

https://leetcode.com/problems/remove-duplicates-from-sorted-array/

解决思路(2019-12-23)

  1. use two pointer. the first pointer marks the postion not repeated, and the second pointer marks the traversed position
  2. if the number of the second pointer is different from the first move the first pointer to next, and store the number.
  3. move the second pointer until to the last one in the array and return the position of first pointer + 1 as the length

代码

class Solution {
    public int removeDuplicates(int[] nums) {

        //corner case
        if(nums == null || nums.length == 0) return 0;
        
        int firstPointer = 0;
        int secondPointer = 1;
        while(secondPointer < nums.length){
            //when the two numbers are different
            if(nums[firstPointer] != nums[secondPointer]){
                firstPointer++;
                nums[firstPointer] = nums[secondPointer];
            }
            //move secondPointer
            secondPointer++;
        }
        
        //the len should be 1 more than the value of firstPointer
        return ++firstPointer;
    }
}

解决思路(2019-05-07)

因为是有序的,其实只要比较前后两个数是不是一样就好啦,一开始还很笨的在想要不要遍历整个数组,真是too young too simple.

问题解惑

其实一开始担心的是java nums[res++] = nums[i] 这个写法,如果重新开辟一个数组写成java arr[res++] = nums[i]我是完全理解,没有问题的。主要一开始担心的就是(其实我也不知道要怎么准确描述我的担心,我尽力描述一下),因为要对原数组进行覆盖,而且是向前覆盖,那会不会影响判断当前数与之前数是否一致?即前一个数会不会被其他数覆盖,导致当前数判断失效?其实不必担心,我自己草稿纸画了一下,的确没有问题。但从理论角度想了一下,因为本身是有序的,所以不会把后面的数提前拿到前面覆盖,要拿也只可能拿当前数,不会有比它大的,比它小的呢?早就放到更前面去啦!

代码

package leetcode;

public class RemoveDuplicatesfromSortedArray {
    public int removeDuplicates(int[] nums) {

        if(nums == null || nums.length == 0) return 0;

        int res = 1;
        for(int i = 1; i < nums.length; i++){
            if(nums[i] != nums[res - 1]){
                nums[res++] = nums[i];
            }
        }
        return res;
    }
}

注意:强烈建议这题和Pro.80对比看一下,理解会加深很多!!!