-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathQ10_交换数组两个元素.java
45 lines (40 loc) · 1.41 KB
/
Q10_交换数组两个元素.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
package com.algorithm.demo.array;
import com.algorithm.demo.PrintArray;
/**
* 484. 交换数组两个元素
* 给你一个数组和两个索引,交换下标为这两个索引的数字
* <p>
* 样例
* Example 1:
* <p>
* Input: `[1,2,3,4]` and index1 = `2`, index2 = `3`
* Output:The array will change to `[1,2,4,3]` after swapping. You don't need return anything, just swap the integers in-place.
* Explanation: You don't need return anything, just swap the integers in-place.
* Example 2:
* <p>
* Input: `[1,2,2,2]` and index1 = `0`, index2 = `3`
* Output:The array will change to `[2,2,2,1]` after swapping. You don't need return anything, just swap the integers in-place.
* Explanation: You don't need return anything, just swap the integers in-place.
*/
public class Q10_交换数组两个元素 {
public static void main(String[] args) {
int[] nums = {1, 2, 3, 4};
swapIntegers(nums, 2, 3);
}
/**
* @param A: An integer array
* @param index1: the first index
* @param index2: the second index
* @return: nothing
*/
public static void swapIntegers(int[] A, int index1, int index2) {
// write your code here
if (A == null || A.length == 0 || index1 > A.length || index2 > A.length) {
return;
}
int temp = A[index1];
A[index1] = A[index2];
A[index2] = temp;
PrintArray.print(A);
}
}