我需要写一个method that needs to return the length of the longest subsequence of sequence that is a zig-zag sequence.
算法方法应该是动态编程。
如果连续数字之间的差异在正数和负数之间严格交替,则数字序列称为zig-zag sequence。第一个差异(如果存在)可以是正面的也可以是负面的。
Eg - 1,7,4,9,2,5 is a zig-zag sequence
because the differences (6,-3,5,-7,3) are alternately positive and negative.
1,4,7,2,5 is not a zig-zag sequence.
我的代码:
public static int longestZigZag(int[] seq){
int len = seq.length;
int[] count= new int[len];
for(int i=0;i<len;i++)
count[i]=1;
for(int i=1;i<len;i++){
int k = (int)Math.pow(-1, i+1);
if(seq[i]>(k*seq[i-1])){
count[i]=count[i-1]+1;
}
}
int max=1;
for(int i=0;i<len;i++)
if(count[i]>max)
max=count[i];
return max;
}
解释
对应于每个元素,我有一个count
元素,表示直到该点的连续交替序列。
seq: 1, 7, 4, 9, 2, 5
count: 1, 1, 1, 1, 1, 1
i=1 7 > 1 count[1]= count[0]+1 = 2
i=2 4 > -7 count[2]= count[1]+1 = 3
i=1 9 > 4 count[3]= count[2]+1 = 4
i=1 2 > -9 count[4]= count[3]+1 = 5
i=1 5 > 2 count[5]= count[4]+1 = 6
之后我只是打印计数数组的最大值。
错误:
上述内容适用于
{ 1, 7, 4, 9, 2, 5 } -> 6
{ 1, 17, 5, 10, 13, 15, 10, 5, 16, 8 } -> 7
然而,它给出了错误的结果
{ 1, 2, 3, 4, 5, 6, 7, 8, 9 } gives 9 but should be 2.
{ 70, 55, 13, 2, 99, 2, 80, 80, 80, 80, 100, 19, 7, 5,
5, 5, 1000, 32, 32 } gives 2 but should be 8.
答案 0 :(得分:1)
我不确定这是多么负责任。 。 。你的方法真的完全错了。 : - /
要查看此内容,请考虑以下事项:count
的每个元素的计算仅取决于count
的前一个元素,而max
的运行计算仅取决于count
count
的当前元素。这意味着您甚至不需要seq
数组:您的整个算法可以转换为需要O(1)空间的单个传递。但是,作为一个“测试者”,你知道这个问题不能(容易)在O(1)空间的单次传递中解决,因为如果它可以,你不会被指示使用动态编程。
您的算法错误的核心原因是您只将seq[i]>(k*seq[i-1])
的每个元素与其前一个元素进行比较,但允许子序列(并且通常会)“跳过”中间值。
导致输出中一些比较混乱的方面的一个混淆因素是k*(seq[i]-seq[i-1])>0
检查并不意味着我认为你的意思。你可能想要更接近{{1}}的东西 - 但即使这样也会产生非常错误的结果。你真的只需要废弃这个算法并编写一个新算法。