如何迭代整数数组以找到基于O(N)解的序列?

Hes*_*sam 5 java arrays data-structures

我看到了以下问题并试图找到答案.

Question:  Given a sequence of positive integers A and an integer T, return whether there is a *continuous sequence* of A that sums up to exactly T
Example
[23, 5, 4, 7, 2, 11], 20. Return True because 7 + 2 + 11 = 20 
[1, 3, 5, 23, 2], 8. Return True  because 3 + 5 = 8
[1, 3, 5, 23, 2], 7 Return False because no sequence in this array adds up to 7

Note: We are looking for an O(N) solution. There is an obvious O(N^2) solution which is a good starting point but is not the final solution we are looking for.
Run Code Online (Sandbox Code Playgroud)

我对上述问题的回答是:

public class Tester {
    public static void main(String[] args) {
        int[] myArray = {23, 5, 4, 7, 2, 11};
        System.out.println(isValid(myArray, 20));
    }

    public static boolean isValid(int[] array, int sum) {
        int pointer = 0;
        int temp = 0;

        while (pointer < array.length)
        {
            for (int i = pointer; i < array.length; i++)
            {
                if (array[i] > sum)
                    break;

                temp += array[i];
                if (temp == sum)
                    return true;
                else if (temp > sum)
                    break;
                // otherwise continue
            }

            temp = 0;
            pointer++;
        }

        return false;
    }
}
Run Code Online (Sandbox Code Playgroud)

我认为我的答案是O(N ^ 2),这是基于问题不可接受的.你知道什么是基于O(N)的解决方案吗?谢谢

dog*_*ant 6

你只需要实际循环一次O(N).

从索引0开始添加,一旦超过sum从数组开头删除的开始.如果temp跌破sum继续循环.

  public static boolean isValid(int[] array, int sum) {
    int init = 0,temp = 0;

    for (int i = 0; i < array.length; i++) {
      temp += array[i];
      while (temp > sum) {
        temp -= array[init];
        init++;
      }
      if (temp == sum)
        return true;
    }
    return false;
  }
Run Code Online (Sandbox Code Playgroud)