Skip to content

Files

Latest commit

af6edcf · Oct 9, 2023

History

History
115 lines (81 loc) · 2.42 KB

README_EN.md

File metadata and controls

115 lines (81 loc) · 2.42 KB

中文文档

Description

Write a function to swap a number in place (that is, without temporary vari­ ables).

Example:

Input: numbers = [1,2]

Output: [2,1]

Note:

  • numbers.length == 2

Solutions

Solution 1: Bitwise Operation

We can use the XOR operation to implement the swap of two numbers.

The XOR operation has the following three properties:

  • Any number XORed with 0 remains unchanged, i.e., a 0 = a .
  • Any number XORed with itself results in 0 , i.e., a a = 0 .
  • The XOR operation satisfies the commutative and associative laws, i.e., a b a = b a a = b ( a a ) = b 0 = b .

Therefore, we can perform the following operations on two numbers a and b in the array n u m b e r s :

  • a = a b , now a stores the XOR result of the two numbers;
  • b = a b , now b stores the original value of a ;
  • a = a b , now a stores the original value of b ;

In this way, we can swap two numbers without using a temporary variable.

The time complexity is O ( 1 ) , and the space complexity is O ( 1 ) .

Python3

class Solution:
    def swapNumbers(self, numbers: List[int]) -> List[int]:
        numbers[0] ^= numbers[1]
        numbers[1] ^= numbers[0]
        numbers[0] ^= numbers[1]
        return numbers

Java

class Solution {
    public int[] swapNumbers(int[] numbers) {
        numbers[0] ^= numbers[1];
        numbers[1] ^= numbers[0];
        numbers[0] ^= numbers[1];
        return numbers;
    }
}

TypeScript

function swapNumbers(numbers: number[]): number[] {
    numbers[0] ^= numbers[1];
    numbers[1] ^= numbers[0];
    numbers[0] ^= numbers[1];
    return numbers;
}

C++

class Solution {
public:
    vector<int> swapNumbers(vector<int>& numbers) {
        numbers[0] ^= numbers[1];
        numbers[1] ^= numbers[0];
        numbers[0] ^= numbers[1];
        return numbers;
    }
};

Go

func swapNumbers(numbers []int) []int {
	numbers[0] ^= numbers[1]
	numbers[1] ^= numbers[0]
	numbers[0] ^= numbers[1]
	return numbers
}

...