kniost

谁怕,一蓑烟雨任平生

0%

LeetCode 136. Single Number

136. Single Number

Difficulty: Easy

Given a non-empty array of integers, every element appears twice except for one. Find that single one.

Note:

Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?

Example 1:

1
2
Input: [2,2,1]
Output: 1

Example 2:

1
2
Input: [4,1,2,1,2]
Output: 4

Solution

Language: Java

1
2
3
4
5
6
7
8
9
10
11
12
class Solution {
public int singleNumber(int[] nums) {
if (nums == null || nums.length % 2 == 0) {
return -1;
}
int result = 0;
for (int n : nums) {
result ^= n;
}
return result;
}
}