1、总结
- 其实我在写方法二的时候已经想到了方法三(不用数组,直接用三个变量保存数据),但是就差那么一步没有去动手实践。知道网上看到别人这么干了才动手,代码跑出来性能果然要更优秀。 ——
做事情,不能总是差一点,要尽全力才不会后悔.
2、题目
Given a non-empty array of integers, return the third maximum number in this array. If it does not exist, return the maximum number. The time complexity must be in O(n).
Example 1:
Input: [3, 2, 1]
Output: 1
Explanation: The third maximum is 1.
Example 2:
Input: [1, 2]
Output: 2
Explanation: The third maximum does not exist, so the maximum (2) is returned instead.
Example 3:
Input: [2, 2, 3, 1]
Output: 1
Explanation: Note that the third maximum here means the third maximum distinct number.
Both numbers with value 2 are both considered as second maximum.
3、我的方法
方法一:笨办法暴力破解,先排序,取third maximum number,如果不存在则返回最大值
/**
* @param {number[]} nums
* @return {number}
*/
// 方法一:
var thirdMax = function(nums) {
nums.sort((a, b) => {
return b - a;
});
console.log('nums', nums);
let i = 0;
let maxIndex = 1;
while(i < nums.length-1) {
if(nums[i] > nums[i+1]) {
maxIndex++;
}
i++;
if(maxIndex == 3) {
return nums[i];
}
}
if(maxIndex < 3) {
return nums[0];
}
};
方法二:题目要求时间复杂度为O(n),但没对空间复杂度做要求,另起一个数组存储遍历结果
/**
* @param {number[]} nums
* @return {number}
*/
// 方法二:
var thirdMax = function(nums) {
let len = 0;
let tempArr = [Number.MIN_SAFE_INTEGER, Number.MIN_SAFE_INTEGER, Number.MIN_SAFE_INTEGER];
for(let i = 0; i < nums.length; i++) {
if(nums[i] > tempArr[0]) {
tempArr.unshift(nums[i]);
len++;
} else if(nums[i] > tempArr[1] && nums[i] < tempArr[0]) {
tempArr.splice(1, 0, nums[i]);
len++;
} else if(nums[i] > tempArr[2] && nums[i] < tempArr[1]) {
tempArr.splice(2, 0, nums[i]);
len++;
}
}
if(len >= 3) {
return tempArr[2];
}
return tempArr[0];
};
想写时间复杂度低的方法,没想到写出来一个空间复杂度最优解…
4、其他方法
方法三:其实不需要数组操作,直接用三个变量保存即可
由于这道题同样没有solution,因此网上搜了一下其他的解法,发现完全不需要用数组缓存数据,也省
很多数组操作。
/**
* @param {number[]} nums
* @return {number}
*/
// 方法三:
var thirdMax = function(nums) {
let tempFirst = Number.MIN_SAFE_INTEGER;
let tempSecond = Number.MIN_SAFE_INTEGER;
let tempThird = Number.MIN_SAFE_INTEGER;
for(let i = 0; i < nums.length; i++) {
if(nums[i] > tempFirst) {
tempThird = tempSecond;
tempSecond = tempFirst;
tempFirst = nums[i];
} else if(nums[i] > tempSecond && nums[i] < tempFirst) {
tempThird = tempSecond;
tempSecond = nums[i];
} else if(nums[i] > tempThird && nums[i] < tempSecond) {
tempThird = nums[i];
}
}
if(tempThird != Number.MIN_SAFE_INTEGER) {
return tempThird;
}
return tempFirst;
};
性能果然好多了。