美文网首页
Leetcode 645. Set Mismatch

Leetcode 645. Set Mismatch

作者: persistent100 | 来源:发表于2017-08-17 22:18 被阅读0次

题目

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:
The given array size will in the range [2, 10000].
The given array's numbers won't have any order.

分析

找出重复和缺少的数字,只需一个数组,一个个数字对应,直接就能找到答案。

int a[10005];
/**
 * 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 *ans=(int*)malloc(sizeof(int)*2);
    *returnSize=2;
    for(int i=0;i<=numsSize;i++)
        a[i]=0;
    for(int i=0;i<numsSize;i++)
    {
        if(a[nums[i]]==0)
        {
            a[nums[i]]=1;
        }
        else
        {
            ans[0]=nums[i];
        }
    }
    for(int i=1;i<=numsSize;i++)
    {
        if(a[i]==0)
            ans[1]=i;
    }
    return ans;
}

相关文章

网友评论

      本文标题:Leetcode 645. Set Mismatch

      本文链接:https://www.haomeiwen.com/subject/uuapkxtx.html