描述
给你一个数组和两个索引,交换下标为这两个索引的数字
样例
样例 1:
[1, 2, 3, 4], index1 = 2, index2 = 3
交换后你的数组应该是[1, 2, 4, 3], 不需要返回任何值,只要就地对数组进行交换即可。
样例解释: 就地交换,不需要返回值
样例 2:
输入: [1, 2, 2, 2], index1 = 0, index2 = 3
输出: 交换后你的数组应该是[2, 2, 2, 1], 不需要返回任何值,只要就地对数组进行交换即可。
样例解释: 就地交换,不需要返回值
python3 代码如下:
class Solution:
"""
@param A: An integer array
@param index1: the first index
@param index2: the second index
@return: nothing
"""
def swapIntegers(self, A, index1, index2):
# write your code here
A[index1],A[index2]=A[index2],A[index1]
本文介绍了一种在不使用额外变量的情况下,直接在原数组中交换两个指定位置元素的方法。通过一个简单的Python3代码示例,展示了如何实现这一操作,适用于初学者理解和实践。

228

被折叠的 条评论
为什么被折叠?



