Created
December 3, 2018 07:00
-
-
Save XcqRomance/25d6fe4d435c61e931679c72fe1a90dd to your computer and use it in GitHub Desktop.
缺失数字
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 缺失数字 方法一使用求和公式-数组的各个元素之和 | |
int missingNumber(int* nums, int numsSize) { | |
int sum = 0; | |
for (int i = 0; i < numsSize; i++) { | |
sum += nums[i]; | |
} | |
return numsSize*(numsSize+1)/2 - sum; | |
} | |
// 缺失数字 方法二使用异或 | |
int missingNumber2(int* nums, int numsSize) { | |
int missingNum = 0; | |
for (int i = 0; i < numsSize; i++) { | |
missingNum ^= (i+1)^nums[i]; | |
} | |
return missingNum; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment