Skip to content

Instantly share code, notes, and snippets.

@XcqRomance
Created December 3, 2018 07:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save XcqRomance/ef5b0d444db4e68030192ebcf52ecc62 to your computer and use it in GitHub Desktop.
Save XcqRomance/ef5b0d444db4e68030192ebcf52ecc62 to your computer and use it in GitHub Desktop.
// 5.只出现一次的数字
int singleNumber(int* nums, int numsSize) {
if (numsSize <= 0) {
return 0;
}
qsort(nums, numsSize, sizeof(nums[0]), cmp);
for (int i = 0; i < numsSize; i++) {
if (i == 0 && nums[i] != nums[i+1]) {
return nums[i];
} else if (i == numsSize - 1 && nums[i-1] != nums[i]) {
return nums[i];
} else if (nums[i] != nums[i+1] && nums[i+1] != nums[i+2]) {
return nums[i+1];
}
}
return 0;
}
int cmp(void const *a,void const *b) {
return *(int*)a - *(int*)b;
}
// 方法二:高效方法,使用按位异或 0与任何数字异或都是数字本身,相同的数字之间异或为0,
int singleNumber2(int* nums, int numsSize) {
int xor = 0;
for(int i = 0; i < numsSize; ++i){
xor ^= nums[i];
}
return xor;
}
//交换两个数字,不用临时变量
//int a=5,b=1;
//a=a^b;
//b=a^b;
//a=a^b;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment