惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

酷 壳 – CoolShell
酷 壳 – CoolShell
D
DataBreaches.Net
C
Check Point Blog
雷峰网
雷峰网
小众软件
小众软件
GbyAI
GbyAI
美团技术团队
P
Proofpoint News Feed
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
罗磊的独立博客
大猫的无限游戏
大猫的无限游戏
WordPress大学
WordPress大学
MyScale Blog
MyScale Blog
The Cloudflare Blog
阮一峰的网络日志
阮一峰的网络日志
Apple Machine Learning Research
Apple Machine Learning Research
Y
Y Combinator Blog
Jina AI
Jina AI
爱范儿
爱范儿
Last Week in AI
Last Week in AI
MongoDB | Blog
MongoDB | Blog
I
InfoQ
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
博客园 - 司徒正美

博客园 - 司徒正美

leetcode 91. Decode Ways leetcode 1214 Two Sum BSTs leetcode 213 House Robber II leetcode 198 House Robber I leetcode 986. Interval List Intersections leetcode 869. Reordered Power of 2 leetcode 925. Long Pressed Name leetcode 457. Circular Array Loop leetcode 1093. Statistics from a Large Sample leetcode 977. Squares of a Sorted Array leetcode 844. Backspace String Compare leetcode 1032. Stream of Characters leetcode 1023. Camelcase Matching leetcode 745 Prefix and Suffix Search leetcode 720. Longest Word in Dictionary leetcode 692. Top K Frequent Words leetcode 677. Map Sum Pairs leetcode 676. Implement Magic Dictionary leetcode 648. Replace Words
leetcode 881. Boats to Save People
司徒正美 · 2020-01-03 · via 博客园 - 司徒正美

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

这是左右节点法。

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)