Skip to content

Commit 13784e0

Browse files
authored
Merge branch 'youngyangyang04:master' into zhicheng-lee-patch-4
2 parents 1214fd9 + 41cf322 commit 13784e0

6 files changed

+157
-29
lines changed

problems/0127.单词接龙.md

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -158,6 +158,57 @@ class Solution:
158158
return 0
159159
```
160160
## Go
161+
```go
162+
func ladderLength(beginWord string, endWord string, wordList []string) int {
163+
wordMap, que, depth := getWordMap(wordList, beginWord), []string{beginWord}, 0
164+
for len(que) > 0 {
165+
depth++
166+
qLen := len(que) // 单词的长度
167+
for i := 0; i < qLen; i++ {
168+
word := que[0]
169+
que = que[1:] // 首位单词出队
170+
candidates := getCandidates(word)
171+
for _, candidate := range candidates {
172+
if _, exist := wordMap[candidate]; exist { // 用生成的结果集去查询
173+
if candidate == endWord {
174+
return depth + 1
175+
}
176+
delete(wordMap, candidate) // 删除集合中的用过的结果
177+
que = append(que, candidate)
178+
}
179+
}
180+
}
181+
}
182+
return 0
183+
}
184+
185+
186+
// 获取单词Map为后续的查询增加速度
187+
func getWordMap(wordList []string, beginWord string) map[string]int {
188+
wordMap := make(map[string]int)
189+
for i, word := range wordList {
190+
if _, exist := wordMap[word]; !exist {
191+
if word != beginWord {
192+
wordMap[word] = i
193+
}
194+
}
195+
}
196+
return wordMap
197+
}
198+
199+
// 用26个英文字母分别替换掉各个位置的字母,生成一个结果集
200+
func getCandidates(word string) []string {
201+
var res []string
202+
for i := 0; i < 26; i++ {
203+
for j := 0; j < len(word); j++ {
204+
if word[j] != byte(int('a')+i) {
205+
res = append(res, word[:j]+string(int('a')+i)+word[j+1:])
206+
}
207+
}
208+
}
209+
return res
210+
}
211+
```
161212

162213
## JavaScript
163214
```javascript

problems/0200.岛屿数量.md

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -247,3 +247,35 @@ public:
247247

248248

249249
## 其他语言版本
250+
251+
### Java
252+
253+
下面的代码使用的是深度优先搜索 DFS 的做法。为了统计岛屿数量同时不重复记录,每当我们搜索到一个岛后,就将这个岛 “淹没” —— 将这个岛所占的地方从 “1” 改为 “0”,这样就不用担心后续会重复记录这个岛屿了。而 DFS 的过程就体现在 “淹没” 这一步中。详见代码:
254+
255+
```java
256+
public int numIslands(char[][] grid) {
257+
int res = 0; //记录找到的岛屿数量
258+
for(int i = 0;i < grid.length;i++){
259+
for(int j = 0;j < grid[0].length;j++){
260+
//找到“1”,res加一,同时淹没这个岛
261+
if(grid[i][j] == '1'){
262+
res++;
263+
dfs(grid,i,j);
264+
}
265+
}
266+
}
267+
return res;
268+
}
269+
//使用DFS“淹没”岛屿
270+
public void dfs(char[][] grid, int i, int j){
271+
//搜索边界:索引越界或遍历到了"0"
272+
if(i < 0 || i >= grid.length || j < 0 || j >= grid[0].length || grid[i][j] == '0') return;
273+
//将这块土地标记为"0"
274+
grid[i][j] = '0';
275+
//根据"每座岛屿只能由水平方向或竖直方向上相邻的陆地连接形成",对上下左右的相邻顶点进行dfs
276+
dfs(grid,i - 1,j);
277+
dfs(grid,i + 1,j);
278+
dfs(grid,i,j + 1);
279+
dfs(grid,i,j - 1);
280+
}
281+
```

problems/0242.有效的字母异位词.md

