检查数组元素的条件

时间:2011-05-19 09:51:01

标签: java arrays algorithm

我有一系列数字nums []和目标,以满足以下条件 {{nums [],target}

 1> {{8, 2, 2, 1},12} --> returns true       
 2> {{8, 2, 2, 1},9}  --> returns true        

 1 condition> identical adjacent values with a subset of remaining numbers sum to target (or)
 2 condition> identical adjacent values are not chosen such that subset of other numbers sum to target. 
so that in this example 
1> 8+2+2 = 12.
2> 8+1=9.

我如何在Java中处理上述两个条件。

为DANTE编辑:
                                        期待此次运行 groupSumClump(0,{2,4,8},10)→true true OK
groupSumClump(0,{1,2,4,8,1},14)→true true OK
groupSumClump(0,{2,4,4,8},14)→false false OK
groupSumClump(0,{8,2,2,1},9)→true false X
groupSumClump(0,{8,2,2,1},11)→false false OK
groupSumClump(0,{1},1)→true false X
groupSumClump(0,{9},1)→false false OK
其他测试假X

* 但丁的代码:
http://www.ideone.com/xz7ll

@ Dante,请检查上面的链接,它对于提到的测试场景失败。

2 个答案:

答案 0 :(得分:1)

您可以使用两个局部变量同时解决这两个条件:一组“孤独”数字和一个“相邻”值的累加器:

逐步完成数组。

对于每个值,检查先前的值(如果有的话)和下一个值(如果有的话)。

如果其中一个与当前值相同,则递增“相邻”累加器,否则将该值添加到“孤独数字”集。

要检查条件2,从目标中减去“相邻”累加器的值,条件1保持不变。

问题的其余部分是确定“孤立集合”中某些值的子集是否与目标值相加。这是众所周知的数值问题,其计算成本高(指数努力),但编程并不困难。如果你搜索它的名字,你可以找到很多解决方案:它被称为“背包问题”。

答案 1 :(得分:1)

我见过你这个问题已经很久了,所以,这里有一些代码......

编辑

    int nums_another[] = new int [nums.length];
    int i = 0;
    int j = 0;
    i++;
    int c = 1;
    while (i < nums.length){
        if (nums[i] == nums[i-1]) { // count identical numbers
            c++;
        }
        else { // not identical, store sum of previous identical numbers (possibly only 1 number)
            if (nums[i-1] != 0) {
                nums_another[j] = nums[i-1] * c;
                j++;
            }
            c = 1;
        }
        i++;
    }
    if (nums[i-1] != 0) { // store last
        nums_another [j] = nums[i-1] * c; 
    }

现在nums_another包括:

  • 相邻相同数字组的总和(在您的情况下为4 = 2 + 2)

  • 不相同的数字(在您的情况下为8,1)

  • 最后为0(因此在所有8 4 1 0中)


顺便说一下,代码的问题在于:

因为你立即将下一个相同的数字设置为0,它将失败3或更多,

例如,8 2 2 2 1 - &gt; 8 4 0 2 1而不是 - &gt; 8 6 0 0 1