LeetCode 645. Set Mismatch (集合不匹配)

Posted 几米空间

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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.

 

 


题目标签:HashTable, Math

 

  题目给了我们一个nums array,nums 包含 1 到 n,其中有一个重复的,让我们找到重复的数字,和另外一个丢失的数字。

  首先我们可以用公式 (1 + n) * n / 2 知道 nums 的总和 corSum。

  接着遍历nums:

    用HashSet 来找到重复的那个数字,存入res[0];

    把所有数字累加sum,除了重复的那个数字。

 

  最后 丢失的数字 = corSum - sum。

 

 

Java Solution:

Runtime beats 30.43% 

完成日期:11/15/2017

关键词:HashMap, Math

关键点:求sum 公式

 1 class Solution 
 2 {
 3     public int[] findErrorNums(int[] nums) 
 4     {
 5         HashSet<Integer> set = new HashSet<>(); 
 6         int[] res = new int[2];
 7         int corSum = (1 + nums.length) * nums.length / 2;
 8         int sum = 0;
 9         
10         
11         for(int num: nums)
12         {
13             if(set.contains(num))
14                 res[0] = num;
15             else
16             {
17                 set.add(num);
18                 sum += num;
19             }
20                 
21         }
22         
23         res[1] = corSum - sum;
24         
25         return res;    
26     }
27 }

参考资料:n/a

LeetCode 题目列表 - LeetCode Questions List

题目来源:https://leetcode.com/

以上是关于LeetCode 645. Set Mismatch (集合不匹配)的主要内容,如果未能解决你的问题,请参考以下文章

645. Set Mismatch - LeetCode

LeetCode 645. Set Mismatch (集合不匹配)

leetcode 645. 错误的集合(Set Mismatch)

leetcode 645. Set Mismatch——凡是要节约空间的题目 都在输入数据上下功夫 不要担心破坏原始的input

645. Set Mismatch

645. Set Mismatch