首页 > 其他分享 >LeetCode #414 第三大的数

LeetCode #414 第三大的数

时间:2023-04-12 15:14:06浏览次数:32  
标签:返回 nums ++ 元素 第三 414 数组 LeetCode

解题思路
数组从大到小排序后,从第2个元素开始遍历,如果与上一个元素不相同,则标志位++,
标志位一旦从1加到3(两次)则代表存在第三大的数,即可返回。
如若不存在第三大的数,则在遍历结束后,函数末尾返回数组的第一个元素(最大的元素)。

标程

 1 class Solution {
 2 public:
 3     int thirdMax(vector<int>& nums) {
 4         sort(nums.begin(), nums.end(), greater<>());
 5         for(int i = 1, flag = 1; i < nums.size(); i++){
 6             if(nums[i] != nums[i-1] && ++flag == 3){ 
 7                 return nums[i]; //存在第三大的元素,则返回
 8             }
 9         }
10         return nums[0]; //否则返回数组中最大的元素
11     }
12 };

时间复杂度

O(N)

标签:返回,nums,++,元素,第三,414,数组,LeetCode
From: https://www.cnblogs.com/miracle-cst/p/17309842.html

相关文章

  • LeetCode #485 最大连续 1 的个数
    解题思路基础题,最后加一个特殊情况处理就好,时间复杂度O(n)代码  classSolution{public:intfindMaxConsecutiveOnes(vector<int>&nums){intcount=0;intMaxcount=0;for(inti=0;i<nums.size();i++){if(nums[i]==1){......
  • 第一天打卡第三个问题
    问题描述:第一个人用10%的单利投资了100美元。第二个人用5%复利投资了100美元。请编写一个程序,计算多少年后第二个人的投资价值会超过第一个人的投资价值,并显示此时两个人的投资价值。解决思路:1.先建立两个变量用于存储第一个人和第二个人的投资价值2.建立一个循环体,在循环体......
  • #yyds干货盘点# LeetCode面试题:矩阵置零
    1.简述:给定一个 mxn的矩阵,如果一个元素为0,则将其所在行和列的所有元素都设为0。请使用原地算法。 示例1:输入:matrix=[[1,1,1],[1,0,1],[1,1,1]]输出:[[1,0,1],[0,0,0],[1,0,1]]示例2:输入:matrix=[[0,1,2,0],[3,4,5,2],[1,3,1,5]]输出:[[0,0,0,0],[0,4,5,0],[0,3,1,0]]......
  • 4月11日leetcode练习
    设计一个支持push,pop,top操作,并能在常数时间内检索到最小元素的栈。实现MinStack类:MinStack()初始化堆栈对象。voidpush(intval)将元素val推入堆栈。voidpop()删除堆栈顶部的元素。inttop()获取堆栈顶部的元素。intgetMin()获取堆栈中的最小元素。 来源:力扣(Le......
  • leetcode 183
    从不订购的客户 selectc.NameasCustomersfromCustomerscleftjoinOrdersoonc.Id=o.CustomerIdwhereo.CustomerIdisnull selectcustomers.namecustomersfromcustomerswherecustomers.idnotin(selectorders.customeridfromorders) ......
  • leetcode 181
    超过经理收入的员工 selecte1.nameasEmployeefromEmployeee1,Employeee2wheree1.managerId=e2.idande1.salary>e2.salary selecte1.nameasEmployeefromEmployeee1leftjoinEmployeee2one1.managerId=e2.idwheree1.salary>e2.salary......
  • 【LeetCode回溯算法#extra01】集合划分问题【火柴拼正方形、划分k个相等子集、公平发
    火柴拼正方形https://leetcode.cn/problems/matchsticks-to-square/你将得到一个整数数组matchsticks,其中matchsticks[i]是第i个火柴棒的长度。你要用所有的火柴棍拼成一个正方形。你不能折断任何一根火柴棒,但你可以把它们连在一起,而且每根火柴棒必须使用一次。如......
  • [LeetCode] 2390. Removing Stars From a String
    Youaregivenastring s,whichcontainsstars *.Inoneoperation,youcan:Chooseastarin s.Removetheclosest non-star charactertoits left,aswellasremovethestaritself.Return thestringafter all starshavebeenremoved.Note:Thei......
  • 差分数组-leetcode1094
    车上最初有 capacity 个空座位。车 只能 向一个方向行驶(也就是说,不允许掉头或改变方向)给定整数 capacity 和一个数组 trips , trip[i]=[numPassengersi,fromi,toi] 表示第 i 次旅行有 numPassengersi 乘客,接他们和放他们的位置分别是 fromi 和 toi 。这些位......
  • leetcode_打卡1
    leetcode_打卡1题目:1768.交替合并字符串解答:思路:模拟即可,字符串的提取:a.charAt(i)classSolution{publicStringmergeAlternately(Stringword1,Stringword2){Stringresult="";intm=word1.length();intn=word2.length();......