leetcode一周汇总(1)

本周心得

  1. vector中,字符串的sort()排序问题(按顺序以字母表比较,前一位优先级高:abc < acb < bca)
  2. 数组中的排序sort问题:(sort函数作用范围为 [begin, end) ,不包含最后一位 )
    静态数组:int a[10] = { 9, 0, 1, 2, 3, 7, 4, 5, 8, 6 }; sort(a, a +10);
    (注意加的是长度,加到数组末尾的下一位)
    vector: sort(heights.begin(), heights.end());
    (vector中的end()代表的是最后一位数的下一位)
  3. string.substr(int start_index, int length)的用法:
    两个参数时,第一个是起始位置,第二个是子串长度 eg: substr(0,5)获得字符串s中 从第0位开始的长度为5的字符串
    一个参数时默认从指定开始位置到尾 eg: substr(1) ) 获得字符串s中 从第1位开始的到结尾的字符串
  4. char字符串数组是以 ‘\0’ 为结尾的,但是string 是一个类,结尾没有字符’\0’
  5. C++删除string最后一个字符的几种方法:
    - str.pop_back();
    - str.erase(str.end() - 1);
    - str = str.substr(0, str.length() - 1);
  6. string.erase()的用法
    (1)erase(pos,n); 删除从pos开始的n个字符,比如erase(0,1)就是删除第一个字符
    (2) erase(pos); 删除从pos开始的到结尾的字符,比如erase(0)就是删除第一个字符后所有元素
    (3)erase(first, last);删除从first到 last之间(last不会删除)的字符(first和last都是迭代器)且返回last迭代器
    (4)erase(first);删除pos处的一个字符(first是迭代器)且返回删除元素的下一个迭代器
  7. 寻找质数的算法:厄拉多塞筛法(精简高效寻找每个数字的倍数的算法)
  8. 关于字符的转码问题:
    char to int : 一般使用 char - ‘0’
    int to cha : 一般使用 int + ‘0’
    (注意: char(4) : 将4转变为’\4’而不是 字符 ‘4’,int(‘a’): 将字符串转换为对应的ASCII码
    因此涉及int/char转换问题最好使用 ±’0’,其中 (char) 绝对不要使用!)
  9. 判断vector中有无某值:(STL)find
    vector<int>::iterator it = find(arr.begin(),arr.end(),res);
    if( it != arr.end() ) //值在数组中
    if( it == arr.end() ) //值不在数组中
  10. 弗洛伊德循环查找算法 (快慢指针法/龟兔指针法)
    原理:兔子每走一步就向乌龟靠近一个节点(在它们的移动方向上)。若有则必相遇
    用于判断一个链表是否有循环

594,最长和谐子序列

class Solution {
   
public:
    int findLHS(vector<int>& nums) {
   
        unordered_map<int, int> hash;
        for(auto num:nums)
            hash[num]++;

        int res = 0;
        for(auto i : hash)
            //if(hash[i.first+1] != 0)
            if(hash.count(i.first+1))
                res = max(res, i.second + hash[i.first + 1]);

        return res;
    }
};

1160, 拼写单词

class Solution {
   
public:
    int countCharacters(vector<string>& words, string chars) {
   
        int res=0;
        int ch[26]={
   0};
        for(char c:chars)
            ch[c-'a']++;
        
        for(string word:words)
        {
   
            int wd[26]={
   0};
            for(char c:word)
                wd[c-'a']++;
            res+=word.size();
            for(char c:word)
            {
   
                if(ch[c-'a']<wd[c-'a'])
                {
   
                    res-=word.size();
                    break;
                }    
            }
        }
        return res;
    }
};

572, 分糖果

class Solution {
   
public:
    int distributeCandies(vector<int>& candies) {
   
        int nums = candies
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值