您的位置:首页 > 其它

Leetcode-378. Kth Smallest Element in a Sorted Matrix

2016-09-03 17:36 295 查看
1、题目来源:点击打开链接

2、题目:

Given a n x n matrix where each of the rows and columns are sorted in ascending order, find the kth smallest element in the matrix.

Note that it is the kth smallest element in the sorted order, not the kth distinct element.

Example:
matrix = [
[ 1,  5,  9],
[10, 11, 13],
[12, 13, 15]
],
k = 8,

return 13.


Note: 

You may assume k is always valid, 1 ≤ k ≤ n2.
3.转换为一维数组,然后进行冒泡排序(未通过):

int kthSmallest(int** matrix, int matrixRowSize, int matrixColSize, int k) {
int i,j,r=0,temp,n=matrixRowSize;
int*a=(int*)malloc(sizeof(int)*(n*n));
for(i=0;i<n;i++)
for(j=0;j<n;j++){
a[r]=matrix[i][j];
r++;
}
for(i=0;i<n*n-1;i++){
for(j=0;j<n*n-1-i;j++){
if(a[j]>a[j+1]){
temp=a[j];
a[j]=a[j+1];
a[j+1]=temp;
}
}
}

return a[k-1];
}
4、冒泡排序的改进版(在比较的一轮中,记录第几个元素是最后一次交换的 ,后面的元素都是已排好序的):

for(i=0;i<pos;i++){
u=pos;pos=0;
for(j=0;j<u;j++){
if(a[j]>a[j+1]){
pos=j;
temp=a[j];
a[j]=a[j+1];
a[j+1]=temp;
}
}
}
5、java使用import java.util.Arrays包里的Arrays.sort(a)可对a进行排序,然后可以通过,因为从Arrays.sort(a)的源码可知其用到了快排,其中还会根据数组的长度来决定使用哪一种排序算法,这可以通过(有时间一定要自己玩一下下面A的这种有趣的工作):
A、该函数的源码解析

B、使用该法通过的代码

6、堆排序待学习.......
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: