资讯详情

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

📅 2026/10/19 15:44:31 | 华诺云谱 👁 阅读
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.
📝

华诺云谱内容团队

资深建站顾问 · 行业研究员

10年+企业数字化服务经验,专注智能建站、SEO优化与品牌营销,持续输出建站技巧、行业洞察与营销干货,已帮助5000+企业实现数字化增长。

你可能需要的服务

订阅华诺云谱资讯周报

每周一封,精选建站技巧、SEO与营销干货,直达邮箱。已有 8,000+ 企业主订阅,助你少走弯路。

↑