Leetcode - 414. Third Maximum Number

숲사람·2022년 6월 14일
0

멘타트 훈련

목록 보기
58/237

문제

주어진 배열에서 3번째로 큰 수를 리턴하라.

Input: nums = [2,2,3,1]
Output: 1
Explanation:
The first distinct maximum is 3.
The second distinct maximum is 2 (both 2's are counted together since they have the same value).
The third distinct maximum is 1.

해결 O(nlogn)

int cmp(const void *a, const void *b)
{
    //return *(int *)b - *(int *)a;
    int num1 = *(int *)b;
    int num2 =  *(int *)a;
    if (num1 > num2)
        return 1;
    else if(num1 < num2)
        return -1;
    else
        return 0;
}

int thirdMax(int* nums, int numsSize){
    qsort(nums, numsSize, sizeof(int), cmp);
    int prev = nums[0];
    int cnt = 1;
    int max = 0;
    for (int i = 1; i < numsSize; i++) {
        max = nums[i];
        if (max != prev)
            cnt++;
        prev = max;
        if (cnt == 3)
            return max;
    }
    if (cnt < 3)
        return nums[0];
    else
        return max;
}
profile
기록 & 정리 아카이브 용도 (보다 완성된 글은 http://soopsaram.com/documentudy)

0개의 댓글