[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.

找出数组中数组第三大的元素,如果不存在这个元素则返回数组中值最大的元素。

首先对数组进行去重,使用STL中的unique函数,然后判断数组的大小,如果存在第三大的元素则返回元素,如果不存在则返回数组中最大值。

需要注意使用unique函数的规则

unique()是将vector相邻重复元素“删除”,所以必须先对vector排序。

unique()并不是将相邻重复元素“删除”,而是将重复的元素全部移动到vector的尾部,所以vector被分为两个部分,前半部分为非重复元素,后半部分为重复的元素。分界线就是unique()的返回值,这个返回值是一个迭代器。

使用vector的操作erase将重复的元素删除。从unique的返回值知道vector的尾后迭代器。

代码如下:

class Solution {
public:
    int thirdMax(vector<int>& nums) {
        sort(nums.begin(), nums.end());
        auto it = unique(nums.begin(), nums.end());
        nums.erase(it, nums.end());
        int n = nums.size();
        if (n > 2)
            return nums[n - 3];
        else
            return nums[n - 1];
    }
};
// 6 ms

 这道题的关键点在于去重,所以使用set也可以实现。

原文地址:https://www.cnblogs.com/immjc/p/8195651.html