LeetCode 热题 hot 100 题解

LeetCode hot 100题解

1.两数之和

给定一个整数数组 nums 和一个整数目标值 target,请你在该数组中找出 和为目标值 target 的那 两个 整数,并返回它们的数组下标。

你可以假设每种输入只会对应一个答案。但是,数组中同一个元素在答案里不能重复出现。

你可以按任意顺序返回答案。

在这里插入图片描述

算法1 暴力枚举

暴力枚举方法很简单:两重循环枚举下标 i,j,然后判断 nums[i]+nums[j] 是否等于 target
时间复杂度:由于有两重循环,所以复杂度是 O(n2)

class Solution {
public:
    vector<int> twoSum(vector<int>& nums, int target) {
        for(int i = 0; i < nums.size(); i++)
        {
            for(int j = i + 1; j < nums.size(); j++)
            {
                if(nums[i] + nums[j] == target) return {i, j};
            }
        }
        return {};
    }
};
算法2 哈希表

使用C++中的哈希表——unordered_map<int, int> hash进行优化。

循环一遍 nums 数组,在每步循环中我们做两件事:

  1. 判断 target−nums[i] 是否在哈希表中;

  2. nums[i] 插入哈希表中

解释:由于数据保证有且仅有一组解,假设是 [i, j] (i < j) ,则我们循环到 j 时,nums[i] 一定在哈希表中,且有 nums[i] + nums[j] == target, 所以我们一定可以找到解。
时间复杂度:由于只扫描一遍,且哈希表的插入和查询操作的复杂度是 O(1),所以总时间复杂度是 O(n).

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

2.两数相加

image-20220805220647813
在这里插入图片描述

算法 模拟

数字由链表存储,类似高精度加法,从个位开始模拟加法过程,用t存进位。

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
    ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
        //定义一个新列表,pre指向头结点,cur指向当前加数位置
        auto pre = new ListNode(-1), cur = pre;
        int t = 0;
        while(l1 || l2 || t)//t放在while里,最后一位(最高位)有进位时的特判不用放下面
        {
            if(l1) t += l1->val, l1 = l1->next;
            if(l2) t += l2->val, l2 = l2->next;
            cur->next = new ListNode(t % 10);
            cur = cur->next;
            t /= 10;
        }
        return pre->next;
    }
};

3.无重复字符的最长字串

image-20220806193524951

在这里插入图片描述

算法 双指针扫描

定义两个指针 i,j(j <= i),表示当前扫描到的字串是 [j, i] 闭区间,维护一个“滑动窗口”。过程中用一个哈希表(序列是数字的话数组也行)表示 [j, i] 中每个字符出现的次数。

双指针算法思想,先想暴力做法:遍历i,i在每个位置上时j从左端开始遍历,记录每个i位置的最长字串。然后想双指针优化:j可以不用每次回到开头,一直向右移动(见代码)。

复杂度分析:由于 i,j 均最多增加n次,且哈希表的插入和更新操作的复杂度都是 O(1),因此,总时间复杂度 是O(n).

class Solution {
public:
    int lengthOfLongestSubstring(string s) {
        unordered_map<char, int> hash;
        int res = 0;
        for(int i = 0, j = 0; i < s.size(); i++)
        {
            hash[s[i]]++;
            //目前段无重复,新进来的数有重复,一定是新进来的数跟之前数重复
            while(hash[s[i]] > 1)
            {	//j会一直向右移(不左移)直到无重复
                hash[s[j]]--;
                j++;
            }
            res = max(res, i - j + 1);
        }
        return res;
    }
};

4.寻找两个正序数组的中位数

在这里插入图片描述
在这里插入图片描述

算法 递归

原问题难以直接递归求解,所以我们先考虑这样一个问题:

在两个有序数组中,找出第k小的数。

如果该问题可以解决,那么第 (n + m) / 2 小的数就是我们要求的中位数。

首先我们给出 find 函数的参数含义:表示从 nums1[i : nums1.size() - 1]nums2[j : nums2.size() - 1] 这两个切片中找到第 k 小的数字。假设 nums1nums2 的切片元素个数分别为 len1len2 ,为了方便讨论,我们定义为 len1 < len2

先从简单情况入手,假设 m, n ≥ k / 2 ,我们先从 nums1nums2 中各取前 k / 2 个元素,令 si = i + k / 2, sj = j + k / 2 ,得到切片 nums1[i : si - 1]nums2[j : sj - 1]

  • 如果 nums1[si − 1] <= nums2[sj − 1],则说明 nums2 中取的元素过多,nums1 中取的元素过少;因此 nums1 中的前 k / 2 个元素一定都小于等于第 k 小的数,所以我们可以先删除(不管)这部分数,将问题递归成在剩下的数中找第 k − ⌊k / 2⌋ 小的数。
  • 如果 nums1[k / 2 − 1 ] > nums2[k / 2 − 1],同理可说明 nums2 中的前 k / 2 个元素一定都小于等于第 k 小的数,类似可将问题的规模减少一半。

