Ruby solution with O(n) time complexity!


  • 0
    A
    def two_sum(nums, target)
        length = nums.length
        position1 = nil
        position2 = nil
        (0..length-1).each do |i|
            remainder = target - nums[i]
            remainder_index = nums[(i+1), length].find_index(remainder)
            if remainder_index
               position1 = i
               position2 = remainder_index + i + 1
               break
            end
        end
        return [position1, position2]
    end
    
    

Log in to reply
 

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