枚举算法-day1

1.两数之和

题目

解析

  • 枚举右指针 j,同时记录进哈希表,对于遍历的 nums[j],寻找哈希表中是否有 target - nums[j];
  • 与双指针算法的不同点在于,本题需要记录下标,而双指针算法需要有序;
  • 时间复杂度: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;
    }
};
相关推荐
多米Domi01139 分钟前
0x3f 第48天 面向实习的八股背诵第五天 + 堆一题 背了JUC的题,java.util.Concurrency
开发语言·数据结构·python·算法·leetcode·面试
2301_8223776540 分钟前
模板元编程调试方法
开发语言·c++·算法
故以往之不谏1 小时前
函数--值传递
开发语言·数据结构·c++·算法·学习方法
渐暖°1 小时前
【leetcode算法从入门到精通】5. 最长回文子串
vscode·算法·leetcode
今天_也很困1 小时前
LeetCode热题100-560. 和为 K 的子数组
java·算法·leetcode
v_for_van1 小时前
力扣刷题记录2(无算法背景,纯C语言)
c语言·算法·leetcode
2301_811232981 小时前
低延迟系统C++优化
开发语言·c++·算法
alphaTao1 小时前
LeetCode 每日一题 2026/1/26-2026/2/1
算法·leetcode
向哆哆2 小时前
构建跨端健身俱乐部管理系统:Flutter × OpenHarmony 的数据结构与设计解析
数据结构·flutter·鸿蒙·openharmony·开源鸿蒙
Christo32 小时前
TFS-2026《Fuzzy Multi-Subspace Clustering 》
人工智能·算法·机器学习·数据挖掘