第三大的数

给定一个非空数组,返回此数组中第三大的数。如果不存在,则返回数组中最大的数。要求算法时间复杂度必须是O(n)。

示例 1:

输入: [3, 2, 1]

输出: 1

解释: 第三大的数是 1.

示例 2:

输入: [1, 2]

输出: 2

解释: 第三大的数不存在, 所以返回最大的数 2 .

示例 3:

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

输出: 1

解释: 注意,要求返回第三大的数,是指第三大且唯一出现的数。
存在两个值为2的数,它们都排第二。

 思路:

  1. 先遍历nums,放入map中,直到map中含有三个元素或不足三个元素就遍历完nums
  2. 当不足三个元素就遍历完nums,则返回map的最后一个数,即最大值
  3. 当map中包含三个元素之后,跳出for循环,记录遍历到当前位置时,在nums中的下标,并将三个元素从小到大赋值给first,second,third
  4. 从记录下的下标开始遍历nums,每遍历到一个位置,维护first,second,third的值
class Solution {
public:
	int thirdMax(vector<int>& nums) {
        int index = -1;
		map<int, int> temp;
		for (size_t i = 0; i < nums.size(); i++)
		{
			temp[nums[i]] = 0;
			if (temp.size() == 3)
			{
				index = i + 1;
				break;
			}
		}
		if (temp.size() < 3)
			return (*--temp.end()).first;

		int first = (*--temp.end()).first;
		int second = (*(----temp.end())).first;
		int third = (*(temp.begin())).first;
		for (int i = index; i < nums.size(); ++i)
		{
			if (nums[i] < third)
				continue;

			if (nums[i] > third &&  nums[i] < second)
				third = nums[i];

			if (nums[i] > second &&  nums[i] < first)
			{
				third = second;
				second = nums[i];
			}

			if (nums[i] > first)
			{
				third = second;
				second = first;
				first = nums[i];
			}
		}
		return third;
	}
};

时间复杂度为O(n)

猜你喜欢

转载自blog.csdn.net/leaf_scar/article/details/88077473