java - 我想不出这个盒子阵列挑战
问题描述
任务描述:给你一个以逗号分隔的字符串的无序列表,其值的顺序对应于以下内容: 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
方法的实现。目前尚不清楚如何获取源列表,但如果您需要从文件中读取它,那么只需使用class 中的方法readAllLInesjava.nio.file.Files
即可。另请注意,以下代码假定方法参数 ieboxArray
包含根据问题描述的有效数据。
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());
}
}
推荐阅读
- python - 如何从文本注释中删除数据点?
- php - Yii2 在重定向中获取 url ID。在创建动作中
- file-io - Xilinx Zynq ZCU102 中 SD 卡的 Filo I/O 操作
- angular - Angular - 为一个元素创建一个 HTML 链接而不用 XSS 删除它
- html - bootstrap 4导航栏折叠的div在激活时正在移动所有标题菜单
- php - 适用于 Linux 的最新可用 PHP 版本不足以用于 Passport
- html - 在图像烧瓶下居中文本
- parameters - 如何在 Prestashop 1.6 的挂钩中从 $params 获取 default_id_categories
- reactjs - 使用 UUID 和 JSON 有效负载中的嵌套对象反应 axios 帖子的正确方法?
- grafana - 使用 statsd + 石墨 + grafana 计算不规则事件