您的位置:首页 > 其它

BGP基本配置(H3C)

2013-06-02 20:26 363 查看
题目详情本题来自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);javaclass 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 //提示:自动阅卷结束唯一标识,请勿删除或增加。
}


本文出自 “TinyKing” 博客,请务必保留此出处http://tinyking.blog.51cto.com/3338571/1296222
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: