【Leetcode】414.Third Maximum Number

本文探讨了一种在非空整数数组中寻找第三大元素的算法,若不存在则返回最大值。采用O(n)时间复杂度,避免排序,通过遍历实现。详细解析了算法的实现过程与注意事项。

题目:
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).

注意:
1.他说是非空的,数组有可能是[1,2]这种情况。
2.时间复杂度是O(n)就不能sort,只能遍历。
3.第一遍写的时候没有看题,他说的是没有第三最大的就返回最大的,所以最后else return返回的是first不是second。
4.我第一遍写的时候是把 first 设置成nums[0],second 和 third 都设置成0,然后在循环里int i = 1 去遍历,后来发现不对,因为如果是[1,2]的情况,相当于最后是[2,1,0]。第三大返回的就是0了。
5.我开始的时候想不明白第二个判断条件,为什么不能等于first,后来终于明白了,会出现这样的结果。
在这里插入图片描述
Code
class Solution {
public int thirdMax(int[] nums) {

   int first = nums[0];
   int second = nums[0];
   int third = nums[0];
    
for(int i=0;i<nums.length;i++){
    if(nums[i]>first){
      third = second;
      second = first;
      first = nums[i];
        
    }else if (nums[i]!=first && (nums[i] > second || second == first)){
        third = second;
        second = nums[i];
    }else if((nums[i]!=first && nums[i] != second) && (nums[i] > third || third == second || third == first)){
        third = nums[i];
        
    }
}    
      
 if(first>second && second>third) return third;
  else return first;  
 
    
}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值