leetcode.com This is the practice of coding interviews for software developers. A total of more than 1,500 coding questions have been posted, and it seems that the same questions are often asked in actual interviews.
Introduction to golang + algorithm I will solve it with go and Python to strengthen the brain. (Python is weak but experienced)
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?
Japanese translation
Given a ** non-empty ** array of integers, all but one
nums
element will be displayed * 2 times *. Find that single one.** Follow-up: ** Can you implement a solution with linear run-time complexity without using additional memory?
Example 1:
Input: nums = [2,2,1]
Output: 1
Example 2:
Input: nums = [4,1,2,1,2]
Output: 4
Example 3:
Input: nums = [1]
Output: 1
Answer code
class Solution:
def singleNumber(self, nums: List[int]) -> int:
result = 0
for n in nums:
result ^= n
return result
--I'll write it in Go too!
func singleNumber(nums []int) int {
result := 0
for _, v := range nums {
result = result ^ v
}
return result
}
Recommended Posts