Remove Duplicates from Sorted Array

又是好久没有刷题 https://leetcode.com/problems/…

26. 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.

一开始想劈叉了,以为是每个重复出现的值可能会重复不定次数

int removeDuplicates(int* nums, int numsSize) {
    if (numsSize == 0) return 0;
    int index = 0;
    for (int i = 1; i < numsSize; i++) {
        if (nums[index] != nums[i]) {
            index++;
            nums[index] = nums[i];
        }
    }
    return index + 1;
}

Leave a Reply

Your email address will not be published. Required fields are marked *