C#LeetCode刷题之#645-错误的集合(Set Mismatch)

版权声明:Iori 的技术分享,所有内容均为本人原创,引用请注明出处,谢谢合作! https://blog.csdn.net/qq_31116753/article/details/82795729

问题

集合 S 包含从1到 n 的整数。不幸的是,因为数据错误,导致集合里面某一个元素复制了成了集合里面的另外一个元素的值,导致集合丢失了一个整数并且有一个元素重复。

给定一个数组 nums 代表了集合 S 发生错误后的结果。你的任务是首先寻找到重复出现的整数,再找到丢失的整数,将它们以数组的形式返回。

输入: nums = [1,2,2,4]

输出: [2,3]

注意:

给定数组的长度范围是 [2, 10000]。
给定的数组是无序的。


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.

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.


示例

public class Program
{

    public static void Main(string[] args)
    {
        var nums = new int[] { 1, 2, 2, 4 };

        var res = FindErrorNums(nums);
        ShowArray(res);

        Console.ReadKey();
    }

    private static void ShowArray(int[] array)
    {
        foreach (var num in array)
        {
            Console.Write($"{num} ");
        }
        Console.WriteLine();
    }

    public static int[] FindErrorNums(int[] nums)
    {
        var miss = 0;
        var dup = 0;
        var dic = new Dictionary<int, int>();
        for (var i = 0; i < nums.Length; i++)
        {
            if (dic.ContainsKey(nums[i]))
            {
                dic[nums[i]]++;
            }
            else
            {
                dic[nums[i]] = 1;
            }
        }
        for (var i = 1; i <= nums.Length; i++)
        {
            if (dic.ContainsKey(i))
            {
                if (dic[i] == 2) dup = i;
            }
            else
            {
                miss = i;
            }
        }
        return new int[] { dup, miss };
    }

}

以上给出1种算法实现,以下是这个案例的输出结果:

2 3

分析:

显而易见,以上算法的时间复杂度为: O(n)

猜你喜欢

转载自blog.csdn.net/qq_31116753/article/details/82795729
今日推荐