我被告知我的代码需要执行太多操作,速度太慢。这是正确的,因为实际上你可以在不修改数组的情况下完成此操作。由于这是你要完成的任务,我只会向你展示如何做到这一点,而不编写任何代码。
Initialize counter to 0, and start iterating from the beginning of the array.
Locate the next (first) triplet.
If not found, you're done, so return the counter value.
start
│ end
│ │
4,4,7,7,6,6,6,7,4
You found a triplet to remove, so increment the counter by 1.
Compare the surrounding values. First compare the values right before and after.
If different, skip to step 7.
start
│ end
│ │
4,4,7,7,6,6,6,7,4
└───────┘ are they equal?
When surrounding values are equal, there are two possibilities for a cascade triplet, either an extra value before, or an extra value after.
If the extra value before/after are both different from surrounding values, skip to step 7.
start start
│ end │ end
│ │ O R │ │
4,4,7,7,6,6,6,7,4 4,7,6,6,6,7,7,4,4
└─┴───────┘ are they equal? └───────┴─┘ are they equal?
Expand the sequence to remove, and go back to step 3 to repeat the cascade search.
start start
│ end │ end
│ │ O R │ │
4,4,7,7,6,6,6,7,4 4,7,6,6,6,7,7,4,4
start start
│ end │ end
│ │ O R │ │
4,4,7,7,6,6,6,7,4 4,7,6,6,6,7,7,4,4
└─┴─────────────┘ └─────────────┴─┘ are they equal?
Now we need to look for a more complicated disjoint triplet.
12344433255666527
││└┴┘││││││││││ simple triplet found (step 2-3)
│└───┴┘││││││││ surrounding triplet found (step 4-6)
│ │││└┴┘││ another simple triplet found
│ │└┴───┘│ surrounding triplet found
└──────┴──────┘ disjoint triplet found
To do that, we need to keep track of a previous sequence removed.
┌ prevStart
│ ┌ prevEnd
│ │ ┌ start
│ │ │ ┌ end
12344433255666527
└──────┴──────┘ are they equal?
If the previous end is 2 positions before the new start, and the 3 values before, between, and after are the equal, then we found a disjoint triplet.
Expand the sequence-to-remove to include both previous sequence, current sequence, and new triplet, then go back to step 3 to repeat the cascade search.
You have now found a section to remove, and incremented the counter the appropriate number of times, so starting after the end
position, go back to step 2 to search for the next triplet.
{4,4,7,7,4,7}
,对吗? - kaya3