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])
... no, here you really wanted to compare. So you can fix that with:
for (i = 0; i < numsSize; ++i) {
j = i + 1;
while (j < numsSize) {
if (nums[i] == nums[j]) {
for (k = j; k < numsSize - 1; ++k) {
nums[k] = nums[k + 1];
}
--numsSize;
}
else {
++j;
}
}
}
Another mistake is in the closing section:
if(numsSize>=3)
return nums[numsSize-3];
else
return nums[0];
}
What if you have two distinct values? You should return the second one. So this is how it could work (assuming a non empty vector, i.e. numsSize>0
):
if (numsSize >= 3) {
return nums[numsSize - 3];
}
else if (numsSize == 2) {
return nums[1];
}
else {
return nums[0];
}
Additional thoughts
The gods of computational complexity are screaming here. Sorting (with O(n^2) operations), then removing duplicates with an O(n^2) approach is really a waste! Take advantage of the fact that equal values will be adjacent. Then I'd suggest to make that nums
const, and not modify it at all.
Here is a O(n) version of the function. I'm pretty sure this can be written better, but this is what I came up with.
int thirdMax(int *nums, int numsSize)
{
int maxs[3] = { 0 }; // this is just to silence some warnings
int valid[3] = { 0 };
for (int i = 0; i < numsSize; ++i) {
if (valid[0]) {
if (maxs[0] < nums[i]) {
if (valid[1]) {
if (maxs[1] < nums[i]) {
if (valid[2]) {
if (maxs[2] < nums[i]) { // new max: kick out 0 and move 1 and 2 down
maxs[0] = maxs[1];
maxs[1] = maxs[2];
maxs[2] = nums[i];
}
else if (maxs[2] > nums[i]) { // between 1 and 2: kick out 0 and move 1 down
maxs[0] = maxs[1];
maxs[1] = nums[i];
}
}
else { // new unseen value (three values now)
valid[2] = 1;
maxs[2] = nums[i];
}
}
else if (maxs[1] > nums[i]) { // between 0 and 1
if (valid[2]) { // kick out 0
maxs[0] = nums[i];
}
else { // put this in between
valid[2] = 1;
maxs[2] = maxs[1];
maxs[1] = nums[i];
}
}
}
else { // new unseen value (two values now)
valid[1] = 1;
maxs[1] = nums[i];
}
}
}
else { // no values up to now
valid[0] = 1;
maxs[0] = nums[i];
}
}
if (!valid[2] && valid[1]) {
return maxs[1];
}
return maxs[0];
}