检查两个字符串是否几乎相等
签到题
- 定义两个数组存放对应两个字符串字母个数
- 最后一次遍历对比每个字母的差值是否大于 3 即可
class Solution {
public boolean checkAlmostEquivalent(String word1, String word2) {
int[] arr1 = new int[26];
for (char c : word1.toCharArray()) {
arr1[c - 'a']++;
}
int[] arr2 = new int[26];
for (char c : word2.toCharArray()) {
arr2[c - 'a']++;
}
for (int i = 0; i < 26; i++) {
if (Math.abs(arr1[i] - arr2[i]) > 3) return false;
}
return true;
}
}
- 进阶:第一个字符串+1,第二个字符串-1
class Solution {
public boolean checkAlmostEquivalent(String word1, String word2) {
int[] arr = new int[26];
for (char c : word1.toCharArray()) {
arr[c - 'a']++;
}
for (char c : word2.toCharArray()) {
arr[c - 'a']--;
}
for (int i = 0; i < 26; i++) {
if (Math.abs(arr[i]) > 3) return false;
}
return true;
}
}
模拟行走机器人 II
- 定义 x,y 作为当前坐标,w、h 为边界右边最大值和边界上方最大值
- flag 判断是否第一次
- 定义String数组和 index 判断当前所处方向
class Robot {
int x = 0, y = 0, index = 0, w, h;
String[] posit = new String[]{"East", "North", "West", "South"};
public Robot(int width, int height) {
w = width;
h = height;
}
public void move(int num) {
if (num > ((w + h - 2) * 2)) {
num %= ((w + h - 2) * 2);
if (x == 0 && y == 0) index = 3;
}
while (num != 0) {
if (x == 0 && y == 0) {
index = 0;
} else if (x == 0 && y == w - 1) {
index = 1;
} else if (x == h - 1 && y == w - 1) {
index = 2;
} else if (x == h - 1 && y == 0) {
index = 3;
}
if (index == 0) {
y++;
} else if (index == 1) {
x++;
} else if (index == 2) {
y--;
} else {
x--;
}
num--;
}
}
public int[] getPos() {
return new int[]{y, x};
}
public String getDir() {
return posit[index];
}
}
每一个查询的最大美丽值
思路:
-
二维数组每一组代表一件物品的价格和美丽值,我们要满足价格小于 queries[i]的前提下,美丽值尽可能地大,最后填充到数组中
-
开始想用暴力循环偷个懒,果然超时了orz…
class Solution {
public int[] maximumBeauty(int[][] items, int[] queries) {
int len = queries.length;
int[] res = new int[len];
for (int i = 0; i < len; i++) {
for (int j = 0; j < items.length; j++) {
if (items[j][0] <= queries[i]) {
res[i] = Math.max(res[i], items[j][1]);
}
}
}
return res;
}
}
转换思路:
- 先对二位数组进行排序
- 因同一价格会有不同美丽值,所以我们可使用 Map 存储对应键值对《价格,当前价格对应的最大美丽值》
- 遍历数组加入map 的同时,维护一个当前最大值,存入map 中
- 但当 queries[i] 值在 map 的 key 值中不存在时,我们需要向下寻找键值,使用 floorKey()
- floorKey(K key)返回小于等于给定键的最大键;如果不存在这样的键,则返回 null(TreeMap独有)
class Solution {
public int[] maximumBeauty(int[][] items, int[] queries) {
TreeMap<Integer, Integer> map = new TreeMap<>();
map.put(0, 0);//防止没有满足条件的结果,map.get()报错
//排序二维数组,o1 和 o2 代表两组数组,例如 o1 = {1,5}, o2 = {1,9}
Arrays.sort(items, (o1, o2) -> {
//当o1[0] == o2[0]相等时,取5 - 9升序排序
if (o1[0] == o2[0]) {
return o1[1] - o2[1];
}
//当o1[0] == o2[0]不相等时,取两个数组索引为 0 的数升序排序
return o1[0] - o2[0];
});
//维护一个当前键的最大值
int max = 0;
for (int[] arr : items) {
if (arr[1] > max) {
max = arr[1];
}
map.put(arr[0], max);
}
int[] res = new int[queries.length];
for (int i = 0; i < queries.length; i++) {
if (map.containsKey(queries[i])) {
res[i] = map.get(queries[i]);
} else {
//floorKey:向下取整键值
res[i] = map.get(map.floorKey(queries[i]));
}
}
return res;
}
}