比赛时间:北京时间 2020 年 6 月 28 日早 10:30
再接再厉!
第 1 题:判断路径是否相交
Java 代码:
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
public class Solution {
public boolean isPathCrossing(String path) {
Map<Character, int[]> directions = new HashMap<>();
directions.put('N', new int[]{0, 1});
directions.put('S', new int[]{0, -1});
directions.put('E', new int[]{1, 0});
directions.put('W', new int[]{-1, 0});
char[] charArray = path.toCharArray();
Set<Pair> visited = new HashSet<>();
int currentX = 0;
int currentY = 0;
visited.add(new Pair(currentX, currentY));
for (char c : charArray) {
int[] direction = directions.get(c);
int newX = currentX + direction[0];
int newY = currentY + direction[1];
boolean add = visited.add(new Pair(newX, newY));
if (!add) {
return true;
}
currentX = newX;
currentY = newY;
}
return false;
}
class Pair {
private int x;
private int y;
public Pair(int x, int y) {
this.x = x;
this.y = y;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
Pair pair = (Pair) o;
return x == pair.x && y == pair.y;
}
@Override
public int hashCode() {
return Objects.hash(x, y);
}
@Override
public String toString() {
return "Pair{" +
"x=" + x +
", y=" + y +
'}';
}
}
public static void main(String[] args) {
Solution solution = new Solution();
// String path = "NES";
String path = "NESWW";
boolean pathCrossing = solution.isPathCrossing(path);
System.out.println(pathCrossing);
}
}
第 2 题:检查数组对是否可以被 k 整除
import java.util.Arrays;
public class Solution {
public boolean canArrange(int[] arr, int k) {
int len = arr.length;
int[] copy = new int[len];
for (int i = 0; i < len; i++) {
copy[i] = ((arr[i] % k) + k) % k;
}
Arrays.sort(copy);
int left = 0;
while (left < len && copy[left] == 0) {
left++;
}
if (left % 2 == 1) {
return false;
}
int right = len - 1;
while (left < right) {
if (copy[left] + copy[right] != k) {
return false;
}
left++;
right--;
}
return true;
}
public static void main(String[] args) {
// int[] arr = {1, 2, 3, 4, 5, 10, 6, 7, 8, 9};
// int k = 5;
// int[] arr = {1, 2, 3, 4, 5, 6};
// int k = 7;
// int[] arr = {1, 2, 3, 4, 5, 6};
// int k = 10;
// int[] arr = {-10, 10};
// int k = 2;
// int[] arr = {-1, 1, -2, 2, -3, 3, -4, 4};
// int k = 3;
int[] arr = {-6, 2, 1, 1, 2, 2, 0, 0};
int k = 2;
Solution solution = new Solution();
boolean res = solution.canArrange(arr, k);
System.out.println(res);
}
}