Data Structures and Algorithm
- Runtime
- java 21.0.12
- Files
- 22 files · 16 KB
- Runs
- 50 runs
- Published
import java.util.*;public class MultiArraySpan { public static void main(String[] args) { /* Input: [1,3][2,4][5,7] output: [1,4][5,7] input: [1,2][3,5][4,6] output: [1,2][3,6] */ int[][] input = { {1,7}, {4,6}, {6,7} }; int[][] ans = mergeArrays(input); System.out.println(Arrays.deepToString(ans)); } public static int[][] mergeArrays(int[][] input) { Arrays.sort(input, (a,b)-> Integer.compare(a[0], b[0])); // input[0] {5,7}; // input[1] {1,3} // input[2] {2,4} // {1,3}, {2,4}, {5,7} List<int[]> result = new ArrayList<>(); int[] current = input[0]; for (int i=1 ; i<input.length ; i++) { int[] next = input[i]; if (current[1] >= next[0]) { current = new int[] { current[0], Math.max(current[1], next[1]) }; } else { result.add(current); current = next; } } result.add(current); int[][] ans = result.toArray(new int[result.size()][]); return ans; } }