You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

已达O(1)时间与空间复杂度的变量交换代码,还能进行哪些优化?

Optimizing Variable Swap Code in Java

Great question! Your current code is already optimal in terms of time and space complexity (both O(1)), but there are still several angles to "optimize"—often focusing on code style, readability, conciseness, or demonstrating alternative techniques that might be contextually useful. Let’s break them down:

1. Eliminate the Temporary Variable (Tradeoffs Apply)

Your code uses a temp variable, which is straightforward but can be removed using arithmetic operations or bitwise XOR. Note that these methods save a tiny amount of stack space (negligible for most cases) but come with tradeoffs:

Bitwise XOR (Works Only for Integers)

This leverages the properties of XOR to swap values without a temp variable. It’s safe as long as var1 and var2 aren’t the same memory location (though in your case, they’re separate primitives so no issue):

int var1 = 6, var2 = 10;
System.out.printf("Before Swap var1 = %d and var2 = %d%n", var1, var2);

var1 = var1 ^ var2;
var2 = var1 ^ var2;
var1 = var1 ^ var2;

System.out.printf("After Swap var1 = %d and var2 = %d%n", var1, var2);

Arithmetic Operations (Risk of Overflow)

You can use addition/subtraction, but this can cause integer overflow if the sum of var1 and var2 exceeds Integer.MAX_VALUE:

int var1 = 6, var2 = 10;
System.out.printf("Before Swap var1 = %d and var2 = %d%n", var1, var2);

var1 = var1 + var2;
var2 = var1 - var2;
var1 = var1 - var2;

System.out.printf("After Swap var1 = %d and var2 = %d%n", var1, var2);

Caveat: These methods hurt readability. Most developers will need a moment to parse what’s happening, whereas your original temp variable approach is instantly clear.

2. Improve Readability and Code Style

Even if performance is maxed out, you can make the code cleaner and easier to maintain:

Use printf for Cleaner Output

Replace string concatenation with formatted strings to avoid messy + chains:

// Instead of:
System.out.println("Before Swap var1 = "+var1+" and var2 = "+var2);

// Use:
System.out.printf("Before Swap var1 = %d and var2 = %d%n", var1, var2);

Encapsulate Swap Logic for Reusability

If you need to swap variables multiple times, wrap the logic in a reusable method. For primitives, you’ll need to pass them in an array (since Java is pass-by-value):

public class Test {
    public static void main(String[] args) {
        int var1 = 6, var2 = 10;
        System.out.printf("Before Swap var1 = %d and var2 = %d%n", var1, var2);
        
        int[] swapped = swap(var1, var2);
        var1 = swapped[0];
        var2 = swapped[1];
        
        System.out.printf("After Swap var1 = %d and var2 = %d%n", var1, var2);
    }
    
    private static int[] swap(int a, int b) {
        return new int[]{b, a};
    }
}

Alternatively, for object types (like Integer), you could use a generic method, but primitives require this array workaround.

3. Leverage Java Syntax Sugar (Modern Versions)

If you’re using Java 14+, you can use records to make the swap method more expressive:

public record IntPair(int first, int second) {}

// In main:
IntPair pair = new IntPair(var1, var2);
var1 = pair.second();
var2 = pair.first();

This is more readable than array hacks and makes the intent clear.

Key Takeaway

Your original code is already performance-optimal. When an interviewer says "optimize" here, they’re likely testing your understanding of:

  • Alternative low-level techniques (like XOR)
  • Tradeoffs between conciseness and readability
  • Code maintainability and reusability

In most production scenarios, your original temp variable approach is the best choice—it’s simple, readable, and avoids edge cases like overflow. The "optimizations" above are more about demonstrating depth of knowledge than improving raw performance.

内容的提问来源于stack exchange,提问作者user15156752

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.29 15:57:37