先贴题和题解,线性思路:
解释:一般这题做的时候都会挨个遍历奇数长度的数组,如果提前计算数组和的话,最优时间复杂度为$O(n^2)$。这里使用讨论区的线性方法:(解法非常非常妙!!!!!)
Just see number of times every position occurs in all the odd length subarray.
Multiply the contribution of position with element at that position.
How to calculate contribution?
Every element will contribute size of array to its right (n-i) * size of array to its left(i+1)
Since here we only consider odd length divide it by two (ceil divison)
Example
Given array: arr = [1, 2, 3, 4, 5] (n = 5) and formula (i + 1) * (n - i)
i = 0, contribution = 1 * 5 = 5
i = 1, contribution = 2 * 4 = 8
i = 2, contribution = 3 * 3 = 9
i = 3, contribution = 4 * 2 = 8
i = 4, contribution = 5 * 1 = 5
For detailed explanation on example refer to comment below
Please upvote if you like the approach :)
至于公式是怎么推出来的,看评论区有个人回复的非常详细:
It took me a while to figure out what it means for Every element will contribute size of array to its right (n-i) * size of array to its left(i+1)
For people who are still confused, please refer to the following explanation:Given array: arr = [1, 2, 3, 4, 5] (n = 5) and formula (i + 1) * (n - i)
i = 0, contribution = 1 * 5 = 5
i = 1, contribution = 2 * 4 = 8
i = 2, contribution = 3 * 3 = 9
i = 3, contribution = 4 * 2 = 8
i = 4, contribution = 5 * 1 = 5How to understand the above?
i + 1 means how many start index there are to the left of arr[i] (included), n - i means how many end index there are to the right of arr[i] (included)
Example:
i = 2 -> i + 1 = 3, n - i = 3
there are 3 start index to the left of arr[2] (included), they are: i = 0, 1, 2
there are 3 end index to the right of arr[2] (included), they are: i = 2, 3, 4
so there are 3 * 3 = 9 in total subarrays that contains arr[2]
if we choose start = 0, end = 2, we get [1, 2, 3]
if we choose start = 2, end = 2, we get [3]
if we choose start = 2, end = 4, we get [3, 4, 5]i = 4 -> i + 1 = 5, n - i = 1
there are 5 start index to the left of arr[4] (included), they are: i = 0, 1, 2, 3, 4
there are 1 end index to the right of arr[4] (included), they are: i = 4
so there are 5 * 1 = 5 in total subarrays that contains arr[4]
具体就是,计算某个元素在数组里出现的次数,次数是怎么计算呢?包含此元素的数组左端点有几种情况就是(i+1),右端点有几种情况就是(n-i),一共有几种情况?就是(i+1)*(n-i),但是,这里只考虑奇数长度的数组,所以要除以2. 那有小数怎么办?通过例子可知是向上取整,因此整个下来就是: ceil((i+1)*(n-i)/2)。
是不是很巧妙?欢迎评论区留言!