Leetcode #26. Remove Duplicates from Sorted Array 移除重复数字 解题报告

1 解题思想

这道题因为是已经排好序的,所以比较简单,相当于设置两个指针,一个用来扫描,一个用来记录当前没有重复的部分的截断位置,当遇到一个全新的值的时候,就将其移动到截断位置那里就好,然后截断位置+1

嗯,截断位置永远小于等于扫描的指针那个位置,且覆盖的时候必然不会影响到之前不重复的值

2 原题

26. Remove Duplicates from Sorted Array
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.

3 AC 解

public class Solution {
    /** * 这题没啥难度,就直接看后一个和前一个相同与否就可以,不相同的话,将他挪到上一个不相同的后面(其实也就是当前已经出现了多少个不相同的数值的位置了) * */
    public int removeDuplicates(int[] nums) {
        if(nums.length==0)
            return 0;
        int count=1;
        for(int i=1;i<nums.length;i++){
            if (nums[i]!=nums[i-1]){
                nums[count++]=nums[i];
            }

        }
        return count;

    }
}

你可能感兴趣的:(LeetCode,排序)