Leetcode Single Number II Operator Solution Explanation [closed]

岁酱吖の 提交于 2020-07-07 09:46:39

问题


The question is 'Given a non-empty array of integers, every element appears three times except for one, which appears exactly once. Find that single one.' I came up with a simple solution but found this solution online and was confused. Can someone explain this code and probably can explain whats the use of these operators and when should we use them while coming up with a solution of a coding problem.

class Solution:
def singleNumber(self, nums: List[int]) -> int:
    seen_once = seen_twice = 0
    for num in nums:
        seen_once = ~seen_twice & (seen_once ^ num)
        seen_twice = ~seen_once & (seen_twice ^ num)
    return seen_once

回答1:


A rough idea of the approach is mentioned in one of the comments by Hung Thai but I would like to elaborate it further.

Variables seen_once and seen_twice are being used to store the value of elements that are being occurred as we traverse through the array. If the element occurs once then it's value is stored in seen_once, if it occurs twice then it is stored in seen_twice variable. If it occurs three times it won't be stored in any of the variables because if we pass an integer several times to the function, (seen_once, seen_twice) will have the following states of value: (0,0) -> (n,0) -> (0,n) -> (0,0) -> .... Thus, any integer processed to the third time will reset the variables to its initial state, which is (0,0). So, the value that we get in the seen_once element after traversing through the whole array will be our answer.

Let's take an array: {2, 2, 2, 3}

seen_once = 00, seen_twice == 00

When we are at first element i.e. 2 its binary representation will be 10.

Now the value of seen_once will be (~00)&(00^10) = 10 which is 2. And the value of seen_twice will be (~10)&(10^10) = 00.

So, seen_once stores 2 because it has occurred only once till now and seen_twice is 0.

As we traverse further, we again get 2, so the value of seen_twice will become 2 as it has occurred twice till now and value of seen_once will become 0.

Then we get 2 for the third time. Now the values of both variables will become 0.

And at last, we get 3, which has occurred only once so it will be stored in seen_once.

After the loop ends, we get our answer as seen_once = 3.



来源:https://stackoverflow.com/questions/62512993/leetcode-single-number-ii-operator-solution-explanation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!