Lunski's Clutter

This is a place to put my clutters, no matter you like it or not, welcome here.

0%

136. Single Number

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

Follow up: Could you implement a solution with a linear runtime complexity and without using extra memory?

Example 1:

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

Example 2:

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

Example 3:

1
2
Input: nums = [1]
Output: 1

Java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
位元運算自動轉Binary,XOR is single number fliter  

0 xor 0 = 0
0 xor 1 = 1
1 xor 0 = 1
1 xor 1 = 0

解釋
int [] array = {2,2,1}; // result ^= i
byte result;
result = (byte)2^(byte)2; // 0b010^0b010 = 0b000 成對的結果一定是 0
result = (byte)0^(byte)1; // 0b000^0b001 = 0b001
System.out.println(result); // 1



import java.util.*;
class Solution {
public int singleNumber(int[] nums) {
int result = 0;
for(int i : nums) {
result ^= i;
}
return result;
}
}

如果你覺得這篇文章很棒,請你不吝點讚 (゚∀゚)

Welcome to my other publishing channels