(C language) delete duplicates in an ordered array

Given an ordered array nums, please delete the repeated elements in place so that each element appears only once, and return the new length of the deleted array. Instead of using extra array space, you have to modify the input array in-place and do it with O(1) extra space. (The question comes from Likou)

Example 1:

Input: nums = [1,1,2]
Output: 2, nums = [1,2]
Explanation: The function should return a new length of 2, and the first two elements of the original array nums are modified to 1, 2. No need to consider elements in the array beyond the new length

#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<string.h>
#include<stdlib.h>

//删除有序数组中的重复项

int removeDuplicates(int* nums, int numsSize) {//原地清除相同元素
    if (nums == NULL) {//如果数组为空直接返回0
        return 0;
    }
    if (numsSize == 1) {//如果数组长度为1(没有重复)直接返回1
        return 1;
    }
    int temp_1;//记录数组中的元素用来做比较
    int index = 0;//记录下标
    int temp_sum = 0;//记录不相同元素的个数后续用来打印
    int j = 0;//遍历数组
    while (j < numsSize) {
        temp_1 = nums[j];//找出不同的元素赋值进行下次判断
        while (j < numsSize && nums[j] == temp_1) {//循环找出下一个不同的元素
            j++;
        }
        temp_sum++;//每找出一个不同的元素就+1,最后便可以算出总共有多少不同的元素
        nums[index++] = temp_1;//把上次记录的元素赋值到第一位,然后index++,至此每找到一个不同的元素都会向前面赋值一次,
//最后所有不同的元素都存储在前面,再以不同元素的个数为基准打印数组,所有的元素都会出现一次,也就去掉了重复出现的元素了.
    }
    return temp_sum;//返回不同元素的长度也就是新数组的长度
}

int main() {
    int arr[] = { 1,1,2,2,3,4,5,5,5,6 };
    int size_ = removeDuplicates(arr, sizeof(arr) / sizeof(arr[0]));
    for (int i = 0; i < size_; i++) {//打印数组
        printf("%d ", arr[i]);
    }
    return 0;
}

Guess you like

Origin blog.csdn.net/weixin_49312527/article/details/121478026