您的位置:首页 > 编程语言 > Java开发

leetcode解题之268# Missing NumberJava版 (找出0~N中缺少的数字)

2017-03-19 13:46 239 查看

268. Missing Number

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?

一个数组包含了从0到n个不同的数字,总共(n+1)个数字,但是其中缺少了一个数字,找出这个数字。题目要求线性时间复杂度,空间复杂度为常数。
相比于从【0...n】的数组,该数组缺少了一个数,那么计算出【0...n】的数组的和,再减去待计算数组的和,那么缺少的数就出来了。

public int missingNumber(int[] nums) {
// i的范围是0~nums.length-1,算上nums.length(N)就是0~N所有数字
int res = nums.length;
for (int i = 0; i < nums.length; i++) {
res += (i - nums[i]);
}
return res;
}


// 使用额外的空间
public int missingNumber(int[] nums) {
Map<Integer, Boolean> map = new HashMap<>();
// 初始化0~N为false
for (int i = 0; i <= nums.length; i++)
map.put(i, false);
// 出现的数字把value置为true
for (int i = 0; i < nums.length; i++)
map.put(nums[i], true);
// 返回为false 的数字
for (int i = 0; i <= nums.length; i++) {
if (!map.get(i))
return i;
}
return -1;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
相关文章推荐