File tree Expand file tree Collapse file tree 3 files changed +72
-1
lines changed Expand file tree Collapse file tree 3 files changed +72
-1
lines changed Original file line number Diff line number Diff line change
1
+ # Kth Smallest Element in a Sorted Matrix
2
+
3
+ ### 解法一
4
+ 多路归并
5
+
6
+ ``` go
7
+ func kthSmallest4 (matrix [][]int , k int ) int {
8
+ if len (matrix) ==0 {
9
+ return 0
10
+ }
11
+
12
+ heapSpec := new (BDS.IntHeapSpec ) // github.com/googege/BDS
13
+
14
+ // init 初始化这个小顶堆。
15
+ for i := 0 ; i < len (matrix); i++ {
16
+
17
+ l := [3 ]int {
18
+ i, 0 , matrix[i][0 ],
19
+ }
20
+
21
+ heapSpec.Push (l)
22
+
23
+ }
24
+ // 使用对路归并原理(min(min1,min2,min3))
25
+ for i := 1 ; i <= k-1 ; i++ {
26
+
27
+ result := heap.Pop (heapSpec).([3 ]int )
28
+ if result[0 ] < len (matrix) && result[1 ] < len (matrix[0 ])-1 {
29
+ heap.Push (heapSpec, [3 ]int {result[0 ], result[1 ] + 1 , matrix[result[0 ]][result[1 ]+1 ]})
30
+ }
31
+
32
+ }
33
+ return heapSpec.Top ().([3 ]int )[2 ]
34
+ }
35
+
36
+ ```
Original file line number Diff line number Diff line change
1
+ # Set Mismatch
2
+ ### 解法一
3
+ 鸽巢理论
4
+ ``` go
5
+ // 解法就是鸽子理论,代表的数字到自己的索引值去(本题是数字-1对应索引因为没有0)
6
+ // 然后那些不该在自己巢里的就是重复的,这个巢本身该有的但是没有的就是缺失的。
7
+ func findErrorNums (nums []int ) []int {
8
+ if len (nums) == 0 {
9
+ return nil
10
+ }
11
+
12
+ result := make ([]int ,0 )
13
+ for i := 0 ; i < len (nums);i++ {
14
+ for i != nums[i] -1 && nums[nums[i] - 1 ] != nums[i] {
15
+ // 这里的for是为了避免比如已经在自己的索引值上的,
16
+ // 然后第二个是自己的索引值已经有了自己一样的数字的
17
+ // 然后也不用再交换了。
18
+ swap (nums,i,nums[i]-1 )
19
+ }
20
+ }
21
+ for i := range nums {
22
+ if nums[i] - 1 != i {
23
+ result = append (result,nums[i],i+1 )
24
+ }
25
+ }
26
+ return result
27
+ }
28
+
29
+ func swap (nums []int ,a ,b int ){
30
+ nums[a],nums[b] = nums[b],nums[a]
31
+ }
32
+
33
+ ```
Original file line number Diff line number Diff line change @@ -6,4 +6,6 @@ All leetcode questions that solved in different methods.
6
6
| :---:| :---:| :---:| :---:|
7
7
| [ 240] ( ./240.md ) | [ Search a 2D Matrix II] ( https://leetcode-cn.com/problems/search-a-2d-matrix-ii/description/ ) | array| 👌|
8
8
| [ 283] ( ./283.md ) | [ Move Zeroes] ( https://leetcode-cn.com/problems/move-zeroes/description/ ) | array| 👌|
9
- | [ 566] ( ./566.md ) | [ Reshape the Matrix] ( https://leetcode-cn.com/problems/reshape-the-matrix/description/ ) | array| 👌|
9
+ | [ 378] ( ./378.md ) | [ Kth Smallest Element in a Sorted Matrix] ( https://leetcode-cn.com/problems/kth-smallest-element-in-a-sorted-matrix/description/ ) | array| 👌|
10
+ | [ 485] ( ./485.md ) | [ Max Consecutive Ones] ( https://leetcode-cn.com/problems/max-consecutive-ones/description/ ) | array| 👌|
11
+ | [ 645] ( ./645.md ) | [ Set Mismatch] ( https://leetcode-cn.com/problems/set-mismatch/description/ ) | array| 👌|
You can’t perform that action at this time.
0 commit comments