博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
668. Kth Smallest Number in Multiplication Table
阅读量:4923 次
发布时间:2019-06-11

本文共 1616 字,大约阅读时间需要 5 分钟。

Nearly every one have used the . But could you find out the k-th smallest number quickly from the multiplication table?

Given the height m and the length n of a m * n Multiplication Table, and a positive integer k, you need to return the k-th smallest number in this table.

Example 1:

Input: m = 3, n = 3, k = 5Output: Explanation: The Multiplication Table:1	2	32	4	63	6	9The 5-th smallest number is 3 (1, 2, 2, 3, 3).

 

Example 2:

Input: m = 2, n = 3, k = 6Output: Explanation: The Multiplication Table:1	2	32	4	6The 6-th smallest number is 6 (1, 2, 2, 3, 4, 6).

 

Note:

  1. The m and n will be in the range [1, 30000].
  2. The k will be in the range [1, m * n]

 

Approach: #1 Bianry Serach
class Solution {public:    int findKthNumber(int m, int n, int k) {        int l = 1, r = m * n;        while (l < r) {            int mid = l + (r - l) / 2;            if (!bignums(mid, m, n, k)) l = mid + 1;            else r = mid;        }        return l;    }private:    bool bignums(int x, int m, int n, int k) {        int count = 0;        for (int i = 1; i <= m; ++i) {            count += min(x/i, n);        }        return count >= k;    }};

Runtime: 24 ms, faster than 12.44% of C++ online submissions for Kth Smallest Number in Multiplication Table. 

 

Analysis:

for (int i = 1; i <= m; ++i) {            count += min(x/i, n);        }

we use this code to find the numbers of elements less than k , in the row of i  the elements are i, 2*i, 3*i, 4*i, 5*i ........ the largest number is k * i <= x, so the numbers of elements which is less than or equal to x is k = x / i;           

 

转载于:https://www.cnblogs.com/ruruozhenhao/p/9930494.html

你可能感兴趣的文章
磁盘文件系统损坏的数据找回办法
查看>>
Learning OpenCV Lecture 6 (Extracting Lines,Contours, and Components)
查看>>
【转】数据结构和算法 — 链表结构
查看>>
帝国ECMS静态生成为一行代码/静态页面打乱教程
查看>>
IE 问题集合
查看>>
anu - browser
查看>>
[转] Fast Fourier transform — FFT (一篇不错的关于一维FFT原理及CPU实现的文章)
查看>>
Java 修饰符
查看>>
Oracle 数据库基础——安装
查看>>
【转载】在Linux中使用VS Code编译调试C++项目
查看>>
分享一个MySQL分库分表备份脚本(原)
查看>>
caffe parse_log.sh
查看>>
C#中利用iTextSharp开发二维码防伪标签(1)
查看>>
【AC自动机】[UESTC 554][USACO 2012]Video Game Combos
查看>>
C# WInform 界面左导航菜单
查看>>
Java 基础之详解 Java IO
查看>>
关于开源精神
查看>>
Stand-alone remote client demo
查看>>
【Alpha】Daily Scrum Meeting——blog3
查看>>
IMetadataAware接口的特性定制Model元数据
查看>>