C语言检查元素是否再数组中--原地删除重复字符串

26. 删除有序数组中的重复项 - 力扣(LeetCode)

int checkIn(int* nums, int numsSize, int target) {

    for (int i = 0; i < numsSize; i++) {
        if (nums[i] == target) {
            return 1;
        }
    }

    return 0;

}



int removeDuplicates(int* nums, int numsSize) {

    int* duplicatedList = (int*)malloc(numsSize * sizeof(int));


    if(duplicatedList == NULL){
        perror("error");
        return -1;
    }

    int left = 0;
    int right = 0;


    while (right < numsSize)
    {
        // 这里要注意,duplicatedList动态内存分配的大小是numsSize,但是可能并不会马上用满,所以要传left作为duplicatedList的当前size,因为没用满内存泄漏会找到0,会误判
        int checkRes = checkIn(duplicatedList, left, nums[right]);

        if (checkRes == 0) {
            printf("%d\n",nums[right]);
            duplicatedList[left] = nums[right];

            nums[left] = nums[right];
            left++;

        }

        right++;
    }

    return left;


}

 

posted @ 2023-09-25 10:52  朵朵奇fa  阅读(18)  评论(0编辑  收藏  举报