Re: [问题] LeetCode 378. Kth Smallest Element...

楼主: powertodream (The Beginning)   2017-06-20 21:24:07
※ 引述《woody3724 (woody)》之铭言:
: LeetCode 378. Kth Smallest Element in a Sorted Matrix
: 题目连结 http://tinyurl.com/y8sc949p
: 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
: 目前正在研究用binary search解这题 http://tinyurl.com/ybqw4ubd
: YUANGAO1023提到的Solution 2: Binary Search
: 大致的结构我都看懂了
: 但是不懂的是为什么是在while循环的最后
: 是else hi = mid; 而不是 else hi = mid - 1;
: 我有自己代数字实际跑一遍, else hi = mid; 是正确的,但是却不知道为什么这是正确
: 也不懂为什么 hi = mid - 1就不行
: 谢谢
他这个看起来是比较标准的写法, 就是如果你有多个符合条件的element的话
他会return 第一个 符合这个条件的 element
之前我的习惯也是写像是这样
while (lo<=hi){
if (mid==target)
...
else if (mid > target)
hi = mid - 1;
else
lo = mid + 1;
};
不过这样写如果有多个符合条件的元素的话, 就会回传随机一个.
我理解上是这样 可以再讨论.
详细可以看topcoder的这一篇, 不过我也没有看完 只大概扫过而已, 有兴趣可以详读
https://tinyurl.com/qcaj9aj

Links booklink

Contact Us: admin [ a t ] ucptt.com