您的位置:首页 > 其它

268. Missing Number

2016-07-07 22:12 295 查看
iven 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,所以例如13,14,15……20这样的序列是不会出现的。先把两个边界处理一下,缺0的情况和完整的情况,缺0的话就是n项和了,完整的话就是n-1项和。再处理一般情况,一般情况直接用min加到max应该的和减去前面的sum就是所求。
public int missingNumber(int[] nums)
{
int len=nums.length;
if(len<1)
return 0;

long min=Integer.MAX_VALUE;
long max=Integer.MIN_VALUE;
long sum=0;

for(int i=0;i<len;i++)
{
min=Math.min(nums[i], min);
max=Math.max(nums[i],max);
sum+=nums[i];
}

if(sum==(len*(len+1)/2))
return 0;

if(sum==(len*(len-1)/2))
return (int) (max+1);

return  (int) ((min+max)*(len+1)/2-sum);
}
简洁版 https://discuss.leetcode.com/topic/24535/4-line-simple-java-bit-manipulate-solution-with-explaination/3 since the n numbersare from 
[0, n]
,we can just add all the numbers from 
[0, n]
 togetherand minus the sum of the n-1 numbersin array.
public static int missingNumber(int[] nums) {
int sum = nums.length;
for (int i = 0; i < nums.length; i++)
sum += i - nums[i];
return sum;
}
-----------------------------------------------------------------------------------位操作版The basic idea is to use XOR operation. We all know that a^b^b =a, which means two xor operations with the same number will eliminate the number and reveal the original number.In this solution, I apply XOR operation to both the index and value of the array. In a complete array with no missing numbers, the index and value should be perfectly corresponding( nums[index] = index), so in a missing array, what left finally is the missingnumber.
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;
}
---------------------------------------------------------
交换元素,把相应的数放在相应的index上,使得num[i]=i+1,然后从头到尾第一个不满足4000这个关系的数就是缺失的数,全部都满足的话,缺失的是0.
public class Solution {public static int missingNumber(int[] nums){int len=nums.length;if(len==0)return 0;for(int i=0;i<len;i++){while(nums[i]!=0&&nums[i]!=i+1){int temp=nums[nums[i]-1];nums[nums[i]-1]=nums[i];nums[i]=temp;}}int missing=-1;for(int i=0;i<len;i++)if(nums[i]!=i+1){missing=i;break;}return missing+1;}}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: