LeetCode Tencent's selection of 50 questions - appear only once digital

Forewarned, if Daniel was either the comments section point out, I may not get stuck in a dead end, this question is actually very simple, takes advantage of any theorem learned people understand binary, that is:

 1. XOR operation is commutative: a ^ b ^ c is equivalent to a ^ c ^ b

 2.0 and Differences are digital or any number itself: 0 ^ n = n

 3. The same XOR of two numbers is 0: a ^ a = 0

Based on the above three theorem disease binding array elements of the same premise only appear twice, can be obtained, a variable is initially set to 0, the XOR result of the recording, through the array, performing an XOR constant, the final result is the elements appear only once

 1 public class SingleNum {
 2 
 3     public int singleNumber(int[] nums) {
 4         if(nums.length == 1){
 5             return nums[0];
 6         }
 7         int index = 0;
 8         for (int i = 0; i < nums.length; i++) {
 9             index = index ^ nums[i];
10         }
11 
12         return index;
13     }  
14 }

 

Guess you like

Origin www.cnblogs.com/Kaithy-Rookie/p/11333224.html