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

标签 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.

我对上述问题的回答是:

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;
    }
}

我认为我的答案是 O(N^2),根据问题这是 Not Acceptable 。是否有基于 O(N) 的解决方案?

最佳答案

实际上只需要循环一次,复杂度为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;
  }

关于java - 如何迭代整数数组以找到基于 O(N) 解决方案的序列?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31871901/

相关文章:

java - TableRow 未显示在 TableLayout 中

c# - 从 url 加载图像并将其保存为字节

arrays - 在 VBA Excel 中重新调整数组的大小

algorithm - 如何检查双向链表是否在java中正确链接?

data-structures - 存储需要在.Net中大量查找的整数列表的最有效数据结构是什么?

java - 在本地开发时,上下文是 '/' 还是 '/appname/' 有什么区别吗?

java - 如何更改子类中变量的实现?

c++ - 在 C++ 中使用 const 表示 std::pair

java - 无法在注释处理器中加载资源(不在类路径上)

arrays - 汇编语言中String和Array的区别