Leetcode2829. k-avoiding 数组的最小总和

Every day a Leetcode

题目来源:2829. k-avoiding 数组的最小总和

解法1:贪心 + 哈希

从 1 开始枚举数 x,如果 k - x 不在哈希表里,说明可以插入 k-avoiding 数组,sum 加上 x,向哈希表插入 x。

当哈希表中有 n 个元素时,退出,返回 sum。

代码:

c 复制代码
/*
 * @lc app=leetcode.cn id=2829 lang=cpp
 *
 * [2829] k-avoiding 数组的最小总和
 */

// @lc code=start

// 贪心 + 哈希

class Solution
{
public:
    int minimumSum(int n, int k)
    {
        unordered_set<int> visited;
        int sum = 0, count = 0;
        for (int x = 1; x <= 2 * n; x++)
        {
            if (!visited.count(k - x))
            {
                sum += x;
                count++;
                if (count == n)
                    break;
                visited.insert(x);
            }
        }
        return sum;
    }
};
// @lc code=end

结果:

复杂度分析:

时间复杂度:O(n)。

空间复杂度:O(n)。

解法2:数学

代码:

c 复制代码
// 数学

class Solution
{
public:
    int minimumSum(int n, int k)
    {
        int m = min(k / 2, n);
        return (m * (m + 1) + (k * 2 + n - m - 1) * (n - m)) / 2;
    }
};

结果:

复杂度分析:

时间复杂度:O(1)。

空间复杂度:O(1)。

相关推荐
所以遗憾是什么呢?2 小时前
【题解】Educational Codeforces Round 195 (Rated for Div. 2) ABCDE
c++·动态规划·acm·icpc·ccpc·xcpc·codeforecs
Lhan.zzZ4 小时前
Qt WebEngineView 在 Linux 上无法加载网页:从“看不见 HTML“到“禁用沙箱“
linux·c++·qt
sysu_chenxy5 小时前
二重循环输出二维图形
c++
Navigator_Z5 小时前
LeetCode //C - 1293. Shortest Path in a Grid with Obstacles Elimination
c语言·算法·leetcode
Nil2086 小时前
leetcode 64最小路径和
算法·leetcode·职场和发展
Nil2086 小时前
leetcode 72编辑距离
算法·leetcode·职场和发展
划破黑暗的第一缕曙光7 小时前
[C++]:2.类和对象(下)
c++·类和对象·对象·类
Nil2087 小时前
leetcode 136只出现一次的数字
leetcode·哈希算法·散列表
黎相思8 小时前
LRU Cache
c++·缓存
UIU1148 小时前
P1003 [NOIP 2011 提高组] 铺地毯
数据结构·c++·算法