这是我的代码:
long sum(int[] arr) {
long sum=0;
int j,k;
long sumtoadd;
for (int i = 0; i < arr.length; i++)
{
for (j = i; j < arr.length; j++)
{
sumtoadd = 0;
for (k = i; k <= j; k++)
{
sumtoadd = sumtoadd + arr[k];
}
sum = sumtoadd + sum;
}
}
return sum;
}
示例:
数组:{1,2,3}输出:20
数组:{1,1,1}输出:10
我试图找到数组的所有连续子数组的总和,但是对于某些情况,时间已经超过了。 此解决方案适用于除大型机箱外的所有情况。有更好的解决方案吗?
答案 0 :(得分:2)
public class Test1 {
static long sum2(int[] arr) {
long n = arr.length;
long sum = 0;
for (int i = 0; i < n; i++) {
sum += (n-i)*(i+1)*arr[i];
}
return sum;
}
static int[] arr1 = new int[]{1,2,3,4,5,6,7,8,9};
static int[] arr2 = new int[]{1,1,1,1};
public static void main(String[] args) {
System.out.println("sum(arr1) = " + sum(arr1));
System.out.println("sum2(arr1) = " + sum2(arr1));
System.out.println("sum(arr2) = " + sum(arr2));
System.out.println("sum2(arr2) = " + sum2(arr2));
}
//your code to check
static long sum(int[] arr) {
long sum=0;
int j,k;
long sumtoadd;
for (int i = 0; i < arr.length; i++)
{
for (j = i; j < arr.length; j++)
{
sumtoadd = 0;
for (k = i; k <= j; k++)
{
sumtoadd = sumtoadd + arr[k];
}
sum = sumtoadd + sum;
}
}
return sum;
}
}
答案 1 :(得分:0)
而不是三个嵌套循环,可以在N
数组元素的一个循环中找到答案。
推理:
如果给定的数组元素A[i]
出现在K
个子数组中,那么它会将其值贡献给K
个子数组,这意味着它贡献K
- 它的总值乘以A[i]
和。现在元素0
出现在所有子数组中,从i
到i+1
(包括)开始,从N
到K = (i+1)*(N-i)
(包括)结束,所以A[i]
。
摘要:每个(i+1)*(N-i)*A[i]
贡献class Room(object):
"""Create general features of a general room
Each room has a certain capacity depending on its type(an office or a living room)
"""
def __init__(self):
super(Room, self).__init__()
self.capacity = '';
class Office(Room):
"""
Add specific features to make a room an office.
An office has a name and a space for maximum of 4 people.
"""
def __init__(self, rname):
#create object if name does not start with a digit
if not (rname[0].isdigit()):
super(Office,self).__init__()
self.name = rname #office name
self.capacity = 4 #number of spaces per office
。在一个循环中完成,然后你就完成了。