枚举算法-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;
    }
};
相关推荐
夜不会漫长1 小时前
C++:红黑树
数据结构·算法
文丑颜不良啊1 小时前
LeetCode1661~1680题目解析
java·leetcode
AI备案指南-满满2 小时前
算法备案审核不通过,一般是什么原因?
java·人工智能·算法·大模型备案·算法备案·大模型登记
Ramble_Naylor2 小时前
Rust深度解读:Send 与 Sync 的本质与线程安全边界
python·算法·rust
秋天的怀念_David2 小时前
算法一千零一夜 · 第二十三夜 电力民生写成的曲线
java·程序人生·算法
不一样的故事1262 小时前
NB/T 47013.8-2015 附录D 吸枪技术
人工智能·经验分享·算法
通问AI2 小时前
用 200 行 Python 给文档库做「上下文完整度」自检:四个可复算的检查项
算法
揽星河..3 小时前
【C语言】扫雷游戏
c语言·算法·游戏
丘山录3 小时前
本地部署 LongCat-2.5,要 7 台机器我只有 4 台
人工智能·算法
Allen_LVyingbo3 小时前
NVIDIA CUDA Tile 在医疗计算中的算子形式化、算法重构与内核实现
大数据·python·算法·重构·知识图谱·健康医疗·数据库架构