简体   繁体   English

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

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

I saw following question and tried to find an answer for that.我看到以下问题并试图找到答案。

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.

My answer to above question is:我对上述问题的回答是:

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

I think my answer is O(N^2) which is not acceptable based on Question.我认为我的答案是 O(N^2),根据问题,这是不可接受的。 Is there a solution based on O(N)?是否有基于 O(N) 的解决方案?

You only need to loop once actually which is O(N).您实际上只需要循环一次,即 O(N)。

Start adding from index 0 and once you exceed the sum start removing from the beginning of the array.从索引 0 开始添加,一旦超过sum就从数组的开头开始删除。 if temp falls below sum continue looping.如果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;
  }

What you should do is to have two indices (start and stop) then you increase stop until the sum is the required (and return true ) or above.您应该做的是有两个索引(开始和停止),然后增加stop直到总和达到要求(并返回true )或更高。 Then you increase start until the sum is the required (and return true or below. Then you repeat this until you reach the end of the array. You can update the sum incrementally (add the element when you increase stop and subtract when you increase start ). This ought to be O(N).然后你增加start直到总和是所需的(并返回true或以下。然后你重复这个直到你到达数组的末尾。你可以增量更新总和(当你增加stop时添加元素,当你增加start时减去元素) ). 这应该是 O(N)。

Here's an example:下面是一个例子:

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.

相关问题 如何在整数数组中查找整数的重复序列? - How to find repeating sequence of Integers in an array of Integers? 如何在O(log(N))时间内找到排序数组中在一定范围内的整数数? - How to find number of integers in a sorted array that are within a certain range in O(log(N)) time? 如何在java中的整数数组中找到整数的重复序列? - How to find repeating sequence of Integers in an array of Integers in java? O(n)算法找到从1到n(非奇数)的连续整数数组中的奇数输出 - O(n) algorithm to find the odd-number-out in array of consecutive integers from 1 to n(not odd numbers) 高效算法在O(log(N))时间内找到排序数组中在一定范围内的整数数量? - Efficient algo to find number of integers in a sorted array that are within a certain range in O(log(N)) time? 以o(n)或o(1)的时间复杂度对整数数组进行排序 - Sorting an array of integers in time complexity of o(n) or o(1) 给定一个+ ve整数数组,找到在O(n)时间和常数空间中出现奇数次的数字。 - Given an array of +ve integers, Find the number which occurs odd number of times in O(n) time & constant space. 找到小于O(N)的序列的第n项 - Find nth term of a sequence in less than O(N) 在 O(n) 中找到重复项的数组中的和对 - Find a sum pair in array with duplicates in O(n) 在 O(n) 中查找数组中的所有差异 - Find all differences in an array in O(n)
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM