Recca Chao 的 gitHub page

推廣網站開發,包含 Laravel 和 Kotlin 後端撰寫、自動化測試、讀書心得等。Taiwan Kotlin User Group 管理員。

View on GitHub

Description

This problem was asked by Google.

Given a list of numbers and a number k, return whether any two numbers from the list add up to k.

For example, given [10, 15, 3, 7] and k of 17, return true since 10 + 7 is 17.

Bonus: Can you do this in one pass?

Kotlin Solution

參考 leet code 連接

https://leetcode.com/problems/two-sum/

假設題目如下

class Solution {
    fun twoSum(nums: IntArray, target: Int): IntArray {
       // 填空
    }
}

Kotlin 參考解答

點擊展開解答
class Solution {
    fun twoSum(nums: IntArray, target: Int): IntArray {
        val map = hashMapOf<Int, Int>()
        for (i in nums.indices) {
            val temp = target - nums[i]
            if (map.containsValue(nums[i])) {
                val keys = map.filterValues { it == nums[i] }.keys
                return intArrayOf(keys.first(), i)
            }
            map.put(i, temp)
        }
        throw IllegalArgumentException("No two sum solution")
    }
}

回到 daily coding problem 列表