简体   繁体   中英

Searching for particular duplicated element in Array every nth element

Is there a way to cycle through an array, and see if an element is duplicated, and if so, delete n elements following it.

There can be duplicates beyond the element I am looking for. Basically, every 12 elements in the array; I want to see if the first element is already in the array, if it is, don't add the next 11. If not, add all 12. I've tried to hash but it is giving me troubles.

My Java is a little rusty, but I don't see a contains() method for an array, so I'd either make a helper method that does the same thing, or use the more useful ArrayList class. If you are married to an array, you can do something like this (my Java syntax may be a bit off):

ReallyCoolType tStatArray = datatList.toArray();  // didn't see a type, so I made up one
int endOf = tStatArray.length; // why declare this but never use it? Not really needed, but...
SortedSet<Object> set = new TreeSet<Object>();
for (int i = 0; i < endOf; i++) {
    // note the use of i, not the undeclared j
    if( !contains(set, tStatArray[i] )
    {
        set.add(tStatArray[i]);
    }
}

// and you can keep printing it out if you want...
Iterator it = set.iterator();
while(it.hasNext()) {
    System.out.println(it.next());
}

...

public bool contains( ReallyCoolType[] paramArray, ReallyCoolType findMe ) {
    bool found = false;
    for (reallyCoolType param : paramArray) {
        if( reallyCoolType.Equals(param, findMe) {
            found = true;
            break;
        }
    }
    return found;
}

Hope that helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM