菜鸟的代码:
import java.util.*; import java.util.regex.*; import java.text.*; import java.math.*; public class TheSwapsDivTwo { public int find(int[] sequence) { int i,j,count; boolean tag=false; count=0; for(i=0;i<sequence.length;i++){ for(j=i+1;j<sequence.length;j++){ if(sequence[i]!=sequence[j]) count++; else tag=true; } } if(tag) count++; return count; } } //Powered by KawigiEdit 2.1.4 (beta) modified by pivanof!
大神的代码:
public class TheSwapsDivTwo { public int find(int[] sequence) { int n = sequence.length; int c =0; int have =0; for(int i =0 ; i < n;i++) for(int j = i+1;j < n;j++) if(sequence[i] != sequence[j])c++; else have++; have = Math.min(have, 1); c+=have; return c; } } // Powered by FileEdit // Powered by moj 4.17 [modified TZTester] // Powered by CodeProcessor
分析:
算法:
对比:
1.方法差别不大。
总结:
出于能少点时间就少点的考虑,可以把sequence.length取出来,免得多做n^2次操作。