Third Maximum Number

easy array sorting

Problem

Given an integer array nums, return the third distinct maximum. If fewer than three distinct values exist, return the overall maximum.

Inputnums = [2, 2, 3, 1]
Output1
Distinct values are {1, 2, 3}; the third largest is 1.

def third_max(nums):
    a = b = c = None
    for x in nums:
        if x in (a, b, c): continue
        if a is None or x > a:    a, b, c = x, a, b
        elif b is None or x > b:  b, c = x, b
        elif c is None or x > c:  c = x
    return c if c is not None else a
function thirdMax(nums) {
  let a = null, b = null, c = null;
  for (const x of nums) {
    if (x === a || x === b || x === c) continue;
    if (a === null || x > a)       { c = b; b = a; a = x; }
    else if (b === null || x > b)  { c = b; b = x; }
    else if (c === null || x > c)  { c = x; }
  }
  return c === null ? a : c;
}
class Solution {
    public int thirdMax(int[] nums) {
        Long a = null, b = null, c = null;
        for (int x : nums) {
            long v = x;
            if ((a != null && a == v) || (b != null && b == v) || (c != null && c == v)) continue;
            if (a == null || v > a)      { c = b; b = a; a = v; }
            else if (b == null || v > b) { c = b; b = v; }
            else if (c == null || v > c) { c = v; }
        }
        return (int) (c == null ? a : c);
    }
}
int thirdMax(vector<int>& nums) {
    long long a = LLONG_MIN, b = LLONG_MIN, c = LLONG_MIN;
    for (int x : nums) {
        if (x == a || x == b || x == c) continue;
        if (x > a)      { c = b; b = a; a = x; }
        else if (x > b) { c = b; b = x; }
        else if (x > c) { c = x; }
    }
    return c == LLONG_MIN ? (int) a : (int) c;
}
Time: O(n) Space: O(1)