patternjavaMinor
Finding the maximum inclusive distance between two duplicate numbers in an array
Viewed 0 times
theinclusivemaximumarrayduplicatenumbersdistancetwobetweenfinding
Problem
The prompt that made me put this function together was sourced from CodingBat.
I was curious about cleaner, more correct methods of doing putting this together such as finding a cleaner way to tell if there is or is not a duplicate in the array. I am also trying to be as efficient as possible. I believe this is an \$O(n^2)\$ function. Let me know what I should change.
The code works just fine. I just feel like there is quite a lot I can streamline and I would like to be pointed in the right direction.
I was curious about cleaner, more correct methods of doing putting this together such as finding a cleaner way to tell if there is or is not a duplicate in the array. I am also trying to be as efficient as possible. I believe this is an \$O(n^2)\$ function. Let me know what I should change.
The code works just fine. I just feel like there is quite a lot I can streamline and I would like to be pointed in the right direction.
public int maxSpan(int[] nums) {
int highestSpan = 0;
int span;
boolean duplicate = false;
if (nums.length == 0)
return highestSpan;
for (int i = 0; i highestSpan)
highestSpan = span;
}
}
}
if (duplicate)
return highestSpan;
else
return 1;
}Solution
Avoid unnecessary flag variables
The variable
Improving the algorithm
I believe this can be solved in \$O(N)\$ time and space, by using a map to record the position of the first occurrences of numbers. If a number was seen already, check the distance and update the max distance if necessary. Otherwise record the current position.
The variable
duplicate is unnecessary, because you could drive the same meaning from highestSpan > 0. It's an extra hurdle to keep this flag, I suggest to drop it.Improving the algorithm
I believe this can be solved in \$O(N)\$ time and space, by using a map to record the position of the first occurrences of numbers. If a number was seen already, check the distance and update the max distance if necessary. Otherwise record the current position.
Context
StackExchange Code Review Q#94277, answer score: 5
Revisions (0)
No revisions yet.