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:
- The given array size will in the range [2, 10000].
- 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 = newHashSet<>(); 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
LeetCode 645. Set Mismatch (集合不匹配)