Codility Lesson 3 MinAvgTwoSlice解答

Codility编程课一MinAvgTwoSlice MinAvgTwoSlice Find the minimal average of any slice containing at least two elements. Task description A non-empty array A consisting of N integers is given. A pair of integers (P, Q), such tha... 阅读详情

*大多数朋友如果找到这篇文章,就是来看解答的,所以完整的题目放到文章的最后了。


思路:

1、首先根据题目,大家第一反应就是无脑嵌套遍历所有情况,这样的时间复杂度是O(n^2+n)/2,远远超出O(n)的题目里的要求。

2、其次就是找规律了,这个slice一定发生在最小值周围吗?不一定!比如[-1, -1, 12, -9, 10]。所以不用去思考先找到最小值,再向两边递归的思路了。

3、其实,这里有一个数学证明,就是对于这个最小avg的slice(n,m),m-n+1一定是2或者3,也就是这个最小avg的slice由2个或者3个元素组成。

4、说说为什么会想到上面这个思路:因为题目中说明0<=n<m<N,因此可以得出2个或者3个元素是最小的组合,比如length=3的数组,你无法一次分出2个slice,length=2的数组也一样。为什么要这么去想呢?因为你要“比较”出最小的avg,怎么才能“比较”?那就是必须一次至少有2个slice才能相互比较。那么当N>=4时,我们就能一次最少分出2个slice。举length=4的例子,情况有以下几种:slice(0,1) slice(1,2) slice(2,3) slice(0,2) slice(1,3) slice(0,3)。可以看出前3个是2个元素的slice,后4-6个是3个元素的slice,最后一个是4个元素的slice。再来回想以下我们的命题,就是“min avg一定存在2/3个元素的slice中”,那么反过来就是length>=4的slice一定不是min avg。这个结论是肯定的,因为当元素>=4个时,我们把它分为2个sliceA sliceB,这两个slice肯定有一个大于另一个,或者2个相等。那么我们得出结论当sliceA>sliceB时,取sliceB为当前min avg的slice(反之亦然),当sliceA=sliceB时,则sliceA和sliceB都为当前min avg的slice。显然,原始slice已经被拆分了,它的存在是不正确的(子slice更优)或者是可被替代的(子slice和它相等)。如此继续拆分slice直到,length=2或者3时,我们就无法确定这个slice不是最优的,因此要去计算和记录它,并和其他slice的比较。

5、得到这个结论后,算法就变得异常简单,就是遍历数组,求连续2或者3个元素的avg,直接看到代码吧!


class Solution {
    public int solution(int[] A) {
        // write your code in Java SE 8
        double min = 10001;
        int minIndex = -1;
        for (int i = 0; i < A.length - 1; i ++) {
            double current2 = (A[i] + A[i + 1]) / 2d;
            if (current2 < min) {
                min = current2;
                minIndex = i;
            }
            
            if (i != A.length - 2) {
                double current3 = (A[i] + A[i + 1] + A[i + 2]) / 3d;
                if (current3 < min) {
                    min = current3;
                    minIndex = i;
                } 
            }
        }
        
        return minIndex;
    }
}


下面是原题:

Task description

A non-empty zero-indexed array A consisting of N integers is given. A pair of integers (P, Q), such that 0 ≤ P < Q < N, is called a slice of array A (notice that the slice contains at least two elements). The average of a slice (P, Q) is the sum of A[P] + A[P + 1] + ... + A[Q] divided by the length of the slice. To be precise, the average equals (A[P] + A[P + 1] + ... + A[Q]) / (Q − P + 1).

For example, array A such that:

    A[0] = 4
    A[1] = 2
    A[2] = 2
    A[3] = 5
    A[4] = 1
    A[5] = 5
    A[6] = 8

contains the following example slices:

  • slice (1, 2), whose average is (2 + 2) / 2 = 2;
  • slice (3, 4), whose average is (5 + 1) / 2 = 3;
  • slice (1, 4), whose average is (2 + 2 + 5 + 1) / 4 = 2.5.

The goal is to find the starting position of a slice whose average is minimal.

Write a function:

class Solution { public int solution(int[] A); }

that, given a non-empty zero-indexed array A consisting of N integers, returns the starting position of the slice with the minimal average. If there is more than one slice with a minimal average, you should return the smallest starting position of such a slice.

For example, given array A such that:

    A[0] = 4
    A[1] = 2
    A[2] = 2
    A[3] = 5
    A[4] = 1
    A[5] = 5
    A[6] = 8

the function should return 1, as explained above.

Assume that:

  • N is an integer within the range [2..100,000];
  • each element of array A is an integer within the range [−10,000..10,000].

Complexity:

  • expected worst-case time complexity is O(N);
  • expected worst-case space complexity is O(N), beyond input storage (not counting the storage required for input arguments).