然后考虑边界情况,如果 m < k / 2,则我们从 nums1 中取出全部的 m 个元素,从 nums2 中取 k / 2 个元素(由于 k = (n + m) / 2,因此 m, n 不可能同时小于 k / 2):

  • 如果 nums1[si − 1] ≤ nums2[sj − 1],则 nums1 中的所有元素一定都小于等于第 k 小的数,因此第 k 小的数是 nums2[sj + k − 1]

  • 如果 nums1[si − 1] > nums2[sj − 1] 同上,即 nums2 中的前 k / 2 个元素一定都小于等于第 k 小的数,我们可以将问题递归成在剩下的数中找第 k − ⌊k / 2⌋ 小的数。

时间复杂度分析:k = (m + n) / 2 ,且每次递归 k 的规模都减少一半,因此时间复杂度是 O( log(k) ) = O( log(m+n) ).

class Solution {
public:
    double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) {
        int total = nums1.size() + nums2.size();
        if(total % 2) return find(nums1, 0, nums2, 0, total / 2 + 1);
        else
        {
            int left = find(nums1, 0, nums2, 0, total / 2);
            int right = find(nums1, 0, nums2, 0, total / 2 + 1);
            return (left + right) / 2.0;
        }
    }

    //找第k小的数
    int find(vector<int>& nums1, int i, vector<int>& nums2, int j, int k)
    {
        if(nums1.size() - i > nums2.size() - j) return find(nums2, j, nums1, i, k);//保证nums1是短的那个
        if(i == nums1.size()) return nums2[j + k - 1];//nums1遍历完了
        if(k == 1) return min(nums1[i], nums2[j]);//k=1且num1未遍历完时,取两数组开头两数中小的那个
        int si = min(i + k / 2, (int)nums1.size()), sj = j + k / 2;
        if(nums1[si - 1] <= nums2[sj - 1])
            return find(nums1, si, nums2, j, k - (si - i));
        else
            return find(nums1, i, nums2, sj, k - (sj - j));
    }
};

5. 最长回文字串

image-20220808233753712

算法 双指针中心扩散(枚举)

时间复杂度分析:一共两重循环,时间复杂度是 O(n2).

class Solution {
public:
    string longestPalindrome(string s) {
        string res;
        //中心扩散法遍历所有奇数和偶数的情况,每个位置从中间往两边匹配
        for(int i = 0; i < s.size(); i++)
        {
            //奇数
            int l = i - 1, r = i + 1;
            while(l >= 0 && r < s.size() && s[l] == s[r]) l--, r++;
            if(res.size() < r - l - 1) res = s.substr(l + 1, r - l - 1);

            //偶数
            l = i, r = i + 1;
            while(l >= 0 && r < s.size() && s[l] == s[r]) l--, r++;
            if(res.size() < r - l - 1) res = s.substr(l + 1, r - l - 1);
        }
        return res;
    }
};

6. Z字形变换

image-20220825213730426

image-20220825213804098

算法 找规律

IMG_0738

按某种形状打印字符的题目,一般考虑通过画图找规律来做。

对于行数是n的情况:

  1. 对于第一行和最后一行,是公差为 2(n−1) 的等差数列,首项是 0 和 n−1;
  2. 对于第 i 行 (0 < i < n − 1),是两个公差为 2(n−1) 的等差数列交替排列(竖着的跟竖着的组成等差数列,斜着的跟斜着的组成等差数列),首项分别是 i 和 2n − 2 − i;

所以我们可以从上到下,依次打印每行的字符。

时间复杂度分析:每个字符遍历一遍,所以时间复杂度是 O(n).

class Solution {
public:
    string convert(string s, int numRows) {
        string res;
        int n = numRows;
        if(n == 1) return s;
        for(int i = 0; i < n; i ++)
        {
            if(i == 0 || i == n - 1)//第一行和最后一行
            {
                for(int j = i; j < s.size(); j += 2 * n - 2)
                    res += s[j];
            }
            else//除了第一行和最后一行的中间行
            {
                for(int j = i, k = 2 * n - 2 - i; j < s.size() || k < s.size(); j += 2 * n - 2, k += 2 * n - 2)
                {
                    if(j < s.size()) res += s[j];
                    if(k < s.size()) res += s[k];
                }
            }
        }
        return res;
    }
};

