Daily Coding Problem: Problem #339

/**
 * This problem was asked by Microsoft.

Given an array of numbers and a number k,
determine if there are three entries in the array which add up to the specified number k.
For example, given [20, 303, 3, 4, 25] and k = 49, return true as 20 + 4 + 25 = 49.
 * */
class Problem_339 {
    fun sumUpEqualK(array: IntArray, K: Int): Boolean {
        var left = 0
        val size = array.size
        var right = 0
        array.sort()
        for (i in 0 until size) {
            left = i + 1
            right = size - 1
            while (left < right) {
                val value = array[i] + array[left] + array[right]
                if (value < K) {
                    left++
                } else if (value > K) {
                    right--
                } else {
                    return true
                }
            }
        }
        return false
    }
}

 

posted @ 2019-07-28 12:38  johnny_zhao  阅读(217)  评论(0编辑  收藏  举报