本文主要是介绍华为OD机试-找座位(C++ Java Python),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
题目描述:
在一个大型体育场内举办了一场大型活动,由于疫情防控的需要,要求每位观众的必须间隔至少一个空位才允许落座。现在给出一排观众座位 分布图,座位中存在已落座的观众,请计算出,在不移动现有观众座位的情况下,最多还能坐下多少名观众。输入描述:
一个数组,用来标识某一排座位中,每个座位是否已经坐人。0表示该座位没有坐人,1表示该座位已经坐人。输出描述:
整数,在不移动现有观众座位的情况下,最多还能坐下多少名观众。补充说明:
1<=数组长度<=10000
示例1
输入:
10001
输出:
1
说明:
示例2
输入:
0101
输出:
0
Java解法:
public class MaxAdditionalSeats {public static int maxAdditionalSeats(int[] seats) {int count = 0; // 新观众的计数int n = seats.length;for (int i = 0; i < n; i++) {// 如果当前座位是空的if (seats[i] == 0) {// 检查左边是否空(或左边界)boolean leftEmpty = (i == 0) || (seats[i - 1] == 0);// 检查右边是否空(或右边界)boolean rightEmpty = (i == n - 1) || (seats[i + 1] == 0);// 如果左右都是空的,当前座位可以坐人if (leftEmpty && rightEmpty) {count++; // 新增观众计数i++; // 跳过下一个座位,因为不能相邻坐人}}}return count;}public static void main(String[] args) {int[] seats1 = {1, 0, 0, 0, 1, 0, 1};System.out.println(maxAdditionalSeats(seats1)); // 输出应为 1int[] seats2 = {0, 0, 0, 0, 0};System.out.println(maxAdditionalSeats(seats2)); // 输出应为 2int[] seats3 = {1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1};System.out.println(maxAdditionalSeats(seats3)); // 输出应为 2int[] seats4 = {1, 0, 0, 0, 0, 1};System.out.println(maxAdditionalSeats(seats4)); // 输出应为 1int[] seats5 = {0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1};System.out.println(maxAdditionalSeats(seats5)); // 输出应为 3}
}
C++解法:
#include <iostream>
#include <string>
#include <tuple>
#include <vector>using namespace std;int main() {string in;cin >> in;size_t len = in.length();int res = 0;if (len == 1) {if (in[0] == '0')cout << 1 << endl;elsecout << 0 << endl;return 0;}for (int i = 0; i < len; i++) {auto curr_char = in[i];if (curr_char == '1') {if (i - 1 >= 0) {in[i - 1] = '_';}if (i + 1 < len) {in[i + 1] = '_';}}if (curr_char == '0') {if (i + 1 == len) {auto prev_char = in[i - 1];if (prev_char == '0' || prev_char == '_') {in[i] = '1';res += 1;}} else if (i - 1 == -1) {auto next_char = in[i + 1];if (next_char == '0' || next_char == '_') {in[i] = '1';res += 1;}} else {auto prev_char = in[i - 1];auto next_char = in[i + 1];if ((prev_char == '0' || prev_char == '_') &&(next_char == '0' || next_char == '_')) {in[i] = '1';res += 1;}}}}cout << res << endl;return 0;
}
Python解法:
while True:try:arr = input()if len(arr) <= 2:if '1' in arr:print(0)breakelse:print(1)breakcount0 = 1countN = 0for s in arr:if s == '0':count0 += 1if count0 == 3:countN += 1count0 = 1else:count0 = 0if arr[-1] != '1' and '1' in arr:temp = arr.split('1')[-1]if len(temp) % 2 == 0:countN += 1print(countN)except:break
这篇关于华为OD机试-找座位(C++ Java Python)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!