亚马逊机试题:Merge 2 given sorted interval sequences
Given 2 sorted interval sequences. Implement a function to get the merged sorted interval sequence from the input. If there's overlapped intervals, please merge them as new interval.
The Given 2 sorted interval sequences as string arrays. Eatch element of the array is a string that indicats an interval. The boundaries of each interval are separated by comma (no space allowed).
Sample 1: Input: ["1,2", "6,7"] ["3,5"] Output: ["1,2", "3,5", "6,7"] Sample 2: Input: ["1,2", "3,5"]["4,6"]
Output:
["1,2", "3,6"]
//以下为c#代码,方法比较愚钝,以后多加练习。
static string[] mergeSortIntervals(string[] intervalSequence1, string[] intervalSequence2) { int iLength1 = intervalSequence1.Length; int iLength2 = intervalSequence2.Length; string[] retVal = new string[iLength1 + iLength2]; int Flag = 0; int i = 0; int j = 0; int One_1 = Int32.Parse(intervalSequence1[0].Substring(0, 1)); int One_2 = Int32.Parse(intervalSequence1[0].Substring(2, 1)); int Two_1 = Int32.Parse(intervalSequence2[0].Substring(0, 1)); int Two_2 = Int32.Parse(intervalSequence2[0].Substring(2, 1)); for (i = 0; i < iLength1; ) { if (One_1 < Two_1 && One_2 < Two_1) { retVal[Flag] = intervalSequence1[i]; Flag++; i++; } else if (One_1 < Two_1 && One_2 >= Two_1 && One_2 <= Two_2) { retVal[Flag] = intervalSequence1[i].Substring(0, 1) + "," + intervalSequence2[j].Substring(2, 1); i++; j++; Flag++; } else if (One_1 < Two_1 && One_2 > Two_2) { retVal[Flag] = intervalSequence1[i]; i++; j++; Flag++; } else if (One_1 >= Two_1 && One_1 <= Two_2 && One_2 <= Two_2) { retVal[Flag] = intervalSequence2[j]; i++; j++; Flag++; } else if (One_1 >= Two_1 && One_1 <= Two_2 && One_2 > Two_2) { retVal[Flag] = intervalSequence2[j].Substring(0, 1) + "," + intervalSequence1[i].Substring(2, 1); i++; j++; Flag++; } else if (One_1 > Two_2) { retVal[Flag] = intervalSequence2[j]; j++; Flag++; } if (i == iLength1 || j == iLength2) { break; } One_1 = Int32.Parse(intervalSequence1[i].Substring(0, 1)); One_2 = Int32.Parse(intervalSequence1[i].Substring(2, 1)); Two_1 = Int32.Parse(intervalSequence2[j].Substring(0, 1)); Two_2 = Int32.Parse(intervalSequence2[j].Substring(2, 1)); } if (i != iLength1) { for (int k = i; k < iLength1; k++) { retVal[Flag] = intervalSequence1[k]; Flag++; } } if (j != iLength2) { for (int k = j; k < iLength2; k++) { retVal[Flag] = intervalSequence2[k]; Flag++; } } //去除数组中空的字符 Liststrs = new List (); foreach (string s in retVal) { if (!string.IsNullOrEmpty(s)) strs.Add(s); } string[] result = strs.ToArray(); return result; }