public
:
int
kthSmallest
(
vector
<
vector
<
int
>>
&
matrix
,
int
k
)
{
vector
<
int
>
res
=
merge
(
matrix
,
0
,
matrix
.
size
(
)
-
1
)
;
return
res
[
k
-
1
]
;
vector
<
int
>
merge
(
vector
<
vector
<
int
>>
&
matrix
,
int
left
,
int
right
)
if
(
left
==
right
)
return
matrix
[
left
]
;
int
mid
=
left
+
(
right
-
left
)
/
2
;
vector
<
int
>
A
=
merge
(
matrix
,
left
,
mid
)
;
vector
<
int
>
B
=
merge
(
matrix
,
mid
+
1
,
right
)
;
return
mergeTwoVector
(
A
,
B
)
;
vector
<
int
>
mergeTwoVector
(
vector
<
int
>
&
A
,
vector
<
int
>
&
B
)
vector
<
int
>
temp
(
A
.
size
(
)
+
B
.
size
(
)
)
;
int
A_start
=
0
;
int
B_start
=
0
;
int
start
=
0
;
while
(
A_start
<
A
.
size
(
)
&&
B_start
<
B
.
size
(
)
)
if
(
A
[
A_start
]
<=
B
[
B_start
]
)
temp
[
start
++
]
=
A
[
A_start
++
]
;
temp
[
start
++
]
=
B
[
B_start
++
]
;
if
(
A_start
==
A
.
size
(
)
)
while
(
B_start
<
B
.
size
(
)
)
temp
[
start
++
]
=
B
[
B_start
++
]
;
while
(
A_start
<
A
.
size
(
)
)
temp
[
start
++
]
=
A
[
A_start
++
]
;
return
temp
;
#include <functional>
class Solution {
public:
int kthSmallest(vector<vector<int>>& matrix, int k) {
struct point
int val, x, y;
point(int val, int x, int y) : val(val), x(x), y(y) {}
bool operator> (const point& a) const { return this->val > a.val; }
priority_queue<point, vector<point>, greater<point>> pri_queue;
for (int i = 0; i < matrix.size(); i++)
pri_queue.push(point(matrix[i][0], i, 0));
for (int i = 0; i < k - 1; i++)
point temp = pri_queue.top();
pri_queue.pop();
if (temp.y + 1 < matrix[temp.x].size())
pri_queue.push(point(matrix[temp.x][temp.y + 1], temp.x, temp.y + 1));
return pri_queue.top().val;
和合并K个排序链表思路完全相同。法1:归并法2:优先级队列(小顶堆)class Solution { //归并public: int kthSmallest(vector<vector<int>>& matrix, int k) { vector<int>res = merge(matrix, 0, matrix.size()-1); return res[k - 1]; } vector<int>merge(vecto.
这是一个经典的面试问题。
通过使用堆可以解决此问题。时间复杂度为O(nlog(k)),其中n是元素总数,而k是数组数。
将O(log(k))插入到堆中需要花费O(log(k))来删除最小元素。
class ArrayContainer implements Comparable {
int[] arr;
int index;
public ArrayContainer(int[] arr, int...
博主小C就读于双非一本大学,Java后端选手,这一段时间过来,感触还是很多~ ,其实自己并不是大佬级别的,只是勤勤恳恳,不算差而已。
今天先记录一下面试中经常考察的两个算法题,主要为了总结以作备忘,算法思想还是很重要的,也希望能帮助到有需要的朋友。
高频出现在面试中的考察的题目:合并k个有序数组、合并k个有序链表。
Given k sorted integer arrays, merge them into one sorted array.
Example Given 3 sorted arrays:
[1, 3, 5, 7],
[2, 4, 6],
[0, 8, 9, 10, 11]]
return [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11].
Challenge D...
public ListNode mergeKLists(ListNode[] lists) {
if(lists==null||lists.length==0)return null;
return sort(lists, 0, l...