Home > Software design >  C code find distinct third maximum. The code is working properly for another test case but for the t
C code find distinct third maximum. The code is working properly for another test case but for the t

Time:06-06

I cannot understand where is the problem occurring here. Input is [1, 2]. Output must be 2, but my code gives 1.

Problem description: Given an integer array nums, return the third distinct maximum number in this array. If the third maximum does not exist, return the maximum number.

int thirdMax(int *nums, int numsSize) {
    int i, j, k, temp;
    for (i = 0; i < numsSize; i  ) {
        for (j = i   1; j < numsSize; j  ) {
            if (nums[j] < nums[i]) {
                temp = nums[i];
                nums[i] = nums[j];
                nums[j] = temp;
            }
        }
    }

    for (i = 0; i < numsSize;   i) {
        while (j = i   1 && j < numsSize) {
            if (nums[i] = nums[j]) {
                for (k = j; k < numsSize - 1;   k)
                    nums[k] = nums[k   1];
                --numsSize;
            } else
                  j;
        }
    }

    if (numsSize >= 3)
        return nums[numsSize - 3];
    else
        return nums[0];
}

CodePudding user response:

So, to solve the problem you sort the vector, remove duplicates, then return the third maximum if it exists.

There are two mistakes in the duplicate removal:

while(j=i 1 && j<numsSize)

which doesn't do what you think. And it's hard to guess what you were thinking. But an assignment there smells of mistake. As the following one:

if(nums[i]=nums[j])

  • Related