diff --git a/001. Single Number/README.md b/001. Single Number/README.md index fc5c22b..15c2883 100644 --- a/001. Single Number/README.md +++ b/001. Single Number/README.md @@ -1,3 +1,5 @@ +# 思路(C++) + 昨晚看C++ Primer 5th的[习题5.14](https://github.com/pezy/Cpp-Primer/blob/master/ch05/ex5_14.cpp) 想了很常规的解法,但脑子里一直都在想有没有更好的方案,因为这道题很像是在一篇文章里检索连续的高频词。应该是非常常见的才对。 但因为多了一个要求**连续**的条件,所以却又不太一样。 @@ -18,3 +20,9 @@ C++ Primer 5th ==> 4.8. The Bitwise Operators ==> Bitwise AND, OR, and XOR Opera 异或(^)的特点是: **按位,同为0,异为1。** 所以这道题要找"落单"那哥们,就将他们全部异或,相同的小伙伴异或后为0了,可不就剩下那个老光棍了么。 + +## Python + +心血来潮用 python 再刷一遍, 这道题有一种更简洁的写法是用 `reduce`. 为啥我只用了最简单的 `for` 循环呢? + +请见 diff --git a/001. Single Number/main.cpp b/001. Single Number/main.cpp index b9fded2..4add067 100644 --- a/001. Single Number/main.cpp +++ b/001. Single Number/main.cpp @@ -8,6 +8,4 @@ int main() Solution s; int A[7] = {1,2,3,5,2,1,3}; std::cout << s.singleNumber(A, 7) << std::endl; - - return 0; } diff --git a/001. Single Number/solution.py b/001. Single Number/solution.py new file mode 100644 index 0000000..16fd36e --- /dev/null +++ b/001. Single Number/solution.py @@ -0,0 +1,15 @@ +class Solution: + def singleNumber(self, nums): + """ + :type nums: List[int] + :rtype: int + """ + single = 0 + for num in nums: + single ^= num + return single + + +# test +if __name__ == '__main__': + print(Solution().singleNumber([2, 4, 5, 4, 5, 2, 6, 7, 7])) diff --git a/README.md b/README.md index 55cc54f..77a3585 100644 --- a/README.md +++ b/README.md @@ -5,7 +5,7 @@ LeetCode solutions in C++ 11. (From Easy to Hard) |NO.|Title|Solution|Add Date|Difficulty| |---|-----|--------|--------|----------| -|1|[Single Number][1]|[C++](001.%20Single%20Number/solution.h)|2014/10/15|Medium| +|1|[Single Number][1]|[C++](001.%20Single%20Number/solution.h)|[Python](001.%20Single%20Number/solution.py)|2014/10/15|Medium| |2|[Maximum Depth of Binary Tree][2]|[C++](002.%20Maximum%20Depth%20of%20Binary%20Tree/solution.h)|2014/10/16|Easy| |3|[Same Tree][3]|[C++](003.%20Same%20Tree/solution.h)|2014/10/17|Easy| |4|[Reverse Integer][4]|[C++](004.%20Reverse%20Integer/solution.h)|2014/10/18|Easy|