力扣学习笔记——49. 字母异位词分组

49. 字母异位词分组

https://leetcode.cn/problems/group-anagrams/?envType=study-plan-v2&envId=top-100-liked
给你一个字符串数组,请你将 字母异位词 组合在一起。可以按任意顺序返回结果列表。

字母异位词 是由重新排列源单词的所有字母得到的一个新单词。

示例 1:

输入: strs = [“eat”, “tea”, “tan”, “ate”, “nat”, “bat”]
输出: [[“bat”],[“nat”,“tan”],[“ate”,“eat”,“tea”]]
示例 2:

输入: strs = [“”]
输出: [[“”]]
示例 3:

输入: strs = [“a”]
输出: [[“a”]]

这个首先是排序,排序后用哈希表将结果和排序的字符串作为键对应起来

知识点

C++ 排序的库函数使用

在 C++ 中,你可以使用 头文件中的库函数来进行排序。以下是一些常用的排序函数:

std::sort():对容器或指定范围内的元素进行排序,默认按升序排序。注意:std::sort(),不光能对数字进行排序,还可以对字母进行排序。

#include 
#include 

int main() {
    std::vector<int> nums = {5, 2, 8, 1, 9};

    std::sort(nums.begin(), nums.end());

    // 输出排序后的结果
    for (const auto& num : nums) {
        std::cout << num << " ";
    }

    return 0;
}

输出结果:1 2 5 8 9

std::stable_sort():与 std::sort() 类似,但保持相等元素的相对顺序不变。

#include 
#include 

int main() {
    std::vector<int> nums = {5, 2, 8, 1, 9};

    std::stable_sort(nums.begin(), nums.end());

    // 输出排序后的结果
    for (const auto& num : nums) {
        std::cout << num << " ";
    }

    return 0;
}

输出结果:1 2 5 8 9

自定义排序:你还可以使用自定义的比较函数来进行排序,例如按照特定的条件进行排序。

#include 
#include 

bool customCompare(int a, int b) {
    // 自定义排序规则:按照奇偶性进行排序
    if (a % 2 == 0 && b % 2 != 0) {
        return false;  // a 在 b 前面
    } else if (a % 2 != 0 && b % 2 == 0) {
        return true;   // a 在 b 后面
    } else {
        return a < b;  // 其他情况按照升序排序
    }
}

int main() {
    std::vector<int> nums = {5, 2, 8, 1, 9};

    std::sort(nums.begin(), nums.end(), customCompare);

    // 输出排序后的结果
    for (const auto& num : nums) {
        std::cout << num << " ";
    }

    return 0;
}

输出结果:1 5 9 2 8

这些是一些常用的排序函数和用法。你可以根据实际需求选择适合的排序函数,并根据需要编写自定义的比较函数

如何用for循环如何拿到std::unordered_map的键和值

如果你想使用 for 循环来获取 std::unordered_map 的键和值,你可以使用迭代器来遍历容器。每个迭代器指向一个键值对,你可以通过解引用迭代器来获取键和值。

以下是一个示例代码,展示了如何使用 for 循环遍历 std::unordered_map 并获取键和值:

#include 
#include 

int main() {
    std::unordered_map<int, std::string> myMap = {{1, "apple"}, {2, "banana"}, {3, "orange"}};

    // 遍历 unordered_map
    for (auto it = myMap.begin(); it != myMap.end(); ++it) {
        int key = it->first;
        std::string value = it->second;
        std::cout << "Key: " << key << ", Value: " << value << std::endl;
    }
    return 0;
}

在上面的示例中,我们使用 auto 关键字来推导出迭代器的类型。然后,使用 begin() 函数获取指向第一个键值对的迭代器,使用 end() 函数获取指向最后一个键值对之后位置的迭代器。在循环中,通过解引用迭代器来获取当前键值对的键和值。

输出结果将是:

Key: 1, Value: apple
Key: 2, Value: banana
Key: 3, Value: orange

你可以根据实际需要修改键和值的类型,并在循环中执行适当的操作

你可能感兴趣的:(leetcode,leetcode,学习,笔记)