MCPcopy Create free account
hub / github.com/Tiwarishashwat/InterviewCodes / merge

Method merge

MergeIntervals.java:2–43  ·  view source on GitHub ↗
(int[][] intervals)

Source from the content-addressed store, hash-verified

1class Solution {
2 public int[][] merge(int[][] intervals) {
3 // Sorting
4 for(int i=0;i<intervals.length-1;i++)
5 {
6 int flag=0;
7 for(int j=0;j<intervals.length-1;j++)
8 {
9 if(intervals[j][0]>intervals[j+1][0])
10 {
11 //Swap
12 int temp[]=new int[2];
13 temp[0]=intervals[j][0];
14 temp[1]=intervals[j][1];
15 intervals[j][0]=intervals[j+1][0];
16 intervals[j][1]=intervals[j+1][1];
17 intervals[j+1][0]=temp[0];
18 intervals[j+1][1]=temp[1];
19 flag=1;
20 }
21 }
22 if(flag==0)
23 {
24 break;
25 }
26 }
27 List<int[]> res=new ArrayList<>();
28 int current_interval[]=intervals[0];
29 res.add(current_interval);
30 for(int i=0;i<intervals.length;i++)
31 {
32 if(intervals[i][0]<=current_interval[1])
33 {
34 current_interval[1]=Math.max(current_interval[1],intervals[i][1]);
35 }
36 else
37 {
38 current_interval=intervals[i];
39 res.add(current_interval);
40 }
41 }
42 return res.toArray(new int[res.size()][]);
43 }
44}

Callers

nothing calls this directly

Calls 1

addMethod · 0.45

Tested by

no test coverage detected