parent
cd828f83de
commit
2f30a4c037
|
|
@ -0,0 +1,65 @@
|
||||||
|
#+title: 136 Single Number
|
||||||
|
|
||||||
|
Given a non-empty array of integers nums, every element appears twice except for one. Find that single one.
|
||||||
|
|
||||||
|
You must implement a solution with a linear runtime complexity and use only constant extra space.
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
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
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
Constraints:
|
||||||
|
|
||||||
|
1 <= nums.length <= 3 * 104
|
||||||
|
-3 * 104 <= nums[i] <= 3 * 104
|
||||||
|
Each element in the array appears twice except for one element which appears only once.
|
||||||
|
|
||||||
|
* Solution
|
||||||
|
|
||||||
|
#+name: solution
|
||||||
|
#+begin_src C
|
||||||
|
int xor(int a, int b) {
|
||||||
|
return a ^ b;
|
||||||
|
}
|
||||||
|
|
||||||
|
int singleNumber(int* nums, int numsSize) {
|
||||||
|
int number = 0;
|
||||||
|
for (int i=0; i < numsSize; i++) {
|
||||||
|
number = xor(number, nums[i]);
|
||||||
|
}
|
||||||
|
return number;
|
||||||
|
}
|
||||||
|
#+end_src
|
||||||
|
|
||||||
|
#+RESULTS: solution
|
||||||
|
|
||||||
|
#+begin_src C :noweb yes
|
||||||
|
#include <stdio.h>
|
||||||
|
|
||||||
|
<<solution>>
|
||||||
|
|
||||||
|
int numbers[3] = {1, 1, 2};
|
||||||
|
int single = singleNumber(numbers, 3);
|
||||||
|
printf("%d\n", single);
|
||||||
|
#+end_src
|
||||||
|
|
||||||
|
#+RESULTS:
|
||||||
|
: -2
|
||||||
Loading…
Reference in New Issue