• 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/

  • 相关阅读:
    个人冲刺二(2)
    个人冲刺二(1)
    三个和尚观后感
    每日总结
    个人冲刺(10)
    个人冲刺(9)
    个人冲刺(8)
    个人冲刺(7)
    个人冲刺(6)
    下次视频面试前把电脑摄像头擦干净吧
  • 原文地址:https://www.cnblogs.com/jimmycheng/p/7843515.html
Copyright © 2020-2023  润新知