任务描述:您将获得一个由逗号分隔的字符串组成的无序列表,其值的顺序对应于以下内容:0:唯一标识符1:表示框左上角的x坐标2:表示框左上角的y坐标3:盒子的高度4:框的宽度
创建一个函数,返回一个由逗号分隔的有效字符串排序的列表。先按y
坐标排序,如果y
坐标相等,再按x
坐标排序。完成下面的"NavigationSort
"功能。该函数预计返回一个STRING_ARRAY
。函数接受STRING_ARRAY boxArray作为参数。
public static List<String> NavigationSort(List<String> boxArray) {
// write your code here
return NavigationSort;
}
}
public class Solution {
public static void main(String[] args) throws IOException {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(System.getenv("OUTPUT_PATH")));
int boxArrayCount = Integer.parseInt(bufferedReader.readLine().trim());
List<String> boxArray = IntStream.range(0, boxArrayCount).mapToObj(i -> {
try {
return bufferedReader.readLine();
} catch (IOException ex) {
throw new RuntimeException(ex);
}
}).collect(toList());
List<String> result = Result.NavigationSort(boxArray);
bufferedWriter.write(result.stream().collect(joining("n")) + "n");
bufferedReader.close();
bufferedWriter.close();
}
}
您只需要编写一个合适的Comparator
.
这只是navigationSort
方法的实现。不清楚如何获取源列表,但是如果需要从文件中读取它,那么只需在类java.nio.file.Files
中使用方法readAllLInes。还要注意,下面的代码假设方法参数,即boxArray
,根据问题描述包含有效数据。
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;
public class Solution {
public static List<String> navigationSort(List<String> boxArray) {
Comparator<String> c = (s1, s2) -> {
String[] s1parts = s1.split(",");
String[] s2parts = s2.split(",");
int y1 = Integer.parseInt(s1parts[2]);
int y2 = Integer.parseInt(s2parts[2]);
int diff = y1 - y2;
if (diff == 0) {
int x1 = Integer.parseInt(s1parts[1]);
int x2 = Integer.parseInt(s2parts[1]);
diff = x1 - x2;
}
return diff;
};
return boxArray.stream()
.sorted(c)
.collect(Collectors.toList());
}
}