7. 整数反转

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-RCvWXiZ4-1666691175359)(https://cdn.jsdelivr.net/gh/RunxunWu/image-store/img/202208252214927.png)]

算法 循环模拟

依次从右往左计算出每位数字,然后逆序累加在一个整数中。需要判断溢出。

在C++中,负数的取模运算和数学意义上的取模运算不同,结果还是负数,所以我们不需要对负数进行额外处理。

class Solution {
public:
    int reverse(int x) {
        int r = 0;
        while(x)
        {
            if(r > 0 && r > (INT_MAX - x % 10) / 10) return 0;
            if(r < 0 && r < (INT_MIN - x % 10) / 10) return 0;
            r = r * 10 + x % 10;
            x /= 10;
        }
        return r;
    }
};

8. 字符串转换整数(atoi)

算法 模拟

时间复杂度分析:假设字符串长度是 n,每个字符最多遍历一次,所以总时间复杂度是 O(n).

class Solution {
public:
    int myAtoi(string s) {
        int res = 0;//结果
        int i = 0;//下标

        while(i < s.size() && s[i] == ' ') i++;
        if(i == s.size()) return 0;//特判空字符串情况

        int minus = 1;
        if(s[i] == '-') minus = -1, i++;
        if(s[i] == '+')
        {
            if(minus == -1) return 0;//陷阱样例"-+12"
            else i++;
        }

        while(i < s.size() && s[i] >= '0' && s[i] <= '9')
        {
            int x = s[i] - '0';
            if(minus > 0 && res > (INT_MAX - x) / 10) return INT_MAX;
            if(minus < 0 && -res < (INT_MIN + x) / 10) return INT_MIN;//这里的res一定是正的
            if(-res * 10 - x == INT_MIN) return INT_MIN;

            res = res * 10 + x;
            i++;
        }

        return res * minus;
    }
};

9. 回文数

算法1 转化为字符串利用函数
class Solution {
public:
    bool isPalindrome(int x) {
        if(x < 0) return false;
        string s = to_string(x);
        return s == string(s.rbegin(), s.rend());
    }
};
算法2 不转成字符串 数学模拟
class Solution {
public:
    bool isPalindrome(int x) {
        if(x < 0) return false;
        int y = x;
        long long res = 0;
        while(x)
        {
            res = res * 10 + x % 10;
            x /= 10;
        }

        return y == res;
    }
};
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
1. Two Sum 2. Add Two Numbers 3. Longest Substring Without Repeating Characters 4. Median of Two Sorted Arrays 5. Longest Palindromic Substring 6. ZigZag Conversion 7. Reverse Integer 8. String to Integer (atoi) 9. Palindrome Number 10. Regular Expression Matching 11. Container With Most Water 12. Integer to Roman 13. Roman to Integer 14. Longest Common Prefix 15. 3Sum 16. 3Sum Closest 17. Letter Combinations of a Phone Number 18. 4Sum 19. Remove Nth Node From End of List 20. Valid Parentheses 21. Merge Two Sorted Lists 22. Generate Parentheses 23. Swap Nodes in Pairs 24. Reverse Nodes in k-Group 25. Remove Duplicates from Sorted Array 26. Remove Element 27. Implement strStr() 28. Divide Two Integers 29. Substring with Concatenation of All Words 30. Next Permutation 31. Longest Valid Parentheses 32. Search in Rotated Sorted Array 33. Search for a Range 34. Find First and Last Position of Element in Sorted Array 35. Valid Sudoku 36. Sudoku Solver 37. Count and Say 38. Combination Sum 39. Combination Sum II 40. First Missing Positive 41. Trapping Rain Water 42. Jump Game 43. Merge Intervals 44. Insert Interval 45. Unique Paths 46. Minimum Path Sum 47. Climbing Stairs 48. Permutations 49. Permutations II 50. Rotate Image 51. Group Anagrams 52. Pow(x, n) 53. Maximum Subarray 54. Spiral Matrix 55. Jump Game II 56. Merge k Sorted Lists 57. Insertion Sort List 58. Sort List 59. Largest Rectangle in Histogram 60. Valid Number 61. Word Search 62. Minimum Window Substring 63. Unique Binary Search Trees 64. Unique Binary Search Trees II 65. Interleaving String 66. Maximum Product Subarray 67. Binary Tree Inorder Traversal 68. Binary Tree Preorder Traversal 69. Binary Tree Postorder Traversal 70. Flatten Binary Tree to Linked List 71. Construct Binary Tree from Preorder and Inorder Traversal 72. Construct Binary Tree from Inorder and Postorder Traversal 73. Binary Tree Level Order Traversal 74. Binary Tree Zigzag Level Order Traversal 75. Convert Sorted Array to Binary Search Tree 76. Convert Sorted List to Binary Search Tree 77. Recover Binary Search Tree 78. Sum Root to Leaf Numbers 79. Path Sum 80. Path Sum II 81. Binary Tree Maximum Path Sum 82. Populating Next Right Pointers in Each Node 83. Populating Next Right Pointers in Each Node II 84. Reverse Linked List 85. Reverse Linked List II 86. Partition List 87. Rotate List 88. Remove Duplicates from Sorted List 89. Remove Duplicates from Sorted List II 90. Intersection of Two Linked Lists 91. Linked List Cycle 92. Linked List Cycle II 93. Reorder List 94. Binary Tree Upside Down 95. Binary Tree Right Side View 96. Palindrome Linked List 97. Convert Binary Search Tree to Sorted Doubly Linked List 98. Lowest Common Ancestor of a Binary Tree 99. Lowest Common Ancestor of a Binary Search Tree 100. Binary Tree Level Order Traversal II

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值