要求:算法时间复杂度为O(n)。
代码:
public int getThirdMaxElement(int[] array) { if(array == null) { return 0; } if(array.length == 1) { return array[0]; } if(array.length == 2) { return array[0] > array[1] ? array[0] : array[1]; } int[] thirdArr = {0,0,0}; //数组存储最大的三个数 int a = 0; //thirdArr数组下标 int b = 1; //array数组下标 thirdArr[0] = array[0]; //填充thirdArr数组 while(a < 2 && b < array.length) { if(thirdArr[a] != array[b]) { thirdArr[a+1] = array[b]; a++; } b++; } if(a < 2) { //如果thirdArr只有两个元素 return thirdArr[0] > thirdArr[1] ? thirdArr[0] : thirdArr[1]; } else { //对thirdArr数组排序 Arrays.sort(thirdArr); //升序 } //对剩余数组进行比较 while(b < array.length) { if(thirdArr[2] < array[b]) { //1.最大的数比较 thirdArr[0] = thirdArr[1]; thirdArr[1] = thirdArr[2]; thirdArr[2] = array[b]; b++; continue; } if(thirdArr[1] < array[b]) { //2.中间数比较 thirdArr[0] = thirdArr[1]; thirdArr[1] = array[b]; b++; continue; } if(thirdArr[0] < array[b]) { //3.最小的数比较 thirdArr[0] = array[b]; b++; continue; } b++; } return thirdArr[0]; }
时间: 2024-10-07 11:50:01