O(n) Kotlin code for Two Sum


  • 0
    W

    Kotlin language, using HashMap method

    class Solution {
        fun twoSum(nums: IntArray, target: Int): IntArray {
            val map = hashMapOf<Int, Int>()
            for(i in 0..nums.size - 1){
                if(map.containsKey(target - nums[i])){
                    val tmp = map.get(target - nums[i])!!.toInt()
                    val ans : IntArray = intArrayOf(tmp,i)
                    return ans
                }
                map.put(nums[i],i)
            }
            return intArrayOf()
        }
    }

Log in to reply
 

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