日期:2014-05-20 浏览次数:20724 次
class T { public static void main(String[] args) { System.out.println(getSecondMax(new int[] { 1, 3, 5, 7, 9, 2, 4, 6, 8, 10 })); } /** * 求整数数组的第2大的数,不许用排序算法 * * @param nums * @return */ public static int getSecondMax(int[] all) { int max, max2;// 第一大,第二大数字 max = all[0]; max2 = all[1]; if (max < max2) { max = all[1]; max2 = all[0]; } for (int i = 1; i < all.length; i++) { if (all[i] > max2) { if (all[i] > max) { max2 = max;// 原来最大值变第二大 max = all[i];// 最大值更新为当前值 } else max2 = all[i];// 当前值为第二大 } } return max2; } }
------解决方案--------------------
public class BigNum {
public static void main(String[] args) {
int[] a = new int[]{1,684,-2,1564,6564,65,465,-465,464874,464874,464874,464874,9874,9546,-54,65,46,568,8,4685,6,8,46,846,8,6,8446,86,46,8,464874};
if(null != a && a.length>2) printTheFirstBigNumAndTheSecondBigNumInIntArray(a);
}
public static void printTheFirstBigNumAndTheSecondBigNumInIntArray(int[] a) {
int fMax = a[0];
int sMax = a[1];
if(fMax < sMax) {
fMax += sMax;
sMax = fMax - sMax;
fMax = fMax - sMax;
}
for(int i=2; i <a.length; i++) {
if(fMax < a[i]) {
if(sMax < fMax) {
sMax = fMax;
}
fMax = a[i];
}else {
if(fMax != a[i] && sMax < a[i]) {
sMax = a[i];
}
}
}
System.out.println("fMax:\t" + fMax + "\nsMax:\t" + sMax);
}
}