资源引用:
今日小记:
回乡聚会+陪家人,休息一天~
稀土掘金-147.寻找独一无二的糖葫芦串(147.寻找独一无二的糖葫芦串)
题目分析:
给定n个长度为m的字符串表示糖葫芦,定义糖葫芦的甜度是该字符串所有甜度的总和,而每个字符的甜度是该字符与'a'的ASCII码差值。
求在"独一无二"的糖葫芦中,甜度最大的一个,返回其甜度。
独一无二的糖葫芦当且仅当它与其他n-1根糖葫芦都不同,且翻转后的字符串也不能与其他糖葫芦相同。
解题思路:
- 用HashMap记录每条字符串及其是否独一无二
-
- 检查HashMap中是否包含该字符串及其翻转
-
-
- 若既不包含该字符串及其翻转,那么设其独一无二的标志为true
- 否则将其独一无二的标志设为false,若Map中有其翻转,则将其翻转的独一无二标志也设为false
-
- 从HashMap的独一无二的字符串中筛选出最大的value
- 返回该value
java
import java.util.Map;
import java.util.HashMap;
public class Main {
public static int solution(int n, int m, String[] strings) {
int maxSweet = 0;
Map<String, Boolean> map = new HashMap<>();
/*1.用HashMap记录每条字符串是否独一无二 */
for (String str : strings) {
String reStr = new StringBuilder(str).reverse().toString();
if (!map.containsKey(str) && !map.containsKey(reStr)) {
map.put(str, true);
} else {
map.put(str, false);
if (map.containsKey(reStr)) {
map.put(reStr, false);
}
}
}
/*2.从HashMap的独一无二的字符串中筛选出最大的value */
for (String tanghulu : map.keySet()) {
if (map.get(tanghulu)) {
int SweetLevel = 0;
for (int i = 0; i < tanghulu.length(); i++) {
SweetLevel += tanghulu.charAt(i) - 'a';
}
maxSweet = SweetLevel > maxSweet ? SweetLevel : maxSweet;
}
}
return maxSweet;
}
public static void main(String[] args) {
System.out.println(solution(3, 3, new String[]{"ccz", "cba", "zcc"}) == 3);
System.out.println(solution(2, 3, new String[]{"abc", "cba"}) == 0);
System.out.println(solution(5, 2, new String[]{"aa", "bb", "ab", "ba", "cc"}) == 4);
}
}
稀土掘金-119.游戏队友搜索(119.游戏队友搜索)
题目分析:
给定一个包含num条比赛游戏记录的array,每个条目包含一个二元数组[玩家ID,比赛局次],现在需要通过查找array表,找到和ID为1的玩家共同玩过至少两局游戏的其他玩家,将他们的ID按升序返回,若没有队友则返回空数组。
解题思路:
- 用一个Set记录ID为id的指定玩家所参与过的游戏局次。
- 用一个Map记录其他玩家与指定玩家的同居数,即该Map的键值对表示[玩家ID, 共同局数]。
- 最终返回Map中value≥2的玩家ID,
- 并按用Araays.sort方法升序排列。
java
import java.util.*;
public class Main {
public static void main(String[] args) {
// Add your test cases here
System.out.println(
Arrays.equals(
solution(1, 10,
new int[][] {
{ 1, 1 }, { 1, 2 }, { 1, 3 }, { 2, 1 }, { 2, 4 }, { 3, 2 },
{ 4, 1 }, { 4, 2 }, { 5, 2 }, { 5, 3 }
}),
new int[] { 4, 5 }));
}
public static int[] solution(int id, int num, int[][] array) {
List<Integer> resList = new ArrayList<>();
Set<Integer> set = new HashSet<>();
Map<Integer, Integer> map = new HashMap<>();
/*1.记录指定玩家的游戏局次 */
for (int[] play : array) {
if (play[0] == id) {
set.add(play[1]);
}
}
/*2.记录其余玩家与该指定玩家共同游玩的游戏局次数 */
for (int[] play : array) {
if (play[0] != id) {
if (set.contains(play[1])) {
map.put(play[0], map.getOrDefault(play[0], 0) + 1);
}
}
}
/*3.从其余玩家中筛选出与指定玩家至少共同游玩两局游戏的玩家 */
for (int player : map.keySet()) {
if (map.get(player) >= 2) resList.add(player);
}
/*4.升序排列并返回 */
int[] resultArray = resList.stream().mapToInt(Integer :: intValue).toArray();
Arrays.sort(resultArray);
return resultArray;
}
}