给你一个非空数组,返回此数组中第三大的数。如果不存在,则返回数组中最大的数。 例如数组 num=[4,1,2,3],返回 3;数组[8,6,5,4,1],返回 5.
时间: 2024-03-05 10:54:02 浏览: 21
好的,这是一道简单的算法题,可以使用桶排序来解决,以下是解题思路:
1. 首先遍历数组,找到最大值,将其作为桶的第一位。
2. 再次遍历数组,找到第二大的数,将其放置在桶的第二位。
3. 同理,找到第三大的数,将其放置在桶的第三位。
4. 最后判断桶的第三位是否有数,有则返回桶的第三位,否则返回桶的第一位。
下面是代码实现:
```python
def thirdMax(nums):
first = second = third = float('-inf')
for num in nums:
if num > first:
third = second
second = first
first = num
elif num > second and num < first:
third = second
second = num
elif num > third and num < second:
third = num
return third if third != float('-inf') else first
```
这个算法的时间复杂度为O(n),空间复杂度为O(1)。
相关问题
给你一个非空数组,返回此数组中的第三大数。如果不存在,则返回数组中最大的数,用java实现
好的,我会使用Java编写一个函数来解决这个问题。以下是代码示例:
```java
import java.util.Arrays;
public class ThirdLargestNumber {
public static int thirdMax(int[] nums) {
// 创建一个长度为3的数组来存储前三大的数
Integer[] maxNums = new Integer[3];
Arrays.fill(maxNums, null);
for (Integer num : nums) {
if (num.equals(maxNums[0]) || num.equals(maxNums[1]) || num.equals(maxNums[2])) {
// 如果当前数已经存在于前三大的数中,则跳过
continue;
}
if (maxNums[0] == null || num > maxNums[0]) {
// 更新最大的数
maxNums[2] = maxNums[1];
maxNums[1] = maxNums[0];
maxNums[0] = num;
} else if (maxNums[1] == null || num > maxNums[1]) {
// 更新第二大的数
maxNums[2] = maxNums[1];
maxNums[1] = num;
} else if (maxNums[2] == null || num > maxNums[2]) {
// 更新第三大的数
maxNums[2] = num;
}
}
if (maxNums[2] != null) {
return maxNums[2]; // 存在第三大的数,返回第三大的数
} else {
return maxNums[0]; // 不存在第三大的数,返回最大的数
}
}
public static void main(String[] args) {
int[] nums = {1, 2, 3, 4, 5};
int result = thirdMax(nums);
System.out.println("第三大的数是:" + result);
}
}
```
您可以将您自己的数组传递给`thirdMax`函数,然后运行代码以获取结果。在这个示例中,数组`nums`为`{1, 2, 3, 4, 5}`,输出将是`3`,因为第三大的数是`3`。
给你一个非空数组,返回此数组中第三大的数 。如果不存在,则返回数组中最大的数。请用JavaScript实现。
好的,我可以回答这个问题。以下是JavaScript的实现代码:
```javascript
function thirdMax(nums) {
let first = -Infinity;
let second = -Infinity;
let third = -Infinity;
for (let i = ; i < nums.length; i++) {
const num = nums[i];
if (num > first) {
third = second;
second = first;
first = num;
} else if (num > second && num < first) {
third = second;
second = num;
} else if (num > third && num < second) {
third = num;
}
}
return third !== -Infinity ? third : first;
}
```
这个函数接收一个数组作为参数,然后使用三个变量来记录数组中的前三大的数。遍历数组时,如果当前数比第一大的数还大,就把第一大的数、第二大的数和第三大的数都更新一下;如果当前数比第二大的数大但比第一大的数小,就把第二大的数和第三大的数更新一下;如果当前数比第三大的数大但比第二大的数小,就把第三大的数更新一下。最后,如果第三大的数存在,就返回它,否则返回第一大的数。