[leetcode]-645. Set Mismatch

The set S originally contains numbers from 1 to n. But unfortunately, due to the data error, one of the numbers in the set got duplicated to another number in the set, which results in repetition of one number and loss of another number.

Given an array nums representing the data status of this set after the error. Your task is to firstly find the number occurs twice and then find the number that is missing. Return them in the form of an array.

Example 1:

Input: nums = [1,2,2,4]
Output: [2,3]

Note:

  1. The given array size will in the range [2, 10000].
  2. The given array's numbers won't have any order.

代码如下:

/**
 * Return an array of size *returnSize.
 * Note: The returned array must be malloced, assume caller calls free().
 */
int* findErrorNums(int* nums, int numsSize, int* returnSize) {
    int i,j,k;
    int t;
    int *res;
    *returnSize=2;
    res=(int *)malloc(sizeof(int*)*2);
    if(nums[0]==1&&nums[1]==1)
    {
        res[0]=1;
        res[1]=2;
        return res;
    }
    for(i=0;i<numsSize-1;i++)
    {
        k=i;
        for(j=i+1;j<numsSize;j++)
           if(nums[j]<nums[k])
                k=j;
        if(i!=k)
            {
                t=nums[k];
                nums[k]=nums[i];
                nums[i]=t;
            }
    }
    
    for(i=0;i<numsSize-1;i++)
        if(nums[i]==nums[i+1])
            res[0]=nums[i];
    
    if(nums[0]!=1)
    {
        res[1]=1;
        return res;
    }
    for(i=1;i<numsSize;i++)
    {
        if(nums[i]-nums[i-1]==2)
        {
            res[1]=nums[i]-1;
            return res;
        }
    }
    res[1]=numsSize;
    return res;
}

猜你喜欢

转载自blog.csdn.net/shen_zhu/article/details/81407368
今日推荐