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?
想法1:
使用ArrayList容器来存放数组,用contains()方法来查找是否有对应元素。
public class Solution {
public int missingNumber(int[] nums) {
int result=0;
ArrayList list=new ArrayList();
for(int i:nums){
list.add(i);
}
for(int j=0;j<=nums.length;j++){
if(list.contains(j))continue;
else{
result=j;
break;
}
}
return result;
}
}
想法2:
先对包含缺失元素的数组(0,1,2...,n,数组长度为nums.length+1)求和,在减去nums[]中所有数。
public class Solution {
public int missingNumber(int[] nums) {
int sum=nums.length*(nums.length+1)/2;
for(int i:nums){
sum-=i;
}
return sum;
}
}