This commit is contained in:
youngyangyang04
2020-07-01 11:33:13 +08:00
parent 7be0bdc04f
commit 7fed9739ed
3 changed files with 45 additions and 5 deletions

View File

@ -16,6 +16,7 @@ LeetCode 最强题解(持续更新中):
|[0142.环形链表II](https://github.com/youngyangyang04/leetcode/blob/master/problems/0142.环形链表II.md) |链表 |中等|**模拟**|
|[0202.快乐数](https://github.com/youngyangyang04/leetcode/blob/master/problems/0202.快乐数.md) |哈希表 |简单|**哈希**|
|[0203.移除链表元素](https://github.com/youngyangyang04/leetcode/blob/master/problems/0203.移除链表元素.md) |链表 |简单|**模拟** **虚拟头结点**|
|[0205.同构字符串](https://github.com/youngyangyang04/leetcode/blob/master/problems/0205.同构字符串.md) |哈希表 |简单| **哈希**|
|[0206.翻转链表](https://github.com/youngyangyang04/leetcode/blob/master/problems/0206.翻转链表.md) |链表 |简单| **模拟** **递归**|
|[0209.长度最小的子数组](https://github.com/youngyangyang04/leetcode/blob/master/problems/0209.长度最小的子数组.md) |数组 |中等| **暴力** **滑动窗口**|
|[0219.存在重复元素II](https://github.com/youngyangyang04/leetcode/blob/master/problems/0219.存在重复元素II.md) | 哈希表 |简单| **哈希** |

View File

@ -0,0 +1,32 @@
## 题目地址
https://leetcode-cn.com/problems/isomorphic-strings/
## 思路
使用两个map 保存 s[i] 到 t[j] 和 t[j] 到 s[i] 的映射关系,如果发现对应不上,立刻返回 false
## C++代码
```
class Solution {
public:
bool isIsomorphic(string s, string t) {
unordered_map<char, char> map1;
unordered_map<char, char> map2;
for (int i = 0, j = 0; i < s.size(); i++, j++) {
if (map1.find(s[i]) == map1.end()) { // map1保存s[i] 到 t[j]的映射
map1[s[i]] = t[j];
}
if (map2.find(t[j]) == map2.end()) { // map2保存t[j] 到 s[i]的映射
map2[t[j]] = s[i];
}
// 发现映射 对应不上立刻返回false
if (map1[s[i]] != t[j] || map2[t[j]] != s[i]) {
return false;
}
}
return true;
}
};
```

View File

@ -3,7 +3,7 @@ https://leetcode-cn.com/problems/distribute-candies/
## 思路
因为种类是可妹妹先来所以思路先求出一共有多少种糖果然后如果糖果种类大于candies的一半了return candies的一半否则就是return 糖果的数量就可以了。
因为种类是可妹妹先来所以思路先求出一共有多少种糖果然后如果糖果种类大于candies的一半了return candies的一半否则就是return 糖果的种类就可以了。
## 代码
@ -12,17 +12,24 @@ https://leetcode-cn.com/problems/distribute-candies/
class Solution {
public:
int distributeCandies(vector<int>& candies) {
std::vector<int> hashTable(200001, -1); // 初始化一个hashtable因为数字的大小在范围[-100,000, 100,000]内所以这个hashtable大小要是200001这样才能取到200000这个下表索引
// 初始化一个record数组因为糖果种类的数值在范围[-100,000, 100,000]内
// 将这个范围的数值统一加上100000可以映射到record数组的索引下表了
// record数组大小必须大于等于200001这样才能取到200000这个下表索引
int record[200001] = {0};
// 通过record来记录糖果的种类
for (int i = 0; i < candies.size(); i++) {
hashTable[candies[i] + 100000]++;
record[candies[i] + 100000]++;
}
// 统计糖果种类的数量
int count = 0;
for (int i = 0; i < hashTable.size(); i++) {
if (hashTable[i] != -1) {
for (int i = 0; i < 200001; i++) {
if (record[i] != 0) {
count ++;
}
}
int half = candies.size() / 2;
// 如果糖果种类大于糖果总数的一半了return 糖果数量的一半
// 否则就是return 糖果的种类。
return count > half ? half : count;
}
};