3

我目前正在尝试从 Vector 中删除“噪音”,但找不到一种优雅的方式来做到这一点。我目前有一个字符串向量,另一个向量表示这些字符串连续出现的次数。

出于某种原因,我似乎无法让它工作。我为此创建的方法如下所示。

public static void correctDisturbance(Vector<String> names, Vector<Integer> lengths, int lengthGuard){

    int guard = lengths.size();

    int total = 0;

    for(int i = 0; i < guard; i++)
    {
        if(lengths.elementAt(i) <= lengthGuard)
        {
            int newTotal = total + lengths.elementAt(i);

            while(total < newTotal)
            {
                System.out.println("Removing: " + names.elementAt(newTotal));
                names.removeElementAt(newTotal);
                newTotal--;
            }
            lengths.removeElementAt(i);
            guard--;
        }
        else
        {
            total += lengths.elementAt(i);
        }
    }

它删除了一些我需要的但不是其他的。我将阈值设置为 5。

长度向量的内容示例如下: [15, 15, 1, 15, 2, 1, 1, 2, 1, 3, 1, 2, 1, 5, 1, 4, 1, 1, 3 ]

提前感谢您的帮助。

4

2 回答 2

0

你的方法几乎没有错。这是调试的版本:

public static void correctDisturbance(List<String> names,
        List<Integer> lengths, int lengthGuard) {
    int guard = lengths.size();
    int total = 0;
    for(int i = 0;i < guard;i++) {
        if (lengths.get(i) <= lengthGuard) {
            int newTotal = total + lengths.get(i);
            while( total < newTotal ) {
                newTotal--; // LINE MOVED
                System.out.println("Removing: " + names.get(newTotal));
                names.remove(newTotal);
            }
            lengths.remove(i);
            i--; // LINE ADDED
            guard--;
        } else {
            total += lengths.get(i);
        }
    }
}

如您所见,只需要进行两项更改。首先,newTotal在使用之前必须递减,因为 Java 数组和列表是从零开始的。其次,当你从lengths列表中删除一个项目时,你也必须减少i,这样你就不会错过一个条目。

于 2011-04-24T14:49:39.207 回答
0

使用 Hash 而不是 Vector 来保持计数。关键是行,值是计数。

顺便说一句,使用 ArrayList 代替 Vector,如果需要,可以使其线程安全。

于 2011-03-23T13:17:13.977 回答