leetcode题解——hot100easy题

leetcode题解——hot100easy题

枚举

LCP33.蓄水

在这里插入图片描述
找到省级水桶的蓄水操作的制约关系,蓄水的次数有上限,可以枚举每一次蓄水,从而计算出相应的升级次数。需要注意边界。

class Solution {
   
public:
    int storeWater(vector<int>& bucket, vector<int>& vat) {
   
        int Maxk=*max_element(vat.begin(),vat.end());
        if(Maxk==0)return 0;
        int res=1000000;
        for(int i=1;i<=Maxk;i++){
   
            int up=0;
            for(int j=0;j<vat.size();j++){
   
                up+=max(vat[j]/i+(vat[j]%i!=0)-bucket[j],0);
            }
            res=min(res,i+up);
        }
        return res;

    }
};

数据结构:栈、哈希、链表

LCP1.两数之和

在这里插入图片描述
和为target的两个数为一对,使用hashmap,存放已遍历的nums[i]和其下标。遍历时,判断当前数在hashmap中是否有配对,如果有则返回下标,如果没有则加入到hashmap中。

class Solution {
   
public:
    vector<int> twoSum(vector<int>& nums, int target) {
   
        unordered_map<int,int> hash;
        for(int i=0;i<nums.size();i++){
   
            auto it=hash.find(target-nums[i]);
            if(it!=hash.end()){
   
                return {
   it->second,i};
            }
            hash[nums[i]]=i;
        }
        return {
   };  
    }
};

LCP20.有效的括号

在这里插入图片描述
使用栈来判断是否匹配,栈底存放’#'方便遍历进行比较。ASCII码相差1或者2可作为判断条件。

class Solution {
   
public:
    bool isValid(string s) {
   
        stack<char> st;
        st.push('#');
        for(int i=0;i<s.length();i++){
   
            if(s[i]-st.top()==1||s[i]-st.top()==2){
   
                st.pop();
            }
            else
            st.push(s[i]);

        }
        if(st.top()=='#')return true;
        else return false;

    }
};

LCP141.环形链表

在这里插入图片描述
链表经典的双指针算法。

class Solution {
   
public:
    bool hasCycle(ListNode *head) {
   
        if(head==NULL
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值