Skip to content

Commit

Permalink
try to added python solution for no.1
Browse files Browse the repository at this point in the history
  • Loading branch information
pezy committed Dec 12, 2017
1 parent 8de6f10 commit 79c0d1c
Show file tree
Hide file tree
Showing 4 changed files with 24 additions and 3 deletions.
8 changes: 8 additions & 0 deletions 001. Single Number/README.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
# 思路(C++)

昨晚看C++ Primer 5th的[习题5.14](https://github.com/pezy/Cpp-Primer/blob/master/ch05/ex5_14.cpp)
想了很常规的解法,但脑子里一直都在想有没有更好的方案,因为这道题很像是在一篇文章里检索连续的高频词。应该是非常常见的才对。
但因为多了一个要求**连续**的条件,所以却又不太一样。
Expand All @@ -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` 循环呢?

请见 <https://stackoverflow.com/questions/181543/what-is-the-problem-with-reduce>
2 changes: 0 additions & 2 deletions 001. Single Number/main.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}
15 changes: 15 additions & 0 deletions 001. Single Number/solution.py
Original file line number Diff line number Diff line change
@@ -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]))
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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)&#124;[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|
Expand Down

0 comments on commit 79c0d1c

Please sign in to comment.