题目
a = [
{time:1},
{time:5},
{time:8},
{time:11},
{time:16},
{time:17},
{time:29},
{time:34},
{time:39}
];
time_line = [3,7,12,17,19,31,40];
请找出,根据time_line,找到a数组中最近的一个数(数组a的值只能被取一次;如果有两个相等,取后面一个;)
返回结果示例 [{line:3,time:5},{line:7,time:8}]
解决:
按照第二个数组顺序暴力扫描第一个数组,将匹配到的移除,循环扫描即可。
public class One {
private String[] a = new String[]{
"{time:1}",
"{time:5}",
"{time:8}",
"{time:11}",
"{time:16}",
"{time:17}",
"{time:29}",
"{time:34}",
"{time:39}"};
private int[] time_line = new int[]{3, 7, 12, 17, 19, 31, 40};
public String[] result() {
String[] strings = new String[time_line.length];
List<Integer> median = new LinkedList<>();
for (int i = 0; i < a.length; i++) {
Integer integ = Integer.valueOf(a[i].substring(6, a[i].length() - 1));
median.add(integ);
}
flag:for (int i = 0; i < time_line.length; i++) {
int temp = time_line[i];
for (int j = 0; j <= median.size()-2; j++) {
//[{line:3,time:5},{line:7,time:8}]
if(temp > median.get(j) && temp < median.get(j+1)){
int re = Math.abs(temp-median.get(j)) < (Math.abs(median.get(j+1) - temp)) ? j : j+1 ;
strings[i] = "{line:" + time_line[i] +",time:"+median.get(re)+"}";
median.remove(re);
continue flag;
}else if(temp == median.get(j)){
strings[i] = "{line:" + time_line[i] +",time:"+median.get(j)+"}";
median.remove(j);
continue flag;
}else if(temp <= median.get(0)){
strings[i] = "{line:" + time_line[i] +",time:"+median.get(0)+"}";
median.remove(0);
continue flag;
}else if(temp >= median.get(median.size()-1)){
strings[i] = "{line:" + time_line[i] +",time:"+median.get(median.size()-1)+"}";
median.remove(median.size()-1);
continue flag;
}
}
}
return strings;
}
public static void main(String[] args) {
One one = new One();
String[] result = one.result();
for (int i = 0; i < result.length; i++) {
System.out.println(result[i]);
}
}
}
希望大家给出更好的解决办法