我的老师告诉我,这是Bubble Sort的唯一代码
int a[]={2,3,7,9,8,1,4,5,10,6};
for(int i=0;i<a.length;i++)
{
for(int j=0;j<a.length-i-1;j++)
{
if(a[j]>a[j+1])
{
int t=a[j];
a[j]=a[j+1];
a[j+1]=t;
}
}
}
for(int i=0;i<a.length;i++)
{
System.out.print(a[i]+"\t");
}
Run Code Online (Sandbox Code Playgroud)
但我用不同的外循环运行程序 -
int b[]={2,3,7,9,8,1,4,5,10,6};
for(int i=0;i<b.length-1;i++)
{
for(int j=0;j<b.length-i-1;j++)
{
if(b[j]>b[j+1])
{
int t=b[j];
b[j]=b[j+1];
b[j+1]=t;
}
}
}
for(int i=0;i<b.length;i++)
{
System.out.print(b[i]+"\t");
}
Run Code Online (Sandbox Code Playgroud)
输出是 - 第一案例 -
1 2 3 4 5 6 7 8 9 10
Run Code Online (Sandbox Code Playgroud)
第二个案例 -
1 2 3 4 5 6 7 8 9 10
Run Code Online (Sandbox Code Playgroud)
所以现在我被告知我的代码是错误的,即使我的输出是正确的.拜托,告诉我,我完全错了?
我从网站上得到了这个编码问题.问题如下:
如果可以通过交换其中一个阵列中的至多一对元素从另一个阵列获得一个阵列,则称这两个阵列是相似的.
给定两个数组,检查它们是否相似.
例
对于A = [1,2,3]和B = [1,2,3],输出应该是相似的(A,B)=真.
数组相等,无需交换任何元素.
对于A = [1,2,3]和B = [2,1,3],输出应该是相似的(A,B)=真.
我们可以通过在B中交换2和1从A获得B.
对于A = [1,2,2]和B = [2,1,1],输出应该是相似的(A,B)=假.
在A或B中任何两个元素的任何交换都不会使A和B相等.
这是我给出的解决方案:
boolean areSimilar(int[] A, int[] B) {
if(A.length != B.length) return false;
int[] copyA = A, copyB = B;
Arrays.sort(copyA); Arrays.sort(copyB);
int countSwap = 0;
if(!Arrays.equals(copyA, copyB)) return false;
for(int i = 0; i < A.length; i++) {
if(A[i] != B[i]) countSwap++;
}
return (countSwap == 2 || countSwap == 0);
}
Run Code Online (Sandbox Code Playgroud)
此代码为以下数组提供了正确的结果:
答:[1,2,3]
B:[1,2,3]
答:[1,2,3]
B:[2,1,3]
答:[1,2,2] …