Lines changed: 13 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -92,18 +92,24 @@ public:
9292
9393
Java:
9494
```java
95+
/**
96+
* 242. 有效的字母异位词 字典解法
97+
* 时间复杂度O(m+n) 空间复杂度O(1)
98+
*/
9599
class Solution {
96100
public boolean isAnagram(String s, String t) {
97-
98101
int[] record = new int[26];
99-
for (char c : s.toCharArray()) {
100-
record[c - 'a'] += 1;
102+
103+
for (int i = 0; i < s.length(); i++) {
104+
record[s.charAt(i) - 'a']++;
101105
}
102-
for (char c : t.toCharArray()) {
103-
record[c - 'a'] -= 1;
106+
107+
for (int i = 0; i < t.length(); i++) {
108+
record[t.charAt(i) - 'a']--;
104109
}
105-
for (int i : record) {
106-
if (i != 0) {
110+
111+
for (int count: record) {
112+
if (count != 0) {
107113
return false;
108114
}
109115
}

problems/0347.前K个高频元素.md

Lines changed: 45 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -140,24 +140,55 @@ public:
140140
Java:
141141
```java
142142
143+
/*Comparator接口说明:
144+
* 返回负数,形参中第一个参数排在前面;返回正数,形参中第二个参数排在前面
145+
* 对于队列:排在前面意味着往队头靠
146+
* 对于堆(使用PriorityQueue实现):从队头到队尾按从小到大排就是最小堆(小顶堆),
147+
* 从队头到队尾按从大到小排就是最大堆(大顶堆)--->队头元素相当于堆的根节点
148+
* */
143149
class Solution {
144-
public int[] topKFrequent(int[] nums, int k) {
145-
int[] result = new int[k];
146-
HashMap<Integer, Integer> map = new HashMap<>();
147-
for (int num : nums) {
148-
map.put(num, map.getOrDefault(num, 0) + 1);
150+
//解法1:基于大顶堆实现
151+
public int[] topKFrequent1(int[] nums, int k) {
152+
Map<Integer,Integer> map = new HashMap<>();//key为数组元素值,val为对应出现次数
153+
for(int num:nums){
154+
map.put(num,map.getOrDefault(num,0)+1);
149155
}
150-
151-
Set<Map.Entry<Integer, Integer>> entries = map.entrySet();
152-
// 根据map的value值,构建于一个大顶堆(o1 - o2: 小顶堆, o2 - o1 : 大顶堆)
153-
PriorityQueue<Map.Entry<Integer, Integer>> queue = new PriorityQueue<>((o1, o2) -> o2.getValue() - o1.getValue());
154-
for (Map.Entry<Integer, Integer> entry : entries) {
155-
queue.offer(entry);
156+
//在优先队列中存储二元组(num,cnt),cnt表示元素值num在数组中的出现次数
157+
//出现次数按从队头到队尾的顺序是从大到小排,出现次数最多的在队头(相当于大顶堆)
158+
PriorityQueue<int[]> pq = new PriorityQueue<>((pair1, pair2)->pair2[1]-pair1[1]);
159+
for(Map.Entry<Integer,Integer> entry:map.entrySet()){//大顶堆需要对所有元素进行排序
160+
pq.add(new int[]{entry.getKey(),entry.getValue()});
156161
}
157-
for (int i = k - 1; i >= 0; i--) {
158-
result[i] = queue.poll().getKey();
162+
int[] ans = new int[k];
163+
for(int i=0;i<k;i++){//依次从队头弹出k个,就是出现频率前k高的元素
164+
ans[i] = pq.poll()[0];
159165
}
160-
return result;
166+
return ans;
167+
}
168+
//解法2:基于小顶堆实现
169+
public int[] topKFrequent2(int[] nums, int k) {
170+
Map<Integer,Integer> map = new HashMap<>();//key为数组元素值,val为对应出现次数
171+
for(int num:nums){
172+
map.put(num,map.getOrDefault(num,0)+1);
173+
}
174+
//在优先队列中存储二元组(num,cnt),cnt表示元素值num在数组中的出现次数
175+
//出现次数按从队头到队尾的顺序是从小到大排,出现次数最低的在队头(相当于小顶堆)
176+
PriorityQueue<int[]> pq = new PriorityQueue<>((pair1,pair2)->pair1[1]-pair2[1]);
177+
for(Map.Entry<Integer,Integer> entry:map.entrySet()){//小顶堆只需要维持k个元素有序
178+
if(pq.size()<k){//小顶堆元素个数小于k个时直接加
179+
pq.add(new int[]{entry.getKey(),entry.getValue()});
180+
}else{
181+
if(entry.getValue()>pq.peek()[1]){//当前元素出现次数大于小顶堆的根结点(这k个元素中出现次数最少的那个)
182+
pq.poll();//弹出队头(小顶堆的根结点),即把堆里出现次数最少的那个删除,留下的就是出现次数多的了
183+
pq.add(new int[]{entry.getKey(),entry.getValue()});
184+
}
185+
}
186+
}
187+
int[] ans = new int[k];
188+
for(int i=k-1;i>=0;i--){//依次弹出小顶堆,先弹出的是堆的根,出现次数少,后面弹出的出现次数多
189+
ans[i] = pq.poll()[0];
190+
}
191+
return ans;
161192
}
162193
}
163194
```

problems/0416.分割等和子集.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -152,6 +152,8 @@ public:
152152
for (int i = 0; i < nums.size(); i++) {
153153
sum += nums[i];
154154
}
155+
// 也可以使用库函数一步求和
156+
// int sum = accumulate(nums.begin(), nums.end(), 0);
155157
if (sum % 2 == 1) return false;
156158
int target = sum / 2;
157159

problems/0977.有序数组的平方.md

Lines changed: 14 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -239,18 +239,24 @@ Typescript:
239239

240240
```typescript
241241
function sortedSquares(nums: number[]): number[] {
242-
let left: number = 0, right: number = nums.length - 1;
243-
let resArr: number[] = new Array(nums.length);
244-
let resArrIndex: number = resArr.length - 1;
242+
const ans: number[] = [];
243+
let left = 0,
244+
right = nums.length - 1;
245+
245246
while (left <= right) {
246-
if (Math.abs(nums[left]) < Math.abs(nums[right])) {
247-
resArr[resArrIndex] = nums[right--] ** 2;
247+
// 右侧的元素不需要取绝对值,nums 为非递减排序的整数数组
248+
// 在同为负数的情况下,左侧的平方值一定大于右侧的平方值
249+
if (Math.abs(nums[left]) > nums[right]) {
250+
// 使用 Array.prototype.unshift() 直接在数组的首项插入当前最大值
251+
ans.unshift(nums[left] ** 2);
252+
left++;
248253
} else {
249-
resArr[resArrIndex] = nums[left++] ** 2;
254+
ans.unshift(nums[right] ** 2);
255+
right--;
250256
}
251-
resArrIndex--;
252257
}
253-
return resArr;
258+
259+
return ans;
254260
};
255261
```
256262

0 commit comments

Comments
 (0)