Skip to content

Instantly share code, notes, and snippets.

@yokolet
Created May 24, 2017 03:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yokolet/4ad1b3b7186d9cd53330b7a5438db514 to your computer and use it in GitHub Desktop.
Save yokolet/4ad1b3b7186d9cd53330b7a5438db514 to your computer and use it in GitHub Desktop.
public class SwapWithoutExtraSpace {
static void swap(int[] nums, int i, int j) {
nums[i] = nums[i] ^ nums[j];
nums[j] = nums[i] ^ nums[j];
nums[i] = nums[i] ^ nums[j];
}
static void printArray(int[] nums) {
for (int i = 0; i < nums.length; i++) {
if (i != 0) { System.out.print(" "); }
System.out.print(nums[i]);
}
System.out.println();
}
public static void main(String[] args) {
int[] nums = {1, 2, 3, 4, 5};
swap(nums, 0, nums.length - 1);
printArray(nums);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment