Last active
December 15, 2020 14:51
-
-
Save loisC123/e638e2be025ffdc091d3fb8252485124 to your computer and use it in GitHub Desktop.
leetcode 30天挑戰
This file contains 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
//Example 1: | |
//Input: nums = [2,2,1] | |
//Output: 1 | |
//Example 2: | |
//Input: nums = [4,1,2,1,2] | |
//Output: 4 | |
//Example 3: | |
//Input: nums = [1] | |
//Output: 1 | |
//way1 | |
int singleNumber(int* nums, int numsSize){ | |
for(int i=0;i<numsSize;i++){ | |
int count=0; | |
for(int j=0;j<numsSize;j++){ | |
if(nums[j]==nums[i]){ | |
count++; | |
} | |
} | |
if(count==1) | |
return nums[i]; | |
} | |
return 0; | |
} | |
//way2 | |
int singleNumber(int* nums, int numsSize){ | |
int n=nums[0]; | |
for(int i=1;i<numsSize;i++){ | |
n^=nums[i]; | |
//n^nums[i]=nums[i]; | |
//nums:[2,2,1] | |
// 2^2^1 = 0^1 = 1 | |
// 00000000 00000000 0000000 00000010 | |
// ^ 00000000 00000000 0000000 00000010 | |
//--------------------------------------- | |
// 00000000 00000000 0000000 00000000 | |
// 以上相同數會為0 A^A => 0 , A^0=>A | |
//n= nums[0] ^ nums[1] ^ nums[2] ^ nums[3] = 2^2^1^2= 1 | |
// bitwise XOR 每個bit分開計算 | |
} | |
return n; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment