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

推荐订阅源

Engineering at Meta
Engineering at Meta
J
Java Code Geeks
I
InfoQ
腾讯CDC
Vercel News
Vercel News
IT之家
IT之家
V
Visual Studio Blog
P
Proofpoint News Feed
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
G
Google Developers Blog
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
博客园 - 叶小钗
有赞技术团队
有赞技术团队
月光博客
月光博客
Martin Fowler
Martin Fowler
量子位
L
LangChain Blog
B
Blog
Last Week in AI
Last Week in AI
博客园 - 司徒正美
Microsoft Security Blog
Microsoft Security Blog
博客园 - 聂微东
Microsoft Azure Blog
Microsoft Azure Blog
A
About on SuperTechFans

博客园 - 司徒正美

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)