华为OD机试 2025A卷题库疯狂收录中,刷题点这里
专栏导读
本专栏收录于《华为OD机试真题(Python/JS/C/C++)》。
刷的越多,抽中的概率越大,私信哪吒,备注华为OD,加入华为OD刷题交流群,每一题都有详细的答题思路、详细的代码注释、3个测试用例、为什么这道题采用XX算法、XX算法的适用场景,发现新题目,随时更新。
一、题目描述
部门组织绿岛骑行团建活动,租用公共双人自行车骑行,每辆自行车最多坐两人、最大载重 M。
给出部门每个人的体重,请问最多需要租用多少双人自行车。
二、输入描述
第一行两个数字 m、n,自行车限重 m,代表部门总人数 n。
第二行,n 个数字,代表每个人的体重。体重都小于等于自行车限重 m。
0<m <= 200
0 < n <= 1000000
三、输出描述
最小需要的双人自行车数量。
四、测试用例
测试用例1:
1、输入
10 4
9 8 6 5
2、输出
4
测试用例2:
1、输入
10 5
5 5 5 5 5
2、输出
3
测试用例3:
1、输入
7 6
3 4 5 3 3 7
2、输出
4
3、说明
- 自行车限重7
- 一共6人,按照体重排序,3 3 3 4 5 7
- 分配自行车,3 + 3 < 7,3 + 4 = 7,5 < 7,7 =7
- 故,一共4台。
五、解题思路
- 先排序;
- 如果两人体重之和小于等于 m,则租一辆双人自行车;
- 如果两人体重之和大于 m,则租一辆单人自行车;
六、Python算法源码
def min_bikes(m, n, weights):
count = [0] * (m + 1)
for weight in weights:
count[weight] += 1
i, j = 0, m
result = 0
while i <= j:
while i <= j and count[i] == 0:
i += 1
while i <= j and count[j] == 0:
j -= 1
if i > j:
break
if i + j <= m:
count[i] -= 1
count[j] -= 1
else:
count[j] -= 1
result += 1
return result
# 测试用例验证
test_cases = [
(7, 6, [3, 4, 5, 3, 3, 7]),
(10, 4, [9, 8, 6, 5]),
(10, 5, [5, 5, 5, 5, 5]),
(20, 8, [1, 2, 3, 4, 5, 15, 10, 8]),
(15, 2, [7, 9])
]
for m, n, weights in test_cases:
print(min_bikes(m, n, weights))
七、JavaScript算法源码
function minBikes(m, n, weights) {
let count = new Array(m + 1).fill(0);
for (let weight of weights) {
count[weight]++;
}
let i = 0, j = m, result = 0;
while (i <= j) {
while (i <= j && count[i] === 0) i++;
while (i <= j && count[j] === 0) j--;
if (i > j) break;
if (i + j <= m) {
count[i]--;
count[j]--;
} else {
count[j]--;
}
result++;
}
return result;
}
// 测试用例
console.log(minBikes(7, 6, [3, 4, 5, 3, 3, 7])); // 输出 4
八、C算法源码
#include <stdio.h>
#include <string.h>
int minBikes(int m, int n, int weights[]) {
int count[m + 1];
memset(count, 0, sizeof(count));
for (int i = 0; i < n; i++) {
count[weights[i]]++;
}
int i = 0, j = m, result = 0;
while (i <= j) {
while (i <= j && count[i] == 0) i++;
while (i <= j && count[j] == 0) j--;
if (i > j) break;
if (i + j <= m) {
count[i]--;
count[j]--;
} else {
count[j]--;
}
result++;
}
return result;
}
// 测试用例
int main() {
int weights[] = {3, 4, 5, 3, 3, 7};
printf("%d\n", minBikes(7, 6, weights)); // 输出 4
return 0;
}
九、C++算法源码
#include <iostream>
#include <vector>
#include <cstring>
using namespace std;
int minBikes(int m, int n, vector<int>& weights) {
vector<int> count(m + 1, 0);
for (int weight : weights) {
count[weight]++;
}
int i = 0, j = m, result = 0;
while (i <= j) {
while (i <= j && count[i] == 0) i++;
while (i <= j && count[j] == 0) j--;
if (i > j) break;
if (i + j <= m) {
count[i]--;
count[j]--;
} else {
count[j]--;
}
result++;
}
return result;
}
int main() {
vector<int> weights = {3, 4, 5, 3, 3, 7};
cout << minBikes(7, 6, weights) << endl; // 输出 4
return 0;
}
🏆下一篇:华为OD机试真题 - 简易内存池(Python/JS/C/C++ 2025 A卷 200分)
🏆本文收录于,华为OD机试真题(Python/JS/C/C++)
刷的越多,抽中的概率越大,私信哪吒,备注华为OD,加入华为OD刷题交流群,每一题都有详细的答题思路、详细的代码注释、3个测试用例、为什么这道题采用XX算法、XX算法的适用场景,发现新题目,随时更新。