编写一个函数,不用临时变量,直接交换numbers = [a, b]
中a
与b
的值。
示例:
输入: numbers = [1,2] 输出: [2,1]
示例代码:
class Solution(object):
def swapNumbers(self, numbers):
"""
:type numbers: List[int]
:rtype: List[int]
"""
return [numbers[1], numbers[0]]
思路解析:返回list
示例代码2:
class Solution(object):
def swapNumbers(self, numbers):
"""
:type numbers: List[int]
:rtype: List[int]
"""
numbers[0] ^= numbers[1]
numbers[1] ^= numbers[0]
numbers[0] ^= numbers[1]
return numbers
思路解析:异或交替求解(可以防止溢出),与加减法类似
示例代码3:
class Solution(object):
def swapNumbers(self, numbers):
"""
:type numbers: List[int]
:rtype: List[int]
"""
numbers[0] = numbers[0] + numbers[1]
numbers[1] = numbers[0] - numbers[1]
numbers[0] -= numbers[1]
return numbers
思路解析:加减法
示例代码4:
class Solution(object):
def swapNumbers(self, numbers):
"""
:type numbers: List[int]
:rtype: List[int]
"""
return numbers[::-1]
思路解析:切片