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 2 3 4 5 6 7 8 9 10 11 12 13 14 | int missingNumber(int* nums, int numsSize) { if(numsSize==0)return 0; int Addtotal=0; int Truetotal=((numsSize+1)*numsSize)/2; for(int i=0;i<numsSize;i++){ Addtotal+=nums[i]; } if(Addtotal == Truetotal){ //miss 0 return 0; }else{ return Truetotal-Addtotal; } } |
還有利用XOR來找出答案的
1 2 3 4 5 6 7 8 | int missingNumber(int* nums, int numsSize) { int i,x=nums[0],y=0; for(i=1;i<numsSize;i++) x^=nums[i]; for(i=1;i<=numsSize;i++) y^=i; return x^y; } |
沒有留言:
張貼留言