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 公式

 class Solution
{
public int[] findErrorNums(int[] nums)
{
HashSet<Integer> set = new HashSet<>();
int[] res = new int[2];
int corSum = (1 + nums.length) * nums.length / 2;
int sum = 0; for(int num: nums)
{
if(set.contains(num))
res[0] = num;
else
{
set.add(num);
sum += num;
} } res[1] = corSum - sum; return res;
}
}

参考资料:n/a

LeetCode 题目列表 - LeetCode Questions List

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

最新文章

  1. 把图标改成web字体
  2. 资源 | 数十种TensorFlow实现案例汇集:代码+笔记
  3. 【原创】storyboard启动应用程序的大致流程
  4. linux 学习笔记3
  5. Linux系统、版本、CPU、内存查看、硬盘空间
  6. Unity 通过Animation实现控件位置的转换
  7. java文件上传--基于ajaxFileUpload+struts2
  8. 在Pythonanywhere上部署Django
  9. MySQL定时逻辑备份
  10. 并行执行 Job - 每天5分钟玩转 Docker 容器技术(134)
  11. 软件测试面试-必掌握的 Linux常用命令大全--2.0更新版!
  12. 编译APR包报错 rm: cannot remove `libtoolT&#39;: No such file or directory
  13. win10监听剪切板变化
  14. 雷林鹏分享:jQuery EasyUI 数据网格 - 使用虚拟滚动视图显示海量数据
  15. mysql timestamp字段定义的
  16. 关于的 recorder robotium 的Eclipse插件(URL:http://recorder.robotium.com/updates/或者说不可用)
  17. Windows Phone 8.1 生命周期调试
  18. Week6——Lifecycle of JSF and Facelets
  19. 解析Array.prototype.slice.call(arguments)
  20. Kotlin Android学习入门

热门文章

  1. MySql IFNULL 联表查询出来的null 如何赋值
  2. STA之Concepts (2)
  3. Qt 5.8.3 部署/添加 Crypto++第三方库(5.6.5版本)
  4. dapper未将对象引用设置到对象的实例
  5. Java基础(七)--Exception异常处理
  6. spring aop 方法增加日志记录
  7. 无插件纯Web HTML5 3D机房 进阶篇(新增设备、线缆、巡查等功能)
  8. C++字符串处理函数总结
  9. UVA-1368 DNA Consensus String(思路)
  10. python文件读写及形式转化和CGI的简单应用