算法基础

数组与字符串

leetcode 15 三数之和

在排序数组中使用左右指针,可以根据左右大小逼近某值

leetcode 3 无重复字符的最长子串

O(n) 使用hash记录前一个子串的重复情况与坐标,若char的字符与前一个子串的某字符相同,那么从此相同字符的后一个开始
map

leetcode 5 最长回文子串

依次遍历整个字符串,从mid开始向左右开始辐射,注意此时要分两种情况,一种为偶对称,一种为奇对称
range * 2 + 2; // a c b b c a 中间是偶数个,因此加2
range * 2 + 1; // a c b c a 中间是奇数,因此加1

leetcode 334 递增的三元子序列

for (int i = 0; i < nums.size(); i++)
{
    if (nums[i] <= minOne) minOne = nums[i];
    else if (nums[i] <= minTwo) minTwo = nums[i];
    else return true;
}

leetcode 242 有效的字母异位词

两次遍历,第一次将次数计入hash表中,第二次将次数从hash表中删除,最后再遍历hash表

leetcode 8 字符串转整数

对于空格和正负号的处理放在最前面做,按照顺序往下筛选

leetcode 28 实现strStr()

kmp算法

链表

leetcode 234 回文链表

1.找到中点

while (fast.next != null && fast.next.next != null)
{
    fast = fast.next.next;
    slow = slow.next;
} 
// 1 2 3 slow 指向2 
// 1 2 3 4 slow 指向2

2.
法1:借助hash,前一半与后一半刚好抵消
法2:反转链表后再比较

leetcode 141 环形链表

使用快慢指针

leetcode 2 两数相加

每位相加后的值都存在一个变量上

leetcode 328 奇偶链表

两个指针分别往后next

while (even != nullptr && even->next != nullptr)
{
    odd->next = even->next;
    odd = odd->next;
    even->next = odd->next;
    even = even->next;
}

leetcode 160 相交链表

a + c + b = b + c + a
1号指针从a出发,遍历完a和c之后开始遍历b
2号指针从b出发,遍历完b和c之后开始遍历a
1和2最终会相遇,相遇即为所求节点

leetcode 23 合并k个排序链表

法1:使用最小堆来记录每个链表的头节点,就可以快速选出下一个节点
法2:二分法

leetcode 148 链表排序

使用二分法,小链表使用链表的排序做,上面由求中点的方法进行分割

    ListNode* sortList(ListNode* head) {
        while (fast->next != NULL && fast->next->next != NULL) {
            slow = slow->next;
            fast = fast->next->next;
        }
        return mergeList(sortList(head), sortList(slow));
    }

leetcode 138 复制带随机指针的链表

首先将整个链表复制下来,复制过程中使用map记录新旧节点之间的对应关系
最后复制随机指针,此时就可以直接通过旧链表和map表直接找到新的节点

leetcode 104 二叉树最大深度

leetcode 110 平衡二叉树

    bool isBalanced(TreeNode* root) 
    {
        if (checkDepth(root) == -1) return false;
        else return true;
    }

    int checkDepth(TreeNode *root)
    {
        if (root == nullptr) return 0;
        int left = checkDepth(root->left);
        if (left == -1) return -1;

        int right = checkDepth(root->right);
        if (right == -1) return -1;

        if (std::abs(left - right) > 1) return -1;
        else return std::max(right, left) + 1;
    }

排序与搜索

动态规划

从上往下分析问题(动态转移方程),从下往上求解问题(子问题最优解逐渐保存下来)

回溯

设计

数学

你可能感兴趣的:(算法基础)