Accepted Scala tail recursive O(n) Solution


  • 0
    Z
    object Solution {
        def twoSum(nums: Array[Int], target: Int): Array[Int] = {
            // helper function for finding answer
            // diff: Map for (value, idx)
            @scala.annotation.tailrec
            def acc(diff: Map[Int, Int], idx: Int): Array[Int] = {
                if(idx >= nums.length) Array()
                else {
                    if(diff contains nums(idx)) Array(diff(nums(idx)), idx)
                    else acc(diff + ((target - nums(idx)) -> idx), idx + 1)
                }
            }
            
            acc(Map(), 0)
        }
    }
    
    

Log in to reply
 

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