标签:python algorithm 遍历 leetcode
Given an array of integers, every element appears three times except for one. Find that single one.
Note:
Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?
本题是一种极其巧妙的做法,参考的别人的,废话不多说,先上代码
class Solution: # @param A, a list of integer # @return an integer def singleNumber(self, A): ones,twos=0,0 for ele in A: ones = ones^ele & ~twos twos = twos^ele & ~ones return ones
这种做法没有那么繁琐,而是非常巧妙的遍历一遍数组,时间复杂度为O(n),而且也没有占用额外的空间。
最关键的两行代码是:
ones = ones^ele & ~twos twos = twos^ele & ~ones
在此之后如果ele不再出现,那么很显然这就是只出现一次的数字,ones即为最终结果,如果它第二次出现,ones将会被清零,而twos则会储存下ele的值。
当其第三次出现时,ones和twos都会被清零,就像从未出现过该数字一样。
很神奇吧?!
【LeetCode】【Python题解】Single NumberII
标签:python algorithm 遍历 leetcode
原文地址:http://blog.csdn.net/monkeyduck/article/details/39300147