LeetCode第41题,关于Python交换机制的思考
题目描述
给你一个未排序的整数数组,请你找出其中没有出现的最小的正整数。
示例1:
输入: [1,2,0]
输出: 3
示例2:
输入: [3,4,-1,1]
输出: 2
示例3:
输入: [7,8,9,11,12]
输出: 1
代码:
class Solution:
def firstMissingPositive(self, nums: List[int]) -> int:
for i in range(len(nums)):
while 1<=nums[i]<=len(nums) and nums[nums[i]-1] != nums[i]:
nums[nums[i]-1],nums[i] = nums[i], nums[nums[i]-1]
//nums[i], nums[nums[i]-1] = nums[nums[i]-1],nums[i]则不能成功交换两个元素
for i in range(len(nums)):
if nums[i] != i+1:
return i+1
return len(nums)+1
关于
n
u
m
s
[
n
u
m
s
[
i
]
−
1
]
,
n
u
m
s
[
i
]
=
n
u
m
s
[
i
]
,
n
u
m
s
[
n
u
m
s
[
i
]
−
1
]
nums[nums[i]-1],nums[i] = nums[i], nums[nums[i]-1]
nums[nums[i]−1],nums[i]=nums[i],nums[nums[i]−1]和
n
u
m
s
[
i
]
,
n
u
m
s
[
n
u
m
s
[
i
]
−
1
]
=
n
u
m
s
[
n
u
m
s
[
i
]
−
1
]
,
n
u
m
s
[
i
]
nums[i], nums[nums[i]-1] = nums[nums[i]-1],nums[i]
nums[i],nums[nums[i]−1]=nums[nums[i]−1],nums[i]的区别