From 99fd9d028fe8b26e8e02595f14b1a3a5f8d81771 Mon Sep 17 00:00:00 2001 From: rui <1527717978@qq.com> Date: Wed, 25 Nov 2020 22:30:02 +0800 Subject: [PATCH] =?UTF-8?q?=E6=B7=BB=E5=8A=A0python3=E4=BB=A3=E7=A0=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- 高频面试系列/消失的元素.md | 30 +++++++++++++++++++++++++++++- 1 file changed, 29 insertions(+), 1 deletion(-) diff --git a/高频面试系列/消失的元素.md b/高频面试系列/消失的元素.md index 844b5cb..b45bfd2 100644 --- a/高频面试系列/消失的元素.md +++ b/高频面试系列/消失的元素.md @@ -131,5 +131,33 @@ public int missingNumber(int[] nums) {

+======其他语言代码====== -======其他语言代码====== \ No newline at end of file + + +```python +def missingNumber(self, nums: List[int]) -> int: + #思路1,位运算 + res = len(nums) + for i,num in enumerate(nums): + res ^= i^num + return res +``` + +```python +def missingNumber(self, nums: List[int]) -> int: + #思路2,求和 + n = len(nums) + return n*(n+1)//2-sum(nums) +``` + +```python +def missingNumber(self, nums: List[int]) -> int: + #思路3,防止整形溢出的优化 + res = len(nums) + for i,num in enumerate(nums): + res+=i-num + return res +``` + +事实上,在python3中不存在整数溢出的问题(只要内存放得下),思路3的优化提升并不大,不过看上去有内味了哈... \ No newline at end of file