/* 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. */ //66ms 3.41% //思路:先把数组排一遍序,用快速排序,然后去重复元素,这些都是我之前写好的leetcode题目中写好的函数,直接拿过来用了。然后输出第三个大数 int thirdMax(int* nums, int numsSize) { int length; quicksort(nums,0,numsSize-1); length = removeDuplicates(nums,numsSize); if(length<3) return nums[length-1]; return nums[length-3]; } void quicksort(int* nums,int left,int right) { int i,j,t,temp; if(left>right) return; temp=nums[left]; //temp中存的就是基准数 i=left; j=right; while(i!=j) { //顺序很重要,要先从右边开始找 while(nums[j]>=temp && i<j) j--; //再找右边的 while(nums[i]<=temp && i<j) i++; //交换两个数在数组中的位置 if(i<j) { t = nums[i]; nums[i] = nums[j]; nums[j] = t; } } //最终将基准数归位 nums[left] = nums[i]; nums[i] = temp; quicksort(nums,left,i-1);//继续处理左边的,这里是一个递归的过程 quicksort(nums,i+1,right);//继续处理右边的 ,这里是一个递归的过程 } int removeDuplicates(int* nums, int numsSize) { int i,count = 1; if(nums[0]==NULL&&numsSize==0) return NULL; for(i=0;i<numsSize-1;i++) if(nums[i]!=nums[i+1]) nums[count++] = nums[i+1]; return count; }
414. Third Maximum Number
原创
©著作权归作者所有:来自51CTO博客作者jenslee的原创作品,请联系作者获取转载授权,否则将追究法律责任
提问和评论都可以,用心的回复会被更多人看到
评论
发布评论
相关文章
-
psql窗口函数 ROW_NUMBER的应用
psql窗口函数的使用
窗口函数 一对多 表结构 -
【Leetcode】414. 第三大的数
给你一个非空数组,返回此数组中 第三大的数。如果不存在,则返回数组中最大的数。
leetcode 算法 数据结构 数组 #include -
Leetcode: Third Maximum Number
My Solution: Highest votes in discussion
Leetcode Array/String sed ide 编程题目