算法 - 最小大于大小

时间:2016-02-12 19:11:08

标签: arrays algorithm time

我有一个问题:

我们有一个整数数组(大小为n)require_command!' from /home/frank/.rbenv/versions/2.2.4/lib/ruby/gems/2.2.0/gems/railties-4.2.5.1/lib/rails/commands/commands_tasks.rb:130:in

我们必须找到generate' from /home/frank/.rbenv/versions/2.2.4/lib/ruby/gems/2.2.0/gems/railties-4.2.5.1/lib/rails/commands/commands_tasks.rb:39:in f.e <top (required)>' from bin/rails:4:in的最小公共部分[x_1,x_2,...,x_n](最长的正确部分是[x_i,x_i+1,...,x_j]

我无法弄清楚如何将时间减少到(x_i,x_i+1,...,x_j) >= j-i+1以下(检查每一段) 我的第二个想法是:每个值[2,2,1,4,3,3,1] -> 3等于&#34;长度范围&#34;这个部分可能有,如果数量较少那么我们改变&#34;长度范围&#34; (同时计算这个细分的时间长度),但如果我们得到更多的数字,我也不知道该怎么做

(我会非常感谢任何帮助 - 可能还有另一个更简单的解决方案,但我不会看到它)

1 个答案:

答案 0 :(得分:0)

Caterpillar method, O(n), assuming all integers will be positive:

  • Put a left and right pointer on the first number, and your minimum = this number. Length = 1
  • Advance the right pointer by one, check for the condition (you know if there's a new minimum very easily, and you know the length += 1)
  • If you cannot advance the right pointer without breaking the condition, advance the left pointer and update your values
  • If you cannot advance the left pointer either, you have found a section satisfying the condition. Note its length, and start a new section in the same way, on the next index.

Example for you:

[2,2,1,4,3,3,1]
[2] <- The first 2
[2,2] <- Moved the right
[2] <- Moved the left, both R and L are pointing at the second 2
<-Can't move either, note max length and indices from previous run.
[1] <- Starting again
<-Can't move either
[4] <- Starting again
[4,3] <- Right
[4,3,3] <- Right (New max length and indices noted)
[3,3] <- Left. Doesn't improve the max
[3] <- Left again.
<- Can't move either, note max and indices, in this case overwrite length
[1] <-Start again
<- end of loop, check global max length, output

This is O(n) because each pointer (L and R) only moves over any given index once.

I think this should be enough for you to write the algorithm in any language you choose. Look out for the end-of-loop condition, because you have to check against the global max length if you run out of array.