持续更新中😬 加个关注,后续上新不错过~
一、题目描述
有一组数(设有N个)。编一程序交换这组数中任意指定的两段。
1. 输入
一个数N(不超过20个)
一行N个数由空格分开
两个空格分开的数(表示要交换的其中一段)
两个空格分开的数(表示要交换的其中另一段)
2. 输出
交换后的一行数(中间用空格隔开)
3. 样例输入
16 3 6 11 45 23 70 67 34 26 89 90 15 56 50 20 10 3 5 13 15
4. 样例输出
3 6 56 50 20 70 67 34 26 89 90 15 11 45 23 10
二、解题思路
首先看到这道题目的时候,我们应该思考下面这两个问题🤔
-
交换的这两段数,长度一定是相等的吗?
不一定 -
交换的这两段数,会有重合的部分吗?
可能会重合
所以这道题,远比样例要复杂!
1. arraycopy方法介绍
这里我们使用arraycopy方法(将数组中指定的数据拷贝到临时数组中),即可解决上述两种情况,用法如下:
public static void arraycopy(Object src, int srcPos, Object dest, int destPos, int length)
数组的拷贝动作是系统级的,性能很高。System.arraycopy方法具有5个参数,含义分别为:
参数序号 | 参数名称 | 参数类型 | 参数含义 |
---|---|---|---|
1 | src | Object | 源数组 |
2 | srcPos | int | 源数组索引起始位置 |
3 | dest | Object | 目标数组 |
4 | destPos | int | 目标数组索引起始位置 |
5 | length | int | 复制元素个数 |
2. 代码思路
首先使用L1、R1、L2、R2分别记录要交换的两段数的左右边界,然后通过调用arraycopy方法,将第一段要交换的数复制到临时数组temp中,然后调用arraycopy方法,将第二段要交换的数复制到数组第一段数的位置,最后再调用arraycopy方法,将临时数组中的的数复制到数组第二段数的位置。
3. 参考代码
import java.util.Scanner;
public class t1334 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
int a[]=new int[n+1];
for (int i = 1; i <=n; i++) {
a[i]=scanner.nextInt();
}
int L1=scanner.nextInt();
int R1=scanner.nextInt();
int L2=scanner.nextInt();
int R2=scanner.nextInt();
// 创建一个临时数组来保存交换的段
int[] temp = new int[(R1-L1)+1];
// 复制要交换的段到临时数组
System.arraycopy(a,L1,temp,0,(R1-L1)+1);
System.arraycopy(a,L2,a,L1,(R2-L2)+1);
System.arraycopy(temp,0,a,L2,(R1-L1)+1);
for (int i = 1; i <n ; i++) {
System.out.print(a[i]+" ");
}
System.out.print(a[n]);
}
}
若有帮助的话,请点个赞吧!😊