3

What do you think about my solution to two sum?
https://leetcode.com/problems/...

It took me about 10 seconds to realize it can be solved this way, and then FUCKING HALF AN HOUR until i finally wrote the actual code in a way that worked as it should...

...i really should sleep more. and get examined for brain decomposition or something.

Comments
  • 1
    oh, TryAdd exists.

    lol, replacing one of the conditions with TryAdd bumps me performance-wise from 83rd to 93rd percentile, but kicks me down memory-wise from 49th to 8th percentile.

    and the difference is about a megabyte =D

    and all the other solutions are basically this same one, just written slightly differently.

    okay.

    well. i still like the solution =D
  • 2
    I'd go for a sorting plus binary search approach that would automatically tackle the bonus question, too.
  • 1
    @Fast-Nop

    bonus question?

    (tries to scroll the description)

    oh.

    ...yeah, i haven't slept all night... again.

    if i had, maybe i would have noticed that.
  • 0
    What about just using the array ?

    public int[] TwoSum(int[] nums, int target) {

    Dictionary<int, int> remainsAtIndex = new Dictionary<int, int>();

    for (int c = 0; c < nums.Length; c++)

    {

    int index = Array.IndexOf(nums, target - nums[c], c+1);

    if (index > -1)

    return new int[] { c, index };

    }

    return new int[] { 0, 0 };

    }

    (It checks all the test data in 192 ms)

    Oh, yeah it will not get you the bonus question either. IndexOf is also O(n)
  • 1
    @Grumm array.IndexOf does linear search though.

    dictionary does it in 153 ms, and I was going for speed
  • 1
    @Midnight-shcode yeah, edited my comment hehe

    Didn't read the Follow-up too.
  • 1
    Looks pretty smart although I'm generally not a fan of allocating when not necessary
  • 0
    @12bitfloat

    ...and where do I do that? i mean, i could do bruteforce two nested loops just adding up together all the combinations, which would still allocate 3 vars, but ints, so maybe that would be faster, allocation-wise, except the whole solution would then be shitslow, so... i'm sorry, but i absolutely don't understand what you mean.
Add Comment