Elements of input arrays can be modified.


Lesson 5 question 3 MinAvgTwoSlice 源地址 https://app.codility.com/programmers/lessons/5-prefix_sums/min_avg_two_slice/ MinAvgTwoSlice(最小切片平均值) 给定一个含有N个整数的非空数组A,一个整数对(P,Q), 0 ≤ P < Q < N,被叫做数组A的切片(至少含有两个元素)。一个切片(P,Q)的平均值是A[P] + A[P ... 阅读详情

相关推荐

Codility每周一课:P5.3 MinAvgTwoSlice

P5.3 MinAvgTwoSlice Find the minimal average of any slice containing at least two elements. P5.3 切片的最小均值 找出至少包含2个元素的切片的最小均值 一个由N个整数组成的非空数组A。对于一对整数(P, Q),如有0≤P&amp;amp;lt;Q&amp;amp;lt;N,称为数组A的切片(切片至少包含两个元素)。 切片(P, ...

AnFany 364

Codility经典算法题之十三:MinAvgTwoSlice

Task description:A non-empty array A consisting of N integers is given. A pair of integers (P, Q), such that 0 ≤ P &lt; Q &lt; N, is called asliceof array A (notice that the slice contains at least ...

数据库 588

麒麟V10 ARM环境离线部署MySQL:从依赖缺失到服务自启的完整避坑指南

本文详细介绍了在麒麟V10 ARM环境下离线部署MySQL的完整流程,包括依赖缺失解决方案、目录配置、服务自启设置及性能调优。特别针对国产操作系统和ARM架构的兼容性问题,提供了实用的避坑指南和优化建议,帮助用户高效完成MySQL部署与维护。

weixin_28741413的博客 412

Colidity--MinAvgTwoSlice

这题挺有意思的,没想到规模大于3的slice的avg肯定要比它的子slice(小于3)的avg来得小的话,就不太好写。 1 int solution(vector<int> &A) { 2 // write your code in C++98 3 int minStart = 0; 4 double minAvg = (A[0]+A...

weixin_30649859的博客 155

ESP32 驱动 SYN6288 语音合成:Arduino IDE 下实现中文数字混合文本的智能播报

本文详细介绍了如何在Arduino IDE环境下使用ESP32驱动SYN6288语音合成模块,实现中文数字混合文本的智能播报。通过硬件选型、开发环境搭建、编码转换原理、命令帧构造及串口通信实战等步骤,帮助开发者快速掌握语音播报技术。文章还提供了混合文本处理技巧和常见问题排查方法,适合智能硬件开发者参考。

weixin_42553471的博客 454

C++ bitset总结

数据结构bitset 术语:某1位置位是置1,某一位复位是某一位清零。 文章目录数据结构bitset一、3种初始化方式二、位访问三、位操作四、 位集操作总结实战练习 一、3种初始化方式 bitset<32> tmp; //默认构造函数,默认全0。 bitset<32> tmp(-1); //从整形数构造 bitset<32> tmp("101"); //从包含1和0的字符串构造 二、位访问 bitset<32> tmp(256)

qq_43807092的博客 725

*[codility]MinAvgTwoSlice

https://codility.com/demo/take-sample-test/min_avg_two_slice 此题要求一个数组子段的最小的平均数(返回第一个数字的index)。刚开始想记录sum,也没用,因为所有子段的组合是O(n^2)的。后来看解释发现,最小值必然存在于长度为2或3的子段中(长度为3的子段也无法分解)。可以用反证法,如果有一个长度大于3的子段,均值小于之前...

weixin_30888707的博客 135

从零到一:Ubuntu22.04下VSCode与中文输入法的深度整合指南

本文详细介绍了在Ubuntu22.04系统中如何深度整合VSCode与中文输入法,包括环境准备、安装方案对比、输入法配置及常见问题解决方案。通过fcitx框架优化中文输入体验,提供从基础设置到高级调试的全方位指南,帮助开发者提升在Linux环境下的开发效率。

weixin_29158047的博客 485

[codility]MinAvgTwoSlice

Python代码如下: def solution(A): # write your code in Python 2.6 # if one slice is the MA, then the average of its subslices # can not be smaller and also it can not be bigger, or the avera

孙佰贵的专栏 2510

基于Plecs的LLC谐振变换器闭环设计:从PI参数整定到动态响应优化

本文详细介绍了在Plecs仿真环境中,如何为半桥LLC谐振变换器设计并优化闭环控制系统。从开环模型搭建与特性分析入手,重点阐述了基于频域法的PI控制器参数整定流程,并通过负载阶跃、输入电压突变等测试优化动态响应。文章还分享了从仿真模型过渡到实际硬件时的关键注意事项,帮助工程师实现稳定、高效的电源设计。

e4f5g6h的博客 629

MicroPython 开发ESP32应用教程 之 WIFI配网 Web页面配网 softAP 配网 web页面控制WS2812灯珠

MicroPython 开发ESP32应用教程 之 WIFI配网 Web页面配网 softAP 配网 web页面控制WS2812灯珠

weald2000的专栏 2091

codelity刷题---MinAvgTwoSlice

https://codility.com/programmers/task/min_avg_two_slicehttp://codesays.com/2014/solution-to-min-avg-two-slice-by-codility/这里其实跟 codelity说要练习的prefix sum没关系。这里需要认识到两个hints,一个就是slice with the global MA mu

xyqzki的专栏 1789

构建.NET网站:VSCode还是Visual Studio?揭开开发工具的选择之谜

选择VSCode还是Visual Studio,归根结底是取决于你的具体需求和偏好。🔍 这两款工具各有千秋,都能为你的.NET网站开发提供强大的支持。希望这篇文章能够帮助你更全面地了解这两款工具,做出明智的选择。

墨夶的博客 794

3.3 MinAvgTwoSlice

求数组最小平均数子序列起始位置 A non-empty zero-indexed array A consisting of N integers is given. A pair of integers (P, Q), such that 0 ≤ P < Q < N, is called a slice of array A (notice that the slice contains at

zll00561的专栏 691

【WRF-Chem工具】anthro_emiss 详解:生成人为排放数据

anthro_emiss 详解:生成人为排放数据

WW、forever的博客 2060

大中型超市收银系统(可直接运行)

光步前台收银系统系统功能:商品销售、商品退货、挂单、收银员权限、会员销售、单品取消、整单取消、商品查询、脱机销售、脱机数据上传,基本资料下载,开钱箱、小票打印、收款结算,支持多币种付款方式(现金、储值卡、礼券、微信等),支持多种促销。运行环境:.net 4.0登陆信息用户名:1001 密码:123456内置商品信息,商品编码可输入00001000 - 00010000,测试效果相关功能键F5 结算 F9挂单 F11商品查询 F8退货 Insert单品取消 Del整单取消 F12开钱箱F2 会员 Ctrl+Z退出系统 Home 锁屏 相关源码待公开

MinAvgTwoSlice【★★★★★】

1 /// <summary> 2 /// Solution 3 /// 100/100 4 /// </summary> 5 /// <param name="A"></param> 6 /// <returns...

aejt95023的博客 192

ssm框架搭建

这个是一个在idea上成功跑起来的ssm框架项目,保存在这里方便以后使用直接下载

Solution to Min-Avg-Two-Slice

Solution to Min-Avg-Two-Slice by codility -  It IS a mathematical problem 6FEB February 6, 2014 Question: https://codility.com/demo/take-sample-test/min_avg_two_slice Question Name: M

screaming的博客 499

jdk-8u144-linux-x64.tar.gz.

该资源为搭建Linux系统Java环境用,资源的后缀为tar.gz格式的压缩包

GenomicRangeQuery MinAvgTwoSlice by Codility

GenomicRangeQuery 题目链接 明明两道题都是标着前缀和 我却都不是用前缀和写的 让人有些费解 思路就是很普通的维护区间最小值 数组线段树做法 int min(int a, int b) { if (a > b) return b; else return a; } int t(char ch) //将碱基转换成数字 { if (ch == 'A') return 1; else if (ch == 'C'

一般 194

3.1 PassingCars

A non-empty zero-indexed array A consisting of N integers is given. The consecutive elements of array A represent consecutive cars on a road. Array A contains only 0s and/or 1s: 0 represents a car tr

zll00561的专栏 867

Codility K complementary pairs

codelity kcomplementary pairs A non-empty zero-indexed array A consisting of N integers is given. A pair of integers (P, Q) is called K-complementary in array A if 0 ≤ P,

xyqzki的专栏 2835

Codeforces911题解

A. Nearest Minimums You are given an array of n integer numbers a0, a1, ..., an - 1. Find the distance between two closest (nearest) minimums in it. It is guaranteed that in the array a minimum occ

OneDay_pyf的博客 3643

Codility-MaxSliceSum&MaxDoubleSlice

Task description A non-empty zero-indexed array A consisting of N integers is given. A triplet (X, Y, Z), such that 0 ≤ X double slice. The sum of double slice (X, Y, Z) is the total of A[X + 1

liushuying668的专栏 1037

Python解算法题:MissingInteger

Task description:This is a demo task.Write a function:class Solution { public int solution(int[] A); }that, given an array A of N integers, returns the smallest positive integer (greater than 0) that ...

数据库 2717
下一篇: Codility Lesson 4 NumberOfDiscIntersections 解答
willyz_90
博客等级 码龄16年 0粉丝 3原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值