codelity刷题---MinAvgTwoSlice

https://codility.com/programmers/task/min_avg_two_slice

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.

解答参考
http://codesays.com/2014/solution-to-min-avg-two-slice-by-codility/

这里难点就是如何用O(N)实现。
这里其实跟 codelity说要练习的prefix sum没关系。

这里需要认识到两个hints,

一个就是slice with the global MA must have the length of 2 or 3.

第二个就是 如果有slice with the length of 4 or more has the global MA, 那么此slice必定存在一个sub slice,其avg要小于或者等于这个longer slice。因为如果所有sub slice 的avg都大于 MA,那么这个longer slice的avg就肯定不止MA,肯定要大于MA.

所以在每次tranverse A[i]时,只需要搜索长度为2或者3的slice即可。

我的java code

class Solution { public int solution(int[] A) { // write your code in Java SE 8 double avg_min = (A[0] + A[1])/2.0; int avg_min_pos = 0; double avg2, avg3; for(int i = 0; i < A.length - 2; i++) { avg2 = (A[i] + A[i + 1]) / 2.0; avg3 = (A[i] + A[i + 1] + A[i + 2]) / 3.0; if( avg2 < avg_min) { avg_min = avg2; avg_min_pos = i; } if( avg3 < avg_min) { avg_min = avg3; avg_min_pos = i; } } if((A[A.length - 1] + A[A.length - 2]) /2.0 < avg_min) { avg_min = (A[A.length - 1] + A[A.length - 2]) /2.0; avg_min_pos = A.length - 2; } return avg_min_pos; } }

你可能感兴趣的:(codelity刷题---MinAvgTwoSlice)