题目详情
本题来自caopengcs,只要你有兴趣,每个人都可以出题(出题入口在主页右侧边栏“贡献题目”->“我要发布”内),以下是题目详情:
给定一个包含1-n的数列,我们通过交换任意两个元素给数列重新排序。求最少需要多少次交换,能把数组排成按1-n递增的顺序,其中,数组长度不超过100。
例如:
原数组是3,2,1, 我们只需要交换1和3就行了,交换次数为1,所以输出1。
原数组是2,3,1,我们需要交换2和1,变成1,3,2,再交换3和2,变为1,2,3,总共需要的交换次数为2,所以输出2。
函数头部:
C/C++
int run(const int *a,int n);
java
class solution {
public static int run(int [] a)
}
public class solution {
public static int run(int []a) {
if(a == null || a.length == 0) return 0;
int start = 0;
// count swap
int swapTimes = 0;
int max = a[0];
int maxIndex = 0;
while(true) {
for(int i = start; i < a.length; i++) {
max = a[maxIndex];
if(max > a[i]) {
max = a[i];
maxIndex = i;
}
}
if(maxIndex != start) {
int tmp = a[start];
a[start] = max;
a[maxIndex] = tmp;
swapTimes ++;
}
start ++;
maxIndex = start;
if(start == a.length) {
break;
}
}
return swapTimes;
}
//start 提示:自动阅卷起始唯一标识,请勿删除或增加。
public static void main(String args[])
{
int a[] = {2, 3, 1};
System.out.println("Array {2, 3, 1}, Swap times :" + run(a));
int b[] = {3, 2, 1};
System.out.println("Array {3, 2, 1}, Swap times : " + run(b));
}
//end //提示:自动阅卷结束唯一标识,请勿删除或增加。
}
















