枚举算法-day1

1.两数之和

题目

解析

  • 枚举右指针 j,同时记录进哈希表,对于遍历的 numsj,寻找哈希表中是否有 target - numsj;
  • 与双指针算法的不同点在于,本题需要记录下标,而双指针算法需要有序;
  • 时间复杂度:O(n);空间复杂度:O(n);空间换时间

代码

cpp 复制代码
class Solution {
public:
    vector<int> twoSum(vector<int>& nums, int target) {
        // 时间复杂度:O(n)
        // 空间复杂度:O(n)

        unordered_map<int,int> idx;

        for(int j = 0; ;j ++){
            auto it = idx.find(target - nums[j]);
            if(it != idx.end()) { // 找到了
                return {it -> second,j};
            }

            idx[nums[j]] = j;// 保存 nums[j] 和 j
        }
    }
};

2.好数对的数目

题目

解析

  • 同理可得

代码

cpp 复制代码
class Solution {
public:
    int numIdenticalPairs(vector<int>& nums) {
        // 时间复杂度:O(n)
        // 空间复杂度:O(n)

        int res = 0;
        unordered_map<int,int> cnt;

        for(int j = 0;j < nums.size();j ++){
            if(cnt[nums[j]]) res += cnt[nums[j]];
            cnt[nums[j]] ++;
        }

        return res;
    }
};

3.可互换矩形的组数

题目

解析

  • 同理可得,注意计算要 * 1.0;

代码

cpp 复制代码
class Solution {
public:
    long long interchangeableRectangles(vector<vector<int>>& rectangles) {
        // 时间复杂度:O(n)
        // 空间复杂度:O(n)

        long long ans = 0;
        unordered_map<double,int> cnt;

        for(int j = 0;j < rectangles.size();j ++){
            double x = rectangles[j][1] * 1.0 / rectangles[j][0];

            if(cnt[x]) ans += cnt[x];
            cnt[x] ++;
        }

        return ans;
    }
};
相关推荐
tachibana212 分钟前
Go 语言的 Map 是否是并发安全的?
开发语言·数据结构·后端·golang·go·语言
行者全栈架构师25 分钟前
【鸿蒙心迹】冷启动从 2.8s 优化到 0.9s——耗时拆解与数据对比实战(HarmonyOS 7.x)
前端·算法·架构
LXY_BUAA28 分钟前
《嵌入式操作系统》_framebuffer驱动_20261008
linux·运维·算法
Logic10131 分钟前
C语言/数据结构字符串题解:统计“chhc“子串权值总和——一次遍历模式匹配
c语言·数据结构·算法·字符串·时间复杂度·空间复杂度·ascii
java_nnnn31 分钟前
LeetCode刷题滑动窗口(最大连续1的个数三+将x减到0的最小操作数)Java
算法·leetcode·职场和发展
bnmoel1 小时前
C++ 基础入门篇(六)类和对象-第三篇:运算符重载
开发语言·c++·算法·语法·运算符重载
wuyk5551 小时前
28 搜索引擎索引更新:从 LSM Tree 到布隆过滤器的高效实现
stm32·单片机·嵌入式硬件·算法
我命由我123451 小时前
LRU 缓存淘汰策略
数据结构·redis·学习·mysql·算法·缓存·学习方法
垆边人似月.1 小时前
华为题:合并区间
数据结构·c++·算法
垆边人似月.2 小时前
华为题:滑动窗口最大值
数据结构·c++·算法