猿问

号段合并算法

若传入参数值21~40,51~100,41~42,1~50(该参数类型可为string,string[]或list)

合并结果为1~100,21~42(类型可同传入参数)。

传入参数可以重复,如:21~40,51~100,41~42,1~50,1~50,
返回结果也同上。


猛跑小猪
浏览 502回答 4
4回答

哔哔one

//new&nbsp;String[]{"21~40","51~100","41~42","1~50"}&nbsp; public&nbsp;static&nbsp;Object&nbsp;merge(Object&nbsp;o) { if(o&nbsp;instanceof&nbsp;String[]) { String[]&nbsp;numbers&nbsp;=&nbsp;(String[])o; int&nbsp;resultLength&nbsp;=&nbsp;numbers.length; for(int&nbsp;i&nbsp;=&nbsp;0;&nbsp;i&nbsp;<&nbsp;numbers.length;&nbsp;i++) { if(numbers[i]&nbsp;==&nbsp;null)&nbsp;continue; int&nbsp;start&nbsp;=&nbsp;getStart(numbers[i]); int&nbsp;end&nbsp;=&nbsp;getEnd(numbers[i]); if(start&nbsp;>&nbsp;end)&nbsp;continue; for(int&nbsp;j&nbsp;=&nbsp;0;&nbsp;j&nbsp;<&nbsp;numbers.length;&nbsp;j++) { if(i&nbsp;==&nbsp;j&nbsp;||&nbsp;numbers[j]&nbsp;==&nbsp;null)&nbsp;continue; int&nbsp;nextStart&nbsp;=&nbsp;getStart(numbers[j]); int&nbsp;nextEnd&nbsp;=&nbsp;getEnd(numbers[j]); if(start&nbsp;==&nbsp;(nextEnd&nbsp;+&nbsp;1)) { numbers[i]&nbsp;=&nbsp;nextStart&nbsp;+&nbsp;delimiter&nbsp;+&nbsp;end; numbers[j]&nbsp;=&nbsp;null; resultLength--; } } } String[]&nbsp;result&nbsp;=&nbsp;new&nbsp;String[resultLength];&nbsp; int&nbsp;index&nbsp;=&nbsp;0; for(int&nbsp;i&nbsp;=&nbsp;0;&nbsp;i&nbsp;<&nbsp;numbers.length;&nbsp;i++) { if(numbers[i]&nbsp;==&nbsp;null)&nbsp;continue; result[index++]&nbsp;=&nbsp;numbers[i]; System.out.println(numbers[i]); } return&nbsp;result; } return&nbsp;null; }只写了string[]类型的,list等参数类型按照这个思路自己补充就行了

千巷猫影

忘记两个方法了[code="java"]private static final String delimiter = "~";public static int getStart(String number){String start = number.substring(0, number.indexOf(delimiter));return Integer.valueOf(start);}public&nbsp;static&nbsp;int&nbsp;getEnd(String&nbsp;number) { &nbsp;&nbsp;&nbsp;&nbsp;String&nbsp;end&nbsp;=&nbsp;number.substring(number.indexOf(delimiter)&nbsp;+&nbsp;1); &nbsp;&nbsp;&nbsp;&nbsp;return&nbsp;Integer.valueOf(end); }
随时随地看视频慕课网APP

相关分类

Java
我要回答