枚举算法-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;
    }
};
相关推荐
KoiHeng14 分钟前
排序算法(二)
算法·排序算法
源远流长jerry29 分钟前
C++、STL面试题总结(一)
c++·算法
穆霖祎2 小时前
数据结构(4)
数据结构
秋难降2 小时前
LeetCode——迭代遍历算法
数据结构·算法·排序算法
yanxing.D2 小时前
考研408_数据结构笔记(第四章 串)
数据结构·笔记·考研·算法
庸子2 小时前
云平台托管集群:EKS、GKE、AKS 深度解析与选型指南-第四章
算法·贪心算法
এ᭄画画的北北3 小时前
力扣-11.盛最多水的容器
算法·leetcode
啊阿狸不会拉杆3 小时前
《算法导论》第 7 章 - 快速排序
开发语言·数据结构·c++·算法·排序算法
John.Lewis3 小时前
C语言数据结构(4)单链表专题2.单链表的应用
c语言·数据结构·链表
冬夜戏雪3 小时前
java学习 73矩阵置零 54螺旋矩阵 148排序链表
数据结构·算法·矩阵