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

来源:互联网 发布:我的世界手机版月球js 编辑:程序博客网 时间:2024/05/29 14:04

268. Missing Number

Given an array containing n distinct numbers taken from0, 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为falsefor (int i = 0; i <= nums.length; i++)map.put(i, false);// 出现的数字把value置为truefor (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;}


0 0
原创粉丝点击