The figures appear only once Leetcode--

Given a non-empty array of integers, in addition to an element appears only once, the rest of each element appears twice. To find out that only appears once in the elements.

Description:

  Your algorithm should have linear time complexity. You can not use the extra space to achieve it?

Example 1:

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

Example 2:

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

 

C ++ solution

/ * 
  XOR Solution: XOR operation is commutative, a ^ b ^ a = a ^ a ^ b = b, ans therefore corresponds nums [0] ^ nums [1 ] ^ nums [2] ^ nums [3] ^ nums [4] ..... 
  then according to the commutative equal to merge together XOR (zero),
  then only occurs once the XOR elements, so that the final result is, appeared only elements (0 ^ arbitrary value = value) time * / class Solution { public: int singleNumber (Vector <int> & the nums) { int ANS = the nums [0]; for (int I =. 1; I < nums.size (); I ++) { ANS = ^ ANS the nums [I]; } return ANS; } };

  

 

Guess you like

Origin www.cnblogs.com/skyeisgood/p/12588729.html