Short ruby code cost O(n) time

  • 0
    def two_sum(nums, target)
    	map = {}
    	nums.each.with_index {|x, j| map[target - x] = j} 
    	nums.each.with_index {|x, j| return [map[x], j] if map[x] and j != map[x]}

  • 0

    Nice solution! I was getting a timeout with my O(n*n) solution but this is much faster.
    Just a suggestion for the first two lines:

    map = { |n| target - n }.each_with_index.to_h

Log in to reply

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.