[leetcode]Single Number @ Python


原題地址:http://www.cnblogs.com/x1957/p/3373994.html

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

要求:線性時間復雜度,並且不用額外空間。

解題思路:這題考的是位操作。只需要使用異或(xor)操作就可以解決問題。異或操作的定義為:x ^ 0 = x; x ^ x = 0。用在這道題里面就是:y ^ x ^ x = y; x ^ x = 0; 舉個例子:序列為:1122334556677。4是那個唯一的數,之前的數異或操作都清零了,之后的數:4 ^ 5 ^ 5 ^ 6 ^ 6 ^ 7 ^ 7 = 4 ^ ( 5 ^ 5 ^ 6 ^ 6 ^ 7 ^ 7 ) = 4 ^ 0 = 4。問題解決。

代碼:

class Solution:
    # @param A, a list of integer
    # @return an integer
    def singleNumber(self, A):
        ans = A[0]
        for i in range(1, len(A)):
            ans = ans ^ A[i]
        return ans

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM