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

268. Missing Number

2018-03-05 22:36 134 查看
Given an array containing n distinct numbers taken from 0, 1, 2, …,

n, find the one that is missing from the array.

Example 1

Input: [3,0,1] Output: 2

Example 2

Input: [9,6,4,2,3,5,7,0,1] Output: 8

Note: Your algorithm should run in linear runtime complexity. Could

you implement it using only constant extra space complexity?

//直接把1到n加起来,减去数组全部元素之和。
public int missingNumber(int[] nums) {
int len=nums.length;
int total=(1+len)*len/2;
int sum=0;
for(int i=0;i!=nums.length;i++){
sum+=nums[i];
}
int res=total-sum;
return res;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  java leetcode