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