• [LeetCode] 2310. Sum of Numbers With Units Digit K


    Given two integers num and k, consider a set of positive integers with the following properties:

    • The units digit of each integer is k.
    • The sum of the integers is num.

    Return the minimum possible size of such a set, or -1 if no such set exists.

    Note:

    • The set can contain multiple instances of the same integer, and the sum of an empty set is considered 0.
    • The units digit of a number is the rightmost digit of the number.

    Example 1:

    Input: num = 58, k = 9
    Output: 2
    Explanation:
    One valid set is [9,49], as the sum is 58 and each integer has a units digit of 9.
    Another valid set is [19,39].
    It can be shown that 2 is the minimum possible size of a valid set.
    

    Example 2:

    Input: num = 37, k = 2
    Output: -1
    Explanation: It is not possible to obtain a sum of 37 using only integers that have a units digit of 2.
    

    Example 3:

    Input: num = 0, k = 7
    Output: 0
    Explanation: The sum of an empty set is considered 0.

    Constraints:

    • 0 <= num <= 3000
    • 0 <= k <= 9

    个位数字为 K 的整数之和。

    给你两个整数 num 和 k ,考虑具有以下属性的正整数多重集:

    每个整数个位数字都是 k 。
    所有整数之和是 num 。
    返回该多重集的最小大小,如果不存在这样的多重集,返回 -1 。

    注意:

    多重集与集合类似,但多重集可以包含多个同一整数,空多重集的和为 0 。
    个位数字 是数字最右边的数位。

    来源:力扣(LeetCode)
    链接:https://leetcode.cn/problems/sum-of-numbers-with-units-digit-k
    著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

    这是一道数学题。题目给了两个参数,num 和 k,问的是是否存在一些数字,他们的个位数都是 k,且他们的和等于 num。

    这道题不难,但是紧张的时候思路容易乱。周赛的时候我就没想清楚,但是事后却可以写出来。

    首先有几个 corner case。如果 k == 0,那么 num 的最后一位也必须是 0,否则就返回 -1。如果 num == 0,k == 0(参见例子三)。

    接下来是一般的情形。对于任何一个 num 而言,能否找到若干个数字满足题意,其实只需要看这若干个数字的最后一位的加和是否等于 num 的最后一位。所以我们设一个变量 i ,让 i 遍历 1 到 9,来看看是否存在 i 个数字,他们的加和的最后一位等于 num 的最后一位,如果存在那一定就是有解的。

    时间O(1) - 至多尝试九次

    空间O(1)

    Java实现

     1 class Solution {
     2     public int minimumNumbers(int num, int k) {
     3         // corner case
     4         if (num == 0) {
     5             return 0;
     6         }
     7         if (k == 0) {
     8             if (num % 10 == 0) {
     9                 return 1;
    10             } else {
    11                 return -1;
    12             }
    13         }
    14 
    15         // normal case
    16         int lastDigit = num % 10;
    17         for (int i = 1; i <= num / k; i++) {
    18             if ((i * k) % 10 == lastDigit) {
    19                 return i;
    20             }
    21         }
    22         return -1;
    23     }
    24 }

    LeetCode 题目总结

  • 相关阅读:
    docker
    电商项目查询模块思路(ElasticSearch)
    Elasticsearch简单的使用步骤以及查询模块的实现
    string常用方法
    通用 Mapper常用方法
    Linux防火墙操作
    简单SQL语句
    InnoDB基础
    浅析索引
    python爬虫面试题集锦及答案
  • 原文地址:https://www.cnblogs.com/cnoodle/p/16390383.html
Copyright © 2020-2023  润新知