Skip to content

Commit b20a907

Browse files
committed
python 交换列表元素的坑:nums[nums[i]-1], nums[i] = nums[i], nums[nums[i]-1] 不可颠倒
1 parent 652544e commit b20a907

File tree

1 file changed

+31
-1
lines changed
  • docs/19_python内置常用算法和数据结构

1 file changed

+31
-1
lines changed

docs/19_python内置常用算法和数据结构/builtins.md

Lines changed: 31 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -34,7 +34,7 @@
3434
- python在数值范围建议用:`MAXINT = 2**63-1; MININT = -2**63` 。因为 python2 sys.maxint 和 python3 sys.maxsize 不统一
3535
- 优先级队列:使用内置queue.PriorityQueue or heapq ,定义一个 Item 类实现"小于" 魔术方法就可以实现,下边有代码演示
3636
- python3 的 functools 模块自带了 cache(等价于lru_cache(maxsize=None)) 和 lru_cache 装饰器,在一些需要递归记忆化搜索的时候会很方便
37-
- 除法变更:python2和 python3 除法做了变更要注意。还有负数除法。 python2 `int(6/-123)==-1`,但是 python3 `int(6/-123)==0`
37+
- 除法变更:python2和 python3 除法做了变更要注意。还有负数除法。 python2 `int(6/-123)==-1`,但是 python3 `int(6/-123)==0`。整数除法统一用 "//"
3838

3939
# python int 值范围
4040

@@ -350,3 +350,33 @@ def gen_tree(vals):
350350
cur.right = right
351351
return root
352352
```
353+
354+
# python 交换列表元素的坑
355+
356+
```
357+
# 41. 缺失的第一个正数 https://leetcode-cn.com/problems/first-missing-positive/
358+
class Solution(object):
359+
def firstMissingPositive(self, nums):
360+
"""
361+
平常习惯了 python 里边交换元素 a,b=b,a 这里你可能这么写,那就中招了!
362+
nums[i], nums[nums[i]-1] = nums[nums[i]-1], nums[i] # 这么写死循环!
363+
这个等价于
364+
x, y = nums[nums[i]-1], nums[i]
365+
nums[i] = x # 这一步 nums[i] 已经修改了,下边一句赋值不是期望的 nums[i]了
366+
nums[nums[i]-1] = y
367+
368+
:type nums: List[int]
369+
:rtype: int
370+
"""
371+
n = len(nums)
372+
for i in range(n):
373+
while 1 <= nums[i] <= n and nums[nums[i]-1] != nums[i]:
374+
# NOTE: 注意这一句交换右边有副作用的,不能颠倒!!!
375+
# nums[i], nums[nums[i]-1] = nums[nums[i]-1], nums[i] # 这么写死循环!
376+
nums[nums[i]-1], nums[i] = nums[i], nums[nums[i]-1]
377+
for i in range(n):
378+
if nums[i] != i+1:
379+
return i+1
380+
381+
return n+1
382+
```

0 commit comments

Comments
 (0)