LeetCode-Third_Maximum_Number

题目:

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.


翻译:

给定一个非空的数组,返回这个数组中第三大的数字。如果不存在的话,返回最大的数字。时间复杂度要控制在O(n)。


例子1:

输入: [3, 2, 1]

输出: 1

解释: 第三大的数字是1。


例子2:

输入: [1, 2]

输出: 2

解释: 第三大的数字不存在,所以返回最大的数字(2)代替。


例子3:

输入: [2, 2, 3, 1]

输出: 1

解释: 注意第三大的数字是指第三大不相同的数字。两个数字值都为2被看成同一个第二大的数字。


思路:

Method1:

能想到的最简单的方法就是先用sort进行排序,然后利用一个set集合(有序且去重)来存储数字,扫描到倒数第三个数字就是所需,若不存在,直接返回s.rbegin()即最大的数字。

Method 2:

LeetCode上有人是这样做的,很巧妙,因为重复的数字算作同一个,因此,用一个有序的集合set来存储数字,而且,整个set中最多只存储3个数字,那么如果set的个数为3,那么set.begin()即是第三大的数字;若set中的数字少于3,也就是不存在第三大的数字,那么s.rbegin()(反向迭代器)中就是最大的数字。


C++代码(Visual Studio 2017):

#include "stdafx.h"
#include <iostream>
#include <vector>
#include <algorithm>
#include <set>
using namespace std;

class Solution {
public:
	int thirdMax(vector<int>& nums) {
		//Method 1:
		set<int> s;
		sort(nums.begin(), nums.end());
		for (int num : nums) {
			s.insert(num);
		}
		if (s.size() < 3)
			return *s.rbegin();
		int count = 0;
		for (set<int>::iterator it = s.begin(); it != s.end(); it++) {
			count++;
			if (count == s.size() - 2)
				return *it;
		}

		/*Method 2:
		set<int> top3;
		for (int num : nums) {
			top3.insert(num);
			if (top3.size() > 3)
				top3.erase(top3.begin());
		}
		return top3.size() == 3 ? *top3.begin(): *top3.rbegin();  //rbegin() 反向迭代器*/	
	}
};

int main()
{
	Solution s;
	vector<int> nums = { 3,2,2,1 };
	int result;
	result = s.thirdMax(nums);
	cout << result;
    return 0;
}


猜你喜欢

转载自blog.csdn.net/tel_annie/article/details/80319693