It seems that coding tests are conducted overseas in interviews with engineers, and in many cases, the main thing is to implement specific functions and classes according to the theme.
As a countermeasure, it seems that a site called Let Code will take measures.
A site that trains algorithmic power that can withstand coding tests that are often done in the home.
I think it's better to have the algorithm power of a human being, so I'll solve the problem irregularly and write down the method I thought at that time as a memo.
Leet Code Table of Contents Starting from Zero
Last time Leet Code Day 13 "338. Counting Bits" starting from zero
Basically, I would like to solve the easy acceptance in descending order.
The difficulty level is easy. This question is also from the Top 100 Liked Questions. Why is it because there are so many good numbers? I thought, but when I tried to solve it, it turned out to be true, so it may be better to solve it by myself before actually seeing the solution.
The problem is that you will be given an array of non-empty numbers, so please extract the two undisplayed numbers and return them.
Example 1:
Input: [2,2,1] Output: 1
In this example, only 1 is returned because there is only one in the array.
Example 2:
Input: [4,1,2,1,2] Output: 4
In this example, only 4 is in the array, so 4 is returned.
This time, I tried to write it as if I knew a little about the information system.
class Solution:
def singleNumber(self, nums: List[int]) -> int:
ans = 0
for n in nums:
ans ^= n
return ans
# Runtime: 80 ms, faster than 93.89% of Python3 online submissions for Single Number.
# Memory Usage: 16.5 MB, less than 6.56% of Python3 online submissions for Single Number.
If you are not familiar with Python
ans ^= n
This may be what it is, so I would like to add that it is an assignment operator that represents exclusive OR (XOR).
As many of you know, an XOR that returns 1 when only one of the two inputs is 1, is perfect for this problem.
In fact, when I looked into Discuss after solving it, there were many answers using XOR. If there seems to be a better answer, I will add it.
Recommended Posts