zoukankan      html  css  js  c++  java
  • 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/

  • 相关阅读:
    U盘为什么还有剩余空间,但却提示说空间不够
    U盘安装系统
    win8 64位+Oracle 11g 64位下使用PL/SQL Developer 的解决办法
    Oracle 去掉重复字符串
    ORACLE获取字符串中数字部分
    MyBatis中的大于、小于、like等符号写法
    Oracle计算时间差函数
    HDU 3569 Imaginary Date 简单期望
    C语言之——文件操作模式
    LeetCode OJ 之 Ugly Number II (丑数-二)
  • 原文地址:https://www.cnblogs.com/jimmycheng/p/7843515.html
Copyright © 2011-2022 走看看