当我想尝试以下版本的python版本时遇到了这个问题:https : //leetcode.com/problems/first-missing-
positive/discuss/17071/My-
short-c++-solution-O(
1)-space- and -准时
我不确定为什么a[0], a[a[0]] = a[a[0]], a[0]不进行交换?
>>> nums
[2, 1, 0]
>>> a = [2,1,0]
>>> a[0], a[a[0]] = a[a[0]], a[0]
>>> a
[2, 1, 0]
>>> a[0]
2
>>> a[0],a[2] = a[2], a[0]
>>> a
[0, 1, 2]
我的猜测是a,b = b的实现,语法类似于:
tmp = a[0] (tmp = 2)
a[0] = a[a[0]] (a[0] = a[2] = 0)
a[a[0]] = tmp (a[a[0]] = a[0] = tmp = 2)
然后,我检查了C 中swap函数的实现。我对C一无所知,但是看起来这个想法是一样的:http
:
//www.cplusplus.com/reference/algorithm/swap/
The behavior of these function templates is equivalent to:
template void swap (T& a, T& b)
{
T c(std::move(a)); a=std::move(b); b=std::move(c);
}
template void swap (T (&a)[N], T (&b)[N])
{
for (size_t i = 0; i
}
我们有c = a,然后a = b和b = a那么,为什么C ++交换函数没有这个问题?以及如何以pythonic方式编写这种交换函数?