"Leetcode" single Number Problem solving report (Java & Python)
[Leetcode]
Https://leetcode.com/problems/single-number/Total accepted:183838 Total submissions:348610 difficulty:easy Question
Given an array of integers, every element appears twice for one. Find is single one.
Note:
Your algorithm should have a linear runtime. Could you implement it without using extra memory? Ways
I was too weak, the problem of bit arithmetic is not basic. Read the high vote answer to understand can do so.
Use XOR or operation.
XOR is an operation that can be exchanged in order, that is, it is independent of the order of the elements, or that they are equal to 0, 0 different or others equal to others. So
We use the bitwise XOR to solve this problem:
Have to know the bitwise XOR in Java
1.0 ^ n = n
2. N ^ n = 0
So ..... If N is the single number
N1 ^ N1 ^ N2 ^ N2 ^..............^ Nx ^ NX ^ N
= (n1^n1) ^ (n2^n2) ^..............^ (nx^nx) ^ N
= 0 ^ 0 ^ .... ^ 0 ^ N
= N
public class Solution {public
int singlenumber (int[] nums) {
int returnnum=0;
for (int i=0; i<nums.length; i++) {
returnnum ^=nums[i];
}
Return Returnnum
}
}
Ac:1ms
Two brushes python
Class Solution (object):
def singlenumber (self, Nums): ""
"
: Type Nums:list[int]
: Rtype:int
" "" Return to
reduce (lambda x, y:x ^ y, nums)
Date
January 7, 2017
March 14, 2018 – Hawking dies