[leetcode] Missing Number
2015-11-22 20:58
253 查看
题目:
分析:
方法一:根据元素的顺序,进行异或^操作:
方法二:利用数学求和,用期望值减去实际值即可:
Given an array containing n distinct numbers taken from 0, 1, 2, ..., n, find the one that is missing from the array. For example, Given nums = [0, 1, 3] return 2. Note: Your algorithm should run in linear runtime complexity. Could you implement it using only constant extra space complexity?
分析:
方法一:根据元素的顺序,进行异或^操作:
public int missingNumber(int[] nums) { int xor = 0, i = 0; for (i = 0; i < nums.length; i++) { xor = xor ^ i ^ nums[i]; } return xor ^ i; }
方法二:利用数学求和,用期望值减去实际值即可:
public int missingNumber(int[] nums) { int sum = 0; for(int i : nums) { sum += i; } int n = nums.length; int tmp = (n+1)*n/2; return tmp-sum; }
相关文章推荐
- 第六章 函数式对象
- hpuoj--1122-- HH的随机数(数据去重)
- js实现返回上一url
- 自定义路径绘图实例
- JavaScript数组练习
- Objective-C Runtime 运行时之五:协议与分类
- hpuoj--1122-- HH的随机数(数据去重)
- POJ 1251 Jungle Roads (prim)
- Java内功提升之阶段练习
- 背景相关与系统架构分析
- Dynamics CRM 2015自定义框架解决方案1.0发布
- Objective-C Runtime 运行时之四:Method Swizzling
- Activity四种启动模式
- 2012 Asia Tianjin Regional Contest - Mahjong
- ASP.NET开源CMS
- 正则基础之——捕获组(capture group)
- 整个linux系统的备份和还原的方法
- CyclicBarrier测试
- sphinx
- SecureCRT连接Ubuntu报The remote system refused the connection.解决方案