Leecode next day-use XOR to find non-repeating elements in an array

Source: Internet
Author: User

Tag: None yield load return CEP appears break next stop

Leecode topics are described as follows:
Given a non-empty array of integers, each of the remaining elements appears two times, except when an element occurs only once. Find the element that only appears once.

Ideas:
The first thing to think about is the use of sorting, which makes it easy to find non-repeating elements after sorting.
Later on there is a more ingenious solution, that is, to use XOR to find non-repeating elements, because the repeated elements of the different or after the elimination of each other to 0, the last array of elements after the different or calculated result is the only non-repeating element.

Code:

class Solution(object):    def singleNumber(self, nums):        """        :type nums: List[int]        :rtype: int        """        num = 0        for i in nums:            num = num ^ i        return numdef stringToIntegerList(input):    return json.loads(input)def intToString(input):    if input is None:        input = 0    return str(input)def main():    import sys    def readlines():        for line in sys.stdin:            yield line.strip(‘\n‘)    lines = readlines()    while True:        try:            line = lines.next()            nums = stringToIntegerList(line)                        ret = Solution().singleNumber(nums)            out = intToString(ret)            print out        except StopIteration:            breakif __name__ == ‘__main__‘:    main()

Leecode next day-use XOR to find non-repeating elements in an array

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.