簡體   English   中英

如何迭代整數數組以找到基於 O(N) 解決方案的序列?

[英]How to iterate over array of integers to find a sequence based on an O(N) solution?

我看到以下問題並試圖找到答案。

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),根據問題,這是不可接受的。 是否有基於 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;
  }

您應該做的是有兩個索引(開始和停止),然后增加stop直到總和達到要求(並返回true )或更高。 然后你增加start直到總和是所需的(並返回true或以下。然后你重復這個直到你到達數組的末尾。你可以增量更新總和(當你增加stop時添加元素,當你增加start時減去元素) ). 這應該是 O(N)。

下面是一個例子:

public class t {
    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 start = 0;
        int stop = 0;
        int tsum = 0;

        while( true )
        {
            if( tsum < sum )
            {
                if( stop >= array.length )
                    break;
                tsum += array[stop];
                stop++;
            }
            else if( tsum > sum )
            {
                tsum -= array[start];
                start++;
            }
            else if( tsum == sum )
                return true;

            // System.out.println(start + " -- " + stop + " => " + tsum);
        }

        return false;
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM