LeetCode1343

LeetCode1343

/*题目描述:给定一个数组Array、子数组长度k、子数组平均值阀值threshold
 * 		      求出 Array的长度小于k平均值大于等于threshold的子数组的数量。
 *解题思路:维持指针tail指向子数组的尾部、指针head指向子数组头部,声明sum
 *		      记录当前子数组的和,每次将head、tail后移一位,sum=sum-tail+newHead
 *		      若sum/k大于等于threshold,result+1;
 * */
public class Question1343 {
	public static void main(String[] args) {
		int[] arr = {11,13,17,23,29,31,7,5,2,3};
		int k = 3;
		int threshold = 5;
		Question1343_Solution qs = new Question1343_Solution();
		System.out.println(qs.numOfSubarrays(arr, k, threshold));

	}
}

class Question1343_Solution {
    public int numOfSubarrays(int[] arr, int k, int threshold) {
    	//声明子数组尾指针、头指针、和
    	int tail = 0;
    	int head = k-1;
    	int sum = 0;
    	//声明目标子数组的数量
    	int result = 0;
    	//遍历第一个子数组
    	for(int i = 0;i < k; i++) {
    		sum = sum+arr[i];
    	}
    	//遍历arr
    	while(head<arr.length) {
    		if((sum/k)>=threshold) {
    			result++;
    		}
    		if(head+1<arr.length) sum = sum-arr[tail]+arr[head+1];
    		tail+=1;
    		head+=1;
    	}
    	return result;
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值