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)。

相关推荐
盐焗鹌鹑蛋3 小时前
【C++】AVL树
c++
杜子不疼.3 小时前
【C++】继承—C++的秘密武器,get父类的智慧
开发语言·c++
ShineWinsu4 小时前
对于Linux:基于UDP实现简单聊天室功能
linux·c++·面试·udp·笔试·进程·简单聊天室
chase_my_dream4 小时前
2D-SLAM 真实数据处理与多传感器工程落地:时间同步、异常过滤、标定对齐和系统调试
c++·人工智能·2d-slam
凌波粒4 小时前
LeetCode--53. 最大子序和(贪心算法)
算法·leetcode·贪心算法
金銀銅鐵4 小时前
[Python] 借助图形化界面探索模n运算的规律
python·数学
Hesionberger4 小时前
快速求解完全平方数的最少数量
开发语言·数据结构·python·算法·leetcode·c#
c238564 小时前
《序列 DP:C++ 中的“最长”套路与编辑距离》
c++·算法·动态规划
aqiu1111114 小时前
【算法日记 19】LeetCode 1. 两数之和:梦开始的地方,哈希表的降维打击
算法·leetcode·职场和发展
鱼子星_4 小时前
【C++】类和对象(下)——初始化列表,类型转换,static成员,友元,内部类,匿名对象,编译器的优化拓展
c语言·c++·笔记