您的位置:首页 > 编程语言 > Python开发

【LeetCode with Python】 Single Number

2008-12-07 12:59 525 查看
博客域名:http://www.xnerv.wang

原题页面:https://oj.leetcode.com/problems/single-number/

题目类型:位操作,异或

难度评价:★★

本文地址:/article/1377554.html

Given an array of integers, every element appears twice except for one. Find that single one.

Note:

Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?

异或操作,知道的人立马能做出来,不知道的人想破脑袋也想不出这个方法。当然用hashmap/map之类的把所有元素插一遍也能找出这个只出现过一次的元素,但是想必面试官不会很开心。位操作还是有很多技巧的,还需要继续深入学习。

此外还可以参考Single Number II

class Solution:
    # @param A, a list of integer
    # @return an integer
    def singleNumber(self, A):
        len_A = len(A)
        if 0 == len_A:
            return 0
        elif 1 == len_A:
            return A[0]
        else:
            result = A[0]
            for i in range(1, len_A):
                result ^= A[i]
        return result
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: