华为OD机试 - 小明找位置(Java & JS & Python & C & C++)
题目描述:
给定一个整数数组arr,小明想找出包含arr中所有奇数的子数组的长度最大是多少。
解法1:Python
def find_max_length_of_subarray_with_all_odd_numbers(arr):
odd_count = 0
max_length = 0
for num in arr:
if num % 2 != 0:
odd_count += 1
else:
max_length = max(max_length, odd_count)
odd_count = 0
return max(max_length, odd_count)
# 示例
arr = [3, 1, 3, 5, 2, 1, 7, 5]
print(find_max_length_of_subarray_with_all_odd_numbers(arr)) # 输出应为4
解法2:Java
public class Main {
public static void main(String[] args) {
int[] arr = {3, 1, 3, 5, 2, 1, 7, 5};
System.out.println(findMaxLengthOfSubarrayWithAllOddNumbers(arr)); // 输出应为4
}
public static int findMaxLengthOfSubarrayWithAllOddNumbers(int[] arr) {
int oddCount = 0;
int maxLength = 0;
for (int num : arr) {
if (num % 2 != 0) {
oddCount++;
} else {
maxLength = Math.max(maxLength, oddCount);
oddCount = 0;
}
}
return Math.max(maxLength, oddCount);
}
}
解法3:JavaScript
function findMaxLengthOfSubarrayWithAllOddNumbers(arr) {
let oddCount = 0;
let maxLength = 0;
for (let num of arr) {
if (num % 2 !== 0) {
oddCount++;
} else {
maxLength = Math.max(maxLength, oddCount);
oddCount = 0;
}
}
return Math.max(maxLength, oddCount);
}
// 示例
const arr = [3, 1, 3, 5, 2, 1, 7, 5];
console.log(findMaxLengthOfSubarrayWithAllOddNumbers(arr)); // 输出应为4
解法4:C
#include <stdio.h>
int findMaxLengthOfSubarrayWithAllOddNumbers(int* arr, int arrSize) {
int oddCount = 0;
int maxLength = 0;
for (int i = 0; i < arrSize; i++) {
if (arr[i] % 2 != 0) {
oddCount++;
} else {
maxLength = oddCount > maxLength ? oddCount : maxLength;
oddCount = 0;
}
}
return oddCount > maxLength ? oddCount : maxLength;
}
int main() {
int arr[] = {3, 1, 3, 5, 2, 1, 7, 5};
int arrSize = sizeof(arr) / sizeof(arr[0]);
printf("%d\n", findMaxLengthOfSubarrayWithAllOddNumbers(arr, arrSize)); // 输出应为4
return 0;
}
解法5:C++
#include <iostream>
int findMaxLengthOfSubarrayWithAllOddNumbers(int* arr, int arrSize) {
int oddCou
评论已关闭