第 24 课
- [888. 公平的糖果棒交换](https://leetcode-cn.com/problems/fair-candy-swap/)
- [720. 词典中最长的单词](https://leetcode-cn.com/problems/longest-word-in-dictionary/)
888. 公平的糖果棒交换
class Solution:
def fairCandySwap(self, aliceSizes: List[int], bobSizes: List[int]) -> List[int]:
a, b = sum(aliceSizes), sum(bobSizes)
c, d = aliceSizes, set(bobSizes)
for i in c:
j = (b - a)//2 + i
if j in d:
return [i, j]
class Solution {
public int[] fairCandySwap(int[] aliceSizes, int[] bobSizes) {
int a = 0, b = 0;
for (int x : aliceSizes) a += x;
Set d = new HashSet();
for (int x : bobSizes){
b += x;
d.add(x);
}
int delta = (b - a) / 2;
for (int i : aliceSizes){
int j = delta + i;
if (d.contains(j)) return new int[]{i, j};
}
return new int[2];
}
}
720. 词典中最长的单词
class Solution(object):
def longestWord(self, words):
wordset = set(words)
words.sort(key = lambda c: (-len(c), c))
for word in words:
if all(word[:k] in wordset for k in range(1, len(word))):
return wordreturn ""
class Solution {
public String longestWord(String[] words) {
Set set = new HashSet<>();
for (String w : words) set.add(w);
Arrays.sort(words);
// 先按字母升序排序再按长度降序排列
Arrays.sort(words, (a, b) -> b.length() - a.length());
sign:
for (String word : words){
for (int i = 1;
i < word.length();
i++){
if (!set.contains(word.substring(0, i))) continue sign;
}
return word;
}
return "";
}
}class Solution {
public String longestWord(String[] words) {
Arrays.sort(words, (a, b) -> { // 升序
if (a.length() != b.length()) return a.length() - b.length();
return b.compareTo(a);
// 相同长度下把字典序较大的排在前面
});
String ans = "";
Set set = new HashSet<>();
set.add("");
for (String word : words) {
if (set.contains(word.substring(0, word.length() - 1))) {
ans = word;
set.add(word);
// 注意是逐步多一,所以,这个添加要放在 if 里面
}
}
return ans;
}
}
推荐阅读
- 实现一个自己的语法解析器与执行引擎
- 蓝桥杯|2021年第十二届蓝桥杯省赛Python组(真题+解析+代码)(路径)
- 蓝桥杯|2021年第十二届蓝桥杯省赛Python组(真题+解析+代码)(杨辉三角形)
- 蓝桥杯Python专项|第十三届蓝桥杯大赛软件组省赛Python大学A组不完全题解
- 蓝桥杯|2021年第十二届蓝桥杯省赛Python组(真题+解析+代码)(货物摆放)
- mapper|selectPage方法重载时遇到问题
- 微服务|初识微服务技术栈
- 小司机上路|编程语言中高级语言中的简单分类和特、优、缺三点
- Spring|【Spring框架】帮助理解AspectJ框架的练习题