华为OD机试-优雅子数组-2022Q4 A卷-Py/Java/JS

如果一个数组中出现次数最多的元素出现大于等于K次,被称为K -优雅数组,k也可以被称为优雅阈值。例如,数组1,2,3,1、2,3,1,它是一个3-优雅数组,因为元素1出现次数大于等于3次,数组1,2,3,1,2就不是一个3-优雅数组,因为其中出现次数最多的元素是1和2,只出现了2次。
给定一个数组A和k,请求出A有多少子数组是k-优雅子数组。
子数组是数组中一个或多个连续元素组成的数组。
例如,数组[1.2.3.4]包含10个子数组,分别是:
[1], [1,2], [1,2,3], [1,2,3,], [2], [2,3], [2,3,4], [3], [3,4] , [4]
输入描述
第一行输入两个数字,以空格隔开,含义是: A数组长度 k值
第二行输入A数组元素,以空格隔开
输出描述
输出A有多少子数组是k-优雅子数组

示例1:

输入:

7 3

1 2 3 1 2 3 1

输出:

1

Java 代码

import java.util.Scanner;
import java.util.*;
import java.util.stream.Collectors;
import java.math.BigInteger;
 
class Main {
	public static void main(String[] args) {
        // 处理输入
        Scanner in = new Scanner(System.in);
        //转为数组
        int A = in.nextInt();
        int k = in.nextInt();
        //转为数组
        int[] nums = new int[A];
        for (int i=0;i num_count = new HashMap<>();
    
        while (left < A && right < A) {
            Integer c = nums[right];
            num_count.put(c, num_count.getOrDefault(c, 0) + 1);
            if (num_count.get(c) >= k) {
                result += A - right;
        
                num_count.put(nums[left], num_count.get(nums[left]) - 1);
                left++;
        
                num_count.put(c, num_count.get(c) - 1);
                right--;
            }
            right++;
        }
        System.out.println(result);
    }
}

Python代码

import functools
import sys
from collections import Counter, defaultdict
import copy
from itertools import permutations
import re
import math
import sys
 
 
 
#处理输入
params = [int(x) for x in input().split(" ")]
A= params[0]
k = params[1]
nums = [int(x) for x in input().split(" ")]
 
result = 0
 
left = 0
right = 0
num_count = {}
 
while (left < A and right < A):
    c = nums[right];
    if (c in num_count):
        num_count[c] +=1
    else:
        num_count[c] =1
    
    
    if (num_count[c] >= k):
        result += A - right;
 
        num_count[nums[left]]-= 1
        left+=1
 
        num_count[c] -=1
 
        right-=1
    right+=1
 
print(result)

JS代码

function main(nums, k) {
    let result = 0
    
    for (let i = 0; i < nums.length; i++) {
        const count_map = {}
        for (let j = i; j < nums.length; j++) {
            const c = nums[j]
            if (c in count_map)
                count_map[c]+=1
            else
                count_map[c] = 1
            if (count_map[c] >= k) {
                result += nums.length - j
                break
            }
        }
    }
    
    console.log(result)
}
 
main([1 ,2 ,3, 1, 2 ,3, 1],3)

你可能感兴趣的:(python,java,javascript,华为)