DeepSeek LeetCode 668. Kth Smallest Number in Multiplication Table Java Implement

发布时间:2026/10/19 15:45:08
DeepSeek    LeetCode 668. Kth Smallest Number in Multiplication Table Java Implement Here is the Java implementation for LeetCode 668. Kth Smallest Number in Multiplication Table, using the standard Binary Search on Value approach.Core IdeaThe multiplication table is far too large to materialize (up to 9 \times 10^8 cells). Instead of finding the k-th number directly, we solve a reverse problem:Given a value x, how many entries in the table are less than or equal to x?This count is easy to compute:· In the i-th row, the entries are i1, i2, …, i*n. The number of entries ≤ x is simply min(x / i, n).· Summing this over all rows gives count(x).The function count(x) is monotonically non-decreasing as x increases. Therefore, we can binary search for the smallest x such that count(x) k. This x is guaranteed to be the k-th smallest number in the table.Java Implementation (Standard Binary Search)classSolution{publicintfindKthNumber(intm,intn,intk){intlo1;inthim*n;while(lohi){intmidlo(hi-lo)/2;intcount0;// Count how many entries are midfor(inti1;im;i){countMath.min(mid/i,n);// Early exit if we already have enoughif(countk)break;}if(countk){himid;// mid could be the answer; search left}else{lomid1;// mid is too small; search right}}returnlo;}}This code is adapted from the standard solution provided in the LeetCode community.Complexity AnalysisMetric Complexity ExplanationTime O(m \log(m \cdot n)) Binary search takes O(\log(m \cdot n)) iterations, and each iteration scans up to m rows.Space O(1) Only a few integer variables are used.Possible Optimization (Optional)The standard loop iterates over all m rows. However, for rows where i \le \lfloor mid / n \rfloor, every entry in that row is \le mid. This creates a “saturated block” of rows where count is simply n per row.We can sum these rows in O(1) using multiplication, and only loop over the remaining rows. This reduces the inner loop from O(m) to O(\sqrt{mid}), bringing the total time down to O(\sqrt{m \cdot n} \log(m \cdot n)). For the given constraints, the standard version is already sufficient.Key Note: Use long for the count variable if you are concerned about integer overflow, although for m, n ≤ 30,000, the maximum total count (9 × 10^8) still fits within a 32-bit signed integer. The mid variable also fits in int.

关于本文作者

来自尧图内容编辑团队

尧图内容编辑团队 内容团队

尧图内容编辑团队

本文由尧图网络内容编辑团队执笔。团队由资深项目经理、前端工程师与设计师组成,所有内容均来自亲手交付的真实项目,先讲清问题、再给出可落地的解法。尧图深耕北京网站建设十年,服务过京华建材集团、智造科技等各行业客户,把一线经验沉淀为可复用的行业观察。

  • 十年建站经验,覆盖建材、制造、服务、文创等
  • 项目经理把关选题与事实准确性
  • 工程师与设计师联合撰写专业细节
  • 统一编辑规范,保证文风与排版一致
  • 每月复盘转化数据,迭代选题方向

延伸阅读

相关资讯与近期热门内容

深度阅读推荐

建站决策前值得细读的三篇

网站改版的5个关键决策
2024-08-12

网站改版的5个关键决策

什么时候该改版、改到什么程度、如何避免流量掉光,京华建材集团改版复盘给出答案。

获取专属建站方案

看完文章,把您的行业与预算告诉我们,免费获取一份量身定制的官网建设方案与报价。

立即免费咨询