需要帮助来优化alogorithmix问题的代码

时间:2019-04-04 08:10:55

标签: python python-3.x algorithm

我正在尝试解决Geeksforgeeks上的“给定总和子数组”问题。我的代码给出了正确的结果,但是花费的时间超出了限制。 https://practice.geeksforgeeks.org/problems/subarray-with-given-sum/0 我不知道该如何优化它。

for j in range(int(input())):
    x,y = map(int,input().split())
    numbers = list(map(int,input().split()))
    result =0
    stack=[]
    location=[]
    for index,i in enumerate(numbers):
        while i+result>y:
            if stack:
                a=stack[0]
                stack= stack[1:]
                location=location[1:]
                result = result-a
        if i+result < y:
            result+=i
            stack.append(i)
            location.append(index+1)
        elif result+i ==y:
            print(location[0],index+1)
            break
    if result+i != y:
        print(-1)

2 个答案:

答案 0 :(得分:0)

我唯一想到的就是删除列表,并存储子数组的开始。如果将if stack更改为if result,则应该可以使用。

for j in range(int(input())):
    x,y = map(int,input().split())
    numbers = list(map(int,input().split()))
    result =0
    start=0
    for index,i in enumerate(numbers):
        while i+result>y:
            if result:
                a=numbers[start]
                start += 1
                result = result-a
        if i+result < y:
            result+=i
            start += 1
        elif result+i ==y:
            print(start,index+1)
            break
    if result+i != y:
        print(-1)

答案 1 :(得分:0)

跟踪直到列表中该点的总/累计总和。那么nums [i:j]的总和等于总和,直到(包括)j减去总和(不包括)i。

private void button1_Click(object sender, EventArgs e)
{
    // Check that nothing has been added yet.
    if (panel1.Controls.Count == 0)
    {
        UserControl1 uc1 = new UserControl1();
        uc1.Dock = DockStyle.Fill;
        panel1.Controls.Add(uc1);
    }
}
def sumsub(nums, target):
  sums = [0] # the accumulated sum of the list of nums
  for i, num in enumerate(nums):
    sums.append(num + sums[i])
  for i in range(len(nums)):
    for j in range(i, len(nums)):
      if sums[j + 1] - sums[i] == target:
         return i, j

print(sumsub([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 15))
print(sumsub([1, 2, 3, 7, 5], 12))