Wednesday, February 3, 2016

Swap Two Integers in Array

Swap Two Integers in Array

Given an array and two indexes, swap the integers on the two indexes.

Example
Given [1,2,3,4] and index1 = 2, index2 = 3. The array will change to [1,2,4,3] after swapping. You don't need return anything, just swap the integers in-place.


corner case: index1 == index2,不需要处理


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
public class Solution {
    /**
     * @param A an integer array
     * @param index1 the first index
     * @param index2 the second index
     * @return void
     */
    public void swapIntegers(int[] A, int index1, int index2) {
        // Write your code here
        if (index1 != index2){
            A[index1] = A[index1] ^ A[index2];
            A[index2] = A[index1] ^ A[index2];
            A[index1] = A[index1] ^ A[index2];
        }
    }
}