Ruby's Louvre

每天学习一点点算法

导航

统计

leetcode 881. Boats to Save People

使用一艘船救人,每次最多只能救两人,请问最少要几次

这是左右节点法。

var numRescueBoats = function (people, limit) {
            people.sort((a, b) => a - b)
            var left = 0;
            var right = people.length - 1;
            var boats = 0, track = []
            track.add = function (a) {
                this.push(JSON.stringify(a))
            }
            while (left < right) { //注意条件两次最多两人
                if (people[left] + people[right] <= limit) {
                    //装上left, right
                    track.add([people[left], people[right]])
                    left++;
                    right--
                    boats++;
                } else {
                    //只能装right
                    track.add([people[right]])
                    boats++
                    right--
                }
                if (right == left) {
                    track.add([people[right]])
                    //只能装left
                    boats++;
                }
            }
            console.log(track, 'only test, limit = ', limit)
            return boats;
        };

        //1,2,2, 3
        numRescueBoats([3, 2, 2, 1], 3)
        numRescueBoats([3, 5, 3, 4], 5)
        numRescueBoats([1, 1, 2, 4], 4)

posted on 2020-01-04 01:31  司徒正美  阅读(1269)  评论(3编辑  收藏