Short ruby code cost O(n) time


  • 0
    O
    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]}
    end
    

  • 0
    D

    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 = nums.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.