- 乘法表中第k小的数
- 乘法表中第k小的数
几乎每一个人都用 乘法表。但是你能在乘法表中快速找到第k小的数字吗?
给定高度m 、宽度n 的一张 m * n的乘法表,以及正整数k,你需要返回表中第k 小的数字。
例 1:
输入: m = 3, n = 3, k = 5
输出: 3
解释:
乘法表:
1 2 3
2 4 6
3 6 9
第5小的数字是 3 (1, 2, 2, 3, 3).
例 2:
输入: m = 2, n = 3, k = 6
输出: 6
解释:
乘法表:
1 2 3
2 4 6
第6小的数字是 6 (1, 2, 2, 3, 4, 6).
注意:
m 和 n 的范围在 [1, 30000] 之间。
k 的范围在 [1, m * n] 之间。
经典二分题
观察乘法表具有什么性质
- 每一行都是
递增的
- 每一列都是
递增的
- 最小值在左上角,最大值在右下角
对于二分答案
首先,我们不知道k
大值是多少,但是我们可以猜一个(单调性显然,整张表是可排序的)
设k
大值为x
,则只需要判断比x
小的数字有多个,就可以调整x
的大小
对于check()
- 每行递增,对于一行,我们可以二分
x
的位置 l o g ( m ) ~~log(m) log(m) - 共
n
行,则可以 n l o g ( m ) ~~nlog(m) nlog(m)
最后注意边界即可 时间复杂度 O ( l o g ( n ∗ m ) ∗ n l o g ( m ) ) ~~~O(~~log(n*m)*nlog(m)~~) O( log(n∗m)∗nlog(m) )
#define debug
#ifdef debug
#include <time.h>
#endif
#include <iostream>
#include <algorithm>
#include <vector>
#include <string.h>
#include <map>
#include <set>
#include <stack>
#include <queue>
#include <math.h>
#define MAXN ((int)1e5+7)
#define ll long long int
#define INF (0x7f7f7f7f)
#define fori(lef, rig) for(int i=lef; i<=rig; i++)
#define forj(lef, rig) for(int j=lef; j<=rig; j++)
#define fork(lef, rig) for(int k=lef; k<=rig; k++)
#define QAQ (0)
using namespace std;
#define show(x...) \
do { \
cout << "\033[31;1m " << #x << " -> "; \
err(x); \
} while (0)
void err() { cout << "\033[39;0m" << endl; }
template<typename T, typename... A>
void err(T a, A... x) { cout << a << ' '; err(x...); }
namespace FastIO{
char print_f[105];
void read() {}
void print() { putchar('\n'); }
template <typename T, typename... T2>
inline void read(T &x, T2 &... oth) {
x = 0;
char ch = getchar();
ll f = 1;
while (!isdigit(ch)) {
if (ch == '-') f *= -1;
ch = getchar();
}
while (isdigit(ch)) {
x = x * 10 + ch - 48;
ch = getchar();
}
x *= f;
read(oth...);
}
template <typename T, typename... T2>
inline void print(T x, T2... oth) {
ll p3=-1;
if(x<0) putchar('-'), x=-x;
do{
print_f[++p3] = x%10 + 48;
} while(x/=10);
while(p3>=0) putchar(print_f[p3--]);
putchar(' ');
print(oth...);
}
} // namespace FastIO
using FastIO::print;
using FastIO::read;
class Solution {
public:
int check(int n, int m, int key) {
int ret = 0;
for(int i=1; i<=n; i++) {
int lef = 1, rig = m, mid, id = 0;
while(lef <= rig) {
mid = lef + rig >> 1;
if(mid*i < key) {
id = mid;
lef = mid + 1;
} else
rig = mid - 1;
}
// show(i, id);
ret += id;
}
return ret;
}
int findKthNumber(int n, int m, int k) {
int lef = 1, rig = n * m, mid, ans = -1;
while(lef <= rig) {
mid = (lef + rig) >> 1;
int ret = check(n, m, mid);
// show(mid, ret);
if(ret < k) {
ans = mid;
lef = mid + 1;
} else
rig = mid - 1;
}
return ans;
}
};
#ifdef debug
signed main() {
Solution s;
cout << s.findKthNumber(45, 12, 471) << endl;
return 0;
}
#endif
java
import java.io.*;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.*;
class Solution {
int check(int n, int m, int key) {
int ret = 0;
for(int i=1; i<=n; i++) {
int lef = 1, rig = m, id = 0;
while(lef <= rig) {
int mid = (lef + rig) >> 1;
if(i*mid < key) {
id = mid;
lef = mid + 1;
} else
rig = mid - 1;
}
ret += id;
}
return ret;
}
public int findKthNumber(int n, int m, int k) {
int lef = 1, rig = n*m, mid, ans = -1;
while(lef <= rig) {
mid = (lef + rig) >> 1;
int ret = check(n, m, mid);
if(ret < k) {
ans = mid;
lef = mid + 1;
} else
rig = mid - 1;
}
return ans;
}
}
public class Main {
public static final boolean debug = true;
public static String INPATH = "C:\\Users\\majiao\\Desktop\\test.txt",
OUTPATH = "C:\\Users\\majiao\\Desktop\\out.txt";
public static StreamTokenizer tok;
public static BufferedReader cin;
public static PrintWriter cout;
public static long start_time = 0, out_time = 0;
public static int n, m, K, Q, MAXN = (int)1e5+7, INF = 0x3f3f3f3f;
public static byte buf[] = new byte[MAXN];
public static void main(String[] args) throws IOException {
main_init();
if(debug) { start_time = System.currentTimeMillis(); }
if(false) { System.setOut(new PrintStream(OUTPATH)); }
Solution solu = new Solution();
int a[] = { };
cout.printf("%d\n", solu.findKthNumber(3, 3, 5));
if(debug) {
out_time = System.currentTimeMillis();
cout.printf("run time : %d ms\n", out_time-start_time);
}
cout.flush();
}
public static void show(List<Object> list, Object... obj) {
cout.printf("%s : ", obj.length>0 ? obj[0] : "");
for(Object x : list) {
cout.printf("[%s] ", x);
}
cout.printf("\n");
}
public static void show(Map<Object, Object> mp, Object... obj) {
cout.printf("%s : ", obj.length>0 ? obj[0] : "");
Set<Map.Entry<Object, Object>> entries = mp.entrySet();
for (Map.Entry<Object, Object> en : entries) {
cout.printf("[%s,%s] ", en.getKey(), en.getValue());
}
cout.printf("\n");
}
public static<T> void forarr(T arr[], int ...args) {
int lef = 0, rig = arr.length - 1;
if(args.length > 0) { lef = args[0]; rig = args[1]; }
cout.printf(" : ");
for( ; lef<=rig; lef++) {
cout.printf("[%s] ", args[lef]);
}
cout.printf("\n");
}
public static void main_init() {
try {
if (debug) {
cin = new BufferedReader(new InputStreamReader(
new FileInputStream(INPATH)));
} else {
cin = new BufferedReader(new InputStreamReader(System.in));
}
cout = new PrintWriter(new OutputStreamWriter(System.out));
// cout = new PrintWriter(OUTPATH);
tok = new StreamTokenizer(cin);
} catch (Exception e) {
e.printStackTrace();
}
}
public static String next_str() {
try {
tok.nextToken();
if (tok.ttype == StreamTokenizer.TT_EOF)
return null;
else if (tok.ttype == StreamTokenizer.TT_NUMBER) {
return String.valueOf((int)tok.nval);
} else if (tok.ttype == StreamTokenizer.TT_WORD) {
return tok.sval;
} else return null;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
public static int read_int() {
String tmp_next_str = next_str();
return null==tmp_next_str ? -1 : Integer.parseInt(tmp_next_str);
}
public static long read_long() { return Long.parseLong(next_str()); }
public static double read_double() { return Double.parseDouble(next_str()); }
public static BigInteger read_big() { return new BigInteger(next_str()); }
public static BigDecimal read_dec() { return new BigDecimal(next_str()); }
}