【LeetCode with Python】 Single Number

来源:互联网 发布:阿里云实名认证 编辑:程序博客网 时间:2024/06/05 20:20
博客域名:http://www.xnerv.wang
原题页面:https://oj.leetcode.com/problems/single-number/
题目类型:位操作,异或
难度评价:★★
本文地址:http://blog.csdn.net/nerv3x3/article/details/3465512

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
原创粉丝点击