In a single pass, we compute the size of the end result, as well as modify in place the intermediate data structure to build up result as we solve it.
| 197 | // in place the intermediate data structure to build up result as we |
| 198 | // solve it. |
| 199 | foreach (const Range& range, ranges) { |
| 200 | // Skip if this range is equivalent to the current range. |
| 201 | if (range.start == current.start && range.end == current.end) { |
| 202 | continue; |
| 203 | } |
| 204 | |
| 205 | // If the current range just needs to be extended on the right. |
| 206 | if (range.start == current.start && range.end > current.end) { |
| 207 | current.end = range.end; |
| 208 | } else if (range.start > current.start) { |
| 209 | // If we are starting farther ahead, then there are 2 cases: |
| 210 | if (range.start <= current.end + 1) { |
| 211 | // 1. Ranges are overlapping and we can merge them. |
| 212 | current.end = max(current.end, range.end); |
| 213 | } else { |
| 214 | // 2. No overlap and we are adding a new range. |
| 215 | ranges[count - 1] = current; |
| 216 | ++count; |
| 217 | current = range; |
| 218 | } |
| 219 | } |
| 220 | } |
| 221 | |
| 222 | // Record the state of the last range into of ranges vector. |
| 223 | ranges[count - 1] = current; |