力扣第十二天

这篇博客记录了作者在LeetCode第十二天的学习内容,主要涉及两个问题:49. Group Anagrams 和 43. Multiply Strings。对于Group Anagrams,作者提供了两种解决方案,利用unordered_map进行字母重新排列的分组;Multiply Strings问题中,作者探讨了如何不借助内置库或直接转换整数来计算两个字符串表示的非负整数的乘积。
摘要由CSDN通过智能技术生成

session Ⅰ Algorithm

problem Ⅰ

49. Group Anagrams
Given an array of strings strs, group the anagrams together. You can return the answer in any order.

An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.

Example 1:

Input: strs = [“eat”,“tea”,“tan”,“ate”,“nat”,“bat”]
Output: [[“bat”],[“nat”,“tan”],[“ate”,“eat”,“tea”]]

Example 2:

Input: strs = [""]
Output: [[""]]

Example 3:

Input: strs = [“a”]
Output: [[“a”]]

my solution Ⅰ Time Limit Exceeded

class Solution {
   
public:
    bool match(vector<int>& word1, vector<int>& word2){
   
        for(int i=0; i<26; i++)
            if(word1[i] != word2[i])return false;
        return true;
    }
    
    vector<vector<string>> groupAnagrams(vector<string>& strs) {
   
        int len = strs.size();
        vector<int> record(len, 0);
        vector<vector<string>> res;
        for(int i=0; i<len; i++){
   
            if(record[i]==0){
   
                vector<string> tmp;
                tmp.push_back(strs[i]);
                record[i]=1;
                if(i==len-1){
   
                    res.push_back(tmp);
                  
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
力扣题礼盒的最大天密度问题可以转化为一个函数 f(x) 的形式,其中 f(x) 表示 "礼盒中最大天数不超过 x" 这个条件下的天密度。 具体地,对于一个给定的天数 x,我们可以使用贪心算法来判断在不超过 x 的情况下,最多能拿到多少天的礼盒。假设当前已经拿到了 k 个礼盒,其天数分别为 d1, d2, ..., dk,且满足 d1 <= d2 <= ... <= dk。此时,我们可以从剩余的礼盒中选择一个最小的天数大于 dk 的礼盒,加入到已拿到的礼盒中,直到不能再加入礼盒为止。这个贪心算法的时间复杂度是 O(nlogn),其中 n 是礼盒的数量。 对于一个给定的天数 x,如果能拿到的最多天数不超过 x,则 f(x) 为 true,否则 f(x) 为 false。这个函数的曲线是一个阶梯状的函数,如下图所示: ``` | | | | | | | | | | |___|___|___|___ x1 x2 x3 x4 ``` 其中,每个竖直的线段表示一个礼盒,x1、x2、x3、x4 分别表示四个礼盒的最大天数,每个水平的线段表示函数值为 true 的区间。例如,当 x 取值在 [x3, x4] 区间内时,f(x) 的值都为 true,因为在不超过 x3 的情况下,最多能拿到的天数为 3+4+4=11,不超过 x4 的限制。 我们要找到的最大的天密度,就是最后一个函数值为 true 的点所对应的 x 值,即 x4。这个问题可以通过二分查找法解决,每次取中间值,判断中间值是否满足条件,然后不断缩小搜索区间,最终找到最大的 x 值。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值