美文网首页
LeetCode之Distance Between Bus St

LeetCode之Distance Between Bus St

作者: 糕冷羊 | 来源:发表于2020-07-13 20:58 被阅读0次

    问题:



    方法:
    easy级别的题目没什么可说的,正向统计距离,然后反向统计距离,反向需要定位index,最后比较两种距离情况的较小值。

    class DistanceBetweenBusStops {
        fun distanceBetweenBusStops(distance: IntArray, start: Int, destination: Int): Int {
            var sum = 0
            var result: Int
            val length = distance.size
            var from: Int
            var to: Int
            if (start < destination) {
                from = start
                to = destination
            } else {
                to = start
                from = destination
            }
            for (index in from until to) {
                sum += distance[index]
            }
            result = sum
            sum = 0
            for (index in to until from + length) {
                sum += if (index >= length) {
                    distance[index - length]
                } else {
                    distance[index]
                }
            }
            return if (sum < result) {
                sum
            } else {
                result
            }
        }
    }
    
    fun main(args: Array<String>) {
        val distance = intArrayOf(7, 10, 1, 12, 11, 14, 5, 0)
        val distanceBetweenBusStops = DistanceBetweenBusStops()
        print(distanceBetweenBusStops.distanceBetweenBusStops(distance, 7, 2))
    }
    

    有问题随时沟通

    具体代码实现可以参考Github

    相关文章

      网友评论

          本文标题:LeetCode之Distance Between Bus St

          本文链接:https://www.haomeiwen.com/subject/lwbzcktx.html