Open Olyadtemesgen opened 1 year ago
** Alternative way to implement the getCatch
function using sorting
and two pointers
technique
func getCatch2(myPicks []int, winningNumbers []int) int {
sort.Ints(myPicks)
// myPicks = qsort(myPicks)
catch := 0
picksLength := len(myPicks)
winningNumbersLength := len(winningNumbers)
picksIndex := 0
winningNumbersIndex := 0
for (picksIndex < picksLength) && (winningNumbersIndex < winningNumbersLength) {
if myPicks[picksIndex] == winningNumbers[winningNumbersIndex] {
catch++
picksIndex++
winningNumbersIndex++
} else if myPicks[picksIndex] < winningNumbers[winningNumbersIndex] {
picksIndex++
} else {
winningNumbersIndex++
}
}
return catch
}
Ussue Overview: The current implementation of the getCatch function uses the sort.SearchInts method to find matching elements between myPicks and winningNumbers. While this approach works correctly, it has a time complexity of O(m * log(n)), where m is the length of myPicks, and n is the length of winningNumbers. To enhance the performance of the getCatch function and reduce the time complexity, we propose implementing getCatch2 using the two-pointer technique.
Proposed Solution: I have implemented a more efficient version of the
getCatch
function, called getCatch2, that leverages the fact that both myPicks and winningNumbers are sorted. By using the two-pointer technique, we can find the common elements between the two arrays with a time complexity of O(m + n), where m is the length of myPicks, and n is the length of winningNumbers