❔ Just got started with leetcode after a year of learning, I need some help...
So the title says it all I guess, I started with leetcode after around a year with learning and I started away with one of its problems. It took me two hours to finally get it right but my code felt so redundant and long for such a simple problem. Can I get some feedback on how to make it more efficient? Thanks
So here is what I had after I was done (it was the two sum problem)
7 Replies
what's the TwoSum problem?
yeah, for starters, there is 0 need to do any allocations, except for the final result
so, we're given that there is only one solution for each input
and the numbers can't be reused
and the output doesn't have to be ordered
so, we want to examine each possible un-ordered pair of numbers in the input, until we find a match
two nested loops gets us the ability to iterate a pair of numbers
I.E. we're going to iterate all posibilities for picking the first number, and then all possibilities for picking the second
we can also optimize the first loop to not actually look at all of the input numbers
since, by the time we reach the last one, we will have checked all the pairs that include the last one, with the last one being picked as the second number
so, the outer loop only has to iterate to
(nums.Length - 1)
the inner loop is similar, in the opposite direction
we don't need to iterate picks for the second number that we've already iterated for picks as the first number
so, we start at i + 1
in the inner loopwasnt there a constraint that
i
and j
have to be different?right
that's accomplished by starting the inner loop at
i + 1
my mistake I had it as i
initiallyoh i see
i think i over complicated it by using a foreach which made me use indexof
very much so
and ig the array copy made it even more complicated idk
Was this issue resolved? If so, run
/close
- otherwise I will mark this as stale and this post will be archived until there is new activity.