返回介绍

lcci / 16.01.Swap Numbers / README_EN

发布于 2024-06-17 01:04:43 字数 3030 浏览 0 评论 0 收藏 0

16.01. Swap Numbers

中文文档

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 $\oplus$ 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 \oplus 0=a$.
  • Any number XORed with itself results in $0$, i.e., $a \oplus a=0$.
  • The XOR operation satisfies the commutative and associative laws, i.e., $a \oplus b \oplus a=b \oplus a \oplus a=b \oplus (a \oplus a)=b \oplus 0=b$.

Therefore, we can perform the following operations on two numbers $a$ and $b$ in the array $numbers$:

  • $a=a \oplus b$, now $a$ stores the XOR result of the two numbers;
  • $b=a \oplus b$, now $b$ stores the original value of $a$;
  • $a=a \oplus 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)$.

class Solution:
  def swapNumbers(self, numbers: List[int]) -> List[int]:
    numbers[0] ^= numbers[1]
    numbers[1] ^= numbers[0]
    numbers[0] ^= numbers[1]
    return numbers
class Solution {
  public int[] swapNumbers(int[] numbers) {
    numbers[0] ^= numbers[1];
    numbers[1] ^= numbers[0];
    numbers[0] ^= numbers[1];
    return numbers;
  }
}
class Solution {
public:
  vector<int> swapNumbers(vector<int>& numbers) {
    numbers[0] ^= numbers[1];
    numbers[1] ^= numbers[0];
    numbers[0] ^= numbers[1];
    return numbers;
  }
};
func swapNumbers(numbers []int) []int {
  numbers[0] ^= numbers[1]
  numbers[1] ^= numbers[0]
  numbers[0] ^= numbers[1]
  return numbers
}
function swapNumbers(numbers: number[]): number[] {
  numbers[0] ^= numbers[1];
  numbers[1] ^= numbers[0];
  numbers[0] ^= numbers[1];
  return numbers;
}

Solution 2

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文