├── .gitignore ├── 700-799 ├── 709. To Lower Case 转换成小写字母.md ├── 796. Rotate String 旋转字符串.md ├── 700. Search in a Binary Search Tree 二叉搜索树中的搜索.md └── 771. Jewels and Stones 宝石与石头.md ├── 300-399 ├── 387. First Unique Character in a String 字符串中的第一个唯一字符.md ├── 319. Bulb Switcher 灯泡开关.md ├── 346. Moving Average from Data Stream 数据流中的移动平均值.md ├── 372. Super Pow 超级次方.md ├── 386. Lexicographical Numbers 字典序排数.md ├── 347. Top K Frequent Elements 前 K 个高频元素.md ├── 334. Increasing Triplet Subsequence 递增的三元子序列.md ├── 344. Reverse String 反转字符串.md ├── 320. Generalized Abbreviation 列举单词的全部缩写.md ├── 395. Longest Substring with At Least K Repeating Characters 至少有 K 个重复字符的最长子串.md ├── 349. Intersection of Two Arrays 两个数组的交集.md ├── 357. Count Numbers with Unique Digits 计算各个位数不同的数字个数.md └── 358. Rearrange String k Distance Apart K 距离间隔重排字符串.md ├── LICENSE ├── make-toc.py ├── 1100-1199 ├── 1119. Remove Vowels from a String 删去字符串中的元音.md ├── 1118. Number of Days in a Month 一月有多少天.md ├── 1137. N-th Tribonacci Number 第 N 个泰波那契数.md ├── 1133. Largest Unique Number 最大唯一数.md ├── 1134. Armstrong Number 阿姆斯特朗数.md ├── 1180. Count Substrings with Only One Distinct Letter 统计只含单一字母的子串.md ├── 1167. Minimum Cost to Connect Sticks 连接棒材的最低费用.md └── 1151. Minimum Swaps to Group All 1's Together 最少交换次数来组合所有的 1.md ├── 200-299 ├── 266. Palindrome Permutation 回文排列.md ├── 280. Wiggle Sort 摆动排序.md ├── 228. Summary Ranges 汇总区间.md ├── 252. Meeting Rooms 会议室.md ├── 201. Bitwise AND of Numbers Range 数字范围按位与.md ├── 243. Shortest Word Distance 最短单词距离.md ├── 293. Flip Game 翻转游戏.md ├── 246. Strobogrammatic Number 中心对称数.md ├── 292. Nim Game Nim 游戏.md ├── 253. Meeting Rooms II 会议室 II.md ├── 268. Missing Number 丢失的数字.md ├── 219. Contains Duplicate II 存在重复元素 II.md ├── 245. Shortest Word Distance III 最短单词距离 III.md └── 238. Product of Array Except Self 除自身以外数组的乘积.md ├── 100-199 ├── 190. Reverse Bits 颠倒二进制位.md ├── 153. Find Minimum in Rotated Sorted Array 寻找旋转排序数组中的最小值.md ├── 162. Find Peak Element 寻找峰值.md ├── 187. Repeated DNA Sequences 重复的DNA序列.md ├── 137. Single Number II 只出现一次的数字 II.md ├── 151. Reverse Words in a String 翻转字符串里的单词.md ├── 106. Construct Binary Tree from Inorder and Postorder Traversal 从中序与后序遍历序列构造二叉树.md ├── 154. Find Minimum in Rotated Sorted Array II 寻找旋转排序数组中的最小值 II.md ├── 171. Excel Sheet Column Number Excel 表列序号.md ├── 129. Sum Root to Leaf Numbers 求根节点到叶节点数字之和.md ├── 163. Missing Ranges 缺失的区间.md ├── 120. Triangle 三角形最小路径和.md ├── 186. Reverse Words in a String II 翻转字符串里的单词 II.md └── 165. Compare Version Numbers 比较版本号.md ├── 900-999 ├── 977. Squares of a Sorted Array 有序数组的平方.md ├── 905. Sort Array By Parity 按奇偶排序数组.md ├── 949. Largest Time for Given Digits 给定数字能组成的最大时间.md ├── 961. N-Repeated Element in Size 2N Array 在长度 2N 的数组中找出重复 N 次的元素.md ├── 915. Partition Array into Disjoint Intervals 分割数组.md ├── 944. Delete Columns to Make Sorted 删列造序.md └── 984. String Without AAA or BBB 不含 AAA 或 BBB 的字符串.md ├── 800-899 ├── 867. Transpose Matrix 转置矩阵.md ├── 896. Monotonic Array 单调数列.md ├── 821. Shortest Distance to a Character 字符的最短距离.md ├── 829. Consecutive Numbers Sum 连续整数求和.md └── 870. Advantage Shuffle 优势洗牌.md ├── 600-699 ├── 628. Maximum Product of Three Numbers 三个数的最大乘积.md ├── 646. Maximum Length of Pair Chain 最长数对链.md ├── 686. Repeated String Match 重复叠加字符串匹配.md ├── 672. Bulb Switcher II 灯泡开关 Ⅱ.md ├── 611. Valid Triangle Number 有效三角形的个数.md ├── 673. Number of Longest Increasing Subsequence 最长递增子序列的个数.md ├── 645. Set Mismatch 错误的集合.md └── 657. Robot Return to Origin 机器人能否返回原点.md ├── 1000-1099 ├── 1064. Fixed Point 不动点.md ├── 1037. Valid Boomerang 有效的回旋镖.md ├── 1085. Sum of Digits in the Minimum Number 最小元素各数位之和.md ├── 1051. Height Checker 高度检查器.md ├── 1047. Remove All Adjacent Duplicates In String 删除字符串中的所有相邻重复项.md ├── 1099. Two Sum Less Than K 小于 K 的两数之和.md ├── 1021. Remove Outermost Parentheses 删除最外层的括号.md ├── 1012. Numbers With Repeated Digits 至少有 1 位重复的数字.md ├── 1002. Find Common Characters 查找共用字符.md ├── 1018. Binary Prefix Divisible By 5 可被 5 整除的二进制前缀.md ├── 1065. Index Pairs of a String 字符串的索引对.md └── 1008. Construct Binary Search Tree from Preorder Traversal 前序遍历构造二叉搜索树.md ├── 1-99 ├── 71. Simplify Path 简化路径.md ├── 86. Partition List 分隔链表.md ├── 9. Palindrome Number 回文数.md ├── 99. Recover Binary Search Tree 恢复二叉搜索树.md ├── 16. 3Sum Closest 最接近的三数之和.md └── 28. Implement strStr() 实现 strStr().md ├── 1400-1499 ├── 1470. Shuffle the Array 重新排列数组.md ├── 1408. String Matching in an Array 数组中的字符串匹配.md ├── 1433. Check If a String Can Break Another String 检查一个字符串是否可以打破另一个字符串.md ├── 1414. Find the Minimum Number of Fibonacci Numbers Whose Sum Is K 和为 K 的最少斐波那契数字数目.md ├── 1431. Kids With the Greatest Number of Candies 拥有最多糖果的孩子.md ├── 1437. Check If All 1's Are at Least Length K Places Away 是否所有 1 都至少相隔 k 个元素.md ├── 1409. Queries on a Permutation With Key 查询带键的排列.md ├── 1410. HTML Entity Parser HTML 实体解析器.md ├── 1436. Destination City 旅行终点站.md └── 1413. Minimum Value to Get Positive Step by Step Sum 逐步求和得到正数的最小值.md ├── 400-499 ├── 400. Nth Digit 第 N 位数字.md ├── 458. Poor Pigs 可怜的小猪.md └── 452. Minimum Number of Arrows to Burst Balloons 用最少数量的箭引爆气球.md ├── 500-599 ├── 593. Valid Square 有效的正方形.md ├── 561. Array Partition I 数组拆分 I.md ├── 509. Fibonacci Number 斐波那契数.md ├── 539. Minimum Time Difference 最小时间差.md ├── 560. Subarray Sum Equals K 和为 K 的子数组.md ├── 538. Convert BST to Greater Tree 把二叉搜索树转换为累加树.md ├── 567. Permutation in String 字符串的排列.md ├── 518. Coin Change 2 零钱兑换 II.md ├── 521. Longest Uncommon Subsequence I 最长特殊序列 Ⅰ.md ├── 581. Shortest Unsorted Continuous Subarray 最短无序连续子数组.md └── 598. Range Addition II 范围求和 II.md ├── 1200-1299 └── 1221. Split a String in Balanced Strings 分割平衡字符串.md └── 1700-1799 └── 1768. Merge Strings Alternately 交替合并字符串.md /.gitignore: -------------------------------------------------------------------------------- 1 | 2 | toc.md 3 | -------------------------------------------------------------------------------- /700-799/709. To Lower Case 转换成小写字母.md: -------------------------------------------------------------------------------- 1 | 2 | 3 | 作者: 负雪明烛 4 | id: fuxuemingzhu 5 | 个人博客: http://fuxuemingzhu.cn/ 6 | 7 | --- 8 | @[TOC](目录) 9 | 10 | 题目地址:https://leetcode.com/problems/to-lower-case/description/ 11 | 12 | ## 题目描述: 13 | 14 | Implement function ToLowerCase() that has a string parameter str, and returns the same string in lowercase. 15 | 16 | ## 题目大意 17 | 18 | 把字符串的大写字母全都转化成小写。 19 | 20 | ## 解题方法 21 | 22 | ### ASIIC码操作 23 | 24 | 当然可以直接使用lower()函数,直接能过。但是,毕竟是让你实现么,所以动手写一下。 25 | 26 | 主要是判断字符处在'A'~'Z'之间,如果这样的话,就把它转成小写字符就行。其他的字符都不要改变。 27 | 28 | 代码如下: 29 | 30 | ```python 31 | class Solution: 32 | def toLowerCase(self, str): 33 | """ 34 | :type str: str 35 | :rtype: str 36 | """ 37 | res = "" 38 | for s in str: 39 | if ord(s) >= ord('A') and ord(s) <= ord('Z'): 40 | res += chr(ord(s) - ord('A') + ord('a')) 41 | else: 42 | res += s 43 | return res 44 | ``` 45 | 46 | ## 日期 47 | 48 | 2018 年 7 月 12 日 ———— 天阴阴地潮潮,已经连着两天这样了 49 | -------------------------------------------------------------------------------- /300-399/387. First Unique Character in a String 字符串中的第一个唯一字符.md: -------------------------------------------------------------------------------- 1 | 作者: 负雪明烛 2 | id: fuxuemingzhu 3 | 个人博客: http://fuxuemingzhu.cn/ 4 | 5 | --- 6 | @[TOC](目录) 7 | 8 | 9 | 题目地址:https://leetcode.com/problems/first-unique-character-in-a-string/description/ 10 | 11 | 12 | ## 题目描述 13 | 14 | Given a string, find the first non-repeating character in it and return it's index. If it doesn't exist, return -1. 15 | 16 | Examples: 17 | 18 | s = "leetcode" 19 | return 0. 20 | 21 | s = "loveleetcode", 22 | return 2. 23 | 24 | Note: You may assume the string contain only lowercase letters. 25 | 26 | 27 | ## 题目大意 28 | 29 | 找出字符串中第一个只出现了1次的字符。 30 | 31 | ## 解题方法 32 | 33 | 首先做个字符出现次数的统计,然后再次遍历,找出只出现了一次的第一个字符。 34 | 35 | 36 | ```python 37 | class Solution: 38 | def firstUniqChar(self, s): 39 | """ 40 | :type s: str 41 | :rtype: int 42 | """ 43 | count = collections.Counter(s) 44 | for i, c in enumerate(s): 45 | if count[c] == 1: 46 | return i 47 | return -1 48 | ``` 49 | 50 | ## 日期 51 | 52 | 2018 年 11 月 16 日 —— 又到周五了! 53 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2021 负雪明烛 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /make-toc.py: -------------------------------------------------------------------------------- 1 | from collections import defaultdict 2 | import os 3 | 4 | leetcodePath = "./" 5 | 6 | with open(leetcodePath + "toc.md", "w") as f: 7 | f.write("\n") 8 | 9 | solutions = os.listdir(leetcodePath) 10 | 11 | indexes = defaultdict(list) 12 | reversed_indexes = defaultdict() 13 | 14 | for solu in solutions: 15 | if os.path.isdir(leetcodePath + solu) and not solu.startswith("."): 16 | for doc in os.listdir(leetcodePath + solu): 17 | problemId = doc.split(".")[0] 18 | fromPath = leetcodePath + solu + "/" + doc.replace(" ", "\ ") 19 | indexes[solu].append([problemId, doc]) 20 | reversed_indexes[doc] = solu 21 | 22 | 23 | cates = list(indexes.keys()) 24 | print(cates) 25 | cates.sort(key=lambda x : int(x.split("-")[0])) 26 | for cate in cates: 27 | with open(leetcodePath + "toc.md", "a") as f: 28 | f.write("\n## " + cate + "\n") 29 | problems = indexes[cate] 30 | problems.sort(key=lambda x : int(x[0])) 31 | for probem in problems: 32 | with open(leetcodePath + "toc.md", "a") as f: 33 | f.write("- [" + probem[1].replace(".md", "") + "](" + reversed_indexes[probem[1]] + "/" + probem[1].replace(" ", "%20") + ")\n") 34 | 35 | -------------------------------------------------------------------------------- /1100-1199/1119. Remove Vowels from a String 删去字符串中的元音.md: -------------------------------------------------------------------------------- 1 | 2 | 3 | - 作者: 负雪明烛 4 | - id: fuxuemingzhu 5 | - 个人博客:[http://fuxuemingzhu.cn/](http://fuxuemingzhu.cn/) 6 | 7 | --- 8 | @[TOC](目录) 9 | 10 | 11 | 题目地址:https://leetcode-cn.com/problems/remove-vowels-from-a-string/ 12 | 13 | ## 题目描述 14 | 15 | Given a string `S`, remove the vowels `'a', 'e', 'i', 'o', and 'u'` from it, and return the new string. 16 | 17 | Example 1: 18 | 19 | Input: "leetcodeisacommunityforcoders" 20 | Output: "ltcdscmmntyfrcdrs" 21 | 22 | Example 2: 23 | 24 | Input: "aeiou" 25 | Output: "" 26 | 27 | Note: 28 | 29 | 1. S consists of lowercase English letters only. 30 | 1. `1 <= S.length <= 1000` 31 | 32 | 33 | ## 题目大意 34 | 35 | 给你一个字符串 S,请你删去其中的所有元音字母( 'a','e','i','o','u'),并返回这个新字符串。 36 | 37 | ## 解题方法 38 | 39 | ### 判断字符是否是aeiou 40 | 41 | 判断是否是元音字符,决定是否加入结果中。 42 | 43 | C++代码如下: 44 | 45 | ```cpp 46 | class Solution { 47 | public: 48 | string removeVowels(string S) { 49 | string res; 50 | for (char c : S) { 51 | if (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u') 52 | continue; 53 | res += c; 54 | } 55 | return res; 56 | } 57 | }; 58 | ``` 59 | 60 | ## 日期 61 | 62 | 2019 年 9 月 18 日 —— 今日又是九一八 63 | -------------------------------------------------------------------------------- /200-299/266. Palindrome Permutation 回文排列.md: -------------------------------------------------------------------------------- 1 | 2 | - 作者: 负雪明烛 3 | - id: fuxuemingzhu 4 | - 个人博客:[http://fuxuemingzhu.cn/](http://fuxuemingzhu.cn/) 5 | 6 | --- 7 | @[TOC](目录) 8 | 9 | 10 | 题目地址:https://leetcode-cn.com/problems/palindrome-permutation/ 11 | 12 | ## 题目描述 13 | 14 | Given a string, determine if a permutation of the string could form a palindrome. 15 | 16 | Example 1: 17 | 18 | Input: "code" 19 | Output: false 20 | 21 | Example 2: 22 | 23 | Input: "aab" 24 | Output: true 25 | 26 | Example 3: 27 | 28 | Input: "carerac" 29 | Output: true 30 | 31 | 32 | ## 题目大意 33 | 34 | 给定一个字符串,判断该字符串中是否可以通过重新排列组合,形成一个回文字符串。 35 | 36 | ## 解题方法 37 | 38 | ### 字典 39 | 40 | 回文串中,左右必须对称,因此出现次数为奇数的字符最多只有一个。 41 | 42 | 使用一个字典,保存每个字符出现的次数。如果出现次数为奇数个的字符<=1,那么可以构成回文串。 43 | 44 | C++代码如下: 45 | 46 | ```cpp 47 | class Solution { 48 | public: 49 | bool canPermutePalindrome(string s) { 50 | unordered_map m_; 51 | for (char c : s) { 52 | m_[c]++; 53 | } 54 | int odd_count = 0; 55 | for (auto& it : m_) { 56 | if (it.second & 1) 57 | odd_count++; 58 | } 59 | return odd_count <= 1; 60 | } 61 | }; 62 | ``` 63 | 64 | 65 | ## 日期 66 | 67 | 2019 年 9 月 17 日 —— 听了hulu宣讲会,觉得hulu的压力不大 68 | -------------------------------------------------------------------------------- /200-299/280. Wiggle Sort 摆动排序.md: -------------------------------------------------------------------------------- 1 | 2 | 3 | - 作者: 负雪明烛 4 | - id: fuxuemingzhu 5 | - 个人博客:[http://fuxuemingzhu.cn/](http://fuxuemingzhu.cn/) 6 | 7 | --- 8 | @[TOC](目录) 9 | 10 | 题目地址:https://leetcode-cn.com/problems/wiggle-sort/ 11 | 12 | ## 题目描述 13 | 14 | Given an unsorted array nums, reorder it in-place such that `nums[0] <= nums[1] >= nums[2] <= nums[3]....` 15 | 16 | Example: 17 | 18 | Input: nums = [3,5,2,1,6,4] 19 | Output: One possible answer is [3,5,1,6,2,4] 20 | 21 | 22 | ## 题目大意 23 | 24 | 给你一个无序的数组 nums, 将该数字 原地 重排后使得 `nums[0] <= nums[1] >= nums[2] <= nums[3]...`。 25 | 26 | ## 解题方法 27 | 28 | ### 排序后交换相邻元素 29 | 30 | 只要给出一种符合要求的结果即可,因此我们可以找出一种最简单易实现的方案就行。 31 | 32 | 先把所有的数字排序,然后交换相邻的元素就可以实现这种波浪形的数组。举例如下: 33 | 34 | 输入:[3,5,2,1,6,4] 35 | 排序:[1,2,3,4,5,6] 36 | 交换:[1,3,2,5,4,6] 37 | 38 | C++代码如下: 39 | 40 | ```cpp 41 | class Solution { 42 | public: 43 | void wiggleSort(vector& nums) { 44 | const int N = nums.size(); 45 | sort(nums.begin(), nums.end()); 46 | for (int i = 1; i < N - 1; i += 2) { 47 | swap(nums[i], nums[i + 1]); 48 | } 49 | } 50 | }; 51 | ``` 52 | 53 | ## 日期 54 | 55 | 2019 年 9 月 22 日 —— 熬夜废掉半条命 56 | 57 | 58 | [1]: https://assets.leetcode.com/uploads/2018/10/12/candy_crush_example_2.png 59 | [2]: https://blog.csdn.net/fuxuemingzhu/article/details/101068011 60 | -------------------------------------------------------------------------------- /200-299/228. Summary Ranges 汇总区间.md: -------------------------------------------------------------------------------- 1 | # 【LeetCode】228. Summary Ranges 解题报告(Python) 2 | 3 | 标签(空格分隔): LeetCode 4 | 5 | --- 6 | 7 | 题目地址:https://leetcode.com/problems/summary-ranges/description/ 8 | 9 | ## 题目描述: 10 | 11 | Given a sorted integer array without duplicates, return the summary of its ranges. 12 | 13 | Example 1: 14 | Input: [0,1,2,4,5,7] 15 | Output: ["0->2","4->5","7"] 16 | 17 | Example 2: 18 | 19 | Input: [0,2,3,4,6,8,9] 20 | Output: ["0","2->4","6","8->9"] 21 | 22 | ## 题目大意 23 | 24 | 把一个有序的数组,合并区间。也就是两个相邻的数字之间的距离如果是1,那么就应该合并。 25 | 26 | ## 解题方法 27 | 28 | 完全是自己想出来的算法哈哈哈。两个while嵌套,第一个嵌套遍历Nums,第二个嵌套要往后走,看看后面的数字是不是比前面的数字大1,是的话就一直后移。根据i和j是否重叠来判断是加上一个数字还是加上一个区间。 29 | 30 | 代码: 31 | 32 | ```python 33 | class Solution(object): 34 | def summaryRanges(self, nums): 35 | """ 36 | :type nums: List[int] 37 | :rtype: List[str] 38 | """ 39 | if not nums: return [] 40 | res = [] 41 | i = 0 42 | while i < len(nums): 43 | j = i 44 | while j < len(nums) - 1 and nums[j] == nums[j + 1] - 1: 45 | j += 1 46 | if j == i: 47 | res.append(str(nums[i])) 48 | else: 49 | res.append('%s->%s' % (str(nums[i]), str(nums[j]))) 50 | i = j + 1 51 | return res 52 | ``` 53 | 54 | ## 日期 55 | 56 | 2018 年 3 月 31 日 ———— 晚上睡不好,一天没精神啊 -------------------------------------------------------------------------------- /200-299/252. Meeting Rooms 会议室.md: -------------------------------------------------------------------------------- 1 | 2 | - 作者: 负雪明烛 3 | - id: fuxuemingzhu 4 | - 个人博客:[http://fuxuemingzhu.cn/](http://fuxuemingzhu.cn/) 5 | 6 | --- 7 | @[TOC](目录) 8 | 9 | 10 | 题目地址:https://leetcode-cn.com/problems/meeting-rooms/ 11 | 12 | ## 题目描述 13 | 14 | Given an array of meeting time intervals consisting of start and end times `[[s1,e1],[s2,e2],...] (si < ei)`, determine if a person could attend all meetings. 15 | 16 | Example 1: 17 | 18 | Input: [[0,30],[5,10],[15,20]] 19 | Output: false 20 | 21 | Example 2: 22 | 23 | Input: [[7,10],[2,4]] 24 | Output: true 25 | 26 | ## 题目大意 27 | 28 | 给定一个会议时间安排的数组,每个会议时间都会包括开始和结束的时间 [[s1,e1],[s2,e2],...] (si < ei),请你判断一个人是否能够参加这里面的全部会议。 29 | 30 | ## 解题方法 31 | 32 | ### 排序 33 | 34 | 很经典的题目,按照会议结束的时间进行排序。排序之后,遍历数组,判断当前会议结束的时间是否比下一个会议开始时间**晚**,如果是,那肯定就无法参加所有的会议了。 35 | 36 | ```cpp 37 | class Solution { 38 | public: 39 | bool canAttendMeetings(vector>& intervals) { 40 | if (intervals.size() <= 1) return true; 41 | sort(intervals.begin(), intervals.end(), 42 | [](vector& a, vector&b) {return a[1] < b[1];}); 43 | for (int i = 0; i < intervals.size() - 1; i++) { 44 | if (intervals[i][1] > intervals[i + 1][0]) 45 | return false; 46 | } 47 | return true; 48 | } 49 | }; 50 | ``` 51 | 52 | ## 日期 53 | 54 | 2019 年 9 月 17 日 —— 听了hulu宣讲会,觉得hulu的压力不大 55 | -------------------------------------------------------------------------------- /200-299/201. Bitwise AND of Numbers Range 数字范围按位与.md: -------------------------------------------------------------------------------- 1 | # 【LeetCode】201. Bitwise AND of Numbers Range 解题报告(Python) 2 | 3 | 标签: LeetCode 4 | 5 | --- 6 | 7 | 题目地址:https://leetcode.com/problems/bitwise-and-of-numbers-range/description/ 8 | 9 | ## 题目描述: 10 | 11 | Given a range [m, n] where 0 <= m <= n <= 2147483647, return the bitwise AND of all numbers in this range, inclusive. 12 | 13 | For example, given the range [5, 7], you should return 4. 14 | 15 | ## 题目大意 16 | 17 | 计算区间[m,n]内所有数字的与。 18 | 19 | ## 解题方法 20 | 21 | 看题感觉需要对所有的[m,n]范围内的数字进行遍历一遍吧。。其实不需要的。 22 | 23 | 我们知道,数组的数字是连续的,那么m,n范围内的二进制表示的末尾相同位置一定会出现不同的0,1.我们只要找出m,n的做左边起的最长相同的二进制头部即可呀。 24 | 25 | 如[5, 7]里共有三个数字,分别写出它们的二进制为: 26 | 27 | 101  110  111 28 | 29 | 相与后的结果为100,仔细观察我们可以得出,最后的数是该数字范围内所有的数的左边共同的部分(即m,n左边的共同部分),如果上面那个例子不太明显,我们再来看一个范围[26, 30],它们的二进制如下: 30 | 31 | 11010  11011  11100  11101  11110 32 | 33 | 也是前两位是11,后面3位在不同数字中一定会出现0和1、相与即为0了。 34 | 35 | 我的做法是把m,n同时向右平移,直到两者相等(头部相同了),再把最后的结果向左平移相同的步数。 36 | 37 | 这个文章讲了4种解法:http://www.cnblogs.com/grandyang/p/4431646.html 38 | 39 | 代码: 40 | 41 | ```python 42 | class Solution(object): 43 | def rangeBitwiseAnd(self, m, n): 44 | """ 45 | :type m: int 46 | :type n: int 47 | :rtype: int 48 | """ 49 | i = 0 50 | while m != n: 51 | m >>= 1 52 | n >>= 1 53 | i += 1 54 | return m << i 55 | ``` 56 | 57 | ## 日期 58 | 59 | 2018 年 3 月 9 日 60 | -------------------------------------------------------------------------------- /300-399/319. Bulb Switcher 灯泡开关.md: -------------------------------------------------------------------------------- 1 | # 【LeetCode】319. Bulb Switcher 解题报告(Python) 2 | 3 | 标签(空格分隔): LeetCode 4 | 5 | --- 6 | 7 | 题目地址:https://leetcode.com/problems/bulb-switcher/description/ 8 | 9 | ## 题目描述: 10 | 11 | There are n bulbs that are initially off. You first turn on all the bulbs. Then, you turn off every second bulb. On the third round, you toggle every third bulb (turning on if it's off or turning off if it's on). For the ith round, you toggle every i bulb. For the nth round, you only toggle the last bulb. Find how many bulbs are on after n rounds. 12 | 13 | Example: 14 | 15 | Given n = 3. 16 | 17 | At first, the three bulbs are [off, off, off]. 18 | After first round, the three bulbs are [on, on, on]. 19 | After second round, the three bulbs are [on, off, on]. 20 | After third round, the three bulbs are [on, off, off]. 21 | 22 | So you should return 1, because there is only one bulb is on. 23 | 24 | ## 题目大意 25 | 26 | n个灯泡,起始状态是灭的,需要按照1的倍数,2的倍数,3的倍数……的位置打开关闭n次,求最后亮了几个。 27 | 28 | ## 解题方法 29 | 30 | 真的是智力题,暴力解法超时,最后的结果是开平方就行。 31 | 32 | 对于这个题,在http://blog.csdn.net/baidu_23318869/article/details/50386323上有详细的解释,应该能看懂。就不多说了。 33 | 34 | 代码: 35 | 36 | ```python 37 | class Solution(object): 38 | def bulbSwitch(self, n): 39 | """ 40 | :type n: int 41 | :rtype: int 42 | """ 43 | return int(math.sqrt(n)) 44 | ``` 45 | 46 | ## 日期 47 | 48 | 2018 年 3 月 5 日 -------------------------------------------------------------------------------- /1100-1199/1118. Number of Days in a Month 一月有多少天.md: -------------------------------------------------------------------------------- 1 | - 作者: 负雪明烛 2 | - id: fuxuemingzhu 3 | - 个人博客:[http://fuxuemingzhu.cn/](http://fuxuemingzhu.cn/) 4 | 5 | --- 6 | @[TOC](目录) 7 | 8 | 9 | 题目地址:https://leetcode.com/problems/day-of-the-year/ 10 | 11 | ## 题目描述 12 | 13 | Given a year `Y` and a month `M`, return how many days there are in that month. 14 | 15 | 16 | Example 1: 17 | 18 | Input: Y = 1992, M = 7 19 | Output: 31 20 | 21 | Example 2: 22 | 23 | Input: Y = 2000, M = 2 24 | Output: 29 25 | 26 | Example 3: 27 | 28 | Input: Y = 1900, M = 2 29 | Output: 28 30 | 31 | Note: 32 | 33 | 1. `1583 <= Y <= 2100` 34 | 1. `1 <= M <= 12` 35 | 36 | 37 | ## 题目大意 38 | 39 | 判断给出的某年某月有多少天。 40 | 41 | ## 解题方法 42 | 43 | ### 判断是否是闰年 44 | 45 | 这个题和[1185. Day of the Week][1]类似。 46 | 47 | 这个题中计算出当年是不是闰年,然后从数组中读取当月的天数。 48 | 49 | C++代码如下: 50 | 51 | ```cpp 52 | class Solution { 53 | public: 54 | int numberOfDays(int Y, int M) { 55 | return daysOfMonth[isLeapYear(Y)][M - 1]; 56 | } 57 | bool isLeapYear(int year) { 58 | return (year % 4 == 0 && year % 100 != 0) || year % 400 == 0; 59 | } 60 | int daysOfMonth[2][12] = { 61 | {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}, 62 | {31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31} 63 | }; 64 | }; 65 | ``` 66 | 67 | ## 日期 68 | 69 | 2019 年 9 月 18 日 —— 今日又是九一八 70 | 71 | 72 | [1]: https://blog.csdn.net/fuxuemingzhu/article/details/100977773 73 | -------------------------------------------------------------------------------- /700-799/796. Rotate String 旋转字符串.md: -------------------------------------------------------------------------------- 1 | 2 | 作者: 负雪明烛 3 | id: fuxuemingzhu 4 | 个人博客: http://fuxuemingzhu.cn/ 5 | 6 | --- 7 | @[TOC](目录) 8 | 9 | 题目地址:https://leetcode.com/problems/rotate-string/description/ 10 | 11 | ## 题目描述 12 | 13 | We are given two strings, A and B. 14 | 15 | A shift on A consists of taking string A and moving the leftmost character to the rightmost position. For example, if A = 'abcde', then it will be 'bcdea' after one shift on A. Return True if and only if A can become B after some number of shifts on A. 16 | 17 | Example 1: 18 | Input: A = 'abcde', B = 'cdeab' 19 | Output: true 20 | 21 | Example 2: 22 | Input: A = 'abcde', B = 'abced' 23 | Output: false 24 | 25 | Note: 26 | 27 | A and B will have length at most 100. 28 | 29 | ## 题目大意 30 | 31 | 判断字符串A执行一定次数的循环移位操作之后能不能变成B. 32 | 33 | ## 解题方法 34 | 35 | 在python中很容易使用切片操作达到循环移位的做法。只需要循环A长度次,看看每个结果即是所有的可能的移位结果。 36 | 37 | ```python 38 | class Solution(object): 39 | def rotateString(self, A, B): 40 | """ 41 | :type A: str 42 | :type B: str 43 | :rtype: bool 44 | """ 45 | if A == B == "": 46 | return True 47 | for i in range(len(A)): 48 | if A[i:] + A[:i] == B: 49 | return True 50 | return False 51 | ``` 52 | 53 | ## 日期 54 | 55 | 2018 年 3 月 11 日 56 | 2018 年 11 月 14 日 —— 很严重的雾霾 57 | 58 | [1]: https://leetcode.com/static/images/problemset/8-queens.png 59 | -------------------------------------------------------------------------------- /100-199/190. Reverse Bits 颠倒二进制位.md: -------------------------------------------------------------------------------- 1 | 2 | 作者: 负雪明烛 3 | id: fuxuemingzhu 4 | 个人博客: http://fuxuemingzhu.cn/ 5 | 6 | --- 7 | @[TOC](目录) 8 | 9 | 题目地址:https://leetcode.com/problems/reverse-bits/description/ 10 | 11 | 12 | ## 题目描述 13 | 14 | 15 | Reverse bits of a given 32 bits unsigned integer. 16 | 17 | Example: 18 | 19 | Input: 43261596 20 | Output: 964176192 21 | Explanation: 43261596 represented in binary as 00000010100101000001111010011100, 22 | return 964176192 represented in binary as 00111001011110000010100101000000. 23 | 24 | Follow up: 25 | 26 | 1. If this function is called many times, how would you optimize it? 27 | 28 | ## 解题方法 29 | 30 | ### 二进制字符串翻转 31 | 32 | python真的好。bin()能求出二进制表示,ine(str,2)能把二进制转十进制表示。注意这个题目里面一定要是32位的二进制表示才行,因此一定要进行补全。 33 | 34 | ```python 35 | class Solution: 36 | # @param n, an integer 37 | # @return an integer 38 | def reverseBits(self, n): 39 | bins = bin(n)[2:][::-1] 40 | rev = (bins + '0' * (32 - len(bins))) 41 | return int(rev, 2) 42 | ``` 43 | 44 | ### 位运算 45 | 46 | 二刷使用C++,进行位运算。每次看n的末尾数字是多少,然后拼接到res的最前面。这样循环32次,则把n的所有数字进行了逆序操作。 47 | 48 | ```cpp 49 | class Solution { 50 | public: 51 | uint32_t reverseBits(uint32_t n) { 52 | uint32_t res = 0; 53 | for (int i = 0; i < 32; ++i) { 54 | res = (res << 1) + (n & 1); 55 | n >>= 1; 56 | } 57 | return res; 58 | } 59 | }; 60 | ``` 61 | 62 | ## 日期 63 | 64 | 2018 年 2 月 4 日 65 | 2018 年 11 月 27 日 —— 最近的雾霾太可怕 66 | -------------------------------------------------------------------------------- /1100-1199/1137. N-th Tribonacci Number 第 N 个泰波那契数.md: -------------------------------------------------------------------------------- 1 | 2 | 作者: 负雪明烛 3 | id: fuxuemingzhu 4 | 个人博客: http://fuxuemingzhu.cn/ 5 | 6 | --- 7 | @[TOC](目录) 8 | 9 | 10 | 题目地址:https://leetcode.com/problems/n-th-tribonacci-number/ 11 | 12 | ## 题目描述 13 | 14 | The Tribonacci sequence `Tn` is defined as follows: 15 | 16 | `T0 = 0, T1 = 1, T2 = 1`, and `Tn+3 = Tn + Tn+1 + Tn+2` for `n >= 0`. 17 | 18 | Given `n`, return the value of `Tn`. 19 | 20 | Example 1: 21 | 22 | Input: n = 4 23 | Output: 4 24 | Explanation: 25 | T_3 = 0 + 1 + 1 = 2 26 | T_4 = 1 + 1 + 2 = 4 27 | 28 | Example 2: 29 | 30 | Input: n = 25 31 | Output: 1389537 32 | 33 | 34 | Constraints: 35 | 36 | 1. 0 <= n <= 37 37 | 2. The answer is guaranteed to fit within a 32-bit integer, ie. answer <= 2^31 - 1. 38 | 39 | 40 | ## 题目大意 41 | 42 | 费布拉奇数列的拓展,每个元素是前面三个元素的和。求第n个元素。 43 | 44 | ## 解题方法 45 | 46 | ### 动态规划 47 | 48 | 众所周知,当递归深度比较大的时候会爆栈,所以使用的动态规划去做。 49 | 50 | 这个题需要注意的是有n=0,1,2三个特殊值,其他都好说。 51 | 52 | C++代码如下: 53 | 54 | ```cpp 55 | class Solution { 56 | public: 57 | int tribonacci(int n) { 58 | if (n == 0) return 0; 59 | if (n == 1) return 1; 60 | if (n == 2) return 1; 61 | vector T(n + 1); 62 | T[0] = 0; 63 | T[1] = T[2] = 1; 64 | for (int i = 3; i <= n; ++i) { 65 | T[i] = T[i - 1] + T[i - 2] + T[i - 3]; 66 | } 67 | return T[n]; 68 | } 69 | }; 70 | ``` 71 | 72 | 73 | ## 日期 74 | 75 | 2019 年 7 月 28 日 —— kickstart完败 76 | -------------------------------------------------------------------------------- /900-999/977. Squares of a Sorted Array 有序数组的平方.md: -------------------------------------------------------------------------------- 1 | 2 | 作者: 负雪明烛 3 | id: fuxuemingzhu 4 | 个人博客: http://fuxuemingzhu.cn/ 5 | 6 | --- 7 | @[TOC](目录) 8 | 9 | 题目地址:https://leetcode.com/problems/squares-of-a-sorted-array/ 10 | 11 | 12 | ## 题目描述 13 | 14 | Given an array of integers ``A`` sorted in non-decreasing order, return an array of the squares of each number, also in sorted non-decreasing order. 15 | 16 | 17 | Example 1: 18 | 19 | Input: [-4,-1,0,3,10] 20 | Output: [0,1,9,16,100] 21 | 22 | Example 2: 23 | 24 | Input: [-7,-3,2,3,11] 25 | Output: [4,9,9,49,121] 26 | 27 | Note: 28 | 29 | 1. 1 <= A.length <= 10000 30 | 1. -10000 <= A[i] <= 10000 31 | 1. A is sorted in non-decreasing order. 32 | 33 | ## 题目大意 34 | 35 | 给了一个单调不减的数组,返回排序了的每个元素求平方的结果。 36 | 37 | ## 解题方法 38 | 39 | ### 排序 40 | 41 | 没错这个是Easy题目,不用想太多,直接对每个元素进行求平方并排序即可。 42 | 43 | 需要注意的是,求平方之后是否会超出int的最大值呢?还好题目给了A[i]的范围只有10000,那么平方是1个亿,不会超过int最大。所以是安全的。 44 | 45 | 数组总长度是10000,所以O(NlongN)的时间复杂度是完全OK的。 46 | 47 | c++代码如下: 48 | 49 | ```cpp 50 | class Solution { 51 | public: 52 | vector sortedSquares(vector& A) { 53 | vector res; 54 | for (int a : A) { 55 | res.push_back(a * a); 56 | } 57 | sort(res.begin(), res.end()); 58 | return res; 59 | } 60 | }; 61 | ``` 62 | 63 | ## 日期 64 | 65 | 2019 年 1 月 20 日 —— 这次周赛有点简单 66 | 67 | 68 | [1]: https://assets.leetcode.com/uploads/2018/12/29/bst_cameras_01.png 69 | [2]: https://assets.leetcode.com/uploads/2018/12/29/bst_cameras_02.png 70 | -------------------------------------------------------------------------------- /1100-1199/1133. Largest Unique Number 最大唯一数.md: -------------------------------------------------------------------------------- 1 | 2 | - 作者: 负雪明烛 3 | - id: fuxuemingzhu 4 | - 个人博客:[http://fuxuemingzhu.cn/](http://fuxuemingzhu.cn/) 5 | 6 | --- 7 | @[TOC](目录) 8 | 9 | 10 | 题目地址:https://leetcode-cn.com/problems/check-if-a-number-is-majority-element-in-a-sorted-array/ 11 | 12 | ## 题目描述 13 | 14 | Given an array of integers A`, return the largest integer that only occurs once. 15 | 16 | If no integer occurs once, return -1. 17 | 18 | Example 1: 19 | 20 | Input: [5,7,3,9,4,9,8,3,1] 21 | Output: 8 22 | Explanation: 23 | The maximum integer in the array is 9 but it is repeated. The number 8 occurs only once, so it's the answer. 24 | Example 2: 25 | 26 | Input: [9,9,8,8] 27 | Output: -1 28 | Explanation: 29 | There is no number that occurs only once. 30 | 31 | Note: 32 | 33 | 1. `1 <= A.length <= 2000` 34 | 1.0 <= A[i] <= 1000 35 | 36 | ## 题目大意 37 | 38 | 给你一个整数数组 A,请找出并返回在该数组中仅出现一次的最大整数。 39 | 40 | 如果不存在这个只出现一次的整数,则返回 -1。 41 | 42 | ## 解题方法 43 | 44 | ### 桶排序 45 | 46 | 类似于桶排序的方式,计算每个数字出现了多少次,从最大数字开始向左遍历,找到第一个出现次数为1的数。 47 | 48 | C++代码如下: 49 | 50 | ```cpp 51 | class Solution { 52 | public: 53 | int largestUniqueNumber(vector& A) { 54 | vector count(1010, 0); 55 | for (int a : A) { 56 | count[a]++; 57 | } 58 | for (int i = 1000; i >= 0; i --) { 59 | if (count[i] == 1) { 60 | return i; 61 | } 62 | } 63 | return -1; 64 | } 65 | }; 66 | ``` 67 | 68 | ## 日期 69 | 70 | 2019 年 9 月 18 日 —— 今日又是九一八 71 | -------------------------------------------------------------------------------- /800-899/867. Transpose Matrix 转置矩阵.md: -------------------------------------------------------------------------------- 1 | 2 | 作者: 负雪明烛 3 | id: fuxuemingzhu 4 | 个人博客: http://fuxuemingzhu.cn/ 5 | 6 | --- 7 | @[TOC](目录) 8 | 9 | 题目地址:https://leetcode.com/problems/transpose-matrix/description/ 10 | 11 | ## 题目描述 12 | 13 | Given a matrix A, return the transpose of A. 14 | 15 | The transpose of a matrix is the matrix flipped over it's main diagonal, switching the row and column indices of the matrix. 16 | 17 | 18 | 19 | Example 1: 20 | 21 | Input: [[1,2,3],[4,5,6],[7,8,9]] 22 | Output: [[1,4,7],[2,5,8],[3,6,9]] 23 | 24 | Example 2: 25 | 26 | Input: [[1,2,3],[4,5,6]] 27 | Output: [[1,4],[2,5],[3,6]] 28 | 29 | 30 | Note: 31 | 32 | 1. 1 <= A.length <= 1000 33 | 1. 1 <= A[0].length <= 1000 34 | 35 | ## 题目大意 36 | 37 | 把矩阵进行转置。 38 | 39 | ## 解题方法 40 | 41 | ### 先构建数组再遍历实现翻转 42 | 43 | 第一遍看这个题的时候,感觉挺难的。今天再次看的时候,突然想明白,所谓转置,就是把一个矩阵的行和列进行互换。因此这个题其实就是考察了,把一个原始矩阵通过行列元素互换得到新的矩阵。 44 | 45 | 那么只要我们新建一个行数等于原始列数,列数等于原始行数的矩阵,再对原始矩阵进行遍历即可。 46 | 47 | 时间复杂度是O(MN),空间复杂度是O(1). 48 | 49 | 代码如下: 50 | 51 | ```python 52 | class Solution: 53 | def transpose(self, A): 54 | """ 55 | :type A: List[List[int]] 56 | :rtype: List[List[int]] 57 | """ 58 | rows, cols = len(A), len(A[0]) 59 | res = [[0] * rows for _ in range(cols)] 60 | for row in range(rows): 61 | for col in range(cols): 62 | res[col][row] = A[row][col] 63 | return res 64 | ``` 65 | 66 | ## 日期 67 | 68 | 2018 年 7 月 12 日 —— 天阴阴地潮潮,已经连着两天这样了 69 | 2018 年 11 月 5 日 —— 打了羽毛球,有点累 70 | -------------------------------------------------------------------------------- /100-199/153. Find Minimum in Rotated Sorted Array 寻找旋转排序数组中的最小值.md: -------------------------------------------------------------------------------- 1 | # 【LeetCode】153. Find Minimum in Rotated Sorted Array 解题报告(Python) 2 | 3 | 标签: LeetCode 4 | 5 | --- 6 | 7 | 题目地址:https://leetcode.com/problems/find-minimum-in-rotated-sorted-array/description/ 8 | 9 | ## 题目描述: 10 | 11 | Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand. 12 | 13 | (i.e., 0 1 2 4 5 6 7 might become 4 5 6 7 0 1 2). 14 | 15 | Find the minimum element. 16 | 17 | You may assume no duplicate exists in the array. 18 | 19 | 20 | ## 题目大意 21 | 22 | 找出旋转有序数组中的最小值。 23 | 24 | ## 解题方法 25 | 26 | 这个题是剑指offer上的原题,这里在复习一下。看到有序的数组就想到二分查找。这个是变种而已。 27 | 28 | 注意边界和循环条件。 29 | 30 | ![这里写图片描述](http://img.blog.csdn.net/20180312214100966?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvZnV4dWVtaW5nemh1/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70) 31 | 32 | ```python 33 | class Solution(object): 34 | def findMin(self, nums): 35 | """ 36 | :type nums: List[int] 37 | :rtype: int 38 | """ 39 | if len(nums) == 1: return nums[0] 40 | left, right = 0, len(nums) - 1 41 | mid = left 42 | while nums[left] >= nums[right]: 43 | if left + 1 == right: 44 | mid = right 45 | break 46 | mid = (left + right) / 2 47 | if nums[mid] >= nums[left]: 48 | left = mid 49 | elif nums[mid] <= nums[right]: 50 | right = mid 51 | return nums[mid] 52 | ``` 53 | 54 | ## 日期 55 | 56 | 2018 年 3 月 12 日 -------------------------------------------------------------------------------- /200-299/243. Shortest Word Distance 最短单词距离.md: -------------------------------------------------------------------------------- 1 | 2 | 3 | - 作者: 负雪明烛 4 | - id: fuxuemingzhu 5 | - 个人博客:[http://fuxuemingzhu.cn/](http://fuxuemingzhu.cn/) 6 | 7 | --- 8 | @[TOC](目录) 9 | 10 | 11 | 题目地址:https://leetcode-cn.com/problems/shortest-word-distance/ 12 | 13 | ## 题目描述 14 | 15 | Given a list of words and two words word1 and word2, return the shortest distance between these two words in the list. 16 | 17 | Example: 18 | 19 | Assume that words = ["practice", "makes", "perfect", "coding", "makes"]. 20 | 21 | Input: word1 = “coding”, word2 = “practice” 22 | Output: 3 23 | Input: word1 = "makes", word2 = "coding" 24 | Output: 1 25 | 26 | Note: 27 | - You may assume that word1 does not equal to word2, and word1 and word2 are both in the list. 28 | 29 | ## 题目大意 30 | 31 | 给定一个单词列表和两个单词 word1 和 word2,返回列表中这两个单词之间的最短距离。 32 | 33 | ## 解题方法 34 | 35 | ### 字典 36 | 37 | 字典保存每个单词出现位置,然后对于word1和word2的位置两两交叉求最小值即可。 38 | 39 | C++代码如下: 40 | 41 | ```cpp 42 | class Solution { 43 | public: 44 | int shortestDistance(vector& words, string word1, string word2) { 45 | unordered_map> position; 46 | for (int i = 0; i < words.size(); ++i) { 47 | position[words[i]].push_back(i); 48 | } 49 | int res = INT_MAX; 50 | for (int i : position[word1]) { 51 | for (int j : position[word2]) { 52 | res = min(res, i < j ? j - i : i - j); 53 | } 54 | } 55 | return res; 56 | } 57 | }; 58 | ``` 59 | 60 | ## 日期 61 | 62 | 2019 年 9 月 18 日 —— 今日又是九一八 63 | -------------------------------------------------------------------------------- /900-999/905. Sort Array By Parity 按奇偶排序数组.md: -------------------------------------------------------------------------------- 1 | 2 | 作者: 负雪明烛 3 | id: fuxuemingzhu 4 | 个人博客: http://fuxuemingzhu.cn/ 5 | 6 | --- 7 | @[TOC](目录) 8 | 9 | 题目地址:https://leetcode.com/problems/sort-array-by-parity/description/ 10 | 11 | ## 题目描述: 12 | 13 | Given an array A of non-negative integers, return an array consisting of all the even elements of A, followed by all the odd elements of A. 14 | 15 | You may return any answer array that satisfies this condition. 16 | 17 | 18 | 19 | Example 1: 20 | 21 | Input: [3,1,2,4] 22 | Output: [2,4,3,1] 23 | The outputs [4,2,3,1], [2,4,1,3], and [4,2,1,3] would also be accepted. 24 | 25 | 26 | Note: 27 | 28 | - 1 <= A.length <= 5000 29 | - 0 <= A[i] <= 5000 30 | 31 | ## 题目大意 32 | 33 | 对数组A按照偶数和奇数重新排序,使得偶数在前,奇数在后。可以返回任何一种满足这个条件的数组即可。 34 | 35 | ## 解题方法 36 | 37 | ### 自定义 sorted 函数的 cmp 38 | 39 | 看到排序就写个排序就行了,比较的 key 是对 2 取余数之后的值。这样偶数取余得 0,排在前面,奇数取余得 1,排在后面。 40 | 41 | Python 代码如下: 42 | 43 | ```python 44 | class Solution(object): 45 | def sortArrayByParity(self, A): 46 | """ 47 | :type A: List[int] 48 | :rtype: List[int] 49 | """ 50 | return sorted(A, key = lambda x : x % 2) 51 | ``` 52 | 53 | C++ 代码如下: 54 | 55 | ```python 56 | bool cmp(int i, int j) { 57 | return i % 2 < j % 2; 58 | }; 59 | class Solution { 60 | public: 61 | vector sortArrayByParity(vector& nums) { 62 | sort(nums.begin(), nums.end(), cmp); 63 | return nums; 64 | } 65 | }; 66 | ``` 67 | 68 | - 时间复杂度是: $O(nlogn)$ 69 | - 空间复杂度是:$O(1)$ 70 | 71 | 72 | ## 日期 73 | 74 | 2018 年 9 月 17 日 —— 早上很凉,夜里更凉 75 | -------------------------------------------------------------------------------- /600-699/628. Maximum Product of Three Numbers 三个数的最大乘积.md: -------------------------------------------------------------------------------- 1 | 2 | 作者: 负雪明烛 3 | id: fuxuemingzhu 4 | 个人博客: http://fuxuemingzhu.cn/ 5 | 6 | --- 7 | @[TOC](目录) 8 | 9 | 题目地址:[https://leetcode.com/problems/maximum-product-of-three-numbers/description/][1] 10 | 11 | 12 | ## 题目描述 13 | 14 | Given an integer array, find three numbers whose product is maximum and output the maximum product. 15 | 16 | Example 1: 17 | 18 | Input: [1,2,3] 19 | Output: 6 20 | 21 | Example 2: 22 | 23 | Input: [1,2,3,4] 24 | Output: 24 25 | 26 | Note: 27 | 28 | 1. The length of the given array will be in range [3,104] and all elements are in the range [-1000, 1000]. 29 | 1. Multiplication of any three numbers in the input won't exceed the range of 32-bit signed integer. 30 | 31 | ## 题目大意 32 | 33 | 从一个数组中找出三个数字,求这三个数字的乘积是最大的值。 34 | 35 | 36 | ## 解题方法 37 | 38 | ### 方法一:排序 39 | 40 | 这个题要求数组中三个数乘积最大的值。我觉得可以从为什么问3个数字而不是其他数字去考虑。 41 | 42 | 输入有可能存在负值,所以3个数字的乘积时会考虑到负负得正的情况。只有三个数都是正数或者有只有两个负数时得到的结果是正的。这样,首先通过排序,得到最右边三个数的乘积,和最小的两个负数(如果存在负数)和最大数字的乘积,比较两个乘积的大小就行了。 43 | 44 | 如果排序后取到的三个数存在奇数个负数也没关系,我们取最大值的时候会保证取到最大的。 45 | 46 | ```python 47 | class Solution(object): 48 | def maximumProduct(self, nums): 49 | """ 50 | :type nums: List[int] 51 | :rtype: int 52 | """ 53 | nums.sort() 54 | right = nums[-3] * nums[-2] * nums[-1] 55 | left = nums[0] * nums[1] * nums[-1] 56 | return max(left, right) 57 | ``` 58 | 59 | ## 日期 60 | 61 | 2018 年 1 月 26 日 62 | 2018 年 11 月 17 日 —— 美妙的周末,美丽的天气 63 | 64 | [1]: https://leetcode.com/problems/minimum-index-sum-of-two-lists/description/ 65 | -------------------------------------------------------------------------------- /1000-1099/1064. Fixed Point 不动点.md: -------------------------------------------------------------------------------- 1 | 2 | - 作者: 负雪明烛 3 | - id: fuxuemingzhu 4 | - 个人博客:[http://fuxuemingzhu.cn/](http://fuxuemingzhu.cn/) 5 | 6 | --- 7 | @[TOC](目录) 8 | 9 | 10 | 题目地址:https://leetcode-cn.com/problems/fixed-point/ 11 | 12 | ## 题目描述 13 | 14 | Given an array A of distinct integers sorted in ascending order, return the smallest index i that satisfies `A[i] == i`. Return -1 if no such i exists. 15 | 16 | 17 | 18 | Example 1: 19 | 20 | Input: [-10,-5,0,3,7] 21 | Output: 3 22 | Explanation: 23 | For the given array, A[0] = -10, A[1] = -5, A[2] = 0, A[3] = 3, thus the output is 3. 24 | 25 | Example 2: 26 | 27 | Input: [0,2,5,8,17] 28 | Output: 0 29 | Explanation: 30 | A[0] = 0, thus the output is 0. 31 | 32 | Example 3: 33 | 34 | Input: [-10,-5,3,4,7,9] 35 | Output: -1 36 | Explanation: 37 | There is no such i that A[i] = i, thus the output is -1. 38 | 39 | 40 | Note: 41 | 42 | 1. `1 <= A.length < 10^4` 43 | 1. `-10^9 <= A[i] <= 10^9` 44 | 45 | 46 | ## 题目大意 47 | 48 | 给定已经按升序排列、由不同整数组成的数组 A,返回满足 A[i] == i 的最小索引 i。如果不存在这样的 i,返回 -1。 49 | 50 | ## 解题方法 51 | 52 | ### 暴力求解 53 | 54 | 从头遍历一遍即可。 55 | 56 | C++代码如下: 57 | 58 | ```cpp 59 | class Solution { 60 | public: 61 | int fixedPoint(vector& A) { 62 | const int N = A.size(); 63 | for (int i = 0; i < N; ++i) { 64 | if (A[i] == i) 65 | return i; 66 | } 67 | return -1; 68 | } 69 | }; 70 | ``` 71 | 72 | ## 日期 73 | 74 | 2019 年 9 月 18 日 —— 今日又是九一八 75 | 76 | 77 | [1]: https://blog.csdn.net/fuxuemingzhu/article/details/100977773 78 | -------------------------------------------------------------------------------- /1-99/71. Simplify Path 简化路径.md: -------------------------------------------------------------------------------- 1 | # 【LeetCode】71. Simplify Path 解题报告(Python) 2 | 3 | 标签(空格分隔): LeetCode 4 | 5 | 作者: 负雪明烛 6 | id: fuxuemingzhu 7 | 个人博客: http://fuxuemingzhu.me/ 8 | 9 | --- 10 | 11 | 题目地址:https://leetcode.com/problems/simplify-path/description/ 12 | 13 | ## 题目描述: 14 | 15 | Given an absolute path for a file (Unix-style), simplify it. 16 | 17 | For example, 18 | 19 | path = "/home/", => "/home" 20 | path = "/a/./b/../../c/", => "/c" 21 | 22 | Corner Cases: 23 | 24 | - Did you consider the case where path = "/../"? 25 | In this case, you should return "/". 26 | 27 | - Another corner case is the path might contain multiple slashes '/' together, such as "/home//foo/". 28 | In this case, you should ignore redundant slashes and return "/home/foo". 29 | 30 | 31 | ## 题目大意 32 | 33 | 简化linux路径。 34 | 35 | ## 解题方法 36 | 37 | 看到这种来来回回,增增删删的题,一般都想到用栈。 38 | 39 | 我们把字符串按照/分割之后就得到了每个文件的目录,然后判断路径是添加还是向上层进行返回。这个题很简单了。 40 | 41 | 有一个地方犯了小错误,不能写成if dir == '..' and stack: stack.pop()。这样的话如果栈是空的,就把..进栈了。 42 | 43 | 44 | ```python 45 | class Solution(object): 46 | def simplifyPath(self, path): 47 | """ 48 | :type path: str 49 | :rtype: str 50 | """ 51 | stack = list() 52 | dirs = path.split('/') 53 | for dir in dirs: 54 | if not dir or dir == '.': 55 | continue 56 | if dir == '..': 57 | if stack: 58 | stack.pop() 59 | else: 60 | stack.append(dir) 61 | return '/' + '/'.join(stack) 62 | ``` 63 | 64 | ## 日期 65 | 66 | 2018 年 6 月 26 日 ———— 早睡早起 -------------------------------------------------------------------------------- /100-199/162. Find Peak Element 寻找峰值.md: -------------------------------------------------------------------------------- 1 | # 【LeetCode】162. Find Peak Element 解题报告(Python) 2 | 3 | 标签(空格分隔): LeetCode 4 | 5 | --- 6 | 7 | 题目地址:https://leetcode.com/problems/find-peak-element/description/ 8 | 9 | ## 题目描述: 10 | 11 | A peak element is an element that is greater than its neighbors. 12 | 13 | Given an input array where num[i] ≠ num[i+1], find a peak element and return its index. 14 | 15 | The array may contain multiple peaks, in that case return the index to any one of the peaks is fine. 16 | 17 | You may imagine that num[-1] = num[n] = -∞. 18 | 19 | For example, in array [1, 2, 3, 1], 3 is a peak element and your function should return the index number 2. 20 | 21 | click to show spoilers. 22 | 23 | Note: 24 | Your solution should be in logarithmic complexity. 25 | 26 | Credits: 27 | Special thanks to @ts for adding this problem and creating all test cases. 28 | 29 | 30 | 31 | ## 题目大意 32 | 33 | 找到数组中的一个山峰节点位置,返回这个节点的位置。 34 | 35 | 36 | ## 解题方法 37 | 38 | 用两个mid,判断上坡还是下坡~二叉搜索,在这种题目中很常用~~ 39 | 40 | 代码: 41 | 42 | ```python 43 | class Solution(object): 44 | def findPeakElement(self, nums): 45 | """ 46 | :type nums: List[int] 47 | :rtype: int 48 | """ 49 | left, right = 0, len(nums) - 1 50 | while left < right: 51 | mid1 = (left + right) / 2 52 | mid2 = mid1 + 1 53 | if nums[mid1] < nums[mid2]: 54 | left = mid2 55 | else: 56 | right = mid1 57 | return left 58 | ``` 59 | 60 | ## 日期 61 | 62 | 2018 年 3 月 20 日 ————阳光明媚~ 63 | 64 | 65 | [1]: http://blog.csdn.net/fuxuemingzhu/article/details/51291406 -------------------------------------------------------------------------------- /100-199/187. Repeated DNA Sequences 重复的DNA序列.md: -------------------------------------------------------------------------------- 1 | 作者: 负雪明烛 2 | id: fuxuemingzhu 3 | 个人博客: http://fuxuemingzhu.cn/ 4 | 5 | --- 6 | 7 | 题目地址: https://leetcode.com/problems/repeated-dna-sequences/description/ 8 | 9 | ## 题目描述: 10 | 11 | All DNA is composed of a series of nucleotides abbreviated as A, C, G, and T, for example: "ACGAATTCCG". When studying DNA, it is sometimes useful to identify repeated sequences within the DNA. 12 | 13 | Write a function to find all the 10-letter-long sequences (substrings) that occur more than once in a DNA molecule. 14 | 15 | Example: 16 | 17 | Input: s = "AAAAACCCCCAAAAACCCCCCAAAAAGGGTTT" 18 | 19 | Output: ["AAAAACCCCC", "CCCCCAAAAA"] 20 | 21 | 22 | ## 题目大意 23 | 24 | 在一个字符串中找出连续的十个字符,这十个字符不止在一个地方出现过。 25 | 26 | ## 解题方法 27 | 28 | 遍历+set。 29 | 30 | 做法简单了,需要一个长度是10的字符串切片,从头到尾把字符遍历一遍,然后不停的判断以这个位置开头的10个字符构成的字符串是否看到过,如果看到过就放到另外一个set里。为什么不直接放入list返回呢?因为一个字符串可能会重复多次,为了防止重复添加到结果里,必须set一下。 31 | 32 | 时间复杂度是O(N),空间复杂度是O(N)。 33 | 34 | ```python 35 | class Solution(object): 36 | def findRepeatedDnaSequences(self, s): 37 | """ 38 | :type s: str 39 | :rtype: List[str] 40 | """ 41 | seen = set() 42 | repeated = set() 43 | N = len(s) 44 | for i in range(N): 45 | cur = s[i : i+ 10] 46 | if cur in seen: 47 | repeated.add(cur) 48 | else: 49 | seen.add(cur) 50 | return list(repeated) 51 | ``` 52 | 53 | 54 | 参考资料: 55 | 56 | https://leetcode.com/problems/repeated-dna-sequences/discuss/53855/7-lines-simple-Java-O(n) 57 | 58 | ## 日期 59 | 60 | 2018 年 10 月 11 日 —— 做Hard题真的很难 61 | -------------------------------------------------------------------------------- /300-399/346. Moving Average from Data Stream 数据流中的移动平均值.md: -------------------------------------------------------------------------------- 1 | 2 | - 作者: 负雪明烛 3 | - id: fuxuemingzhu 4 | - 个人博客:[http://fuxuemingzhu.cn/](http://fuxuemingzhu.cn/) 5 | 6 | --- 7 | @[TOC](目录) 8 | 9 | 10 | 题目地址:https://leetcode-cn.com/problems/moving-average-from-data-stream/ 11 | 12 | ## 题目描述 13 | 14 | Given a stream of integers and a window size, calculate the moving average of all integers in the sliding window. 15 | 16 | Example: 17 | 18 | MovingAverage m = new MovingAverage(3); 19 | m.next(1) = 1 20 | m.next(10) = (1 + 10) / 2 21 | m.next(3) = (1 + 10 + 3) / 3 22 | m.next(5) = (10 + 3 + 5) / 3 23 | 24 | 25 | ## 题目大意 26 | 27 | 计算一个固定大小的滑动窗口中的平均数。 28 | 29 | ## 解题方法 30 | 31 | ### 队列 32 | 33 | 一个固定大小的队列,每次插入数据之前判断队列是否已满,删除队列的头部元素,在队列的尾部插入元素即可。由于每次都求和比较耗时,因此可以使用一个sum变量保存队列里面元素的和。 34 | 35 | C++代码如下: 36 | 37 | ```cpp 38 | class MovingAverage { 39 | public: 40 | /** Initialize your data structure here. */ 41 | MovingAverage(int size) { 42 | cap = size; 43 | } 44 | 45 | double next(int val) { 46 | if (que.size() >= cap) { 47 | sum -= que.front(); 48 | que.pop_front(); 49 | } 50 | que.push_back(val); 51 | sum += val; 52 | return (double) sum / que.size(); 53 | } 54 | private: 55 | deque que; 56 | int cap = 0; 57 | int count = 0; 58 | long long sum = 0; 59 | }; 60 | 61 | /** 62 | * Your MovingAverage object will be instantiated and called as such: 63 | * MovingAverage* obj = new MovingAverage(size); 64 | * double param_1 = obj->next(val); 65 | */ 66 | ``` 67 | 68 | 69 | ## 日期 70 | 71 | 2019 年 9 月 18 日 —— 今日又是九一八 72 | -------------------------------------------------------------------------------- /1400-1499/1470. Shuffle the Array 重新排列数组.md: -------------------------------------------------------------------------------- 1 | # 2 | 3 | - 作者: 负雪明烛 4 | - id: fuxuemingzhu 5 | - 个人博客:[http://fuxuemingzhu.cn/](http://fuxuemingzhu.cn/) 6 | 7 | --- 8 | @[TOC](目录) 9 | 10 | 11 | 题目地址:https://leetcode-cn.com/problems/shuffle-the-array/ 12 | 13 | 14 | # 题目描述 15 | 16 | 17 | 给你一个数组 `nums` ,数组中有 `2n` 个元素,按 `[x1,x2,...,xn,y1,y2,...,yn]` 的格式排列。 18 | 19 | 请你将数组按 `[x1,y1,x2,y2,...,xn,yn]` 格式重新排列,返回重排后的数组。 20 | 21 | 示例 1: 22 | 23 | 输入:nums = [2,5,1,3,4,7], n = 3 24 | 输出:[2,3,5,4,1,7] 25 | 解释:由于 x1=2, x2=5, x3=1, y1=3, y2=4, y3=7 ,所以答案为 [2,3,5,4,1,7] 26 | 27 | 示例 2: 28 | 29 | 输入:nums = [1,2,3,4,4,3,2,1], n = 4 30 | 输出:[1,4,2,3,3,2,4,1] 31 | 32 | 示例 3: 33 | 34 | 输入:nums = [1,1,2,2], n = 2 35 | 输出:[1,2,1,2] 36 | 37 | 提示: 38 | 39 | 1. `1 <= n <= 500` 40 | 1. `nums.length == 2n` 41 | 1. `1 <= nums[i] <= 10^3` 42 | 43 | 44 | # 题目大意 45 | 46 | 略。 47 | 48 | # 解题方法 49 | 50 | 本题比较简单,可以重拳出击。 51 | 52 | 用一个新的数组按照 `nums[0], nums[n], nums[1], nums[n + 1], ...` 的顺序依次保存所有的排列即可。 53 | 54 | Python 代码如下: 55 | 56 | ```python 57 | class Solution: 58 | def shuffle(self, nums: List[int], n: int) -> List[int]: 59 | res = [] 60 | for i in range(n): 61 | res.append(nums[i]) 62 | res.append(nums[i + n]) 63 | return res 64 | ``` 65 | 66 | **欢迎关注[负雪明烛的刷题博客](https://blog.csdn.net/fuxuemingzhu),leetcode刷题800多,每道都讲解了详细写法!** 67 | 68 | 69 | 70 | # 日期 71 | 72 | 2020 年 6 月 14 日 —— 今晚争取也直播讲题 73 | 74 | 75 | [1]: https://assets.leetcode-cn.com/aliyun-lc-upload/uploads/2020/05/30/leetcode_max_area_2.png 76 | [2]: https://assets.leetcode-cn.com/aliyun-lc-upload/uploads/2020/05/30/leetcode_max_area_3.png 77 | -------------------------------------------------------------------------------- /300-399/372. Super Pow 超级次方.md: -------------------------------------------------------------------------------- 1 | 作者: 负雪明烛 2 | id: fuxuemingzhu 3 | 个人博客: http://fuxuemingzhu.cn/ 4 | 5 | --- 6 | 7 | 题目地址: https://leetcode.com/problems/super-pow/description/ 8 | 9 | ## 题目描述: 10 | 11 | Your task is to calculate ``a^b`` mod 1337 where a is a positive integer and b is an extremely large positive integer given in the form of an array. 12 | 13 | Example 1: 14 | 15 | Input: a = 2, b = [3] 16 | Output: 8 17 | 18 | Example 2: 19 | 20 | Input: a = 2, b = [1,0] 21 | Output: 1024 22 | 23 | ## 题目大意 24 | 25 | 实现a的b次方的函数。但是给出的b是超级巨大的,而且是用数组保存着每一位的。 26 | 27 | ## 解题方法 28 | 29 | 这个题是[50. Pow(x, n)][1]的拓展题,都是求幂的问题,但是这个题由于数值大,需要模1337,对于模什么数一般都是瞎选的,不用考虑这个题为什么模这个数。 30 | 31 | 我觉得这个题的难点在于,如何求数组表示的超级大的数字b次幂。原来是求幂也可以做展开,比如求2^23,相当于求(2^2)^10 * (2^3).也就是说把前面以求的结果求一次10次幂,然后再去求后面的幂。 32 | 33 | 注意这里每次计算的结果都要%1337,保留后面的部分。前面被模掉的部分对结果不影响的,所以不用顾虑太多,直接求模。 34 | 35 | 时间复杂度是O(N),空间复杂度是O(1)。N是b的长度。 36 | 37 | ```python 38 | class Solution(object): 39 | def superPow(self, a, b): 40 | """ 41 | :type a: int 42 | :type b: List[int] 43 | :rtype: int 44 | """ 45 | res = 1 46 | for x in b: 47 | res = self.pow(res, 10) * self.pow(a, x) % 1337 48 | return res 49 | 50 | def pow(self, a, b): 51 | if b == 0 or a == 1: return 1 52 | if b % 2: 53 | return a * self.pow(a, b - 1) % 1337 54 | return self.pow((a * a) % 1337, b / 2) % 1337 55 | ``` 56 | 57 | 58 | 参考资料: 59 | 60 | http://www.cnblogs.com/grandyang/p/5651982.html 61 | 62 | ## 日期 63 | 64 | 2018 年 10 月 7 日 —— 假期最后一天!! 65 | 66 | 67 | [1]: https://blog.csdn.net/fuxuemingzhu/article/details/82960833 68 | -------------------------------------------------------------------------------- /1000-1099/1037. Valid Boomerang 有效的回旋镖.md: -------------------------------------------------------------------------------- 1 | 作者: 负雪明烛 2 | id: fuxuemingzhu 3 | 个人博客: http://fuxuemingzhu.cn/ 4 | 5 | --- 6 | @[TOC](目录) 7 | 8 | 9 | 题目地址:https://leetcode.com/problems/valid-boomerang/ 10 | 11 | ## 题目描述 12 | 13 | A boomerang is a set of 3 points that are all distinct and not in a straight line. 14 | 15 | Given a list of three points in the plane, return whether these points are a boomerang. 16 | 17 | Example 1: 18 | 19 | Input: [[1,1],[2,3],[3,2]] 20 | Output: true 21 | 22 | Example 2: 23 | 24 | Input: [[1,1],[2,2],[3,3]] 25 | Output: false 26 | 27 | 28 | Note: 29 | 30 | 1. `points.length == 3` 31 | 1. `points[i].length == 2` 32 | 1. `0 <= points[i][j] <= 100` 33 | 34 | ## 题目大意 35 | 36 | 判断三个点是否不重叠,并且不在一个直线上。 37 | 38 | ## 解题方法 39 | 40 | ### 中学数学题 41 | 42 | 不重叠很好说,三个点两两判断即可。 43 | 44 | 判断三个点是不是在一个直线上,那么三个点中任意两个点的连线之斜率是否相等(或者不存在)。用数学公式表示就是dx1 * dy2 == dx2 * dy1则在一条直线上。 45 | 46 | C++代码如下: 47 | 48 | ```cpp 49 | class Solution { 50 | public: 51 | bool isBoomerang(vector>& points) { 52 | if (points[0][0] == points[1][0] && points[0][1] == points[1][1]) 53 | return false; 54 | if (points[0][0] == points[2][0] && points[0][1] == points[2][1]) 55 | return false; 56 | if (points[1][0] == points[2][0] && points[1][1] == points[2][1]) 57 | return false; 58 | int dx1 = points[1][0] - points[0][0]; 59 | int dy1 = points[1][1] - points[0][1]; 60 | int dx2 = points[2][0] - points[1][0]; 61 | int dy2 = points[2][1] - points[1][1]; 62 | return dx1 * dy2 != dx2 * dy1; 63 | } 64 | }; 65 | ``` 66 | 67 | ## 日期 68 | 69 | 2019 年 8 月 31 日 —— 赶在月底做个题 70 | -------------------------------------------------------------------------------- /200-299/293. Flip Game 翻转游戏.md: -------------------------------------------------------------------------------- 1 | 2 | 3 | - 作者: 负雪明烛 4 | - id: fuxuemingzhu 5 | - 个人博客:[http://fuxuemingzhu.cn/](http://fuxuemingzhu.cn/) 6 | 7 | --- 8 | @[TOC](目录) 9 | 10 | 11 | 题目地址:https://leetcode-cn.com/problems/flip-game/ 12 | 13 | ## 题目描述 14 | 15 | You are playing the following Flip Game with your friend: Given a string that contains only these two characters: `+` and `-`, you and your friend take turns to flip two consecutive `"++"` into `"--"`. The game ends when a person can no longer make a move and therefore the other person will be the winner. 16 | 17 | Write a function to compute all possible states of the string after one valid move. 18 | 19 | Example: 20 | 21 | Input: s = "++++" 22 | Output: 23 | [ 24 | "--++", 25 | "+--+", 26 | "++--" 27 | ] 28 | 29 | Note: If there is no valid move, return an empty list []. 30 | 31 | 32 | ## 题目大意 33 | 34 | 把给定字符串中的`++`换成`--`,返回所有可能的结果。 35 | 36 | ## 解题方法 37 | 38 | ### 遍历 39 | 40 | 题目表述不清,其实只要把所有`++`换成`--`即可,那就很简单了,直接遍历一次就行了。 41 | 42 | C++代码如下: 43 | 44 | ```cpp 45 | class Solution { 46 | public: 47 | vector generatePossibleNextMoves(string s) { 48 | vector res; 49 | if (s.empty() || s.size() == 1) return res; 50 | for (int i = 1; i < s.size(); ++i) { 51 | if (s[i] == '+' && s[i - 1] == '+') { 52 | string move = s; 53 | move[i] = move[i - 1] = '-'; 54 | res.push_back(move); 55 | } 56 | } 57 | return res; 58 | } 59 | }; 60 | ``` 61 | 62 | ## 日期 63 | 64 | 2019 年 9 月 19 日 —— 举杯邀明月,对影成三人 65 | 66 | 67 | [1]: https://blog.csdn.net/fuxuemingzhu/article/details/100977773 68 | -------------------------------------------------------------------------------- /300-399/386. Lexicographical Numbers 字典序排数.md: -------------------------------------------------------------------------------- 1 | ## 【LeetCode】386. Lexicographical Numbers 解题报告(Python) 2 | 3 | 标签(空格分隔): LeetCode 4 | 5 | 作者: 负雪明烛 6 | id: fuxuemingzhu 7 | 个人博客: http://fuxuemingzhu.me/ 8 | 9 | --- 10 | 11 | 题目地址:https://leetcode.com/problems/lexicographical-numbers/description/ 12 | 13 | ## 题目描述: 14 | 15 | Given an integer n, return 1 - n in lexicographical order. 16 | 17 | For example, given 13, return: [1,10,11,12,13,2,3,4,5,6,7,8,9]. 18 | 19 | Please optimize your algorithm to use less time and space. The input size may be as large as 5,000,000. 20 | 21 | 22 | 23 | ## 题目大意 24 | 25 | 给了一个数字n,找出1~n的所有数字的字典序排列。 26 | 27 | ## 解题方法 28 | 29 | 题目中说了输入可能是5百万,那么只能用O(N)的时间复杂度。 30 | 31 | 这个题的思路我是参考的[Lexicographical Numbers 字典顺序的数字][1],不太好想。 32 | 33 | 1. 如果curr乘以10小于等于n,那么下个数字应该是curr末尾补0; 34 | 2. 如果curr已经到达了n,那么说明各位数字已经到头了,应该变化十位数字了,所以除以10,再加一。这时可能会出现恰好进位的情况,而字典序可能是从末尾没有0的数字开始的,所以要把末尾的0去掉。 35 | 36 | 比如``n=300``时,会有这个队列``1,10,100,101,102...198,199,2,20,200,201...299,3,30,300`` 37 | 38 | 代码如下: 39 | 40 | ```python3 41 | class Solution: 42 | def lexicalOrder(self, n): 43 | """ 44 | :type n: int 45 | :rtype: List[int] 46 | """ 47 | cur = 1 48 | ans = [] 49 | for i in range(n): 50 | ans.append(cur) 51 | if cur * 10 <= n: 52 | cur *= 10 53 | else: 54 | if cur >= n: 55 | cur //= 10 56 | cur += 1 57 | while cur % 10 == 0: 58 | cur //= 10 59 | return ans 60 | ``` 61 | 62 | ## 日期 63 | 64 | 2018 年 8 月 17 日 ———— 别人七夕,我在刷题。。 65 | 66 | 67 | [1]: http://www.cnblogs.com/grandyang/p/5798275.html -------------------------------------------------------------------------------- /400-499/400. Nth Digit 第 N 位数字.md: -------------------------------------------------------------------------------- 1 | 作者: 负雪明烛 2 | id: fuxuemingzhu 3 | 个人博客: http://fuxuemingzhu.cn/ 4 | 5 | --- 6 | @[TOC](目录) 7 | 8 | 9 | 题目地址:https://leetcode.com/problems/reach-a-number/description/ 10 | 11 | 12 | ## 题目描述 13 | 14 | Find the nth digit of the infinite integer sequence 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, ... 15 | 16 | Note: 17 | 18 | 1. n is positive and will fit within the range of a 32-bit signed integer (n < 231). 19 | 20 | Example 1: 21 | 22 | Input: 23 | 3 24 | 25 | Output: 26 | 3 27 | Example 2: 28 | 29 | Input: 30 | 11 31 | 32 | Output: 33 | 0 34 | 35 | Explanation: 36 | The 11th digit of the sequence 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, ... is a 0, which is part of the number 10. 37 | 38 | ## 题目大意 39 | 40 | 找出一个连续的自然数序列中,第N``位``数字是多少。 41 | 42 | ## 解题方法 43 | 44 | 我们要得到第N位数字,如果直接暴力是超时的。正确的做法是找规律:个位数字有9个,2位数字有9*10=90个,3位数字有9*100=900个……所以我们先求出n是几位数字,然后判断第n个数字应该落在哪个自然数上,最后再求这个自然数会落在自然数的那一位上。 45 | 46 | ```python 47 | class Solution(object): 48 | def findNthDigit(self, n): 49 | """ 50 | :type n: int 51 | :rtype: int 52 | """ 53 | _len = 1 54 | cnt = 9 55 | start = 1 56 | while n > _len * cnt: 57 | n -= _len * cnt 58 | _len += 1 59 | cnt *= 10 60 | start *= 10 61 | start += (n - 1) / _len 62 | return int(str(start)[(n - 1) % _len]) 63 | ``` 64 | 65 | 66 | 参考资料:http://www.cnblogs.com/grandyang/p/5891871.html 67 | 68 | ## 日期 69 | 70 | 2018 年 11 月 27 日 —— 最近的雾霾太可怕 71 | 72 | 73 | [1]: http://zxi.mytechroad.com/blog/dynamic-programming/leetcode-730-count-different-palindromic-subsequences/ 74 | -------------------------------------------------------------------------------- /100-199/137. Single Number II 只出现一次的数字 II.md: -------------------------------------------------------------------------------- 1 | # 【LeetCode】137. Single Number II 解题报告(Python) 2 | 3 | 标签: LeetCode 4 | 5 | --- 6 | 7 | 题目地址:https://leetcode.com/problems/single-number-ii/description/ 8 | 9 | ## 题目描述: 10 | 11 | Given an array of integers, every element appears three times except for one, which appears exactly once. Find that single one. 12 | 13 | Note: 14 | 15 | Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory? 16 | 17 | ## 题目大意 18 | 19 | 有一个数组,每个数字都出现了3次,除了其中的某一个只出现了1次。找出这个只出现了1次的数字。 20 | 21 | ## 解题方法 22 | 23 | 这个题本身不是很难,注意,不能使用异或运算搞定了。这个题的做法是把32位的二进制数进行遍历,统计每个数字的每一位出现的和。因为每个数字出现了3次或者1次,所以如果某一位出现的次数不是3次,那么这个位置一定是因为那个只出现1次的数字导致的。用来保存结果的res是0,因此使用或操作,就能把这个位置的数字变成1. 24 | 25 | 需要注意的是:python的整型方便是方便了,但是由于其没有最大值,所以,当输入是一堆负数的时候,会导致认为结果是个整数!因为32位有符号的被认为成了无符号的,所以这就是Python的一个坑。。 26 | 27 | 注意一下结论,以后出现位运算的时候,需要对结果进行判断一下最好。如果不在这个范围内,说明了结果被认为是无符号的数了,需要减去2 ^ 32。 28 | 29 | > 16位整数中-32768到32767 30 | > 31 | > 32位整数中-2147483648到2147 483 647 32 | > 33 | > 34 | > 最高位为符号位 ,请您计算2的15次方以及2的31次方,就可以得到以上结果 35 | > 36 | > 16位整数-2^15~2^15-1 37 | > 38 | > 32位整数-2^31~2^31-1 39 | 40 | ```python 41 | class Solution(object): 42 | def singleNumber(self, nums): 43 | """ 44 | :type nums: List[int] 45 | :rtype: int 46 | """ 47 | res = 0 48 | for i in range(32): 49 | cnt = 0 50 | mask = 1 << i 51 | for num in nums: 52 | if num & mask: 53 | cnt += 1 54 | if cnt % 3 == 1: 55 | res |= mask 56 | if res >= 2 ** 31: 57 | res -= 2 ** 32 58 | return res 59 | ``` 60 | 61 | ## 日期 62 | 63 | 2018 年 3 月 14 日 --霍金去世日 -------------------------------------------------------------------------------- /100-199/151. Reverse Words in a String 翻转字符串里的单词.md: -------------------------------------------------------------------------------- 1 | - 作者: 负雪明烛 2 | - id: fuxuemingzhu 3 | - 个人博客:[http://fuxuemingzhu.cn/](http://fuxuemingzhu.cn/) 4 | 5 | --- 6 | 7 | @[TOC](目录) 8 | 9 | 题目地址:https://leetcode.com/problems/reverse-words-in-a-string/description/ 10 | 11 | ## 题目描述 12 | 13 | Given an input string, reverse the string word by word. 14 | 15 | Example 1: 16 | 17 | Input: "the sky is blue" 18 | Output: "blue is sky the" 19 | 20 | Example 2: 21 | 22 | Input: " hello world! " 23 | Output: "world! hello" 24 | Explanation: Your reversed string should not contain leading or trailing spaces. 25 | 26 | Example 3: 27 | 28 | Input: "a good example" 29 | Output: "example good a" 30 | Explanation: You need to reduce multiple spaces between two words to a single space in the reversed string. 31 | 32 | Note: 33 | 34 | - A word is defined as a sequence of non-space characters. 35 | - Input string may contain leading or trailing spaces. However, your reversed string should not contain leading or trailing spaces. 36 | - You need to reduce multiple spaces between two words to a single space in the reversed string. 37 | 38 | Follow up: For C programmers, try to solve it in-place in O(1) space. 39 | 40 | 41 | ## 题目大意 42 | 43 | 翻转字符串里面的单词。同时去掉多余的空格。 44 | 45 | ## 解题方法 46 | 47 | 字符串操作直接放弃 C++ ,一般都选择 Python。建议大家刷题的时候会 Python。 48 | 49 | Python 的 split() 函数: 50 | 51 | - split()的时候,多个连续空格当成分割符; 52 | - split(' ')的时候,多个空格都要分割,每个空格分割出来空。 53 | 54 | 所以可以直接用split()函数,把多个连续空格当成分割符,进行分割。 55 | 56 | 然后再翻转字符串。 57 | 58 | ```python 59 | class Solution: 60 | def reverseWords(self, s: str) -> str: 61 | return " ".join(s.split()[::-1]) 62 | ``` 63 | 64 | ## 日期 65 | 66 | 2018 年 6 月 26 日 —— 早睡早起 67 | 2020 年 4 月 10 日 —— 春眠不觉晓 68 | -------------------------------------------------------------------------------- /200-299/246. Strobogrammatic Number 中心对称数.md: -------------------------------------------------------------------------------- 1 | 2 | 3 | - 作者: 负雪明烛 4 | - id: fuxuemingzhu 5 | - 个人博客:[http://fuxuemingzhu.cn/](http://fuxuemingzhu.cn/) 6 | 7 | --- 8 | @[TOC](目录) 9 | 10 | 11 | 题目地址:https://leetcode-cn.com/problems/strobogrammatic-number/ 12 | 13 | ## 题目描述 14 | 15 | A strobogrammatic number is a number that looks the same when rotated 180 degrees (looked at upside down). 16 | 17 | Write a function to determine if a number is strobogrammatic. The number is represented as a string. 18 | 19 | Example 1: 20 | 21 | Input: "69" 22 | Output: true 23 | 24 | Example 2: 25 | 26 | Input: "88" 27 | Output: true 28 | 29 | Example 3: 30 | 31 | Input: "962" 32 | Output: false 33 | 34 | ## 题目大意 35 | 36 | 中心对称数是指一个数字在旋转了 180 度之后看起来依旧相同的数字(或者上下颠倒地看)。 37 | 请写一个函数来判断该数字是否是中心对称数,其输入将会以一个字符串的形式来表达数字。 38 | 39 | 40 | ## 解题方法 41 | 42 | ### 字典 43 | 44 | 这个题和[1056. Confusing Number][1]是类似的,只不过这个题目使用的是字符串,因此需要更小心:字符串如果转整数越界!所以使用一个指针从最右边移动到最左边,把翻转后的字符拼接到一起,判断和原始字符串是否相等。 45 | 46 | C++代码如下: 47 | 48 | ```cpp 49 | class Solution { 50 | public: 51 | bool isStrobogrammatic(string num) { 52 | if (num.empty()) return false; 53 | unordered_map m{{'0', '0'}, {'1', '1'}, {'6', '9'}, {'8', '8'}, {'9', '6'}}; 54 | string rotate; 55 | int pos = num.size() - 1; 56 | while (pos != -1) { 57 | char mod = num[pos]; 58 | if (!m.count(mod)) 59 | return false; 60 | rotate += m[mod]; 61 | pos --; 62 | } 63 | return rotate == num; 64 | } 65 | }; 66 | ``` 67 | 68 | ## 日期 69 | 70 | 2019 年 9 月 19 日 —— 举杯邀明月,对影成三人 71 | 72 | 73 | [1]: https://blog.csdn.net/fuxuemingzhu/article/details/100992424 74 | -------------------------------------------------------------------------------- /1100-1199/1134. Armstrong Number 阿姆斯特朗数.md: -------------------------------------------------------------------------------- 1 | 2 | - 作者: 负雪明烛 3 | - id: fuxuemingzhu 4 | - 个人博客:[http://fuxuemingzhu.cn/](http://fuxuemingzhu.cn/) 5 | 6 | --- 7 | @[TOC](目录) 8 | 9 | 10 | 题目地址:https://leetcode-cn.com/problems/check-if-a-number-is-majority-element-in-a-sorted-array/ 11 | 12 | ## 题目描述 13 | 14 | The `k`-digit number `N` is an Armstrong number if and only if the `k`-th power of each digit sums to `N`. 15 | 16 | Given a positive integer `N`, return true if and only if it is an Armstrong number. 17 | 18 | Example 1: 19 | 20 | Input: 153 21 | Output: true 22 | Explanation: 23 | 153 is a 3-digit number, and 153 = 1^3 + 5^3 + 3^3. 24 | 25 | Example 2: 26 | 27 | Input: 123 28 | Output: false 29 | Explanation: 30 | 123 is a 3-digit number, and 123 != 1^3 + 2^3 + 3^3 = 36. 31 | 32 | Note: 33 | 34 | 1. `1 <= N <= 10^8` 35 | 36 | ## 题目大意 37 | 38 | 给你一个整数数组 A,请找出并返回在该数组中仅出现一次的最大整数。 39 | 40 | 如果不存在这个只出现一次的整数,则返回 -1。 41 | 42 | ## 解题方法 43 | 44 | ### 直接计算 45 | 46 | 先算k,然后判断即可。 47 | 48 | C++代码如下: 49 | 50 | ```cpp 51 | class Solution { 52 | public: 53 | bool isArmstrong(int N) { 54 | int k = 0; 55 | int temp = N; 56 | while (temp != 0) { 57 | k++; 58 | temp /= 10; 59 | } 60 | long long res = 0; 61 | temp = N; 62 | while (temp != 0) { 63 | int mod = temp % 10; 64 | res += pow(mod, k); 65 | temp /= 10; 66 | } 67 | return res == N; 68 | } 69 | int pow(int N, int k) { 70 | int res = 1; 71 | while (k --) { 72 | res *= N; 73 | } 74 | return res; 75 | } 76 | }; 77 | ``` 78 | 79 | ## 日期 80 | 81 | 2019 年 9 月 18 日 —— 今日又是九一八 82 | -------------------------------------------------------------------------------- /500-599/593. Valid Square 有效的正方形.md: -------------------------------------------------------------------------------- 1 | # 【LeetCode】593. Valid Square 解题报告(Python) 2 | 3 | 作者: 负雪明烛 4 | id: fuxuemingzhu 5 | 个人博客: http://fuxuemingzhu.cn/ 6 | 7 | --- 8 | 9 | 题目地址:https://leetcode.com/problems/valid-square/description/ 10 | 11 | ## 题目描述: 12 | 13 | Given the coordinates of four points in 2D space, return whether the four points could construct a square. 14 | 15 | The coordinate (x,y) of a point is represented by an integer array with two integers. 16 | 17 | Example: 18 | 19 | Input: p1 = [0,0], p2 = [1,1], p3 = [1,0], p4 = [0,1] 20 | Output: True 21 | 22 | Note: 23 | 24 | 1. All the input integers are in the range [-10000, 10000]. 25 | 1. A valid square has four equal sides with positive length and four equal angles (90-degree angles). 26 | 1. Input points have no order. 27 | 28 | ## 题目大意 29 | 30 | 给出4个点,看能不能构成正方形。 31 | 32 | ## 解题方法 33 | 34 | 数学问题还得数学好才行。我们想一想,肯定要按照边来判断。一个四边形有6条边,如果是正方形的话需要满足,4条相等的短边,以及两边相等的对角线边。 35 | 36 | 所以我们计算一下边的长度,然后判断一下是否只有两类边即可。注意四边形没有长度为0的边。 37 | 38 | 时间复杂度是O(1),空间复杂度是O(1). 39 | 40 | 代码如下: 41 | 42 | ```python 43 | class Solution(object): 44 | def validSquare(self, p1, p2, p3, p4): 45 | """ 46 | :type p1: List[int] 47 | :type p2: List[int] 48 | :type p3: List[int] 49 | :type p4: List[int] 50 | :rtype: bool 51 | """ 52 | def d(point1, point2): 53 | return (point1[0] - point2[0]) ** 2 + (point1[1] - point2[1]) ** 2 54 | s = set([d(p1, p2), d(p1, p3), d(p1, p4), d(p2, p3), d(p2, p4), d(p3, p4)]) 55 | return 0 not in s and len(s) == 2 56 | ``` 57 | 58 | 参考资料: 59 | 60 | https://leetcode.com/problems/valid-square/discuss/103442/C++-3-lines-(unordered_set) 61 | 62 | ## 日期 63 | 64 | 2018 年 9 月 20 日 —— 趁年轻多读书 65 | -------------------------------------------------------------------------------- /500-599/561. Array Partition I 数组拆分 I.md: -------------------------------------------------------------------------------- 1 | 2 | 作者: 负雪明烛 3 | id: fuxuemingzhu 4 | 个人博客: http://fuxuemingzhu.cn/ 5 | 6 | --- 7 | @[TOC](目录) 8 | 9 | 题目地址:[https://leetcode.com/problems/array-partition-i/#/description][1] 10 | 11 | 12 | ## 题目描述 13 | 14 | Given an array of 2n integers, your task is to group these integers into n pairs of integer, say (a1, b1), (a2, b2), ..., (an, bn) which makes sum of min(ai, bi) for all i from 1 to n as large as possible. 15 | 16 | Example 1: 17 | 18 | Input: [1,4,3,2] 19 | 20 | Output: 4 21 | Explanation: n is 2, and the maximum sum of pairs is 4. 22 | 23 | Note: 24 | 25 | 1. n is a positive integer, which is in the range of [1, 10000]. 26 | 2. All the integers in the array will be in the range of [-10000, 10000]. 27 | 28 | ## 题目大意 29 | 30 | 给出2n个数字,找出如何划分数据使每个括号内的最小值的和是最大的。 31 | 32 | ## 解题方法 33 | 34 | ### 排序 35 | 36 | 这个题我的方法比较简单直白。那么我想,比较大的数字一定要和比较大的数字在一起才行,否则括号内的小的结果是较小的数字。所以先排序,排序后的结果找每个组中数据的第一个数字即可。 37 | 38 | 时间复杂度是O(NlogN),空间复杂度是O(1). 39 | 40 | Java代码如下: 41 | 42 | ```java 43 | public class Solution { 44 | public int arrayPairSum(int[] nums) { 45 | Arrays.sort(nums); 46 | int ans = 0; 47 | for(int i = 0; i < nums.length; i += 2){ 48 | ans += nums[i]; 49 | } 50 | return ans; 51 | } 52 | } 53 | ``` 54 | 55 | python版本可以写的更简单,因为可以使用切片直接取出偶数位置的数字进行求和。 56 | 57 | ```python 58 | class Solution: 59 | def arrayPairSum(self, nums): 60 | """ 61 | :type nums: List[int] 62 | :rtype: int 63 | """ 64 | nums.sort() 65 | return sum(nums[::2]) 66 | ``` 67 | 68 | ## 日期 69 | 70 | 2017 年 5 月 8 日 71 | 2018 年 11 月 5 日 —— 打了羽毛球,有点累 72 | 73 | [1]: https://leetcode.com/problems/array-partition-i/#/description 74 | -------------------------------------------------------------------------------- /1400-1499/1408. String Matching in an Array 数组中的字符串匹配.md: -------------------------------------------------------------------------------- 1 | - 作者: 负雪明烛 2 | - id: fuxuemingzhu 3 | - 个人博客:[http://fuxuemingzhu.cn/](http://fuxuemingzhu.cn/) 4 | 5 | --- 6 | @[TOC](目录) 7 | 8 | 9 | 题目地址:https://leetcode-cn.com/problems/string-matching-in-an-array/ 10 | 11 | # 题目描述 12 | 13 | 给你一个字符串数组 `words` ,数组中的每个字符串都可以看作是一个单词。请你按 任意 顺序返回 `words` 中是其他单词的子字符串的所有单词。 14 | 15 | 如果你可以删除 `words[j]` 最左侧和/或最右侧的若干字符得到 `word[i]` ,那么字符串 `words[i]` 就是 `words[j]` 的一个子字符串。 16 | 17 | 18 | 19 | 示例 1: 20 | 21 | 输入:words = ["mass","as","hero","superhero"] 22 | 输出:["as","hero"] 23 | 解释:"as" 是 "mass" 的子字符串,"hero" 是 "superhero" 的子字符串。 24 | ["hero","as"] 也是有效的答案。 25 | 26 | 示例 2: 27 | 28 | 输入:words = ["leetcode","et","code"] 29 | 输出:["et","code"] 30 | 解释:"et" 和 "code" 都是 "leetcode" 的子字符串。 31 | 32 | 示例 3: 33 | 34 | 输入:words = ["blue","green","bu"] 35 | 输出:[] 36 | 37 | 38 | 提示: 39 | 40 | 1. `1 <= words.length <= 100` 41 | 1. `1 <= words[i].length <= 30` 42 | 1. `words[i]` 仅包含小写英文字母。 43 | 1. 题目数据 保证 每个 `words[i]` 都是独一无二的。 44 | 45 | 46 | # 题目大意 47 | 48 | 看有哪些词被另外一个词所包含。 49 | 50 | # 解题方法 51 | 52 | ## 暴力遍历 53 | 54 | 题目给出的规模很少,所以直接暴力两两遍历,直接判断其中一个是不是包含另外一个单词。 55 | 56 | Python代码如下: 57 | 58 | ```python 59 | class Solution: 60 | def stringMatching(self, words: List[str]) -> List[str]: 61 | res = set() 62 | for word in words: 63 | for cur in words: 64 | if cur in word and cur != word: 65 | res.add(cur) 66 | return list(res) 67 | ``` 68 | 69 | 70 | **欢迎关注[负雪明烛的刷题博客](https://blog.csdn.net/fuxuemingzhu),leetcode刷题800多,每道都讲解了详细写法!** 71 | 72 | # 日期 73 | 74 | 2020 年 4 月 12 日 —— dp问题还是不太会 75 | 76 | 77 | [1]: https://blog.csdn.net/fuxuemingzhu/article/details/79451733 78 | -------------------------------------------------------------------------------- /800-899/896. Monotonic Array 单调数列.md: -------------------------------------------------------------------------------- 1 | 2 | 作者: 负雪明烛 3 | id: fuxuemingzhu 4 | 个人博客: http://fuxuemingzhu.cn/ 5 | 6 | --- 7 | @[TOC](目录) 8 | 9 | 题目地址:https://leetcode.com/problems/monotonic-array/description/ 10 | 11 | ## 题目描述 12 | 13 | An array is monotonic if it is either monotone increasing or monotone decreasing. 14 | 15 | An array ``A`` is monotone increasing if for all ``i <= j``, ``A[i] <= A[j]``. An array ``A`` is monotone decreasing if for all ``i <= j``, ``A[i] >= A[j]``. 16 | 17 | Return ``true`` if and only if the given array ``A`` is monotonic. 18 | 19 | 20 | 21 | Example 1: 22 | 23 | Input: [1,2,2,3] 24 | Output: true 25 | 26 | Example 2: 27 | 28 | Input: [6,5,4,4] 29 | Output: true 30 | 31 | Example 3: 32 | 33 | Input: [1,3,2] 34 | Output: false 35 | 36 | Example 4: 37 | 38 | Input: [1,2,4,5] 39 | Output: true 40 | 41 | Example 5: 42 | 43 | Input: [1,1,1] 44 | Output: true 45 | 46 | 47 | Note: 48 | 49 | - 1 <= A.length <= 50000 50 | - -100000 <= A[i] <= 100000 51 | 52 | 53 | ## 题目大意 54 | 55 | 判断一个数组是不是单调的。单调包括单调递增和单调递减。 56 | 57 | ## 解题方法 58 | 59 | 用python的话,最快的方式应该是使用all,只用看连续两个数字之间的差值和0之间的比较就行了。 60 | 61 | 代码如下: 62 | 63 | ```python 64 | class Solution(object): 65 | def isMonotonic(self, A): 66 | """ 67 | :type A: List[int] 68 | :rtype: bool 69 | """ 70 | return self.isIncrease(A) or self.isDecrease(A) 71 | 72 | def isIncrease(self, A): 73 | return all(A[i] - A[i+1] >= 0 for i in range(len(A) - 1)) 74 | 75 | def isDecrease(self, A): 76 | return all(A[i] - A[i+1] <= 0 for i in range(len(A) - 1)) 77 | ``` 78 | 79 | 参考资料: 80 | 81 | 82 | ## 日期 83 | 84 | 2018 年 9 月 3 日 —— 新学期开学第一天! 85 | 2018 年 11 月 9 日 —— 睡眠可以2018 年 11 月 9 日 —— 睡眠可以 86 | -------------------------------------------------------------------------------- /1000-1099/1085. Sum of Digits in the Minimum Number 最小元素各数位之和.md: -------------------------------------------------------------------------------- 1 | 2 | - 作者: 负雪明烛 3 | - id: fuxuemingzhu 4 | - 个人博客:[http://fuxuemingzhu.cn/](http://fuxuemingzhu.cn/) 5 | 6 | --- 7 | @[TOC](目录) 8 | 9 | 10 | 题目地址:https://leetcode-cn.com/problems/sum-of-digits-in-the-minimum-number/ 11 | 12 | ## 题目描述 13 | 14 | Given an array `A` of positive integers, let `S` be the sum of the digits of the minimal element of `A`. 15 | 16 | Return 0 if S is odd, otherwise return 1. 17 | 18 | Example 1: 19 | 20 | Input: [34,23,1,24,75,33,54,8] 21 | Output: 0 22 | Explanation: 23 | The minimal element is 1, and the sum of those digits is S = 1 which is odd, so the answer is 0. 24 | 25 | Example 2: 26 | 27 | Input: [99,77,33,66,55] 28 | Output: 1 29 | Explanation: 30 | The minimal element is 33, and the sum of those digits is S = 3 + 3 = 6 which is even, so the answer is 1. 31 | 32 | Note: 33 | 34 | 1. 1 <= A.length <= 100 35 | 1. 1 <= A[i].length <= 100 36 | 37 | 38 | ## 题目大意 39 | 40 | 给你一个正整数的数组 A。 41 | 然后计算 S,使其等于数组 A 当中最小的那个元素各个数位上数字之和。 42 | 最后,假如 S 所得计算结果是 奇数 的请你返回 0,否则请返回 1。 43 | 44 | 45 | ## 解题方法 46 | 47 | ### 遍历 48 | 49 | 先找出最小的数字,然后求其各位数字的和。 50 | 51 | C++代码如下: 52 | 53 | ```cpp 54 | class Solution { 55 | public: 56 | int sumOfDigits(vector& A) { 57 | int min_num = INT_MAX; 58 | for (int a : A) { 59 | min_num = min(min_num, a); 60 | } 61 | int k = 0; 62 | int s = 0; 63 | while (min_num != 0) { 64 | s += min_num % 10; 65 | k++; 66 | min_num /= 10; 67 | } 68 | return 1 - (s & 1); 69 | } 70 | }; 71 | ``` 72 | 73 | ## 日期 74 | 75 | 2019 年 9 月 18 日 —— 今日又是九一八 76 | 77 | 78 | [1]: https://blog.csdn.net/fuxuemingzhu/article/details/100977773 79 | -------------------------------------------------------------------------------- /500-599/509. Fibonacci Number 斐波那契数.md: -------------------------------------------------------------------------------- 1 | 2 | 作者: 负雪明烛 3 | id: fuxuemingzhu 4 | 个人博客: http://fuxuemingzhu.cn/ 5 | 6 | --- 7 | @[TOC](目录) 8 | 9 | 10 | 题目地址:https://leetcode.com/problems/fibonacci-number/ 11 | 12 | ## 题目描述 13 | 14 | The **Fibonacci numbers**, commonly denoted F(n) form a sequence, called the **Fibonacci sequence**, such that each number is the sum of the two preceding ones, starting from 0 and 1. That is, 15 | 16 | F(0) = 0, F(1) = 1 17 | F(N) = F(N - 1) + F(N - 2), for N > 1. 18 | 19 | Given `N`, calculate ``F(N)``. 20 | 21 | 22 | 23 | Example 1: 24 | 25 | Input: 2 26 | Output: 1 27 | Explanation: F(2) = F(1) + F(0) = 1 + 0 = 1. 28 | 29 | Example 2: 30 | 31 | Input: 3 32 | Output: 2 33 | Explanation: F(3) = F(2) + F(1) = 1 + 1 = 2. 34 | 35 | Example 3: 36 | 37 | Input: 4 38 | Output: 3 39 | Explanation: F(4) = F(3) + F(2) = 2 + 1 = 3. 40 | 41 | Note: 42 | 43 | 1. 0 ≤ N ≤ 30. 44 | 45 | ## 题目大意 46 | 47 | 求费布拉奇数列的第N个元素是多少。 48 | 49 | ## 解题方法 50 | 51 | ### 动态规划 52 | 53 | 常见的求费布拉奇数列的方法是递归,但是估计这个题目会超时,另外太简单了我不写了。 54 | 55 | 一个常见的优化就是改成了一维的动态规划,因为每个状态只和前两个状态有关,所以我们可以依次从第0个位置推到我们想要的位置。 56 | 57 | 这个题需要注意的是N的取值范围,注意当N<=1的时候相当于终止条件,直接返回结果。 58 | 59 | 这种解法的时间复杂度是O(N)。 60 | 61 | 另外一提,费布拉奇数列是有通项公式的,可以直接用公式求出来,时间复杂度降到O(1). 62 | 63 | Python代码如下: 64 | 65 | ```cpp 66 | class Solution { 67 | public: 68 | int fib(int N) { 69 | if (N <= 1) return N; 70 | vector fibs(N + 1); 71 | fibs[0] = 0; 72 | fibs[1] = 1; 73 | for (int i = 2; i <= N; ++i) { 74 | fibs[i] = fibs[i - 1] + fibs[i - 2]; 75 | } 76 | return fibs[N]; 77 | } 78 | }; 79 | ``` 80 | 81 | ## 日期 82 | 83 | 2019 年 7 月 13 日 —— 又是一个多月没刷题 84 | 85 | 86 | [1]: https://blog.csdn.net/fuxuemingzhu/article/details/79463006 87 | -------------------------------------------------------------------------------- /200-299/292. Nim Game Nim 游戏.md: -------------------------------------------------------------------------------- 1 | 2 | 作者: 负雪明烛 3 | id: fuxuemingzhu 4 | 个人博客: http://fuxuemingzhu.cn/ 5 | 6 | --- 7 | @[TOC](目录) 8 | 9 | 题目地址:[https://leetcode.com/problems/nim-game/](https://leetcode.com/problems/nim-game/) 10 | 11 | Total Accepted: 66290 Total Submissions: 125590 Difficulty: Easy 12 | 13 | 14 | ## 题目描述 15 | 16 | You are playing the following Nim Game with your friend: There is a heap of stones on the table, each time one of you take turns to remove 1 to 3 stones. The one who removes the last stone will be the winner. You will take the first turn to remove the stones. 17 | 18 | Both of you are very clever and have optimal strategies for the game. Write a function to determine whether you can win the game given the number of stones in the heap. 19 | 20 | Example: 21 | 22 | Input: 4 23 | Output: false 24 | Explanation: If there are 4 stones in the heap, then you will never win the game; 25 | No matter 1, 2, or 3 stones you remove, the last stone will always be 26 | removed by your friend. 27 | 28 | ## 题目大意 29 | 30 | 你和另一个人在玩一个游戏,每次可以取1~3个石头,而且每次都必须取。现在要你先取,并且能取到最后的那个石头的人能赢。问你是不是有机会赢? 31 | 32 | ## 解题方法 33 | 34 | 题目的意思是只要拿最后一个石子的人赢。 35 | 36 | 因为每次最多拿三个,所以只要我拿走子之后,最后剩余四个的话,我就输了。 37 | 38 | 所以,所有子的个数不能被四整除我就赢了,否则我会输。输的原因是对手每次都拿4-n,n为当次我拿到子的个数。 39 | 40 | Java代码: 41 | 42 | ```java 43 | public class Solution { 44 | public boolean canWinNim(int n) { 45 | return n % 4!= 0; 46 | } 47 | } 48 | ``` 49 | 50 | --- 51 | 52 | 二刷,python. 53 | 54 | 转眼两年办过去了,再次做了这个题。python代码如下: 55 | 56 | ```python 57 | class Solution(object): 58 | def canWinNim(self, n): 59 | """ 60 | :type n: int 61 | :rtype: bool 62 | """ 63 | return n % 4 != 0 64 | ``` 65 | 66 | 67 | ## 日期 68 | 69 | 2016/4/29 21:39:23 70 | 2018 年 11 月 9 日 —— 睡眠可以 71 | -------------------------------------------------------------------------------- /1000-1099/1051. Height Checker 高度检查器.md: -------------------------------------------------------------------------------- 1 | 2 | 3 | 作者: 负雪明烛 4 | id: fuxuemingzhu 5 | 个人博客: http://fuxuemingzhu.cn/ 6 | 7 | --- 8 | @[TOC](目录) 9 | 10 | 11 | 题目地址:https://leetcode.com/problems/height-checker/ 12 | 13 | ## 题目描述 14 | 15 | Students are asked to stand in non-decreasing order of heights for an annual photo. 16 | 17 | Return the minimum number of students not standing in the right positions. (This is the number of students that must move in order for all students to be standing in non-decreasing order of height.) 18 | 19 | 20 | 21 | Example 1: 22 | 23 | Input: [1,1,4,2,1,3] 24 | Output: 3 25 | Explanation: 26 | Students with heights 4, 3 and the last 1 are not standing in the right positions. 27 | 28 | 29 | Note: 30 | 31 | 1. 1 <= heights.length <= 100 32 | 1. 1 <= heights[i] <= 100 33 | 34 | ## 题目大意 35 | 36 | 一组数字和排序后的这组数字有多少个位置是不一致的? 37 | 38 | ## 解题方法 39 | 40 | ### 排序比较 41 | 42 | 这个题这么直白啊,直接问和排序后的数字有多少个位置是不一样的。所以排序之后比较就行了呀。看了下数字的范围,竟然只有100个!哪怕是100000直接排序比较也应该会通过! 43 | 44 | 时间复杂度是O(NlogN)。 45 | 46 | Python代码如下: 47 | 48 | ```python 49 | class Solution(object): 50 | def heightChecker(self, heights): 51 | """ 52 | :type heights: List[int] 53 | :rtype: int 54 | """ 55 | return sum(a != b for a, b in zip(sorted(heights), heights)) 56 | ``` 57 | 58 | C++代码如下: 59 | 60 | 61 | ```cpp 62 | class Solution { 63 | public: 64 | int heightChecker(vector& heights) { 65 | vector sortedHeights(heights); 66 | sort(heights.begin(), heights.end()); 67 | int res = 0; 68 | for (int i = 0; i < heights.size(); ++i) { 69 | if (heights[i] != sortedHeights[i]) 70 | ++res; 71 | } 72 | return res; 73 | } 74 | }; 75 | ``` 76 | 77 | ## 日期 78 | 79 | 2019 年 6 月 8 日 —— 刷题尽量不要停 80 | -------------------------------------------------------------------------------- /200-299/253. Meeting Rooms II 会议室 II.md: -------------------------------------------------------------------------------- 1 | 2 | - 作者: 负雪明烛 3 | - id: fuxuemingzhu 4 | - 个人博客:[http://fuxuemingzhu.cn/](http://fuxuemingzhu.cn/) 5 | 6 | --- 7 | @[TOC](目录) 8 | 9 | 10 | 题目地址:https://leetcode-cn.com/problems/meeting-rooms/ 11 | 12 | ## 题目描述 13 | 14 | Given an array of meeting time intervals consisting of start and end times `[[s1,e1],[s2,e2],...] (si < ei)`, find the minimum number of conference rooms required. 15 | 16 | Example 1: 17 | 18 | Input: [[0, 30],[5, 10],[15, 20]] 19 | Output: 2 20 | 21 | Example 2: 22 | 23 | Input: [[7,10],[2,4]] 24 | Output: 1 25 | 26 | ## 题目大意 27 | 28 | 给定一个会议时间安排的数组,每个会议时间都会包括开始和结束的时间 [[s1,e1],[s2,e2],...] (si < ei),为避免会议冲突,同时要考虑充分利用会议室资源,请你计算至少需要多少间会议室,才能满足这些会议安排。 29 | 30 | ## 解题方法 31 | 32 | ### 排序+堆 33 | 34 | 这个做法参考了官方解答,先对所有的区间按照开始时间进行排序,使用小根堆保存每个会议的结束时间,堆的大小表示了现在已经占用了多少个会议室。 35 | 36 | 思路是,我们要申请会议室的时候,先看是不是可以释放会议室,将已经占用的会议室释放。 37 | 38 | 遍历判断每个区间的开始时间是否大于等于小根堆中最小元素(最早结束时间),如果大于等于,说明堆里面有个会议要结束了,将其弹出,代表释放了一个会议室;否则,说明堆里面的已经在使用的会议室没有空闲,只能新增加一个会议室。 39 | 40 | 由于优先占用释放的会议室,所以最后堆里面的元素个数表示总的需要占用多少个会议室。 41 | 42 | C++代码如下: 43 | 44 | ```cpp 45 | class Solution { 46 | public: 47 | int minMeetingRooms(vector>& intervals) { 48 | sort(intervals.begin(), intervals.end(), [](vector& a, vector&b) {return a[0] < b[0];}); 49 | priority_queue, greater> que; 50 | for (vector& interval : intervals) { 51 | if (!que.empty() && interval[0] >= que.top()) { 52 | que.pop(); 53 | } 54 | que.push(interval[1]); 55 | } 56 | return que.size(); 57 | } 58 | }; 59 | ``` 60 | 61 | 参考资料:https://leetcode-cn.com/problems/meeting-rooms-ii/solution/hui-yi-shi-ii-by-leetcode/ 62 | 63 | ## 日期 64 | 65 | 2019 年 9 月 17 日 —— 听了hulu宣讲会,觉得hulu的压力不大 66 | -------------------------------------------------------------------------------- /1200-1299/1221. Split a String in Balanced Strings 分割平衡字符串.md: -------------------------------------------------------------------------------- 1 | - 作者: 负雪明烛 2 | - id: fuxuemingzhu 3 | - 个人博客:[http://fuxuemingzhu.cn/](http://fuxuemingzhu.cn/) 4 | 5 | --- 6 | @[TOC](目录) 7 | 8 | 题目地址:https://leetcode.com/problems/split-a-string-in-balanced-strings/ 9 | 10 | ## 题目描述 11 | 12 | Balanced strings are those who have equal quantity of `'L'` and `'R'` characters. 13 | 14 | Given a balanced string `s` split it in the maximum amount of balanced strings. 15 | 16 | Return the maximum amount of splitted balanced strings. 17 | 18 | Example 1: 19 | 20 | Input: s = "RLRRLLRLRL" 21 | Output: 4 22 | Explanation: s can be split into "RL", "RRLL", "RL", "RL", each substring contains same number of 'L' and 'R'. 23 | 24 | Example 2: 25 | 26 | Input: s = "RLLLLRRRLR" 27 | Output: 3 28 | Explanation: s can be split into "RL", "LLLRRR", "LR", each substring contains same number of 'L' and 'R'. 29 | 30 | Example 3: 31 | 32 | Input: s = "LLLLRRRR" 33 | Output: 1 34 | Explanation: s can be split into "LLLLRRRR". 35 | 36 | 37 | Constraints: 38 | 39 | 1. `1 <= s.length <= 1000` 40 | 1. `s[i] = 'L' or 'R'` 41 | 42 | ## 题目大意 43 | 44 | 计算一个字符串中有多少个合法的括号匹配。 45 | 46 | ## 解题方法 47 | 48 | ### 统计 49 | 50 | 括号匹配可以使用一个变量cnt进行统计,如果遇到左括号,cnt++;如果遇到右括号,cnt--;如果cnt==0说明是一个合法的括号匹配。 51 | 52 | C++代码如下: 53 | 54 | ```cpp 55 | class Solution { 56 | public: 57 | int balancedStringSplit(string s) { 58 | int cnt = 0; 59 | int res = 0; 60 | for (char c : s) { 61 | if (c == 'R') { 62 | cnt ++; 63 | } else { 64 | cnt --; 65 | } 66 | if (cnt == 0) 67 | res ++; 68 | } 69 | return res; 70 | } 71 | }; 72 | ``` 73 | 74 | 75 | ## 日期 76 | 77 | 2019 年 10 月 13 日 —— 国庆调休,这周末只有这一天假 78 | -------------------------------------------------------------------------------- /300-399/347. Top K Frequent Elements 前 K 个高频元素.md: -------------------------------------------------------------------------------- 1 | 2 | 作者: 负雪明烛 3 | id: fuxuemingzhu 4 | 个人博客: http://fuxuemingzhu.cn/ 5 | 6 | --- 7 | @[TOC](目录) 8 | 9 | 题目地址:https://leetcode.com/problems/top-k-frequent-elements/description/ 10 | 11 | ## 题目描述 12 | 13 | Given a non-empty array of integers, return the k most frequent elements. 14 | 15 | For example, 16 | 17 | Given [1,1,1,2,2,3] and k = 2, return [1,2]. 18 | 19 | Note: 20 | 21 | 1. You may assume k is always valid, 1 ≤ k ≤ number of unique elements. 22 | 1. Your algorithm's time complexity must be better than O(n log n), where n is the array's size. 23 | 24 | ## 解题方法 25 | 26 | 把出现次数最大的前k个数输出。 27 | 28 | ## 解题方法 29 | 30 | ### 字典 31 | 32 | 这个题要求时间复杂度是O(nlogn),就可以按照出现的次数先排个序,然后找到出现最多的k个就好。Counter类有most_common()函数,能按出现的次数进行排序。返回的是个列表,列表中每个元素都是一个元组,元组的第一个元素是数字,第二个数字是出现的次数。 33 | 34 | ```python 35 | from collections import Counter 36 | class Solution(object): 37 | def topKFrequent(self, nums, k): 38 | """ 39 | :type nums: List[int] 40 | :type k: int 41 | :rtype: List[int] 42 | """ 43 | counter = Counter(nums).most_common() 44 | return [counter[i][0] for i in range(k)] 45 | ``` 46 | 47 | ### 优先级队列 48 | 49 | 使用优先级队列来让出现次数多的优先弹出来,当然需要字典统计次数。 50 | 51 | ```cpp 52 | class Solution { 53 | public: 54 | vector topKFrequent(vector& nums, int k) { 55 | map m; 56 | for (int n : nums) m[n] ++; 57 | priority_queue> p; 58 | for (auto a : m) 59 | p.push({a.second, a.first}); 60 | vector res; 61 | for (int i = 0; i < k; i++) { 62 | res.push_back(p.top().second); p.pop(); 63 | } 64 | return res; 65 | } 66 | }; 67 | ``` 68 | 69 | 70 | ## 日期 71 | 72 | 2018 年 2 月 8 日 73 | 2018 年 12 月 14 日 —— 12月过半,2019就要开始 74 | 75 | -------------------------------------------------------------------------------- /900-999/949. Largest Time for Given Digits 给定数字能组成的最大时间.md: -------------------------------------------------------------------------------- 1 | 2 | 作者: 负雪明烛 3 | id: fuxuemingzhu 4 | 个人博客: http://fuxuemingzhu.cn/ 5 | 6 | --- 7 | @[TOC](目录) 8 | 9 | 10 | 题目地址:https://leetcode.com/problems/largest-time-for-given-digits/description/ 11 | 12 | 13 | ## 题目描述 14 | 15 | Given an array of 4 digits, return the largest 24 hour time that can be made. 16 | 17 | The smallest 24 hour time is 00:00, and the largest is 23:59. Starting from 00:00, a time is larger if more time has elapsed since midnight. 18 | 19 | Return the answer as a string of length 5. If no valid time can be made, return an empty string. 20 | 21 | Example 1: 22 | 23 | Input: [1,2,3,4] 24 | Output: "23:41" 25 | 26 | Example 2: 27 | 28 | Input: [5,5,5,5] 29 | Output: "" 30 | 31 | 32 | Note: 33 | 34 | 1. A.length == 4 35 | 1. 0 <= A[i] <= 9 36 | 37 | ## 题目大意 38 | 39 | 给了4个数字,找出能做到的排列出的24小时制时间最大值。 40 | 41 | ## 解题方法 42 | 43 | 这个题有人使用的是Permutation的方法,需要把每个permutation做出来,然后进行判断。当然了,只有4个数字,不会超时。 44 | 45 | 我的做法是从23:59向00:00遍历24小时制的每一个分钟,这样的话,我们看这个时间能不能由题目给的4个数字表示出来。如果可以的话立即终止即可。总共24*60个分钟,中间进行判断的方式是排序,整体的时间复杂度很小的。所以也能通过。 46 | 47 | ```python 48 | class Solution(object): 49 | def largestTimeFromDigits(self, A): 50 | """ 51 | :type A: List[int] 52 | :rtype: str 53 | """ 54 | A.sort() 55 | for h in range(23, -1, -1): 56 | for m in range(59, -1, -1): 57 | t = [h / 10, h % 10, m / 10, m % 10] 58 | ts = sorted(t) 59 | if ts == A: 60 | return str(t[0]) + str(t[1]) + ":" + str(t[2]) + str(t[3]) 61 | return "" 62 | ``` 63 | 64 | 65 | ## 日期 66 | 67 | 2018 年 12 月 2 日 —— 又到了周日 68 | 69 | 70 | [1]: https://blog.csdn.net/fuxuemingzhu/article/details/84640318 71 | [2]: http://www.cnblogs.com/grandyang/p/4295761.html 72 | -------------------------------------------------------------------------------- /800-899/821. Shortest Distance to a Character 字符的最短距离.md: -------------------------------------------------------------------------------- 1 | 2 | 作者: 负雪明烛 3 | id: fuxuemingzhu 4 | 个人博客: http://fuxuemingzhu.cn/ 5 | 6 | --- 7 | @[TOC](目录) 8 | 9 | 题目地址:https://leetcode.com/problems/shortest-distance-to-a-character/description/ 10 | 11 | ## 题目描述 12 | 13 | Given a string S and a character C, return an array of integers representing the shortest distance from the character C in the string. 14 | 15 | Example 1: 16 | 17 | Input: S = "loveleetcode", C = 'e' 18 | Output: [3, 2, 1, 0, 1, 0, 0, 1, 2, 2, 1, 0] 19 | 20 | 21 | Note: 22 | 23 | 1. S string length is in [1, 10000]. 24 | 1. C is a single character, and guaranteed to be in string S. 25 | 1. All letters in S and C are lowercase. 26 | 27 | 28 | ## 题目大意 29 | 30 | 给定字符串S和属于该字符串的一个字符C,要求出字符串中的每个字符到最近的C的距离。 31 | 32 | 33 | ## 解题方法 34 | 35 | ### 过两遍数组 36 | 37 | 这个解题方法,有点骚。属于两步走的方案: 38 | 39 | 第一步,先假设在很远的位置有个C字符,那么从左到右开始遍历,找出每个字符到其最近的左边的字符C的距离; 40 | 第二步,先假设在很远的位置有个C字符,那么从右到左开始遍历,找出每个字符到其最近的右边的字符C的距离,并和第一步求出的距离进行比较,找出最小值为结果; 41 | 42 | 两个技巧: 43 | 44 | 1. 设了一个比字符串长度更远的一个字符C,保证后面求最小值更新距离时一定会被更新。 45 | 2. 无论如何都用到了abs求绝对值,哪怕可能是不需要的,目的是不用费脑子思考谁大谁小了。 46 | 47 | 48 | ```python 49 | class Solution: 50 | def shortestToChar(self, S, C): 51 | """ 52 | :type S: str 53 | :type C: str 54 | :rtype: List[int] 55 | """ 56 | _len = len(S) 57 | index = -1000000 58 | ans = [0] * _len 59 | for i, s in enumerate(S): 60 | if s == C: 61 | index = i 62 | ans[i] = abs(i - index) 63 | index = -100000 64 | for i in range(_len - 1, -1 , -1): 65 | if S[i] == C: 66 | index = i 67 | ans[i] = min(abs(i - index), ans[i]) 68 | return ans 69 | ``` 70 | 71 | ## 日期 72 | 73 | 2018 年 5 月 27 日 —— 周末的天气很好~ 74 | 2018 年 11 月 6 日 —— 腰酸背痛要废了 75 | -------------------------------------------------------------------------------- /1100-1199/1180. Count Substrings with Only One Distinct Letter 统计只含单一字母的子串.md: -------------------------------------------------------------------------------- 1 | 2 | - 作者: 负雪明烛 3 | - id: fuxuemingzhu 4 | - 个人博客:[http://fuxuemingzhu.cn/](http://fuxuemingzhu.cn/) 5 | 6 | --- 7 | @[TOC](目录) 8 | 9 | 10 | 题目地址:https://leetcode-cn.com/problems/count-substrings-with-only-one-distinct-letter/ 11 | 12 | ## 题目描述 13 | 14 | Given a string `S`, return the number of substrings that have only one distinct letter. 15 | 16 | 17 | Example 1: 18 | 19 | Input: S = "aaaba" 20 | Output: 8 21 | Explanation: The substrings with one distinct letter are "aaa", "aa", "a", "b". 22 | "aaa" occurs 1 time. 23 | "aa" occurs 2 times. 24 | "a" occurs 4 times. 25 | "b" occurs 1 time. 26 | So the answer is 1 + 2 + 4 + 1 = 8. 27 | 28 | Example 2: 29 | 30 | Input: S = "aaaaaaaaaa" 31 | Output: 55 32 | 33 | Constraints: 34 | 35 | 1. `1 <= S.length <= 1000` 36 | 1. `S[i]` consists of only lowercase English letters. 37 | 38 | 39 | ## 题目大意 40 | 41 | 给你一个字符串 S,返回只含 **单一字母** 的子串个数。 42 | 43 | ## 解题方法 44 | 45 | ### 组合数 46 | 47 | 从一段长度为n的单一字母字符串中,分别选择出长度为1,2,3,...,n的子串,共有`n * (n + 1) / 2`个结果。 48 | 49 | 因此,遍历字符串,分别统计出单一字母字符串的长度,累加所有结果即可。 50 | 51 | 52 | C++代码如下: 53 | 54 | ```cpp 55 | class Solution { 56 | public: 57 | int countLetters(string S) { 58 | if (S.empty()) return 0; 59 | int count = 1; 60 | int res = 0; 61 | char cur = S[0]; 62 | cout << endl; 63 | for (int i = 1; i <= S.size(); ++i) { 64 | if (i == S.size() || S[i] != cur) { 65 | res += count * (count + 1) / 2; 66 | cur = S[i]; 67 | count = 1; 68 | } else { 69 | count ++; 70 | } 71 | 72 | } 73 | return res; 74 | } 75 | }; 76 | ``` 77 | 78 | ## 日期 79 | 80 | 2019 年 9 月 18 日 —— 今日又是九一八 81 | -------------------------------------------------------------------------------- /300-399/334. Increasing Triplet Subsequence 递增的三元子序列.md: -------------------------------------------------------------------------------- 1 | # 【LeetCode】334. Increasing Triplet Subsequence 解题报告(Python) 2 | 3 | 标签(空格分隔): LeetCode 4 | 5 | --- 6 | 7 | 题目地址:https://leetcode.com/problems/increasing-triplet-subsequence/description/ 8 | 9 | ## 题目描述: 10 | 11 | Given an unsorted array return whether an increasing subsequence of length 3 exists or not in the array. 12 | 13 | Formally the function should: 14 | 15 | > Return true if there exists i, j, k such that arr[i] < arr[j] < arr[k] 16 | > given 0 ≤ i < j < k ≤ n-1 else return false. 17 | 18 | Your algorithm should run in O(n) time complexity and O(1) space complexity. 19 | 20 | Examples: 21 | Given [1, 2, 3, 4, 5], 22 | return true. 23 | 24 | Given [5, 4, 3, 2, 1], 25 | return false. 26 | 27 | ## 题目大意 28 | 29 | 判断一个无序的数组中是否包含长度为3的递增的序列。 30 | 31 | ## 解题方法 32 | 33 | 用LIS的解法一定能做出来的,但是不符合题目给出的O(n)的时间复杂度。看了别人的解法发现真的很巧妙。我们完全可以抛弃什么DP啊,dfs啊,老夫写代码就是一把梭,抓起键盘就是干! 34 | 35 | 既然要求我们从前到后遍历,那么在遍历的时候保存已经看到的最小值和次小值,然后再发现比这两个值大的的第3小的值存在的时候,那么就说明有长度为3的递增的子序列了。 36 | 37 | 当然,对于这种情况: 38 | 39 | 4 5 1 2 6 40 | 41 | 长度为3递增子序列有两种,但是由于我们保存的是最小的优先,所以最后的结果求得的是1 2 6这组。 42 | 43 | 整体的思想其实是很灵活的,保存的是遍历时**见到的**最小和次小,因此千万不要使用一成不变的min和max函数。 44 | 45 | 代码: 46 | 47 | ```python 48 | class Solution(object): 49 | def increasingTriplet(self, nums): 50 | """ 51 | :type nums: List[int] 52 | :rtype: bool 53 | """ 54 | first, second = float('inf'), float('inf') 55 | for num in nums: 56 | if num <= first: 57 | first = num 58 | elif num <= second: 59 | second = num 60 | else: 61 | return True 62 | return False 63 | ``` 64 | 65 | ## 日期 66 | 67 | 2018 年 4 月 5 日 ———— 清明节假期开始,小长假真好~~ 68 | 69 | 70 | [1]: https://blog.csdn.net/fuxuemingzhu/article/details/79821305 -------------------------------------------------------------------------------- /100-199/106. Construct Binary Tree from Inorder and Postorder Traversal 从中序与后序遍历序列构造二叉树.md: -------------------------------------------------------------------------------- 1 | # 【LeetCode】106. Construct Binary Tree from Inorder and Postorder Traversal 解题报告(Python) 2 | 3 | 标签: LeetCode 4 | 5 | --- 6 | 7 | 题目地址:https://leetcode.com/problems/construct-binary-tree-from-inorder-and-postorder-traversal/description/ 8 | 9 | ## 题目描述: 10 | 11 | Given inorder and postorder traversal of a tree, construct the binary tree. 12 | 13 | Note: 14 | You may assume that duplicates do not exist in the tree. 15 | 16 | For example, given 17 | 18 | inorder = [9,3,15,20,7] 19 | postorder = [9,15,7,20,3] 20 | Return the following binary tree: 21 | 22 | 3 23 | / \ 24 | 9 20 25 | / \ 26 | 15 7 27 | 28 | 29 | ## 题目大意 30 | 31 | 根据中序遍历和后序遍历重建二叉树。 32 | 33 | ## 解题方法 34 | 35 | 这个是套路题,我没有完全记住每一步是多少,而是根据树的样子和两个数组进行分析,得出切片的位置。 36 | 37 | 后序遍历的最后一个元素一定是根节点,在中序遍历中找出此根节点的位置序号。中序遍历序号左边的是左孩子,右边的是右孩子。再根据左孩子和右孩子的长度对后序遍历进行切片即可。 38 | 39 | ```python 40 | # Definition for a binary tree node. 41 | # class TreeNode(object): 42 | # def __init__(self, x): 43 | # self.val = x 44 | # self.left = None 45 | # self.right = None 46 | 47 | class Solution(object): 48 | def buildTree(self, inorder, postorder): 49 | """ 50 | :type inorder: List[int] 51 | :type postorder: List[int] 52 | :rtype: TreeNode 53 | """ 54 | if not inorder or not postorder: return None 55 | val = postorder[-1] 56 | root = TreeNode(val) 57 | index = inorder.index(val) 58 | root.left = self.buildTree(inorder[:index], postorder[:index]) 59 | root.right = self.buildTree(inorder[index+1:], postorder[index:-1]) 60 | return root 61 | ``` 62 | 63 | ## 日期 64 | 65 | 2018 年 3 月 12 日 66 | 67 | 68 | [1]: http://img.blog.csdn.net/20160101111128525 -------------------------------------------------------------------------------- /1000-1099/1047. Remove All Adjacent Duplicates In String 删除字符串中的所有相邻重复项.md: -------------------------------------------------------------------------------- 1 | 作者: 负雪明烛 2 | id: fuxuemingzhu 3 | 个人博客: http://fuxuemingzhu.cn/ 4 | 5 | --- 6 | @[TOC](目录) 7 | 8 | 9 | 题目地址:https://leetcode.com/problems/remove-all-adjacent-duplicates-in-string/ 10 | 11 | ## 题目描述 12 | 13 | Given a string ``S`` of lowercase letters, a *duplicate removal* consists of choosing two adjacent and equal letters, and removing them. 14 | 15 | We repeatedly make duplicate removals on S until we no longer can. 16 | 17 | Return the final string after all such duplicate removals have been made. It is guaranteed the answer is unique. 18 | 19 | 20 | Example 1: 21 | 22 | Input: "abbaca" 23 | Output: "ca" 24 | Explanation: 25 | For example, in "abbaca" we could remove "bb" since the letters are adjacent and equal, and this is the only possible move. The result of this move is that the string is "aaca", of which only "aa" is possible, so the final string is "ca". 26 | 27 | 28 | Note: 29 | 30 | 1. ``1 <= S.length <= 20000`` 31 | 1. ``S`` consists only of English lowercase letters. 32 | 33 | 34 | ## 题目大意 35 | 36 | 每次去除字符串中两个相邻且相等的字符,求最后剩下的字符串(结果唯一)。 37 | 38 | ## 解题方法 39 | 40 | ### 栈 41 | 42 | 两个相等的字符连续出现则都消除掉,另外题目也说了结果唯一。有点类似与括号匹配问题,所以,我们一个很容易想到栈去解决。 43 | 44 | 顺序遍历字符串,如果当前的字符和栈顶字符相同,那么出栈;否则,把结果放到栈里面。最后栈里剩余的字符串即为所求。 45 | 46 | Python代码如下: 47 | 48 | ```python 49 | class Solution(object): 50 | def removeDuplicates(self, S): 51 | """ 52 | :type S: str 53 | :rtype: str 54 | """ 55 | stack = [] 56 | for s in S: 57 | if stack and s == stack[-1]: 58 | stack.pop() 59 | continue 60 | stack.append(s) 61 | return "".join(stack) 62 | ``` 63 | 64 | ## 日期 65 | 66 | 2019 年 5 月 22 日 —— 一个多月不刷题了,重新捡起来 67 | 68 | 69 | [1]: https://blog.csdn.net/fuxuemingzhu/article/details/79463006 70 | -------------------------------------------------------------------------------- /1000-1099/1099. Two Sum Less Than K 小于 K 的两数之和.md: -------------------------------------------------------------------------------- 1 | 2 | - 作者: 负雪明烛 3 | - id: fuxuemingzhu 4 | - 个人博客:[http://fuxuemingzhu.cn/](http://fuxuemingzhu.cn/) 5 | 6 | --- 7 | @[TOC](目录) 8 | 9 | 10 | 题目地址:https://leetcode-cn.com/problems/two-sum-less-than-k/ 11 | 12 | ## 题目描述 13 | 14 | Given an array `A` of integers and integer `K`, return the maximum `S` such that there exists `i < j` with `A[i] + A[j] = S` and `S < K`. If no `i, j` exist satisfying this equation, return -1. 15 | 16 | 17 | Example 1: 18 | 19 | Input: A = [34,23,1,24,75,33,54,8], K = 60 20 | Output: 58 21 | Explanation: 22 | We can use 34 and 24 to sum 58 which is less than 60. 23 | 24 | Example 2: 25 | 26 | Input: A = [10,20,30], K = 15 27 | Output: -1 28 | Explanation: 29 | In this case it's not possible to get a pair sum less that 15. 30 | 31 | Note: 32 | 33 | 1. `1 <= A.length <= 100` 34 | 1. `1 <= A[i] <= 1000` 35 | 1. `1 <= K <= 2000` 36 | 37 | ## 题目大意 38 | 39 | 给你一个整数数组 A 和一个整数 K,请在该数组中找出两个元素,使它们的和小于 K 但尽可能地接近 K,返回这两个元素的和。 40 | 41 | 如不存在这样的两个元素,请返回 -1。 42 | 43 | ## 解题方法 44 | 45 | ### 暴力求解 46 | 47 | 本来觉得这个题好难,但是看了数组的范围才有100个元素,果断暴力求解即可。 48 | 49 | C++代码如下: 50 | 51 | ```cpp 52 | class Solution { 53 | public: 54 | int twoSumLessThanK(vector& A, int K) { 55 | const int N = A.size(); 56 | int res = -1; 57 | int minDist = INT_MAX; 58 | for (int i = 0; i < N; i ++) { 59 | for (int j = i + 1; j < N; j ++) { 60 | int sum = A[i] + A[j]; 61 | if (sum < K && K - sum < minDist) { 62 | minDist = K - sum; 63 | res = sum; 64 | } 65 | } 66 | } 67 | return res; 68 | } 69 | }; 70 | ``` 71 | 72 | ## 日期 73 | 74 | 2019 年 9 月 18 日 —— 今日又是九一八 75 | 76 | 77 | [1]: https://blog.csdn.net/fuxuemingzhu/article/details/100977773 78 | -------------------------------------------------------------------------------- /500-599/539. Minimum Time Difference 最小时间差.md: -------------------------------------------------------------------------------- 1 | 作者: 负雪明烛 2 | id: fuxuemingzhu 3 | 个人博客: http://fuxuemingzhu.me/ 4 | 5 | --- 6 | 7 | 题目地址:https://leetcode.com/problems/minimum-time-difference/description/ 8 | 9 | ## 题目描述: 10 | 11 | Given a list of 24-hour clock time points in "Hour:Minutes" format, find the minimum minutes difference between any two time points in the list. 12 | 13 | Example 1: 14 | Input: ["23:59","00:00"] 15 | Output: 1 16 | 17 | Note: 18 | 19 | 1. The number of time points in the given list is at least 2 and won't exceed 20000. 20 | 1. The input time is legal and ranges from 00:00 to 23:59. 21 | 22 | 23 | ## 题目大意 24 | 25 | 给出了一个时间数组,找出这个数组中最接近的两个时间的差。 26 | 27 | ## 解题方法 28 | 29 | 容易想到时间是个循环,正如题目中的所示,需要考虑循环问题。所以解决的方案是先求出每个时间点超出0点的分钟数,对时间进行排序。然后采取zip循环的方式,找出每两个时间之间的时间差,求最小值即可。 30 | 31 | 注意对24小时的分钟总数进行了求余,这样能保证题目中所示的例子能得到正确结果。 32 | 33 | 补充一下zip的用法: 34 | 35 | ```python 36 | >>> a = [1,2,3] 37 | >>> b = [4,5,6] 38 | >>> c = [4,5,6,7,8] 39 | >>> zipped = zip(a,b) # 打包为元组的列表 40 | [(1, 4), (2, 5), (3, 6)] 41 | >>> zip(a,c) # 元素个数与最短的列表一致 42 | [(1, 4), (2, 5), (3, 6)] 43 | >>> zip(*zipped) # 与 zip 相反,可理解为解压,返回二维矩阵式 44 | [(1, 2, 3), (4, 5, 6)] 45 | ``` 46 | 47 | 代码如下: 48 | 49 | ```python 50 | class Solution(object): 51 | def findMinDifference(self, timePoints): 52 | """ 53 | :type timePoints: List[str] 54 | :rtype: int 55 | """ 56 | def convert(time): 57 | return int(time[:2]) * 60 + int(time[3:]) 58 | timePoints = map(convert, timePoints) 59 | timePoints.sort() 60 | return min((y - x) % (24 * 60) for x, y in zip(timePoints, timePoints[1:] + timePoints[:1])) 61 | ``` 62 | 63 | 参考资料:https://leetcode.com/problems/minimum-time-difference/discuss/100637/Python-Straightforward-with-Explanation 64 | 65 | ## 日期 66 | 67 | 2018 年 5 月 31 日 ———— 太阳暴晒,明天就要过儿童节了。激动 68 | -------------------------------------------------------------------------------- /300-399/344. Reverse String 反转字符串.md: -------------------------------------------------------------------------------- 1 | 作者: 负雪明烛 2 | id: fuxuemingzhu 3 | 个人博客: http://fuxuemingzhu.cn/ 4 | 5 | --- 6 | @[TOC](目录) 7 | 8 | 题目地址:[https://leetcode.com/problems/reverse-string/](https://leetcode.com/problems/reverse-string/) 9 | 10 | Total Accepted: 11014 Total Submissions: 18864 Difficulty: Easy 11 | 12 | 13 | ## 题目描述 14 | 15 | 16 | Write a function that takes a string as input and returns the string reversed. 17 | 18 | Example 1: 19 | 20 | Input: "hello" 21 | Output: "olleh" 22 | 23 | Example 2: 24 | 25 | Input: "A man, a plan, a canal: Panama" 26 | Output: "amanaP :lanac a ,nalp a ,nam A" 27 | 28 | 29 | ## 题目大意 30 | 31 | ### 新构建字符串 32 | 33 | 字符串按位翻转: 34 | 35 | ```java 36 | public class Solution { 37 | public String reverseString(String s) { 38 | StringBuffer answer=new StringBuffer(""); 39 | int tail=s.length()-1; 40 | for(int i=tail;i>=0;i--){ 41 | answer.append(s.charAt(i)); 42 | } 43 | return answer.toString(); 44 | 45 | } 46 | } 47 | ``` 48 | AC:6ms 49 | 50 | python支持切片进行翻转,所以代码只有一行。 51 | 52 | ```python 53 | class Solution: 54 | def reverseString(self, s): 55 | """ 56 | :type s: str 57 | :rtype: str 58 | """ 59 | return s[::-1] 60 | ``` 61 | 62 | 63 | ### 原地翻转 64 | 65 | 转换为字符串数组后,in-place翻转。下面的这个java解法返回值是个新的字符串,但是作为结果应该不计算空间复杂度之内。 66 | 67 | java代码: 68 | 69 | ```java 70 | public class Solution { 71 | public String reverseString(String s) { 72 | char[] chars=s.toCharArray(); 73 | for(int i=0;i= nums[p2]: 45 | if p2 - p1 == 1: 46 | mid = p2 47 | break 48 | mid = (p1 + p2) / 2 49 | if nums[mid] == nums[p1] and nums[mid] == nums[p2]: 50 | return self.minInOrder(nums, p1, p2) 51 | if nums[mid] >= nums[p1]: 52 | p1 = mid 53 | elif nums[mid] <= nums[p2]: 54 | p2 = mid 55 | return nums[mid] 56 | 57 | def minInOrder(self, nums, index1, index2): 58 | n1 = nums[index1] 59 | for i in range(index1 + 1, index2): 60 | if n1 > nums[i]: 61 | return nums[i] 62 | return n1 63 | ``` 64 | 65 | ## 日期 66 | 67 | 2018 年 3 月 13 日 -------------------------------------------------------------------------------- /700-799/700. Search in a Binary Search Tree 二叉搜索树中的搜索.md: -------------------------------------------------------------------------------- 1 | 2 | 作者: 负雪明烛 3 | id: fuxuemingzhu 4 | 个人博客: http://fuxuemingzhu.cn/ 5 | 6 | --- 7 | @[TOC](目录) 8 | 9 | 题目地址:https://leetcode.com/problems/search-in-a-binary-search-tree/description/ 10 | 11 | ## 题目描述 12 | 13 | Given the root node of a binary search tree (BST) and a value. You need to find the node in the BST that the node's value equals the given value. Return the subtree rooted with that node. If such node doesn't exist, you should return NULL. 14 | 15 | For example, 16 | 17 | Given the tree: 18 | 19 | 4 20 | / \ 21 | 2 7 22 | / \ 23 | 1 3 24 | 25 | And the value to search: 2 26 | 27 | You should return this subtree: 28 | 29 | 2 30 | / \ 31 | 1 3 32 | 33 | In the example above, if we want to search the value ``5``, since there is no node with value 5, we should return ``NULL``. 34 | 35 | ## 题目大意 36 | 37 | 在一个BST中查找某值,如果找到的话,返回找到的那个节点,如果找不到就返回None. 38 | 39 | ## 解题方法 40 | 41 | ### 递归 42 | 43 | 只要是BST查找,那肯定都好说。树的查找比较简单的就是递归,如果节点是空,那么肯定没找到;节点值相等,返回这个节点;如果节点值小于要查找的值,那么在当前节点的右子树中找;否则在左子树中找。 44 | 45 | 代码如下: 46 | 47 | ```python 48 | # Definition for a binary tree node. 49 | # class TreeNode: 50 | # def __init__(self, x): 51 | # self.val = x 52 | # self.left = None 53 | # self.right = None 54 | 55 | class Solution: 56 | def searchBST(self, root, val): 57 | """ 58 | :type root: TreeNode 59 | :type val: int 60 | :rtype: TreeNode 61 | """ 62 | if not root: 63 | return None 64 | if root.val == val: 65 | return root 66 | elif root.val < val: 67 | return self.searchBST(root.right, val) 68 | else: 69 | return self.searchBST(root.left, val) 70 | ``` 71 | 72 | ## 日期 73 | 74 | 2018 年 7 月 12 日 ———— 天阴阴地潮潮,已经连着两天这样了 75 | 2018 年 11 月 6 日 —— 腰酸背痛要废了 76 | -------------------------------------------------------------------------------- /1-99/86. Partition List 分隔链表.md: -------------------------------------------------------------------------------- 1 | # 【LeetCode】86. Partition List 解题报告(Python) 2 | 3 | 标签(空格分隔): LeetCode 4 | 5 | 作者: 负雪明烛 6 | id: fuxuemingzhu 7 | 个人博客: http://fuxuemingzhu.me/ 8 | 9 | --- 10 | 11 | 题目地址:https://leetcode.com/problems/partition-list/description/ 12 | 13 | ## 题目描述: 14 | 15 | Given a linked list and a value x, partition it such that all nodes less than x come before nodes greater than or equal to x. 16 | 17 | You should preserve the original relative order of the nodes in each of the two partitions. 18 | 19 | Example: 20 | 21 | Input: head = 1->4->3->2->5->2, x = 3 22 | Output: 1->2->2->4->3->5 23 | 24 | 25 | ## 题目大意 26 | 27 | 要把一个单链表中,小于某个数字的所有节点放到前面,其余的位置都不要变化。 28 | 29 | ## 解题方法 30 | 31 | 乍一看,感觉原地做这些操作很难。但是,我们换个思路就感觉很简单了。 32 | 33 | **做链表的题,不要省指针。** 34 | 35 | 用两个新指针,分别记录比x值小的和比x值大的,遍历原来的链表的时候根据值的大小拼接到对应的链表后面。 36 | 37 | 最后再把两个链表拼接到一起就行了。 38 | 39 | ```python 40 | # Definition for singly-linked list. 41 | # class ListNode(object): 42 | # def __init__(self, x): 43 | # self.val = x 44 | # self.next = None 45 | 46 | class Solution(object): 47 | def partition(self, head, x): 48 | """ 49 | :type head: ListNode 50 | :type x: int 51 | :rtype: ListNode 52 | """ 53 | small = ListNode(0) 54 | large = ListNode(0) 55 | small_root, large_root = small, large 56 | while head: 57 | if head.val < x: 58 | small.next = head 59 | small = small.next 60 | else: 61 | large.next = head 62 | large = large.next 63 | temp = head.next 64 | head.next = None 65 | head = temp 66 | small.next = large_root.next 67 | return small_root.next 68 | ``` 69 | 70 | ## 日期 71 | 72 | 2018 年 6 月 24 日 ———— 今天请客吃了海底捞~ 73 | 74 | 75 | [1]: https://blog.csdn.net/fuxuemingzhu/article/details/80786149 -------------------------------------------------------------------------------- /100-199/171. Excel Sheet Column Number Excel 表列序号.md: -------------------------------------------------------------------------------- 1 | 作者: 负雪明烛 2 | id: fuxuemingzhu 3 | 个人博客: http://fuxuemingzhu.cn/ 4 | 5 | --- 6 | @[TOC](目录) 7 | 8 | [LeetCode] 9 | 10 | 题目地址:[https://leetcode.com/problems/excel-sheet-column-number/](https://leetcode.com/problems/excel-sheet-column-number/) 11 | 12 | Total Accepted: 77115 Total Submissions: 185238 Difficulty: Easy 13 | 14 | 15 | ## 题目大意 16 | 17 | Given a column title as appear in an Excel sheet, return its corresponding column number. 18 | 19 | For example: 20 | 21 | A -> 1 22 | B -> 2 23 | C -> 3 24 | ... 25 | Z -> 26 26 | AA -> 27 27 | AB -> 28 28 | ... 29 | 30 | Example 1: 31 | 32 | Input: "A" 33 | Output: 1 34 | 35 | Example 2: 36 | 37 | Input: "AB" 38 | Output: 28 39 | 40 | Example 3: 41 | 42 | Input: "ZY" 43 | Output: 701 44 | 45 | ## 解题方法 46 | 47 | 典型的26进制题目啊!没啥难度。 48 | 49 | 重点是26进制中每一位对应的26的多少次幂。不要搞错。另外,为了防止计算时间过 50 | 长,而且避免数据转化,没有采用Math.exp的方法。直接手撸26的次幂。 51 | 52 | ### Java解法 53 | 54 | 算法如下: 55 | 56 | ```java 57 | public class Solution { 58 | public int titleToNumber(String s) { 59 | int answer=0; 60 | char[] nums=s.toCharArray(); 61 | for(int i=0; i2->3 which represents the number 123. 14 | 15 | Find the total sum of all root-to-leaf numbers. 16 | 17 | For example, 18 | 19 | 1 20 | / \ 21 | 2 3 22 | The root-to-leaf path 1->2 represents the number 12. 23 | The root-to-leaf path 1->3 represents the number 13. 24 | 25 | Return the sum = 12 + 13 = 25. 26 | 27 | ## 解题方法 28 | 29 | 30 | 这个题和[Binary Tree Paths][1]一模一样,前个题是求路径,这个题是把路径按照10的倍数拼接在一起,最后求和即可。 31 | 32 | 有个技巧就是``res = 0``当做参数传给函数,那么函数最后的结果不会影响到res,但是如果把``res = [0]``即可。 33 | 34 | 代码: 35 | 36 | ```python 37 | # Definition for a binary tree node. 38 | # class TreeNode(object): 39 | # def __init__(self, x): 40 | # self.val = x 41 | # self.left = None 42 | # self.right = None 43 | 44 | class Solution(object): 45 | def sumNumbers(self, root): 46 | """ 47 | :type root: TreeNode 48 | :rtype: int 49 | """ 50 | if root == None: 51 | return 0 52 | res = [0] 53 | self.dfs(root, res, root.val) 54 | return res[0] 55 | 56 | def dfs(self, root, res, path): 57 | if root.left == None and root.right == None: 58 | res[0] += path 59 | if root.left != None: 60 | self.dfs(root.left, res, path * 10 + root.left.val) 61 | if root.right != None: 62 | self.dfs(root.right, res, path * 10 + root.right.val) 63 | ``` 64 | 65 | 66 | ## 日期 67 | 68 | 2018 年 2 月 25 日 69 | 70 | 71 | [1]: http://blog.csdn.net/fuxuemingzhu/article/details/71249429 -------------------------------------------------------------------------------- /600-699/646. Maximum Length of Pair Chain 最长数对链.md: -------------------------------------------------------------------------------- 1 | 作者: 负雪明烛 2 | id: fuxuemingzhu 3 | 个人博客: http://fuxuemingzhu.cn/ 4 | 5 | --- 6 | @[TOC](目录) 7 | 8 | 题目地址:https://leetcode.com/problems/maximum-length-of-pair-chain/description/ 9 | 10 | ## 题目描述 11 | 12 | You are given n pairs of numbers. In every pair, the first number is always smaller than the second number. 13 | 14 | Now, we define a pair ``(c, d)`` can follow another pair ``(a, b)`` if and only if ``b < c``. Chain of pairs can be formed in this fashion. 15 | 16 | Given a set of pairs, find the length longest chain which can be formed. You needn't use up all the given pairs. You can select pairs in any order. 17 | 18 | Example 1: 19 | 20 | Input: [[1,2], [2,3], [3,4]] 21 | Output: 2 22 | Explanation: The longest chain is [1,2] -> [3,4] 23 | 24 | Note: 25 | 26 | 1. The number of given pairs will be in the range [1, 1000]. 27 | 28 | ## 题目大意 29 | 30 | 给出了很多区间,找出能够成的连续增长的区间的个数。区间是闭区间,不能有任何重叠。 31 | 32 | ## 解题方法 33 | 34 | ### 贪心算法 35 | 36 | 题目给的提示是DP,我用Python的DP竟然超时了。其实我第一想法是贪心算法,在机试指南中的39页,题目是《今年暑假不AC》,原题是能收看到的最多的电视节目的数量。 37 | 38 | 这题的做法是按照每个区间的右边界进行排序,我们优先选择结束时间最早的区间,这样的贪心做法能保证最后得到的区间的数目是最多的。 39 | 40 | ![这里写图片描述](https://img-blog.csdn.net/20180405151123730?watermark/2/text/aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L2Z1eHVlbWluZ3podQ==/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70) 41 | 42 | Python代码: 43 | 44 | ```python 45 | class Solution(object): 46 | def findLongestChain(self, pairs): 47 | """ 48 | :type pairs: List[List[int]] 49 | :rtype: int 50 | """ 51 | pairs.sort(key=lambda x: x[1]) 52 | currTime, ans = float('-inf'), 0 53 | for x, y in pairs: 54 | if currTime < x: 55 | currTime = y 56 | ans += 1 57 | return ans 58 | ``` 59 | 60 | ## 日期 61 | 62 | 2018 年 4 月 5 日 —— 清明节假期开始,小长假真好~~ 63 | 64 | 65 | [1]: https://blog.csdn.net/fuxuemingzhu/article/details/79821305 66 | -------------------------------------------------------------------------------- /500-599/538. Convert BST to Greater Tree 把二叉搜索树转换为累加树.md: -------------------------------------------------------------------------------- 1 | 2 | 作者: 负雪明烛 3 | id: fuxuemingzhu 4 | 个人博客: http://fuxuemingzhu.cn/ 5 | 6 | --- 7 | @[TOC](目录) 8 | 9 | 题目地址:[https://leetcode.com/problems/convert-bst-to-greater-tree/description/][1] 10 | 11 | 12 | ## 题目描述 13 | 14 | Given a Binary Search Tree (BST), convert it to a Greater Tree such that every key of the original BST is changed to the original key plus sum of all keys greater than the original key in BST. 15 | 16 | Example: 17 | 18 | Input: The root of a Binary Search Tree like this: 19 | 5 20 | / \ 21 | 2 13 22 | 23 | Output: The root of a Greater Tree like this: 24 | 18 25 | / \ 26 | 20 13 27 | 28 | ## 题目大意 29 | 30 | 把BST的每个节点的值重新设置为所有比它值大的节点的值的和。 31 | 32 | ## 解题方法 33 | 34 | ### 递归 35 | 36 | 这个题要把每个节点变为比该节点值大(包含)的所有节点之和。 37 | 38 | 这个题的动机是我们应该先修改数值比较大的节点,然后修改数值比较小的节点。这样做,才能保证,我们只需要一次遍历,就把每个节点的值修改成了比它值更大的所有节点的和。 39 | 40 | BST的右子树都比该节点大,所以修改次序是右-->中-->左。用一个变量储存遍历过程中所有有节点之和就得到了所有的比当前把该节点的值更大的和,然后修改为该变量的值即可。 41 | 42 | 43 | ```python 44 | # Definition for a binary tree node. 45 | # class TreeNode(object): 46 | # def __init__(self, x): 47 | # self.val = x 48 | # self.left = None 49 | # self.right = None 50 | 51 | class Solution(object): 52 | def convertBST(self, root): 53 | """ 54 | :type root: TreeNode 55 | :rtype: TreeNode 56 | """ 57 | self.sum = 0 58 | def afterOrder(cur): 59 | if not cur: return 60 | afterOrder(cur.right) 61 | self.sum += cur.val 62 | cur.val = self.sum 63 | afterOrder(cur.left) 64 | afterOrder(root) 65 | return root 66 | ``` 67 | 68 | ## 日期 69 | 70 | 2018 年 1 月 22 日 71 | 2018 年 11 月 13 日 —— 时间有点快 72 | 73 | [1]: https://leetcode.com/problems/convert-bst-to-greater-tree/description/ 74 | -------------------------------------------------------------------------------- /1100-1199/1167. Minimum Cost to Connect Sticks 连接棒材的最低费用.md: -------------------------------------------------------------------------------- 1 | 2 | 3 | - 作者: 负雪明烛 4 | - id: fuxuemingzhu 5 | - 个人博客:[http://fuxuemingzhu.cn/](http://fuxuemingzhu.cn/) 6 | 7 | --- 8 | @[TOC](目录) 9 | 10 | 题目地址:https://leetcode-cn.com/problems/minimum-cost-to-connect-sticks/ 11 | 12 | ## 题目描述 13 | 14 | You have some sticks with positive integer lengths. 15 | 16 | You can connect any two sticks of lengths `X` and `Y` into one stick by paying a cost of `X + Y`. You perform this action until there is one stick remaining. 17 | 18 | Return the minimum cost of connecting all the given sticks into one stick in this way. 19 | 20 | Example 1: 21 | 22 | Input: sticks = [2,4,3] 23 | Output: 14 24 | 25 | Example 2: 26 | 27 | Input: sticks = [1,8,3,5] 28 | Output: 30 29 | 30 | Constraints: 31 | 32 | 1. `1 <= sticks.length <= 10^4` 33 | 1. `1 <= sticks[i] <= 10^4` 34 | 35 | 36 | 37 | ## 题目大意 38 | 39 | 为了装修新房,你需要加工一些长度为正整数的棒材 sticks。 40 | 如果要将长度分别为 X 和 Y 的两根棒材连接在一起,你需要支付 X + Y 的费用。 由于施工需要,你必须将所有棒材连接成一根。 41 | 返回你把所有棒材 sticks 连成一根所需要的最低费用。注意你可以任意选择棒材连接的顺序。 42 | 43 | ## 解题方法 44 | 45 | ### 小根堆 46 | 47 | 这个题是遇到过的微软面试题。 48 | 49 | 其实题目是让我们生成一个哈弗曼树,做法是使用小根堆,每次选用最小的两根棒材,拼接到一块,然后放入小根堆中。重复这个操作,直至小根堆中只有一个棒材为止。 50 | 51 | 52 | C++代码如下: 53 | 54 | ```cpp 55 | class Solution { 56 | public: 57 | int connectSticks(vector& sticks) { 58 | priority_queue, greater> que; 59 | for (int stick : sticks) { 60 | que.push(stick); 61 | } 62 | int res = 0; 63 | while (!que.empty()) { 64 | int first = que.top(); que.pop(); 65 | if (!que.empty()) { 66 | int second = que.top(); que.pop(); 67 | int sum = first + second; 68 | res += sum; 69 | que.push(sum); 70 | } 71 | } 72 | return res; 73 | } 74 | }; 75 | ``` 76 | 77 | ## 日期 78 | 79 | 2019 年 9 月 23 日 —— 昨夜睡的早,错过了北京的烟火 80 | -------------------------------------------------------------------------------- /600-699/686. Repeated String Match 重复叠加字符串匹配.md: -------------------------------------------------------------------------------- 1 | 2 | 作者: 负雪明烛 3 | id: fuxuemingzhu 4 | 个人博客: http://fuxuemingzhu.cn/ 5 | 6 | --- 7 | @[TOC](目录) 8 | 9 | 题目地址:https://leetcode.com/problems/repeated-string-match/description/ 10 | 11 | ## 题目描述 12 | 13 | Given two strings A and B, find the minimum number of times A has to be repeated such that B is a substring of it. If no such solution, return -1. 14 | 15 | For example, with A = "abcd" and B = "cdabcdab". 16 | 17 | Return 3, because by repeating A three times (“abcdabcdabcd”), B is a substring of it; and B is not a substring of A repeated two times ("abcdabcd"). 18 | 19 | Note: 20 | 21 | The length of A and B will be between 1 and 10000. 22 | 23 | ## 题目大意 24 | 25 | 判断当A重复一定次数之后,B能否成为其子串。 26 | 27 | ## 解题方法 28 | 29 | 自己想了很久没想出怎么做,可是看到别人的解法后,立马就懂了:当A重复一定次数后,长度比B长了,那么就可以停止了!因为如果这种情况下B都不是A的子串,那么循环再多也没用。。因为对于B来说,A所有可能的重复都已经出现了。 30 | 31 | python的除会向下取整,所以多加几次,比如+3。(+2会错误) 32 | 33 | ```python 34 | class Solution(object): 35 | def repeatedStringMatch(self, A, B): 36 | """ 37 | :type A: str 38 | :type B: str 39 | :rtype: int 40 | """ 41 | na, nb = len(A), len(B) 42 | times = nb / na + 3 43 | for i in range(1, times): 44 | if B in A * i: 45 | return i 46 | return -1 47 | ``` 48 | 49 | C++版本如下: 50 | 51 | ```cpp 52 | class Solution { 53 | public: 54 | int repeatedStringMatch(string A, string B) { 55 | int NA = A.size(), NB = B.size(); 56 | int times = NB / NA + 3; 57 | string t = A; 58 | for (int i = 1; i < times; i++) { 59 | if (t.find(B) != string::npos) return i; 60 | t += A; 61 | } 62 | return -1; 63 | } 64 | }; 65 | ``` 66 | 67 | 参考资料: 68 | 69 | [\[LeetCode\] Repeated String Match 重复字符串匹配](http://www.cnblogs.com/grandyang/p/7631434.html) 70 | 71 | 72 | ## 日期 73 | 74 | 2018 年 3 月 15 日 --雾霾消散,春光明媚 75 | 2018 年 11 月 24 日 —— 周日开始!一周就过去了~ 76 | -------------------------------------------------------------------------------- /300-399/320. Generalized Abbreviation 列举单词的全部缩写.md: -------------------------------------------------------------------------------- 1 | - 作者: 负雪明烛 2 | - id: fuxuemingzhu 3 | - 个人博客:[http://fuxuemingzhu.cn/](http://fuxuemingzhu.cn/) 4 | 5 | --- 6 | @[TOC](目录) 7 | 8 | 题目地址:https://leetcode-cn.com/problems/generalized-abbreviation/ 9 | 10 | ## 题目描述 11 | 12 | Write a function to generate the generalized abbreviations of a word. 13 | 14 | Note: The order of the output does not matter. 15 | 16 | Example: 17 | 18 | Input: "word" 19 | Output: 20 | ["word", "1ord", "w1rd", "wo1d", "wor1", "2rd", "w2d", "wo2", "1o1d", "1or1", "w1r1", "1o2", "2r1", "3d", "w3", "4"] 21 | 22 | 23 | ## 题目大意 24 | 25 | 生成一个字符串的所有缩写。 26 | 27 | ## 解题方法 28 | 29 | ### DFS 30 | 31 | 该题是让我们生成缩写,本质是个搜索题。 32 | 33 | 使用index表示当前遍历到哪个字符了,使用nums表示在遍历到当前字符时前面已经省略掉了多少个字符。 34 | 35 | 对于每个位置,我们有两个选择: 36 | 37 | 1. 这个位置如果不使用,则累加现在已有的省略掉的数字num 38 | 1. 这个位置如果使用,则拼接前面已经累加的数字num,拼接当前字符,省略掉的字符从0开始 39 | 40 | 所以这个问题本身还是简单的,需要注意的是num为0的时候不应该进行拼接。 41 | 另外,这个题为什么没有像全排列/子集一样,进行for循环呢?这是由于在构造字符缩写的时候起点、顺序都不能变的,这个不是抽取或者排列的问题。 42 | 43 | C++代码如下: 44 | 45 | ```cpp 46 | class Solution { 47 | public: 48 | vector generateAbbreviations(string word) { 49 | vector res; 50 | dfs(res, word, 0, 0, ""); 51 | return res; 52 | } 53 | void dfs(vector& res, string& word, int index, int num, string cur) { 54 | if (index == word.size()) { 55 | if (num != 0) 56 | cur = cur + to_string(num); 57 | res.push_back(cur); 58 | return; 59 | } 60 | // 不用word[index] 61 | dfs(res, word, index + 1, num + 1, cur); 62 | // 用word[index] 63 | dfs(res, word, index + 1, 0, cur + (num == 0 ? "" : to_string(num)) + word[index]); 64 | } 65 | }; 66 | ``` 67 | 68 | ## 日期 69 | 70 | 2019 年 9 月 27 日 —— 昨天面快手,竟然是纯刷题 71 | 72 | 73 | [1]: https://assets.leetcode.com/uploads/2019/05/03/capture.JPG 74 | [2]: https://blog.csdn.net/fuxuemingzhu/article/details/79616156 75 | -------------------------------------------------------------------------------- /600-699/672. Bulb Switcher II 灯泡开关 Ⅱ.md: -------------------------------------------------------------------------------- 1 | 2 | 作者: 负雪明烛 3 | id: fuxuemingzhu 4 | 个人博客: http://fuxuemingzhu.cn/ 5 | 6 | --- 7 | @[TOC](目录) 8 | 9 | 题目地址:https://leetcode.com/problems/bulb-switcher-ii/description/ 10 | 11 | ## 题目描述 12 | 13 | There is a room with n lights which are turned on initially and 4 buttons on the wall. After performing exactly m unknown operations towards buttons, you need to return how many different kinds of status of the n lights could be. 14 | 15 | Suppose n lights are labeled as number [1, 2, 3 ..., n], function of these 4 buttons are given below: 16 | 17 | 1. Flip all the lights. 18 | 1. Flip lights with even numbers. 19 | 1. Flip lights with odd numbers. 20 | 1. Flip lights with (3k + 1) numbers, k = 0, 1, 2, ... 21 | 22 | Example 1: 23 | 24 | Input: n = 1, m = 1. 25 | Output: 2 26 | Explanation: Status can be: [on], [off] 27 | 28 | Example 2: 29 | 30 | Input: n = 2, m = 1. 31 | Output: 3 32 | Explanation: Status can be: [on, off], [off, on], [off, off] 33 | 34 | Example 3: 35 | 36 | Input: n = 3, m = 1. 37 | Output: 4 38 | Explanation: Status can be: [off, on, off], [on, off, on], [off, off, off], [off, on, on]. 39 | 40 | Note: n and m both fit in range [0, 1000]. 41 | 42 | ## 题目大意 43 | 44 | 有四种操作。分别对灯进行变换。。不是一个数学题,这个是脑筋急转弯。 45 | 46 | ## 解题方法 47 | 48 | 额,不会做。脑子不够用。。这个题被踩了这么多下,其实没有做的必要了。 49 | 50 | 可以看http://blog.csdn.net/huanghanqian/article/details/77857912 51 | 52 | 代码: 53 | 54 | ```python 55 | class Solution: 56 | def flipLights(self, n, m): 57 | """ 58 | :type n: int 59 | :type m: int 60 | :rtype: int 61 | """ 62 | if m == 0: 63 | return 1 64 | if n >= 3: 65 | return 4 if m == 1 else 7 if m == 2 else 8 66 | if n == 2: 67 | return 3 if m == 1 else 4 68 | if n == 1: 69 | return 2 70 | ``` 71 | 72 | ## 日期 73 | 74 | 2018 年 3 月 5 日 75 | -------------------------------------------------------------------------------- /1000-1099/1021. Remove Outermost Parentheses 删除最外层的括号.md: -------------------------------------------------------------------------------- 1 | 2 | 3 | 作者: 负雪明烛 4 | id: fuxuemingzhu 5 | 个人博客: http://fuxuemingzhu.cn/ 6 | 7 | --- 8 | @[TOC](目录) 9 | 10 | 11 | 题目地址:https://leetcode.com/problems/best-sightseeing-pair/ 12 | 13 | ## 题目描述 14 | 15 | 16 | Given an array ``A`` of positive integers, ``A[i]`` represents the value of the ``i``-th sightseeing spot, and two sightseeing spots ``i`` and ``j`` have distance ``j - i`` between them. 17 | 18 | The score of a pair (``i < j``) of sightseeing spots is (``A[i] + A[j] + i - j``) : the sum of the values of the sightseeing spots, **minus** the distance between them. 19 | 20 | Return the maximum score of a pair of sightseeing spots. 21 | 22 | 23 | Example 1: 24 | 25 | Input: [8,1,5,2,6] 26 | Output: 11 27 | Explanation: i = 0, j = 2, A[i] + A[j] + i - j = 8 + 5 + 0 - 2 = 11 28 | 29 | 30 | Note: 31 | 32 | 1. ``2 <= A.length <= 50000`` 33 | 1. ``1 <= A[i] <= 1000`` 34 | 35 | ## 题目大意 36 | 37 | 对于数组中的两个下标i, j,求``A[i] + A[j] + i - j``最大值. 38 | 39 | ## 解题方法 40 | 一般暴力解法是两重循环,即先找到一个位置 `i` 之后,从其后位置 `j` 继续循环遍历,这样的复杂度是`O(N ^ 2)` 的。看到题目给出的数据范围,数组的长度是 50000, 对于这个题`O(N ^ 2)` 的时间复杂度肯定不可取。 41 | 42 | 对于这个题,我们知道肯定只能用 `O(N)` 的解法,把公式稍加变化成`(A[i] + i) + (A[j] - j)`,我们可以看出要找出这两部分和的最大值。 43 | 44 | 具体方法是保存每个位置 `j` ,时刻维护其前面的`A[i] + i`的最大值出现的位置 `pre_i`。最后结果就是对于每个位置`j`对应的``A[i] + A[j] + i - j``最大值。 45 | 46 | 47 | Python代码如下: 48 | 49 | ```python 50 | class Solution(object): 51 | def maxScoreSightseeingPair(self, A): 52 | """ 53 | :type A: List[int] 54 | :rtype: int 55 | """ 56 | pre_i = 0 57 | res = 0 58 | for j in range(1, len(A)): 59 | res = max(A[j] - j + A[pre_i] + pre_i, res) 60 | if A[j] + j > A[pre_i] + pre_i: 61 | pre_i = j 62 | return res 63 | ``` 64 | 65 | 参考资料:https://leetcode.com/problems/best-sightseeing-pair/discuss/260850/JavaC%2B%2BPython-One-Pass 66 | 67 | ## 日期 68 | 69 | 2019 年 3 月 24 日 —— 这个周赛太悲催了 70 | -------------------------------------------------------------------------------- /1000-1099/1012. Numbers With Repeated Digits 至少有 1 位重复的数字.md: -------------------------------------------------------------------------------- 1 | 作者: 负雪明烛 2 | id: fuxuemingzhu 3 | 个人博客: http://fuxuemingzhu.cn/ 4 | 5 | --- 6 | @[TOC](目录) 7 | 8 | 9 | 题目地址:https://leetcode.com/problems/complement-of-base-10-integer/ 10 | 11 | ## 题目描述 12 | 13 | Every non-negative integer ``N`` has a binary representation. For example, ``5`` can be represented as ``"101"`` in binary, ``11`` as ``"1011"`` in binary, and so on. Note that except for ``N = 0``, there are no leading zeroes in any binary representation. 14 | 15 | The complement of a binary representation is the number in binary you get when changing every ``1`` to a ``0`` and ``0`` to a ``1``. For example, the complement of ``"101"`` in binary is ``"010"`` in binary. 16 | 17 | For a given number ``N`` in base-10, return the complement of it's binary representation as a base-10 integer. 18 | 19 | Example 1: 20 | 21 | Input: 5 22 | Output: 2 23 | Explanation: 5 is "101" in binary, with complement "010" in binary, which is 2 in base-10. 24 | 25 | Example 2: 26 | 27 | Input: 7 28 | Output: 0 29 | Explanation: 7 is "111" in binary, with complement "000" in binary, which is 0 in base-10. 30 | 31 | Example 3: 32 | 33 | Input: 10 34 | Output: 5 35 | Explanation: 10 is "1010" in binary, with complement "0101" in binary, which is 5 in base-10. 36 | 37 | 38 | Note: 39 | 40 | 1. ``0 <= N < 10^9`` 41 | 42 | ## 题目大意 43 | 44 | 求一个数的补码。 45 | 46 | ## 解题方法 47 | 48 | 很简单一个作弊方法,直接求二进制,然后把1改成0,把0改成1即可。 49 | 50 | Python代码如下: 51 | 52 | ```python 53 | class Solution(object): 54 | def bitwiseComplement(self, N): 55 | """ 56 | :type N: int 57 | :rtype: int 58 | """ 59 | return int("".join(map(lambda x :"0" if x == "1" else "1", bin(N)[2:])), 2) 60 | ``` 61 | 62 | 63 | ## 日期 64 | 65 | 2019 年 3 月 21 日 —— 好久不刷题,重拾有点难 66 | 67 | 68 | [1]: https://assets.leetcode.com/uploads/2019/03/06/1266.png 69 | [2]: https://assets.leetcode.com/uploads/2019/03/08/domino.png 70 | -------------------------------------------------------------------------------- /900-999/961. N-Repeated Element in Size 2N Array 在长度 2N 的数组中找出重复 N 次的元素.md: -------------------------------------------------------------------------------- 1 | 2 | 作者: 负雪明烛 3 | id: fuxuemingzhu 4 | 个人博客: http://fuxuemingzhu.cn/ 5 | 6 | --- 7 | @[TOC](目录) 8 | 9 | 10 | 题目地址:https://leetcode.com/problems/n-repeated-element-in-size-2n-array/ 11 | 12 | 13 | ## 题目描述 14 | 15 | In a array ``A`` of size ``2N``, there are ``N+1`` unique elements, and exactly one of these elements is repeated N times. 16 | 17 | Return the element repeated ``N`` times. 18 | 19 | 20 | Example 1: 21 | 22 | Input: [1,2,3,3] 23 | Output: 3 24 | 25 | Example 2: 26 | 27 | Input: [2,1,2,5,3,2] 28 | Output: 2 29 | 30 | Example 3: 31 | 32 | Input: [5,1,5,2,5,3,5,4] 33 | Output: 5 34 | 35 | 36 | Note: 37 | 38 | 1. 4 <= A.length <= 10000 39 | 1. 0 <= A[i] < 10000 40 | 1. A.length is even 41 | 42 | 43 | ## 题目大意 44 | 45 | 一个数组有2N个数字,其中有N+1个不同的数字。在这里边恰好有一个数字重复了N次,找出这个重复了N次的数字是什么。 46 | 47 | ## 解题方法 48 | 49 | ### 字典 50 | 51 | 只要是和次数有关的题目,可以直接使用字典解决。这个题直接统计每个数字出现的次数,然后把次数等于N的返回即可。 52 | 53 | python代码如下: 54 | 55 | ```python 56 | class Solution(object): 57 | def repeatedNTimes(self, A): 58 | """ 59 | :type A: List[int] 60 | :rtype: int 61 | """ 62 | N = len(A) / 2 63 | count = collections.Counter(A) 64 | for k, v in count.items(): 65 | if v == N: 66 | return k 67 | return 0 68 | ``` 69 | 70 | 71 | C++代码如下: 72 | 73 | ```cpp 74 | class Solution { 75 | public: 76 | int repeatedNTimes(vector& A) { 77 | const int N = A.size() / 2; 78 | unordered_map m; 79 | for (int a : A) { 80 | m[a] ++; 81 | } 82 | for (auto x : m) { 83 | if (x.second == N) { 84 | return x.first; 85 | } 86 | } 87 | return 0; 88 | } 89 | }; 90 | ``` 91 | 92 | 93 | ## 日期 94 | 95 | 2018 年 12 月 23 日 —— 周赛成绩新高 96 | 97 | 98 | [1]: https://blog.csdn.net/fuxuemingzhu/article/details/79368360 99 | -------------------------------------------------------------------------------- /1000-1099/1002. Find Common Characters 查找共用字符.md: -------------------------------------------------------------------------------- 1 | 作者: 负雪明烛 2 | id: fuxuemingzhu 3 | 个人博客: http://fuxuemingzhu.cn/ 4 | 5 | --- 6 | @[TOC](目录) 7 | 8 | 9 | 题目地址:https://leetcode.com/problems/find-common-characters/ 10 | 11 | 12 | ## 题目描述 13 | 14 | Given an array ``A`` of strings made only from lowercase letters, return a list of all characters that show up in all strings within the list (**including duplicates**). For example, if a character occurs 3 times in all strings but not 4 times, you need to include that character three times in the final answer. 15 | 16 | You may return the answer in any order. 17 | 18 | 19 | 20 | Example 1: 21 | 22 | Input: ["bella","label","roller"] 23 | Output: ["e","l","l"] 24 | 25 | Example 2: 26 | 27 | Input: ["cool","lock","cook"] 28 | Output: ["c","o"] 29 | 30 | Note: 31 | 32 | 1. ``1 <= A.length <= 100`` 33 | 1. ``1 <= A[i].length <= 100`` 34 | 1. ``A[i][j]`` is a lowercase letter 35 | 36 | ## 题目大意 37 | 38 | 给出了一个字符串列表,每个字符串都只包含小写字符,如果某个字符在所有的字符串中均出现,那么就把这个字符放到结果列表中。注意,如果同样的字符出现了不止一次,那么需要放等量的数目到结果中。 39 | 40 | ## 解题方法 41 | 42 | ### 字典 43 | 44 | 毕竟周赛第一题,比较简单。只要明白题意之后,我们就知道了这个题可以用字典解决。 45 | 46 | 使用字典统计每个字符串中的每个字符的次数,然后对26个字符进行遍历,统计在所有字符串中这个字符出现的最少次数,把该最小次数个该字符放到结果列表中即可。 47 | 48 | 问:在统计完一个小写字符之后需要把每个字符串对应的字典中减去该最小次数吗? 49 | 50 | 答:不需要,因为我们接着就会遍历下一个字符,当前字符出现的次数不影响。 51 | 52 | python代码如下: 53 | 54 | ```python 55 | class Solution(object): 56 | def commonChars(self, A): 57 | """ 58 | :type A: List[str] 59 | :rtype: List[str] 60 | """ 61 | A_count = map(lambda x : collections.Counter(x), A) 62 | res = [] 63 | for i in range(26): 64 | c = chr(ord('a') + i) 65 | min_count = min([a_count[c] for a_count in A_count]) 66 | if min_count: 67 | res.extend([c] * min_count) 68 | return res 69 | ``` 70 | 71 | ## 日期 72 | 73 | 2019 年 3 月 3 日 —— 3月开始,春天到了 74 | 75 | 76 | [1]: https://blog.csdn.net/fuxuemingzhu/article/details/85227593 77 | -------------------------------------------------------------------------------- /300-399/395. Longest Substring with At Least K Repeating Characters 至少有 K 个重复字符的最长子串.md: -------------------------------------------------------------------------------- 1 | 作者: 负雪明烛 2 | id: fuxuemingzhu 3 | 个人博客: http://fuxuemingzhu.cn/ 4 | 5 | --- 6 | 7 | 题目地址: https://leetcode.com/problems/longest-substring-with-at-least-k-repeating-characters/description/ 8 | 9 | ## 题目描述: 10 | 11 | Find the length of the longest substring ``T`` of a given string (consists of lowercase letters only) such that every character in T appears no less than k times. 12 | 13 | Example 1: 14 | 15 | Input: 16 | s = "aaabb", k = 3 17 | 18 | Output: 19 | 3 20 | 21 | The longest substring is "aaa", as 'a' is repeated 3 times. 22 | 23 | Example 2: 24 | 25 | Input: 26 | s = "ababbc", k = 2 27 | 28 | Output: 29 | 5 30 | 31 | The longest substring is "ababb", as 'a' is repeated 2 times and 'b' is repeated 3 times. 32 | 33 | ## 题目大意 34 | 35 | 找出一个字符串T的最长连续子字符串,要求这个子字符串中每个字符出现的次数都最少为K,求出这个子字符串的最长长度。 36 | 37 | 38 | ## 解题方法 39 | 40 | 为什么第一个感觉总是错的……这次我的第一感觉是使用双指针,但是没有想好怎么移动后面的哪个指针,所以放弃。 41 | 42 | 看到大神的做法,还是比我思路更活跃,思路是这样的: 43 | 44 | 1. 如果字符串s的长度少于k,那么一定不存在满足题意的子字符串,返回0; 45 | 2. 如果一个字符在s中出现的次数少于k次,那么所有的包含这个字符的子字符串都不能满足题意。所以,应该去不包含这个字符的子字符串继续寻找。这就是分而治之的思路,返回不同子串的长度最大值。 46 | 3. 如果s中的每个字符出现的次数都大于k次,那么s就是我们要求的字符串。 47 | 48 | 虽然代码比较简短,但这个题的思路还是挺新颖的, 49 | 50 | 递归的时间复杂度不会计算,最坏为O(n^2)吧,空间复杂度O(1)。n为字符串长度。 51 | 52 | 代码如下: 53 | 54 | ```python 55 | class Solution(object): 56 | def longestSubstring(self, s, k): 57 | """ 58 | :type s: str 59 | :type k: int 60 | :rtype: int 61 | """ 62 | if len(s) < k: 63 | return 0 64 | for c in set(s): 65 | if s.count(c) < k: 66 | return max(self.longestSubstring(t, k) for t in s.split(c)) 67 | return len(s) 68 | ``` 69 | 70 | 参考资料: 71 | 72 | https://leetcode.com/problems/longest-substring-with-at-least-k-repeating-characters/discuss/87768/4-lines-Python 73 | 74 | ## 日期 75 | 76 | 2018 年 9 月 27 日 —— 国庆9天长假就要开始了! 77 | -------------------------------------------------------------------------------- /800-899/829. Consecutive Numbers Sum 连续整数求和.md: -------------------------------------------------------------------------------- 1 | 2 | 作者: 负雪明烛 3 | id: fuxuemingzhu 4 | 个人博客: http://fuxuemingzhu.cn/ 5 | 6 | --- 7 | @[TOC](目录) 8 | 9 | 10 | 题目地址:https://leetcode.com/problems/consecutive-numbers-sum/ 11 | 12 | 13 | ## 题目描述 14 | 15 | Given a positive integer ``N``, how many ways can we write it as a sum of consecutive positive integers? 16 | 17 | Example 1: 18 | 19 | Input: 5 20 | Output: 2 21 | Explanation: 5 = 5 = 2 + 3 22 | 23 | Example 2: 24 | 25 | Input: 9 26 | Output: 3 27 | Explanation: 9 = 9 = 4 + 5 = 2 + 3 + 4 28 | 29 | Example 3: 30 | 31 | Input: 15 32 | Output: 4 33 | Explanation: 15 = 15 = 8 + 7 = 4 + 5 + 6 = 1 + 2 + 3 + 4 + 5 34 | 35 | Note: ``1 <= N <= 10 ^ 9``. 36 | 37 | ## 题目大意 38 | 39 | 问给定一个数字N,有多少种把它展开成连续正整数之和的方案。 40 | 41 | ## 解题方法 42 | 43 | ### 数学方法 44 | 45 | 有些题会让人陷入常规做法不能自拔,比如这个题就可能想成回溯或者O(M*N)的循环。事实上可以通过数学方法进行优化。 46 | 47 | 因为是连续正整数之和,所以可以使用数列求和公式直接求和,把O(M*N)的方案降到O(M)。 48 | 49 | 由``N = a + (a + 1) + (a + 2) + (a + 3) + ... + (a + i)``得, 50 | 51 | ``N = a * (i + 1) + (i * (i + 1)) / 2``,其中,``a > 0``并且`` i>= 0``。 52 | 53 | 所以,我们先求出prod = (i * (i + 1)) / 2 , 如果这个数字大于N了,就立刻结束。否则,remain = N - prod ==> a * (i + 1). 所以,remain应该能够整除(i + 1),而且余数为a > 0。 54 | 55 | 这个题用python代码会超时,改用C++就能通过。 56 | 57 | C++代码如下: 58 | 59 | ```cpp 60 | class Solution { 61 | public: 62 | int consecutiveNumbersSum(int N) { 63 | int res = 0; 64 | for (int i = 0; i < N; i++) { 65 | int prod = (i + 1) * i / 2; 66 | if (prod > N) break; 67 | int remain = N - prod; 68 | if (remain % (i + 1) != 0) 69 | continue; 70 | if (remain / (i + 1) > 0) 71 | res ++; 72 | } 73 | return res; 74 | } 75 | }; 76 | ``` 77 | 78 | 79 | ## 日期 80 | 81 | 2019 年 1 月 5 日 —— 美好的周末又开始了 82 | 83 | 84 | [1]: https://assets.leetcode.com/uploads/2018/10/12/8-queens.png 85 | [2]: https://blog.csdn.net/fuxuemingzhu/article/details/79517109 86 | -------------------------------------------------------------------------------- /500-599/567. Permutation in String 字符串的排列.md: -------------------------------------------------------------------------------- 1 | 作者: 负雪明烛 2 | id: fuxuemingzhu 3 | 个人博客: http://fuxuemingzhu.cn/ 4 | 5 | --- 6 | 7 | 题目地址:https://leetcode.com/problems/permutation-in-string/description/ 8 | 9 | ## 题目描述: 10 | 11 | Given two strings ``s1`` and ``s2``, write a function to return true if s2 contains the permutation of s1. In other words, one of the first string's permutations is the substring of the second string. 12 | 13 | Example 1: 14 | 15 | Input:s1 = "ab" s2 = "eidbaooo" 16 | Output:True 17 | Explanation: s2 contains one permutation of s1 ("ba"). 18 | 19 | Example 2: 20 | 21 | Input:s1= "ab" s2 = "eidboaoo" 22 | Output: False 23 | 24 | Note: 25 | 26 | 1. The input strings only contain lower case letters. 27 | 1. The length of both given strings is in range [1, 10,000]. 28 | 29 | ## 题目大意 30 | 31 | 判断s1的某个全排列是不是在s2中(连续子字符串)。 32 | 33 | ## 解题方法 34 | 35 | 肯定不可能手动全排列的,时间复杂度太高。 36 | 37 | 思想是,使用和s1等长的滑动窗口判断s2在这个窗口内的字符出现个数和s1的字符出现个数是否相等。 38 | 39 | 使用的是一个字典,统计次数就行,比较简单。第一遍的时候是每次切片都去使用Counter,这样的话超时了。所以改用了每次增加窗口最右边的元素,删除最左边的元素,如果左边的元素次数已经为0了,需要手动删除这个元素,否则影响字典相等的判断。 40 | 41 | 时间复杂度为O(N),空间复杂度O(1)。N为s2长度,假设判断两个字典是否相等的时间复杂度是O(1). 42 | 43 | 代码如下: 44 | 45 | ```python 46 | class Solution(object): 47 | def checkInclusion(self, s1, s2): 48 | """ 49 | :type s1: str 50 | :type s2: str 51 | :rtype: bool 52 | """ 53 | if len(s2) < len(s1): return False 54 | c = collections.Counter(s1) 55 | n = len(s1) 56 | l, r = 0, n - 1 57 | s = collections.Counter(s2[l : r]) 58 | while r < len(s2): 59 | s[s2[r]] += 1 60 | if s == c: 61 | return True 62 | s[s2[l]] -= 1 63 | if s[s2[l]] == 0: 64 | del s[s2[l]] 65 | l += 1 66 | r += 1 67 | return False 68 | ``` 69 | 70 | 参考资料: 71 | 72 | https://www.youtube.com/watch?v=wpq03MmEHIM 73 | 74 | ## 日期 75 | 76 | 2018 年 9 月 27 日 —— 国庆9天长假就要开始了! 77 | -------------------------------------------------------------------------------- /200-299/268. Missing Number 丢失的数字.md: -------------------------------------------------------------------------------- 1 | 2 | 作者: 负雪明烛 3 | id: fuxuemingzhu 4 | 个人博客: http://fuxuemingzhu.cn/ 5 | 6 | --- 7 | @[TOC](目录) 8 | 9 | 题目地址:[https://leetcode.com/problems/missing-number/#/description][1] 10 | 11 | 12 | ## 题目描述 13 | 14 | 15 | Given an array containing ``n`` distinct numbers taken from ``0, 1, 2, ..., n``, find the one that is missing from the array. 16 | 17 | Example 1: 18 | 19 | Input: [3,0,1] 20 | Output: 2 21 | 22 | Example 2: 23 | 24 | Input: [9,6,4,2,3,5,7,0,1] 25 | Output: 8 26 | 27 | Note: 28 | Your algorithm should run in linear runtime complexity. Could you implement it using only constant extra space complexity? 29 | 30 | ## 题目大意 31 | 32 | 求N+1个不同的数字(0~N)中缺失了一个数字,求这个数字是多少? 33 | 34 | ## 解题方法 35 | 36 | ### 求和 37 | 38 | 因为数字是从0, 1, 2, ..., n中抽走一个,因此,该数字的值是0, 1, 2, ..., n的和减去现有数字的和。 39 | 40 | ```java 41 | public class Solution { 42 | public int missingNumber(int[] nums) { 43 | int sum = 0; 44 | int len = nums.length; 45 | for(int i = 0; i < len; i++){ 46 | sum += nums[i]; 47 | } 48 | return len * (len + 1)/2 - sum; 49 | } 50 | } 51 | ``` 52 | 53 | --- 54 | 二刷,python 55 | 56 | ```python 57 | class Solution(object): 58 | def missingNumber(self, nums): 59 | """ 60 | :type nums: List[int] 61 | :rtype: int 62 | """ 63 | n = len(nums) 64 | num_sum = sum(nums) 65 | return n * (n + 1) / 2 - num_sum 66 | ``` 67 | 68 | ### 异或 69 | 70 | 索引是0~N,直接异或一遍0~N各个数字共N+1个,并且异或所有出现的数字,剩下的结果是只出现一次的数字,也就是说缺失的那个数字。 71 | 72 | 需要注意的是初始化是N,这样才能把0~N各个索引多异或一遍。 73 | 74 | ```java 75 | public int missingNumber(int[] nums) { //xor 76 | int res = nums.length; 77 | for(int i=0; i49", "51->74", "76->99"] 18 | 19 | 20 | ## 题目大意 21 | 22 | 给定一个排序的整数数组 nums ,其中元素的范围在 闭区间 [lower, upper] 当中,返回不包含在数组中的缺失区间。 23 | 24 | ## 解题方法 25 | 26 | ### 遍历 27 | 28 | 这个题的坑比较多,比如: 29 | 30 | 1. 小心整数操作溢出 31 | 2. 区间中数据可能有重复 32 | 3. 处理第一个和最后一个节点 33 | 34 | 采用long long类型的数据,然后依次遍历所有的元素,判断这个元素和上一个元素的差值是否>=2。另外需要注意最后一个元素也要判断。 35 | 36 | 第一次提交的时候,我想在`nums.push_back(upper+1)`,只要一次遍历就行。结果发现哦upper+1可能会超出int范围。所以只能用下面的解法了。 37 | 38 | C++代码如下: 39 | 40 | ```cpp 41 | class Solution { 42 | public: 43 | vector findMissingRanges(vector& nums, int lower, int upper) { 44 | vector res; 45 | long long left = (long long)lower - 1; 46 | long long val = 0; 47 | for (long long right : nums) { 48 | val = right - left; 49 | if (val == 2) { 50 | res.push_back(to_string(left + 1)); 51 | } else if (val > 2) { 52 | res.push_back(to_string(left + 1) + "->" + to_string(right - 1)); 53 | } 54 | left = right; 55 | } 56 | val = upper - left; 57 | if (val == 1) { 58 | res.push_back(to_string(upper)); 59 | } else if (val > 1) { 60 | res.push_back(to_string(left + 1) + "->" + to_string(upper)); 61 | } 62 | return res; 63 | } 64 | }; 65 | ``` 66 | 67 | 参考资料:https://leetcode-cn.com/problems/missing-ranges/solution/cte-shu-qing-kuang-duo-dao-bao-by-liyupi/ 68 | 69 | ## 日期 70 | 71 | 2019 年 9 月 23 日 —— 昨夜睡的早,错过了北京的烟火 72 | -------------------------------------------------------------------------------- /1400-1499/1433. Check If a String Can Break Another String 检查一个字符串是否可以打破另一个字符串.md: -------------------------------------------------------------------------------- 1 | - 作者: 负雪明烛 2 | - id: fuxuemingzhu 3 | - 个人博客:[http://fuxuemingzhu.cn/](http://fuxuemingzhu.cn/) 4 | 5 | --- 6 | @[TOC](目录) 7 | 8 | 9 | 题目地址:https://leetcode-cn.com/problems/check-if-a-string-can-break-another-string/ 10 | 11 | # 题目描述 12 | 13 | 给你两个字符串 `s1` 和 `s2` ,它们长度相等,请你检查是否存在一个 `s1` 的排列可以打破 `s2` 的一个排列,或者是否存在一个 `s2` 的排列可以打破 `s1` 的一个排列。 14 | 15 | 字符串 `x` 可以打破字符串 `y` (两者长度都为 `n` )需满足对于所有 `i`(在 `0` 到 `n - 1` 之间)都有 `x[i] >= y[i]`(字典序意义下的顺序)。 16 | 17 | 示例 1: 18 | 19 | 输入:s1 = "abc", s2 = "xya" 20 | 输出:true 21 | 解释:"ayx" 是 s2="xya" 的一个排列,"abc" 是字符串 s1="abc" 的一个排列,且 "ayx" 可以打破 "abc" 。 22 | 23 | 示例 2: 24 | 25 | 输入:s1 = "abe", s2 = "acd" 26 | 输出:false 27 | 解释:s1="abe" 的所有排列包括:"abe","aeb","bae","bea","eab" 和 "eba" ,s2="acd" 的所有排列包括:"acd","adc","cad","cda","dac" 和 "dca"。然而没有任何 s1 的排列可以打破 s2 的排列。也没有 s2 的排列能打破 s1 的排列。 28 | 29 | 示例 3: 30 | 31 | 输入:s1 = "leetcodee", s2 = "interview" 32 | 输出:true 33 | 34 | 提示: 35 | 36 | 1. `s1.length == n` 37 | 1. `s2.length == n` 38 | 1. `1 <= n <= 10^5` 39 | 1. 所有字符串都只包含小写英文字母。 40 | 41 | # 题目大意 42 | 43 | 对两个字符串分别进行重新排序,是否可以让某个字符串的每个字符 都大于等于 另外一个字符串对应位置的字符。 44 | 45 | # 解题方法 46 | 47 | ## 排序 48 | 49 | 这个题不用想复杂,只用分别对两个字符串进行排序,然后依次比较两个字符串各个位置的字符。 50 | 51 | 为什么这样可行? 52 | 53 | 比如 bac 和 xyz 两个字符串,先对 bac 排序得到 abc。 54 | 55 | 假如把最小的 x 放到了最前面,如果 x 仍然小于 a,那么把 x 放在其他位置会仍然小于 abc 的对应字符。因此必须把第二个字符最小的字符也放在最前。 56 | 57 | 所以只用对两个字符串排序,然后按位置比较就行了。 58 | 59 | Python 代码如下: 60 | 61 | ```python 62 | class Solution: 63 | def checkIfCanBreak(self, s1: str, s2: str) -> bool: 64 | s1 = sorted(s1) 65 | s2 = sorted(s2) 66 | return all(s1[i] >= s2[i] for i in range(len(s1))) or all(s1[i] <= s2[i] for i in range(len(s1))) 67 | ``` 68 | 69 | **欢迎关注[负雪明烛的刷题博客](https://blog.csdn.net/fuxuemingzhu),leetcode刷题800多,每道都讲解了详细写法!** 70 | 71 | # 日期 72 | 73 | 2020 年 5 月 2 日 —— 双周赛最后一题不会,是时候多练练hard题了 74 | 75 | 76 | [1]: https://blog.csdn.net/fuxuemingzhu/article/details/79451733 77 | -------------------------------------------------------------------------------- /1400-1499/1414. Find the Minimum Number of Fibonacci Numbers Whose Sum Is K 和为 K 的最少斐波那契数字数目.md: -------------------------------------------------------------------------------- 1 | 2 | - 作者: 负雪明烛 3 | - id: fuxuemingzhu 4 | - 个人博客:[http://fuxuemingzhu.cn/](http://fuxuemingzhu.cn/) 5 | 6 | --- 7 | @[TOC](目录) 8 | 9 | 10 | 题目地址:https://leetcode-cn.com/contest/biweekly-contest-24/problems/find-the-minimum-number-of-fibonacci-numbers-whose-sum-is-k/ 11 | 12 | # 题目描述 13 | 14 | 给你数字 k ,请你返回和为 k 的斐波那契数字的最少数目,其中,每个斐波那契数字都可以被使用多次。 15 | 16 | 斐波那契数字定义为: 17 | 18 | - `F1 = 1` 19 | - `F2 = 1` 20 | - `Fn = Fn-1 + Fn-2` , 其中 n > 2 。 21 | 22 | 数据保证对于给定的 k ,一定能找到可行解。 23 | 24 | 25 | 示例 1: 26 | 27 | 输入:k = 7 28 | 输出:2 29 | 解释:斐波那契数字为:1,1,2,3,5,8,13,…… 30 | 对于 k = 7 ,我们可以得到 2 + 5 = 7 。 31 | 32 | 示例 2: 33 | 34 | 输入:k = 10 35 | 输出:2 36 | 解释:对于 k = 10 ,我们可以得到 2 + 8 = 10 。 37 | 38 | 示例 3: 39 | 40 | 输入:k = 19 41 | 输出:3 42 | 解释:对于 k = 19 ,我们可以得到 1 + 5 + 13 = 19 。 43 | 44 | 45 | 提示: 46 | 47 | 1. `1 <= k <= 10^9` 48 | 49 | # 题目大意 50 | 51 | 在斐波那契数列中,至少取多少个数字(可重复),从而构成k. 52 | 53 | # 解题方法 54 | 55 | ## 贪心 56 | 57 | 看 k 的数字规模是 `10 ^ 9`,但是我们应该关注斐波那契数列的规模有多大。当斐波那契数列越往后,越接近与 `2 ^ x`,那么估算 `2 ** 30 = 1073741824`,所以本题中的斐波那契数列不会超过30. 58 | 59 | 那就暴力求就行了啊! 60 | 61 | 只要 k 没变成0, 那么就**贪心**地从斐波那契数列中找出比 k 小的那个最大数字,让k减去它。计算总的减了多少次。 62 | 63 | 因为数列中有1的存在,所以 k 最后一定会变成0。 64 | 65 | Python代码如下: 66 | 67 | ```python 68 | class Solution: 69 | def findMinFibonacciNumbers(self, k: int) -> int: 70 | fib = [1, 1] 71 | while fib[-1] < k: 72 | fib.append(fib[-1] + fib[-2]) 73 | res = 0 74 | while k != 0: 75 | for i in range(len(fib) - 1, -1, -1): 76 | if fib[i] <= k: 77 | k -= fib[i] 78 | res += 1 79 | break 80 | return res 81 | ``` 82 | 83 | 84 | **欢迎关注[负雪明烛的刷题博客](https://blog.csdn.net/fuxuemingzhu),leetcode刷题800多,每道都讲解了详细写法!** 85 | 86 | # 日期 87 | 88 | 2020 年 4 月 18 日 —— 个人赛蒙了 89 | 90 | 91 | [1]: https://blog.csdn.net/fuxuemingzhu/article/details/79451733 92 | -------------------------------------------------------------------------------- /100-199/120. Triangle 三角形最小路径和.md: -------------------------------------------------------------------------------- 1 | # 【LeetCode】120. Triangle 解题报告(Python) 2 | 3 | 作者: 负雪明烛 4 | id: fuxuemingzhu 5 | 个人博客: http://fuxuemingzhu.cn/ 6 | 7 | --- 8 | 9 | 题目地址https://leetcode.com/problems/triangle/description/ 10 | 11 | ## 题目描述: 12 | 13 | Given a triangle, find the minimum path sum from top to bottom. Each step you may move to adjacent numbers on the row below. 14 | 15 | For example, given the following triangle 16 | 17 | [ 18 | [2], 19 | [3,4], 20 | [6,5,7], 21 | [4,1,8,3] 22 | ] 23 | 24 | The minimum path sum from top to bottom is 11 (i.e., 2 + 3 + 5 + 1 = 11). 25 | 26 | Note: 27 | 28 | Bonus point if you are able to do this using only O(n) extra space, where n is the total number of rows in the triangle. 29 | 30 | ## 题目大意 31 | 32 | 找出一个正三角形从顶到下的最短路径。 33 | 34 | ## 解题方法 35 | 36 | 很多人肯定和我一样想到的是类似于二叉树的DFS,但是二叉树的每个叶子只会遍历一遍,但是这个三角形中,每个位置相当于被上面的两个节点所共有。所以转而用DP求解。 37 | 38 | 从顶向下的DP会导致元素越来越多,因此不是很方便,看到大神是从下向上的DP做的,很佩服! 39 | 40 | 使用minpath[k][i]保存从下向上得到的第k层第i个位置的最短路径。那么有: 41 | 42 | ``` 43 | minpath[k][i] = min( minpath[k+1][i], minpath[k+1][i+1]) + triangle[k][i]; 44 | ``` 45 | 46 | 然后可以看出minpath[k][i]只被用到了一次,所以可以变成一维DP: 47 | 48 | ``` 49 | For the kth level: 50 | minpath[i] = min( minpath[i], minpath[i+1]) + triangle[k][i]; 51 | ``` 52 | 53 | 代码里需要注意的是dp的初始化应该是最下面一层,然后从倒数第二层开始遍历;第layer的元素是layer + 1个。 54 | 55 | 时间复杂度为O(n^2),空间复杂度O(n)。n为三角形高度。 56 | 57 | 代码如下: 58 | 59 | ```python 60 | class Solution(object): 61 | def minimumTotal(self, triangle): 62 | """ 63 | :type triangle: List[List[int]] 64 | :rtype: int 65 | """ 66 | n = len(triangle) 67 | dp = triangle[-1] 68 | for layer in range(n - 2, -1, -1): 69 | for i in range(layer + 1): 70 | dp[i] = min(dp[i], dp[i + 1]) + triangle[layer][i] 71 | return dp[0] 72 | ``` 73 | 74 | 参考资料: 75 | 76 | https://leetcode.com/problems/triangle/discuss/38730/DP-Solution-for-Triangle 77 | 78 | ## 日期 79 | 80 | 2018 年 9 月 27 日 —— 国庆9天长假就要开始了! 81 | -------------------------------------------------------------------------------- /200-299/219. Contains Duplicate II 存在重复元素 II.md: -------------------------------------------------------------------------------- 1 | 2 | 作者: 负雪明烛 3 | id: fuxuemingzhu 4 | 个人博客: http://fuxuemingzhu.cn/ 5 | 6 | --- 7 | @[TOC](目录) 8 | 9 | 题目地址:[https://leetcode.com/problems/contains-duplicate-ii/description/][1] 10 | 11 | 12 | ## 题目描述 13 | 14 | Given an array of integers and an integer k, find out whether there are two distinct indices ``i`` and ``j`` in the array such that ``nums[i] = nums[j]`` and the absolute difference between ``i`` and ``j`` is at most ``k``. 15 | 16 | Example 1: 17 | 18 | Input: nums = [1,2,3,1], k = 3 19 | Output: true 20 | 21 | Example 2: 22 | 23 | Input: nums = [1,0,1,1], k = 1 24 | Output: true 25 | 26 | Example 3: 27 | 28 | Input: nums = [1,2,3,1,2,3], k = 2 29 | Output: false 30 | 31 | ## 题目大意 32 | 33 | 在一个数组中是否存在两个数字相等,并且他们的间距最多为k. 34 | 35 | ## 解题方法 36 | 37 | ### 使用set 38 | 39 | 想法是用一个set来保存已经出现过的数据,然后只用遍历一次数组,把每个数放到set里,因为步长最多是k,所以,如果i超过k就删除最早放到set里的元素。set添加元素的时候,如果已经包含了该元素,那么add方法会返回false. 40 | 41 | ```java 42 | class Solution { 43 | public boolean containsNearbyDuplicate(int[] nums, int k) { 44 | Set set = new HashSet(); 45 | for(int i = 0; i < nums.length; i++){ 46 | if(i > k) set.remove(nums[i - k - 1]); 47 | if(!set.add(nums[i])) return true; 48 | } 49 | return false; 50 | } 51 | } 52 | ``` 53 | 54 | ### 使用字典 55 | 56 | 更通用的方法是使用一个字典,保存每个数字出现的位置,如果在K以内,说明满足要求的,否则就更新这个位置。 57 | 58 | ```python 59 | class Solution(object): 60 | def containsNearbyDuplicate(self, nums, k): 61 | """ 62 | :type nums: List[int] 63 | :type k: int 64 | :rtype: bool 65 | """ 66 | d = dict() 67 | for i, num in enumerate(nums): 68 | if num in d: 69 | if i - d[num] <= k: 70 | return True 71 | d[num] = i 72 | return False 73 | ``` 74 | 75 | 76 | ## 日期 77 | 78 | 2017 年 8 月 18 日 79 | 2018 年 11 月 24 日 —— 周六快乐 80 | 81 | [1]: https://leetcode.com/problems/contains-duplicate-ii/description/ 82 | -------------------------------------------------------------------------------- /1400-1499/1431. Kids With the Greatest Number of Candies 拥有最多糖果的孩子.md: -------------------------------------------------------------------------------- 1 | 2 | 3 | - 作者: 负雪明烛 4 | - id: fuxuemingzhu 5 | - 个人博客:[http://fuxuemingzhu.cn/](http://fuxuemingzhu.cn/) 6 | 7 | --- 8 | @[TOC](目录) 9 | 10 | 11 | 题目地址:https://leetcode-cn.com/problems/kids-with-the-greatest-number-of-candies/ 12 | 13 | # 题目描述 14 | 15 | 给你一个数组 `candies` 和一个整数 `extraCandies` ,其中 `candies[i]` 代表第 `i` 个孩子拥有的糖果数目。 16 | 17 | 对每一个孩子,检查是否存在一种方案,将额外的 `extraCandies` 个糖果分配给孩子们之后,此孩子有 最多 的糖果。注意,允许有多个孩子同时拥有 最多 的糖果数目。 18 | 19 | 示例 1: 20 | 21 | 输入:candies = [2,3,5,1,3], extraCandies = 3 22 | 输出:[true,true,true,false,true] 23 | 解释: 24 | 孩子 1 有 2 个糖果,如果他得到所有额外的糖果(3个),那么他总共有 5 个糖果,他将成为拥有最多糖果的孩子。 25 | 孩子 2 有 3 个糖果,如果他得到至少 2 个额外糖果,那么他将成为拥有最多糖果的孩子。 26 | 孩子 3 有 5 个糖果,他已经是拥有最多糖果的孩子。 27 | 孩子 4 有 1 个糖果,即使他得到所有额外的糖果,他也只有 4 个糖果,无法成为拥有糖果最多的孩子。 28 | 孩子 5 有 3 个糖果,如果他得到至少 2 个额外糖果,那么他将成为拥有最多糖果的孩子。 29 | 30 | 示例 2: 31 | 32 | 输入:candies = [4,2,1,1,2], extraCandies = 1 33 | 输出:[true,false,false,false,false] 34 | 解释:只有 1 个额外糖果,所以不管额外糖果给谁,只有孩子 1 可以成为拥有糖果最多的孩子。 35 | 36 | 示例 3: 37 | 38 | 输入:candies = [12,1,12], extraCandies = 10 39 | 输出:[true,false,true] 40 | 41 | 42 | 提示: 43 | 44 | 1. `2 <= candies.length <= 100` 45 | 1. `1 <= candies[i] <= 100` 46 | 1. `1 <= extraCandies <= 50` 47 | 48 | 49 | # 题目大意 50 | 51 | 如果把剩下的 extraCandies 分给某个孩子,这个孩子能否变为拥有最多糖果的小朋友? 52 | 53 | # 解题方法 54 | 55 | ## 遍历 56 | 57 | 我们按照题目意思,我们要判断这个小朋友变成拥有糖果最多的小朋友,那么应该先知道再没给糖果之前,小朋友拥有的最多糖果数目是多少。 58 | 59 | 把糖果依次给各个小朋友,即让各个小朋友的现有的数目 加上 附加糖果数,是否大于等于最多糖果数目。 60 | 61 | Python 代码如下: 62 | 63 | ```python 64 | class Solution: 65 | def kidsWithCandies(self, candies: List[int], extraCandies: int) -> List[bool]: 66 | max_ = max(candies) 67 | return [extraCandies + candy >= max_ for candy in candies] 68 | ``` 69 | 70 | **欢迎关注[负雪明烛的刷题博客](https://blog.csdn.net/fuxuemingzhu),leetcode刷题800多,每道都讲解了详细写法!** 71 | 72 | # 日期 73 | 74 | 2020 年 5 月 2 日 —— 双周赛最后一题不会,是时候多练练hard题了 75 | 76 | 77 | [1]: https://blog.csdn.net/fuxuemingzhu/article/details/79451733 78 | -------------------------------------------------------------------------------- /300-399/349. Intersection of Two Arrays 两个数组的交集.md: -------------------------------------------------------------------------------- 1 | 2 | 作者: 负雪明烛 3 | id: fuxuemingzhu 4 | 个人博客: http://fuxuemingzhu.cn/ 5 | 6 | --- 7 | @[TOC](目录) 8 | 9 | [LeetCode] 10 | 11 | 题目地址:[https://leetcode.com/problems/intersection-of-two-arrays/][1] 12 | 13 | - Difficulty: Easy 14 | 15 | ## 题目描述 16 | 17 | 18 | Given two arrays, write a function to compute their intersection. 19 | 20 | Example 1: 21 | 22 | Input: nums1 = [1,2,2,1], nums2 = [2,2] 23 | Output: [2] 24 | 25 | Example 2: 26 | 27 | Input: nums1 = [4,9,5], nums2 = [9,4,9,8,4] 28 | Output: [9,4] 29 | 30 | Note: 31 | 32 | 1. Each element in the result must be unique. 33 | 2. The result can be in any order. 34 | 35 | ## 题目大意 36 | 37 | 找出两个数组中共同出现的数字,保证结果中返回的数字是唯一的,返回结果的顺序无所谓。 38 | 39 | ## 解题方法 40 | 41 | ### 方法一:Java解法,HashSet 42 | 43 | 每次都要看解析啊摔!用HashSet去除每个数组的重复元素,统计重复出现的元素即可。java只有元素的个数确定了才能新建数组,所以这里注意一下。 44 | 45 | ```java 46 | public class Solution { 47 | public int[] intersection(int[] nums1, int[] nums2) { 48 | HashSet set1=new HashSet(); 49 | for(int i : nums1){ 50 | set1.add(i); 51 | } 52 | HashSet set2=new HashSet(); 53 | for(int i: nums2){ 54 | if(set1.contains(i)){ 55 | set2.add(i); 56 | } 57 | } 58 | int answer[]=new int[set2.size()]; 59 | int i=0; 60 | for(int n:set2){ 61 | answer[i++]=n; 62 | } 63 | return answer; 64 | } 65 | } 66 | ``` 67 | 68 | AC:8 ms 69 | 70 | ### 方法二:Python解法,set 71 | 72 | 还是python对于这种多种数据结构的题处理来方便。打败96%的提交。 73 | 74 | ```python 75 | class Solution(object): 76 | def intersection(self, nums1, nums2): 77 | """ 78 | :type nums1: List[int] 79 | :type nums2: List[int] 80 | :rtype: List[int] 81 | """ 82 | return list(set(nums1) & set(nums2)) 83 | ``` 84 | 85 | ## 日期 86 | 87 | 2017 年 1 月 8 日 88 | 2018 年 11 月 11 日 —— 剁手节快乐 89 | 90 | [1]: https://leetcode.com/problems/intersection-of-two-arrays/ 91 | -------------------------------------------------------------------------------- /1-99/9. Palindrome Number 回文数.md: -------------------------------------------------------------------------------- 1 | 2 | 作者: 负雪明烛 3 | id: fuxuemingzhu 4 | 个人博客: http://fuxuemingzhu.cn/ 5 | 公众号:负雪明烛 6 | 本文关键词:回文数,回文,题解,Leetcode, 力扣,Python, C++, Java 7 | 8 | --- 9 | @[TOC](目录) 10 | 11 | 题目地址:[https://leetcode.com/problems/palindrome-number/#/description][1] 12 | 13 | 14 | ## 题目描述 15 | 16 | Determine whether an integer is a palindrome. An integer is a palindrome when it reads the same backward as forward. 17 | 18 | Example 1: 19 | 20 | Input: 121 21 | Output: true 22 | 23 | Example 2: 24 | 25 | Input: -121 26 | Output: false 27 | Explanation: From left to right, it reads -121. From right to left, it becomes 121-. Therefore it is not a palindrome. 28 | 29 | Example 3: 30 | 31 | Input: 10 32 | Output: false 33 | Explanation: Reads 01 from right to left. Therefore it is not a palindrome. 34 | 35 | Follow up: 36 | 37 | - Coud you solve it without converting the integer to a string? 38 | 39 | ## 题目大意 40 | 41 | 判断一个数字是不是回文数字。 42 | 43 | ## 解题方法 44 | 45 | ### 判断回文字符串 46 | 47 | 可以先转化成字符串,然后判断这个字符串是不是回文串。 48 | 49 | ```python 50 | class Solution(object): 51 | def isPalindrome(self, x): 52 | """ 53 | :type x: int 54 | :rtype: bool 55 | """ 56 | if x < 0: return False 57 | x = str(x) 58 | N = len(x) 59 | for i in range(N / 2): 60 | if x[i] != x[N - 1 - i]: 61 | return False 62 | return True 63 | ``` 64 | 65 | ### 翻转数字 66 | 67 | 这个题的意思很简单就是判断一个数字是不是回文数,这个和一个字符串是不是回文的方法不一样。可以通过重新构建一个数字,和之前的数字的顺序是反着的,最后看两个数字是不是相等即可。 68 | 69 | 注意,常量空间不算附加空间。 70 | 71 | ```java 72 | public class Solution { 73 | public boolean isPalindrome(int x) { 74 | if (x < 0) return false; 75 | int y = x; 76 | int res = 0; 77 | while(y > 0){ 78 | res = res * 10 + y % 10; 79 | y /= 10; 80 | } 81 | return x == res; 82 | } 83 | } 84 | ``` 85 | 86 | ## 日期 87 | 88 | 2017 年 5 月 7 日 89 | 2018 年 11 月 22 日 —— 感恩节快乐~ 90 | 91 | [1]: https://leetcode.com/problems/arranging-coins/#/description 92 | -------------------------------------------------------------------------------- /700-799/771. Jewels and Stones 宝石与石头.md: -------------------------------------------------------------------------------- 1 | 2 | 作者: 负雪明烛 3 | id: fuxuemingzhu 4 | 个人博客: http://fuxuemingzhu.cn/ 5 | 6 | --- 7 | @[TOC](目录) 8 | 9 | 题目地址:[https://leetcode.com/problems/jewels-and-stones/description/][1] 10 | 11 | 12 | ## 题目描述: 13 | 14 | You're given strings J representing the types of stones that are jewels, and S representing the stones you have. Each character in S is a type of stone you have. You want to know how many of the stones you have are also jewels. 15 | 16 | The letters in J are guaranteed distinct, and all characters in J and S are letters. Letters are case sensitive, so "a" is considered a different type of stone from "A". 17 | 18 | Example 1: 19 | 20 | Input: J = "aA", S = "aAAbbbb" 21 | Output: 3 22 | 23 | Example 2: 24 | 25 | Input: J = "z", S = "ZZ" 26 | Output: 0 27 | 28 | Note: 29 | 30 | 1. S and J will consist of letters and have length at most 50. 31 | 1. The characters in J are distinct. 32 | 33 | ## 题目大意 34 | 35 | J里面的每个字符是个宝石,保证不重复。S中的每个字符是一个石头,有可能出现重复。统计有多少个石头恰好也是宝石。 36 | 37 | ## 解题方法 38 | 39 | ### 数组count 40 | 41 | 因为J里的元素是独一无二的,所以只要数一数S中出现了多少个j就行了。不需要用set(). 42 | 43 | 时间复杂度是O(MN),空间复杂度是O(1)。M是J长度,N是S长度。 44 | 45 | 46 | ```python 47 | class Solution(object): 48 | def numJewelsInStones(self, J, S): 49 | """ 50 | :type J: str 51 | :type S: str 52 | :rtype: int 53 | """ 54 | return sum(S.count(j) for j in J) 55 | ``` 56 | 57 | ### 字典Counter 58 | 59 | 先用Counter保存每个字母出现的次数,然后由于J里面的字符是不重复的,所以直接遍历,然后统计其中的每个字符在S中出现的次数就行了。 60 | 61 | 时间复杂度是O(MN),空间复杂度是O(N)。M是J长度,N是S长度。 62 | 63 | ```python 64 | class Solution: 65 | def numJewelsInStones(self, J, S): 66 | """ 67 | :type J: str 68 | :type S: str 69 | :rtype: int 70 | """ 71 | sCount = collections.Counter(S) 72 | res = 0 73 | for j in J: 74 | res += sCount[j] 75 | return res 76 | ``` 77 | 78 | ## 日期 79 | 80 | 2018 年 1 月 28 日 81 | 2018 年 11 月 2 日 —— 浑浑噩噩的一天 82 | 83 | [1]: https://leetcode.com/problems/jewels-and-stones/description/ 84 | -------------------------------------------------------------------------------- /1-99/99. Recover Binary Search Tree 恢复二叉搜索树.md: -------------------------------------------------------------------------------- 1 | # 【LeetCode】99. Recover Binary Search Tree 解题报告(Python) 2 | 3 | 标签(空格分隔): LeetCode 4 | 5 | --- 6 | 7 | 题目地址:https://leetcode.com/problems/recover-binary-search-tree/description/ 8 | 9 | ## 题目描述: 10 | 11 | Two elements of a binary search tree (BST) are swapped by mistake. 12 | 13 | Recover the tree without changing its structure. 14 | 15 | Note: 16 | A solution using O(n) space is pretty straight forward. Could you devise a constant space solution? 17 | 18 | 19 | ## 题目大意 20 | 21 | 删除二叉树中指定一节点,并调整二叉树,使得结果的二叉树仍然满足BST的条件。 22 | 23 | ## 解题方法 24 | 25 | 同学们,看到BST就想什么?对,中序遍历是有序的。 26 | 27 | 那么,如果其中两个被交换了,那么中序遍历的结果一定也就不对了。比如: 28 | 29 | [1, 2, 3, 4, 5, 6] ==> [1, 5, 3, 4, 2, 6] 30 | 31 | 那么,可以看出5这个数字比后面的3大,说明他被打乱了;另外2这个数字,比前面的数字4小,所以他也被打乱了。 32 | 33 | 所以,可以通过先进行中序遍历得到所有的,然后再查找哪些乱了,再复原,时间复杂度O(n)。 34 | 35 | 但是,中序遍历的操作不需要完全完成。在中序遍历的过程中,用一个指针保存上个节点,那么当前节点值应该小于前一个节点的值。否则就存在乱序。 36 | 37 | 第一个乱序的数字是pre,第二个乱序的数字是root,所以用两个指针分别保存。 38 | 39 | 代码: 40 | 41 | ```python 42 | # Definition for a binary tree node. 43 | # class TreeNode(object): 44 | # def __init__(self, x): 45 | # self.val = x 46 | # self.left = None 47 | # self.right = None 48 | 49 | class Solution(object): 50 | def recoverTree(self, root): 51 | """ 52 | :type root: TreeNode 53 | :rtype: void Do not return anything, modify root in-place instead. 54 | """ 55 | self.pre, self.first, self.second = None, None, None 56 | self.inOrder(root) 57 | self.first.val, self.second.val = self.second.val, self.first.val 58 | 59 | def inOrder(self, root): 60 | if not root: return 61 | self.inOrder(root.left) 62 | if self.pre and self.pre.val > root.val: 63 | if not self.first: 64 | self.first = self.pre 65 | self.second = root 66 | self.pre = root 67 | self.inOrder(root.right) 68 | ``` 69 | 70 | ## 日期 71 | 72 | 2018 年 3 月 23 日 ———— 科目一考了100分哈哈哈哈~嗝~ 73 | 74 | 75 | [1]: http://blog.csdn.net/fuxuemingzhu/article/details/51291406 -------------------------------------------------------------------------------- /600-699/611. Valid Triangle Number 有效三角形的个数.md: -------------------------------------------------------------------------------- 1 | 2 | 作者: 负雪明烛 3 | id: fuxuemingzhu 4 | 个人博客: http://fuxuemingzhu.cn/ 5 | 6 | --- 7 | 8 | 题目地址:https://leetcode.com/problems/valid-triangle-number/description/ 9 | 10 | ## 题目描述: 11 | 12 | Given an array consists of non-negative integers, your task is to count the number of triplets chosen from the array that can make triangles if we take them as side lengths of a triangle. 13 | 14 | Example 1: 15 | 16 | Input: [2,2,3,4] 17 | Output: 3 18 | Explanation: 19 | Valid combinations are: 20 | 2,3,4 (using the first 2) 21 | 2,3,4 (using the second 2) 22 | 2,2,3 23 | 24 | Note: 25 | 26 | 1. The length of the given array won't exceed 1000. 27 | 1. The integers in the given array are in the range of [0, 1000]. 28 | 29 | ## 题目大意 30 | 31 | 给出了一个数组,求在这个数组中能组成多少个三角形。 32 | 33 | ## 解题方法 34 | 35 | 36 | 看了下,这个规模是 1000,那么用 `O(n^3)` 的暴力解法肯定就TLE了。那么只能用更高效的算法。 37 | 38 | 这个方法是这样的,我们先对这个数组进行排序,排序之后我们来指出这个三角形中最长的边,那么剩下两条边的要求是:两边之和大于最长边。 39 | 40 | 所以,我们只需要对最长边进行变遍历,对两个短边再遍历即可。短边的遍历方法是:一个从 0 开始的短边 `l` ,一个从比最长边的短的一个边 `r` 开始向中间遍历。如果能够成三角形,那么说明比l长的短边和r结合也都能组成三角形。如果不能组成三角形,那么说明l太小了,需要向中间移动。 41 | 42 | 排序算法时间复杂度是 `O(nlogn)`,for循环时间复杂度为`O(n)`,while循环虽然有两个变量,但是这两个变量是同时向中间移动的关系,所以时间复杂度不会超过`O(n)`。总体的时间复杂度是`O(n^2)`。空间复杂度是`O(1)`。 43 | 44 | 注意,sorted() 函数不是原地排序,如果原地排序需要使用 nums.sort()。这就是我第一次提交失败的地方。 45 | 46 | 代码如下: 47 | 48 | ```python3 49 | class Solution: 50 | def triangleNumber(self, nums): 51 | """ 52 | :type nums: List[int] 53 | :rtype: int 54 | """ 55 | nums.sort() 56 | count = 0 57 | for i in range(len(nums) - 1, 1, -1): 58 | l, r = 0, i - 1 59 | while l < r: 60 | if nums[l] + nums[r] > nums[i]: 61 | count += r - l 62 | r -= 1 63 | else: 64 | l += 1 65 | return count 66 | ``` 67 | 68 | 69 | 参考资料: 70 | https://leetcode.com/problems/valid-triangle-number/discuss/104174/Java-O(n2)-Time-O(1)-Space 71 | 72 | ## 日期 73 | 74 | 2018 年 9 月 11 日 ———— 天好阴啊 75 | -------------------------------------------------------------------------------- /100-199/186. Reverse Words in a String II 翻转字符串里的单词 II.md: -------------------------------------------------------------------------------- 1 | 2 | 3 | - 作者: 负雪明烛 4 | - id: fuxuemingzhu 5 | - 个人博客:[http://fuxuemingzhu.cn/](http://fuxuemingzhu.cn/) 6 | 7 | --- 8 | @[TOC](目录) 9 | 10 | 题目地址:https://leetcode-cn.com/problems/reverse-words-in-a-string-ii/ 11 | 12 | ## 题目描述 13 | 14 | Given an input string , reverse the string word by word. 15 | 16 | Example: 17 | 18 | Input: ["t","h","e"," ","s","k","y"," ","i","s"," ","b","l","u","e"] 19 | Output: ["b","l","u","e"," ","i","s"," ","s","k","y"," ","t","h","e"] 20 | 21 | Note: 22 | 23 | 1. A word is defined as a sequence of non-space characters. 24 | 1. The input string does not contain leading or trailing spaces. 25 | 1. The words are always separated by a single space. 26 | 27 | Follow up: Could you do it in-place without allocating extra space? 28 | 29 | ## 题目大意 30 | 31 | 给定一个字符串,逐个翻转字符串中的每个单词。 32 | 33 | ## 解题方法 34 | 35 | ### 每个单词单独翻转+总的翻转 36 | 37 | 没记错的话是剑指offer上的题目,做法是用到了一个公式`c b a = (aT bT cT)T`,如果知道这个公式应该很好办了。 38 | 39 | 为什么需要公式而不是直接找到首尾单词互换位置呢?很容易看出每个单词的长度是不同的,互换位置可能会覆盖其他的单词。 40 | 41 | C++代码如下: 42 | 43 | ```cpp 44 | class Solution { 45 | public: 46 | void reverseWords(vector& s) { 47 | if (s.empty()) return; 48 | int pre = 0; 49 | int cur = 0; 50 | while (cur <= s.size()) { 51 | if (cur == s.size() || s[cur] == ' ') { 52 | reverse(s, pre, cur - 1); 53 | pre = cur + 1; 54 | } 55 | cur ++; 56 | } 57 | reverse(s, 0, s.size() - 1); 58 | } 59 | // reverse [start, end] 60 | void reverse(vector& s, int start, int end) { 61 | for (int i = 0; i <= (end - start) / 2; ++i) { 62 | swap(s[start + i], s[end - i]); 63 | } 64 | } 65 | }; 66 | ``` 67 | 68 | ## 日期 69 | 70 | 2019 年 9 月 22 日 —— 熬夜废掉半条命 71 | 72 | 73 | [1]: https://assets.leetcode.com/uploads/2018/10/12/maze_1_example_1.png 74 | [2]: https://assets.leetcode.com/uploads/2018/10/13/maze_1_example_2.png 75 | [3]: https://blog.csdn.net/fuxuemingzhu/article/details/101056461 76 | -------------------------------------------------------------------------------- /1400-1499/1437. Check If All 1's Are at Least Length K Places Away 是否所有 1 都至少相隔 k 个元素.md: -------------------------------------------------------------------------------- 1 | 2 | - 作者: 负雪明烛 3 | - id: fuxuemingzhu 4 | - 个人博客:[http://fuxuemingzhu.cn/](http://fuxuemingzhu.cn/) 5 | 6 | --- 7 | @[TOC](目录) 8 | 9 | 10 | 题目地址:https://leetcode-cn.com/problems/check-if-all-1s-are-at-least-length-k-places-away/ 11 | 12 | 13 | # 题目描述 14 | 15 | 给你一个由若干 `0` 和 `1` 组成的数组 `nums` 以及整数 `k`。如果所有 `1` 都至少相隔 `k` 个元素,则返回 `True` ;否则,返回 `False` 。 16 | 17 | 18 | 示例 1: 19 | 20 | ![此处输入图片的描述][1] 21 | 22 | 输入:nums = [1,0,0,0,1,0,0,1], k = 2 23 | 输出:true 24 | 解释:每个 1 都至少相隔 2 个元素。 25 | 26 | 示例 2: 27 | 28 | ![此处输入图片的描述][2] 29 | 30 | 输入:nums = [1,0,0,1,0,1], k = 2 31 | 输出:false 32 | 解释:第二个 1 和第三个 1 之间只隔了 1 个元素。 33 | 34 | 示例 3: 35 | 36 | 输入:nums = [1,1,1,1,1], k = 0 37 | 输出:true 38 | 39 | 示例 4: 40 | 41 | 输入:nums = [0,1,0,1], k = 1 42 | 输出:true 43 | 44 | 45 | 提示: 46 | 47 | 1. `1 <= nums.length <= 10^5` 48 | 1. `0 <= k <= nums.length` 49 | 1. `nums[i]` 的值为 `0` 或 `1` 50 | 51 | 52 | 53 | # 题目大意 54 | 55 | 判断给出的数组中,是否所有的 1 的间隔都至少为 k. 56 | 57 | # 解题方法 58 | 59 | ## 指针 60 | 61 | 看一眼题目给出的 nums 的长度,我们知道必须用 O(1) 的时间复杂度解决。 62 | 63 | 使用一次遍历,在遍历的过程中,使用 left_1 指针保存当前遍历位置左边的最后一个 1。如果当前遍历的数字也是 1,则判断一下和左边最后一个 1 的距离是否 >= k + 1。 64 | 65 | Python 代码如下: 66 | 67 | ```python 68 | class Solution(object): 69 | def kLengthApart(self, nums, k): 70 | """ 71 | :type nums: List[int] 72 | :type k: int 73 | :rtype: bool 74 | """ 75 | left_1 = float("-inf") 76 | for i, num in enumerate(nums): 77 | if num == 1: 78 | if i - left_1 < k + 1: 79 | return False 80 | left_1 = i 81 | return True 82 | ``` 83 | 84 | **欢迎关注[负雪明烛的刷题博客](https://blog.csdn.net/fuxuemingzhu),leetcode刷题800多,每道都讲解了详细写法!** 85 | 86 | # 日期 87 | 88 | 2020 年 5 月 3 日 —— 天气好热,瞬间入夏 89 | 90 | 91 | [1]: https://assets.leetcode-cn.com/aliyun-lc-upload/uploads/2020/05/03/sample_1_1791.png 92 | [2]: https://assets.leetcode-cn.com/aliyun-lc-upload/uploads/2020/05/03/sample_2_1791.png 93 | -------------------------------------------------------------------------------- /800-899/870. Advantage Shuffle 优势洗牌.md: -------------------------------------------------------------------------------- 1 | # 【LeetCode】870. Advantage Shuffle 解题报告(Python) 2 | 3 | 作者: 负雪明烛 4 | id: fuxuemingzhu 5 | 个人博客: http://fuxuemingzhu.cn/ 6 | 7 | --- 8 | 9 | 题目地址:https://leetcode.com/problems/advantage-shuffle/description/ 10 | 11 | ## 题目描述: 12 | 13 | Given two arrays A and B of equal size, the advantage of A with respect to B is the number of indices i for which A[i] > B[i]. 14 | 15 | Return any permutation of A that maximizes its advantage with respect to B. 16 | 17 | 18 | 19 | Example 1: 20 | 21 | Input: A = [2,7,11,15], B = [1,10,4,11] 22 | Output: [2,11,7,15] 23 | 24 | Example 2: 25 | 26 | Input: A = [12,24,8,32], B = [13,25,32,11] 27 | Output: [24,32,8,12] 28 | 29 | 30 | Note: 31 | 32 | 1. 1 <= A.length = B.length <= 10000 33 | 1. 0 <= A[i] <= 10^9 34 | 1. 0 <= B[i] <= 10^9 35 | 36 | ## 题目大意 37 | 38 | 如何安排A的各个数字,使得对于每个位置A[i]>B[i]的情况最多。 39 | 40 | ## 解题方法 41 | 42 | 中国人小时候学过的一个故事,叫做田忌赛马,大家应该都知道的,用自己比对方强一点点的马去战胜对方的马,如果对方的马太强了,那么就用自己的最弱的马去参加比赛。这样做的好处就是我们用自己的弱鸡消耗掉对方的精锐,自己获胜的概率就最大。 43 | 44 | 使用了双向队列解决这个问题。同样是对A,B进行从小到大的排序,排序时需要保存B中的数字原来在数组中的哪个位置。这样我们对A进行一次遍历,每次出动自己的最弱的马,如果这个马能战胜B中最弱的马,那么就这么使用;如果战胜不了的话,那么就用这个最弱的马去和B中最强的马比赛,这样就干掉了对方的精锐。 45 | 46 | 时间复杂度是O(nlogn),空间复杂度是O(n). 47 | 48 | 代码如下: 49 | 50 | ```python 51 | class Solution(object): 52 | def advantageCount(self, A, B): 53 | """ 54 | :type A: List[int] 55 | :type B: List[int] 56 | :rtype: List[int] 57 | """ 58 | res = [-1] * len(A) 59 | A = collections.deque(sorted(A)) 60 | B = collections.deque(sorted((b, i) for i, b in enumerate(B))) 61 | for i in range(len(A)): 62 | a = A.popleft() 63 | b = B[0] 64 | if a > b[0]: 65 | B.popleft() 66 | else: 67 | b = B.pop() 68 | res[b[1]] = a 69 | return res 70 | ``` 71 | 72 | 参考资料: 73 | 74 | https://leetcode.com/problems/advantage-shuffle/discuss/149932/Python-greedy-sol-with-detailed-comment-Chinese-story:-Tian-Ji's-Horse-race 75 | 76 | ## 日期 77 | 78 | 2018 年 9 月 21 日 —— 转眼这个月又快过去了 79 | -------------------------------------------------------------------------------- /200-299/245. Shortest Word Distance III 最短单词距离 III.md: -------------------------------------------------------------------------------- 1 | 2 | - 作者: 负雪明烛 3 | - id: fuxuemingzhu 4 | - 个人博客:[http://fuxuemingzhu.cn/](http://fuxuemingzhu.cn/) 5 | 6 | --- 7 | @[TOC](目录) 8 | 9 | 题目地址:https://leetcode-cn.com/problems/shortest-word-distance-iii/ 10 | 11 | ## 题目描述 12 | 13 | Given a list of words and two words `word1` and `word2`, return the shortest distance between these two words in the list. 14 | 15 | `word1` and `word2` may be the same and they represent two individual words in the list. 16 | 17 | Example: 18 | 19 | Assume that words = ["practice", "makes", "perfect", "coding", "makes"]. 20 | 21 | Input: word1 = “makes”, word2 = “coding” 22 | Output: 1 23 | Input: word1 = "makes", word2 = "makes" 24 | Output: 3 25 | 26 | Note: 27 | 28 | - You may assume word1 and word2 are both in the list. 29 | 30 | 31 | ## 题目大意 32 | 33 | 给定一个单词列表和两个单词 word1 和 word2,返回列表中这两个单词之间的最短距离。 34 | 35 | word1 和 word2 是有可能相同的,并且它们将分别表示为列表中两个独立的单词。 36 | 37 | ## 解题方法 38 | 39 | ### 字典+暴力检索 40 | 41 | 字典保存每个单词的下标,然后分类讨论: 42 | 43 | 1. 如果两个单词不同,那么直接暴力检索这两个的所有坐标的差值绝对值,找最小的。 44 | 2. 如果两个单词相同,那么相当于从一个有序数组中找到相邻数字的最小差值,需要一次遍历。 45 | 46 | C++代码如下: 47 | 48 | ```cpp 49 | class Solution { 50 | public: 51 | int shortestWordDistance(vector& words, string word1, string word2) { 52 | unordered_map> m; 53 | for (int i = 0; i < words.size(); ++i) { 54 | m[words[i]].push_back(i); 55 | } 56 | int res = INT_MAX; 57 | if (word1 != word2) { 58 | for (int i : m[word1]) { 59 | for (int j : m[word2]) { 60 | res = min(res, abs(i - j)); 61 | } 62 | } 63 | } else { 64 | for (int i = 1; i < m[word1].size(); ++i) { 65 | res = min(res, m[word1][i] - m[word1][i - 1]); 66 | } 67 | } 68 | return res; 69 | } 70 | }; 71 | ``` 72 | 73 | ## 日期 74 | 75 | 2019 年 9 月 24 日 —— 梦见回到了小学,小学已经芳草萋萋破败不堪 76 | 77 | 78 | [1]: https://ss0.bdstatic.com/70cFvHSh_Q1YnxGkpoWK1HF6hhy/it/u=3958884440,3883801982&fm=26&gp=0.jpg 79 | -------------------------------------------------------------------------------- /300-399/357. Count Numbers with Unique Digits 计算各个位数不同的数字个数.md: -------------------------------------------------------------------------------- 1 | 2 | 作者: 负雪明烛 3 | id: fuxuemingzhu 4 | 个人博客: http://fuxuemingzhu.cn/ 5 | 6 | --- 7 | @[TOC](目录) 8 | 9 | --- 10 | 11 | 题目地址:https://leetcode.com/problems/count-numbers-with-unique-digits/description/ 12 | 13 | ## 题目描述 14 | 15 | Given a non-negative integer n, count all numbers with unique digits, x, where 0 ≤ x < 10^n. 16 | 17 | Example: 18 | Given n = 2, return 91. (The answer should be the total numbers in the range of 0 ≤ x < 100, excluding ``[11,22,33,44,55,66,77,88,99]``) 19 | 20 | Credits: 21 | Special thanks to @memoryless for adding this problem and creating all test cases. 22 | 23 | 24 | ## 题目大意 25 | 26 | 给出了一个n,找出n位的10进制数中,有多少个数字是不包含重复数字的。 27 | 28 | ## 解题方法 29 | 30 | 这个题明显不能用暴力解法,想都不用想。 31 | 32 | 还是找规律吧: 33 | 34 | 1. 如果n = 1,那么可以有10个数字不同(0~9) 35 | 2. 如果n >= 2,那么第一位可以是1~9共9个数字,第二位可以是出去第一位的数字+0共9个数字,之后的每位数字都必须不能使用前面已经用过的数字所以依次递减。即9,9,8,7,...,1 36 | 3. n位数字中由不同的数字构成的数字,是比它小的各位数字所能构成的该条件的数字求和。 37 | 38 | 使用循环求解,根据数字的位数,来求这个位数的能够满足条件的个数。ans是小于等于n位的求和。 39 | 40 | 如果看不明白代码,可以这么理解:题目要求的是0 ≤ x < 10^n的x个数,那么x可以为1位数,2位数……n位数。当x为1位数的时候有10个结果;当x为2位数的时候,有9*9个结果;当x为3位数的时候,有9*9*8个结果……也就是说当x为n位数的时候,有9*9*...*(11 - n个结果),其中n必须小于等于10了(11位数字不可能每一位都不相同)。最后求和就好。 41 | 42 | Python代码如下: 43 | 44 | ```python 45 | class Solution(object): 46 | def countNumbersWithUniqueDigits(self, n): 47 | """ 48 | :type n: int 49 | :rtype: int 50 | """ 51 | nums = [9, 9, 8, 7, 6, 5, 4, 3, 2, 1] 52 | ans, product = 1, 1 53 | for i in range(min(n, 10)): 54 | product *= nums[i] 55 | ans += product 56 | return ans 57 | ``` 58 | 59 | C++代码如下: 60 | 61 | ```cpp 62 | class Solution { 63 | public: 64 | int countNumbersWithUniqueDigits(int n) { 65 | int count[]= {9,9,8,7,6,5,4,3,2,1}; 66 | int res = 1, prod = 1; 67 | for (int i = 0; i < min(10, n); i ++) { 68 | prod *= count[i]; 69 | res += prod; 70 | } 71 | return res; 72 | } 73 | }; 74 | ``` 75 | 76 | ## 日期 77 | 78 | 2018 年 6 月 2 日 —— 周末在学习 79 | 2018 年 12 月 20 日 —— 感冒害的我睡不着 80 | -------------------------------------------------------------------------------- /300-399/358. Rearrange String k Distance Apart K 距离间隔重排字符串.md: -------------------------------------------------------------------------------- 1 | 作者: 负雪明烛 2 | id: fuxuemingzhu 3 | 个人博客: http://fuxuemingzhu.cn/ 4 | 5 | --- 6 | 7 | 题目地址: https://leetcode.com/problems/rearrange-string-k-distance-apart 8 | 9 | ## 题目描述: 10 | 11 | Given a non-empty string str and an integer k, rearrange the string such that the same characters are at least distance k from each other. 12 | 13 | All input strings are given in lowercase letters. If it is not possible to rearrange the string, return an empty string ``""``. 14 | 15 | Example 1: 16 | 17 | str = " ", k = 3 18 | 19 | Result: "abcabc" 20 | 21 | The same letters are at least distance 3 from each other. 22 | 23 | Example 2: 24 | 25 | str = "aaabc", k = 3 26 | 27 | Answer: "" 28 | 29 | It is not possible to rearrange the string. 30 | 31 | Example 3: 32 | 33 | str = "aaadbbcc", k = 2 34 | 35 | Answer: "abacabcd" 36 | 37 | Another possible answer is: "abcabcda" 38 | 39 | The same letters are at least distance 2 from each other. 40 | 41 | 42 | ## 题目大意 43 | 44 | 判断给出的字符串能不能构成一个新的排列,在这个排列中,所有的相同字符之间的间距最少是k. 45 | 46 | ## 解题方法 47 | 48 | 使用Counter统计每个字符出现的次数,然后使用大根堆,每次弹出出现次数最多的字符,添加到生成结果字符串的末尾。如果剩余的不同字符个数不够k,那么说明不能满足题目的要求,返回空字符串。另外,每次弹出出现次数最多的字符之后,不能直接放入堆中,因为直接放入堆中可能下次又被弹出来,所以应该放入一个临时的数组中,在单次操作结束之后再重新插入堆中。 49 | 50 | 时间复杂度是O(N),空间复杂度是O(N)。 51 | 52 | ```python 53 | class Solution: 54 | def rearrangeString(self, words, k): 55 | _len = len(words) 56 | words_count = collections.Counter(words) 57 | que = [] 58 | heapq.heapify(que) 59 | for w, v in words_count.items(): 60 | heapq.heappush(que, (-v, w)) 61 | res = "" 62 | while que: 63 | cnt = min(_len, k) 64 | used = [] 65 | for i in range(cnt): 66 | if not que: 67 | return "" 68 | v, w = heapq.heappop(que) 69 | res += w 70 | if -v > 1: 71 | used.append((v + 1, w)) 72 | _len -= 1 73 | for use in used: 74 | heapq.heappush(que, use) 75 | return res 76 | ``` 77 | 78 | 79 | 参考资料: 80 | 81 | http://www.cnblogs.com/grandyang/p/5586009.html 82 | 83 | ## 日期 84 | 85 | 2018 年 10 月 13 日 —— 这个题没有用OJ测试 86 | -------------------------------------------------------------------------------- /600-699/673. Number of Longest Increasing Subsequence 最长递增子序列的个数.md: -------------------------------------------------------------------------------- 1 | # 【LeetCode】673. Number of Longest Increasing Subsequence 解题报告(Python) 2 | 3 | 标签(空格分隔): LeetCode 4 | 5 | --- 6 | 7 | 题目地址:https://leetcode.com/problems/number-of-longest-increasing-subsequence/description/ 8 | 9 | ## 题目描述: 10 | 11 | Given an unsorted array of integers, find the number of longest increasing subsequence. 12 | 13 | Example 1: 14 | Input: [1,3,5,4,7] 15 | Output: 2 16 | Explanation: The two longest increasing subsequence are [1, 3, 4, 7] and [1, 3, 5, 7]. 17 | 18 | Example 2: 19 | Input: [2,2,2,2,2] 20 | Output: 5 21 | Explanation: The length of longest continuous increasing subsequence is 1, and there are 5 subsequences' length is 1, so output 5. 22 | 23 | Note: Length of the given array will be not exceed 2000 and the answer is guaranteed to be fit in 32-bit signed int. 24 | 25 | 26 | ## 题目大意 27 | 28 | 这个题是最长递增子序列的变种。求最长的子序列有多少个。 29 | 30 | ## 解题方法 31 | 32 | 首先肯定还是使用dp去求。不过,我们得对dp的数组进行改进,我们在每个位置记录当前的LIS和能得到该LIS长度的子序列数目。在对每个位置进行计算的时候,我们都要找到该位置的LIS长度,并对能得到该长度的子序列的个数进行求和。 33 | 34 | 最后,我们需要对所有位置等于LIS长度的进行统计。 35 | 36 | 代码: 37 | 38 | ```python 39 | class Solution(object): 40 | def findNumberOfLIS(self, nums): 41 | """ 42 | :type nums: List[int] 43 | :rtype: int 44 | """ 45 | dp, longest = [[1, 1] for _ in range(len(nums))], 1 46 | for i in range(1, len(nums)): 47 | curr_longest, count = 1, 0 48 | for j in range(i): 49 | if nums[j] < nums[i]: 50 | curr_longest = max(curr_longest, dp[j][0] + 1) 51 | for j in range(i): 52 | if dp[j][0] == curr_longest - 1 and nums[j] < nums[i]: 53 | count += dp[j][1] 54 | dp[i] = [curr_longest, max(count, dp[i][1])] 55 | longest = max(longest, curr_longest) 56 | return sum([item[1] for item in dp if item[0] == longest]) 57 | ``` 58 | 59 | ## 日期 60 | 61 | 2018 年 4 月 4 日 ———— 清明时节雪纷纷~~下雪了,惊不惊喜,意不意外? 62 | 63 | 64 | [1]: https://leetcode.com/articles/delete-operation-for-two-strings/ -------------------------------------------------------------------------------- /900-999/915. Partition Array into Disjoint Intervals 分割数组.md: -------------------------------------------------------------------------------- 1 | 作者: 负雪明烛 2 | id: fuxuemingzhu 3 | 个人博客: http://fuxuemingzhu.cn/ 4 | 5 | --- 6 | 7 | 题目地址: https://leetcode.com/problems/partition-array-into-disjoint-intervals/description/ 8 | 9 | ## 题目描述: 10 | 11 | Given an array A, partition it into two (contiguous) subarrays left and right so that: 12 | 13 | 1. Every element in left is less than or equal to every element in right. 14 | 1. left and right are non-empty. 15 | 1. left has the smallest possible size. 16 | 17 | Return the length of left after such a partitioning. It is guaranteed that such a partitioning exists. 18 | 19 | 20 | 21 | Example 1: 22 | 23 | Input: [5,0,3,8,6] 24 | Output: 3 25 | Explanation: left = [5,0,3], right = [8,6] 26 | 27 | Example 2: 28 | 29 | Input: [1,1,1,0,6,12] 30 | Output: 4 31 | Explanation: left = [1,1,1,0], right = [6,12] 32 | 33 | 34 | Note: 35 | 36 | 1. 2 <= A.length <= 30000 37 | 1. 0 <= A[i] <= 10^6 38 | 1. It is guaranteed there is at least one way to partition A as described. 39 | 40 | 41 | ## 题目大意 42 | 43 | 找出数组的一个分界点长度,使得这个分界点左边的元素都小于分界点右边的元素。 44 | 45 | ## 解题方法 46 | 47 | 有的题目就是那么烧脑,我现在还是不太能想通没见过的题目。这个题的范围超级大,所以只能用O(N)的算法。 48 | 49 | 这个题的做法是,我们记录当前已经遍历到的元素最大值和这个元素前面的最大值,如果当前元素比前面已经遇到的最大值更小,说明这个元素一定在左边的划分中(否则前面的最大值会大于这个值),我们的划分要更新到这个元素。 50 | 51 | 这个做法应该还是挺直观的,理解两个值:当前元素前面的最大值(不包括当前值),到目前元素为止所有值的最大值(包括当前值)。 52 | 53 | 最坏情况下的时间复杂度是O(N),空间复杂度是O(1)。 54 | 55 | ```python 56 | class Solution(object): 57 | def partitionDisjoint(self, A): 58 | """ 59 | :type A: List[int] 60 | :rtype: int 61 | """ 62 | disjoint = 0 63 | v = A[0] 64 | max_so_far = v 65 | for i in range(len(A)): 66 | max_so_far = max(max_so_far, A[i]) 67 | if A[i] < v: 68 | v = max_so_far 69 | disjoint = i 70 | return disjoint + 1 71 | ``` 72 | 73 | 参考资料: 74 | 75 | https://leetcode.com/problems/partition-array-into-disjoint-intervals/discuss/175904/Explained-Python-simple-O(N)-time-O(1)-space 76 | 77 | ## 日期 78 | 79 | 2018 年 9 月 30 日 —— 9月最后一天啦! 80 | -------------------------------------------------------------------------------- /200-299/238. Product of Array Except Self 除自身以外数组的乘积.md: -------------------------------------------------------------------------------- 1 | 2 | 作者: 负雪明烛 3 | id: fuxuemingzhu 4 | 个人博客: http://fuxuemingzhu.cn/ 5 | 6 | --- 7 | @[TOC](目录) 8 | 9 | 题目地址:https://leetcode.com/problems/product-of-array-except-self/description/ 10 | 11 | ## 题目描述 12 | 13 | Given an array of n integers where n > 1, nums, return an array output such that output[i] is equal to the product of all the elements of nums except nums[i]. 14 | 15 | Solve it without division and in O(n). 16 | 17 | For example, given [1,2,3,4], return [24,12,8,6]. 18 | 19 | Follow up: 20 | 21 | Could you solve it with constant space complexity? (Note: The output array does not count as extra space for the purpose of space complexity analysis.) 22 | 23 | 24 | 25 | ## 解题方法 26 | 27 | ### 两次遍历 28 | 29 | 当我想了一个用除法做的答案之后就发现题目不允许用除法做233333. 30 | 31 | 这个题巧妙的地方在于,结果数组不算作空间复杂度里,所以可以用在结果数组中遍历的方式去做。第一次遍历在结果数组里保存每个数字左边的数字乘积,第二个遍历保存的是左边乘积和这个数字右边的乘积的乘积。 32 | 33 | 所以就得到了出了本身以外的其他元素的乘积。 34 | 35 | ```python 36 | class Solution(object): 37 | def productExceptSelf(self, nums): 38 | """ 39 | :type nums: List[int] 40 | :rtype: List[int] 41 | """ 42 | answer = [] 43 | _len = len(nums) 44 | prod = 1 45 | for i in range(_len): 46 | answer.append(prod) 47 | prod *= nums[i] 48 | prod = 1 49 | for i in range(_len - 1, -1, -1): 50 | answer[i] *= prod 51 | prod *= nums[i] 52 | return answer 53 | ``` 54 | 55 | C++代码如下: 56 | 57 | ```cpp 58 | class Solution { 59 | public: 60 | vector productExceptSelf(vector& nums) { 61 | const int N = nums.size(); 62 | vector res(N, 1); 63 | int prod = 1; 64 | for (int i = 0; i < N; i ++) { 65 | res[i] = prod; 66 | prod *= nums[i]; 67 | } 68 | prod = 1; 69 | for (int i = N - 1; i >= 0; i--) { 70 | res[i] *= prod; 71 | prod *= nums[i]; 72 | } 73 | return res; 74 | } 75 | }; 76 | ``` 77 | 78 | ## 日期 79 | 80 | 2018 年 2 月 14 日 81 | 2018 年 12 月 14 日 —— 12月过半,2019就要开始 82 | 83 | -------------------------------------------------------------------------------- /900-999/944. Delete Columns to Make Sorted 删列造序.md: -------------------------------------------------------------------------------- 1 | 2 | 作者: 负雪明烛 3 | id: fuxuemingzhu 4 | 个人博客: http://fuxuemingzhu.cn/ 5 | 6 | --- 7 | @[TOC](目录) 8 | 9 | 10 | 题目地址:https://leetcode.com/problems/delete-columns-to-make-sorted/description/ 11 | 12 | 13 | ## 题目描述 14 | 15 | We are given an array ``A`` of ``N`` lowercase letter strings, all of the same length. 16 | 17 | Now, we may choose any set of deletion indices, and for each string, we delete all the characters in those indices. 18 | 19 | For example, if we have a string ``"abcdef"`` and deletion indices ``{0, 2, 3}``, then the final string after deletion is "bef". 20 | 21 | Suppose we chose a set of deletion indices D such that after deletions, each remaining column in A is in non-decreasing sorted order. 22 | 23 | Formally, the ``c``-th column is ``[A[0][c], A[1][c], ..., A[A.length-1][c]]`` 24 | 25 | Return the minimum possible value of ``D.length``. 26 | 27 | 28 | 29 | Example 1: 30 | 31 | Input: ["cba","daf","ghi"] 32 | Output: 1 33 | 34 | Example 2: 35 | 36 | Input: ["a","b"] 37 | Output: 0 38 | 39 | Example 3: 40 | 41 | Input: ["zyx","wvu","tsr"] 42 | Output: 3 43 | 44 | 45 | Note: 46 | 47 | 1. ``1 <= A.length <= 100`` 48 | 1. ``1 <= A[i].length <= 1000`` 49 | 50 | ## 题目大意 51 | 52 | 有一个数组A,其中它的每个元素都是等长度的字符串。现在求最短的要删除的切片的长度,使得做完操作之后,数组中剩下的相同列是递增的。 53 | 54 | ## 解题方法 55 | 56 | 又是乍一看很难的题目,其实很简单的,直接暴力解决就好了。 57 | 58 | 主要是思路:如果一个列的元素已经是递增的,那么我们一定不能把这个列删除掉。如果删除掉某一列,那么其他的列将不受到任何影响。 59 | 60 | 所以,基于上面两个原则,我们可以直接对所有的列进行遍历,也就是说取得所有的列,然后判断这个列是不是递增的,如果不是递增的话,就删除掉。统计要删除掉多少个列即可。而判断某个列是不是递增的最简单方法就是排序之后,然后看是不是和之前的相等。 61 | 62 | 时间复杂度是O(N*(MlogM)),空间复杂度是O(M)。N是每个字符串长度,M是数组长度。还好给的区间很小,直接能过的。 63 | 64 | 65 | ```python 66 | class Solution: 67 | def minDeletionSize(self, A): 68 | """ 69 | :type A: List[str] 70 | :rtype: int 71 | """ 72 | res = 0 73 | N = len(A[0]) 74 | for i in range(N): 75 | col = [a[i] for a in A] 76 | if col != sorted(col): 77 | res += 1 78 | return res 79 | ``` 80 | 81 | ## 日期 82 | 83 | 2018 年 11 月 18 日 —— 出去玩了一天,腿都要废了 84 | -------------------------------------------------------------------------------- /100-199/165. Compare Version Numbers 比较版本号.md: -------------------------------------------------------------------------------- 1 | # 【LeetCode】165. Compare Version Numbers 解题报告(Python) 2 | 3 | 标签(空格分隔): LeetCode 4 | 5 | 作者: 负雪明烛 6 | id: fuxuemingzhu 7 | 个人博客: http://fuxuemingzhu.me/ 8 | 9 | --- 10 | 11 | 题目地址:https://leetcode.com/problems/compare-version-numbers/description/ 12 | 13 | ## 题目描述: 14 | 15 | Compare two version numbers version1 and version2. 16 | If ``version1 > version2`` return ``1``; if ``version1 < version2`` return ``-1``;otherwise return ``0``. 17 | 18 | You may assume that the version strings are non-empty and contain only digits and the . character. 19 | The . character does not represent a decimal point and is used to separate number sequences. 20 | For instance, 2.5 is not "two and a half" or "half way to version three", it is the fifth second-level revision of the second first-level revision. 21 | 22 | Example 1: 23 | 24 | Input: version1 = "0.1", version2 = "1.1" 25 | Output: -1 26 | 27 | Example 2: 28 | 29 | Input: version1 = "1.0.1", version2 = "1" 30 | Output: 1 31 | 32 | Example 3: 33 | 34 | Input: version1 = "7.5.2.4", version2 = "7.5.3" 35 | Output: -1 36 | 37 | ## 题目大意 38 | 39 | 比较两个版本号的大小。 40 | 41 | ## 解题方法 42 | 43 | 版本是用.进行分割的,那么我们也只能通过用.进行分割来判定版本号的大小。把版本号进行分割,需要找出一个较长的版本号的长度,把较短的版本的后面用0进行补齐。恩,然后进行比较。 44 | 45 | ```python 46 | class Solution(object): 47 | def compareVersion(self, version1, version2): 48 | """ 49 | :type version1: str 50 | :type version2: str 51 | :rtype: int 52 | """ 53 | v1_split = version1.split('.') 54 | v2_split = version2.split('.') 55 | v1_len, v2_len = len(v1_split), len(v2_split) 56 | maxLen = max(v1_len, v2_len) 57 | for i in range(maxLen): 58 | temp1, temp2 = 0, 0 59 | if i < v1_len: 60 | temp1 = int(v1_split[i]) 61 | if i < v2_len: 62 | temp2 = int(v2_split[i]) 63 | if temp1 < temp2: 64 | return -1 65 | elif temp1 > temp2: 66 | return 1 67 | return 0 68 | ``` 69 | 70 | ## 日期 71 | 72 | 2018 年 6 月 26 日 ———— 早睡早起 -------------------------------------------------------------------------------- /500-599/518. Coin Change 2 零钱兑换 II.md: -------------------------------------------------------------------------------- 1 | # 【LeetCode】518. Coin Change 2 解题报告(Python) 2 | 3 | 作者: 负雪明烛 4 | id: fuxuemingzhu 5 | 个人博客: http://fuxuemingzhu.cn/ 6 | 7 | --- 8 | 9 | 题目地址:https://leetcode.com/problems/coin-change-2/description/ 10 | 11 | ## 题目描述: 12 | 13 | You are given coins of different denominations and a total amount of money. Write a function to compute the number of combinations that make up that amount. You may assume that you have infinite number of each kind of coin. 14 | 15 | Note: You can assume that 16 | 17 | 1. 0 <= amount <= 5000 18 | 1. 1 <= coin <= 5000 19 | 1. the number of coins is less than 500 20 | 1. the answer is guaranteed to fit into signed 32-bit integer 21 | 22 | 23 | Example 1: 24 | 25 | Input: amount = 5, coins = [1, 2, 5] 26 | Output: 4 27 | Explanation: there are four ways to make up the amount: 28 | 5=5 29 | 5=2+2+1 30 | 5=2+1+1+1 31 | 5=1+1+1+1+1 32 | 33 | 34 | Example 2: 35 | 36 | Input: amount = 3, coins = [2] 37 | Output: 0 38 | Explanation: the amount of 3 cannot be made up just with coins of 2. 39 | 40 | 41 | Example 3: 42 | 43 | Input: amount = 10, coins = [10] 44 | Output: 1 45 | 46 | ## 题目大意 47 | 48 | 有一堆一定面额的硬币,问有多少种可以组成amount的方案。假定硬币的数量是不限量的。 49 | 50 | ## 解题方法 51 | 52 | DP。第一感觉是完全背包问题,但其实由于没有重量和价值的对应关系,所以不一样。 53 | 54 | 生成了一个一维数组dp,dp[i]代表了生成总价值为i有多少方案。 55 | 56 | 对已有的所有面值的硬币进行遍历,其实思路很简单:dp[i] += dp[i - coin],价值为i的解决方案应该加上价值为i - coin的解决方案。 57 | 58 | 时间复杂度是O(L * A),空间复杂度是O(A); A = amount. 59 | 60 | 代码如下: 61 | 62 | ```python 63 | class Solution(object): 64 | def change(self, amount, coins): 65 | """ 66 | :type amount: int 67 | :type coins: List[int] 68 | :rtype: int 69 | """ 70 | dp = [0] * (amount + 1) 71 | dp[0] = 1 72 | for coin in coins: 73 | for i in range(1, amount + 1): 74 | if coin <= i: 75 | dp[i] += dp[i - coin] 76 | return dp[amount] 77 | ``` 78 | 79 | 参考资料: 80 | 81 | https://www.youtube.com/watch?v=jaNZ83Q3QGc 82 | 83 | ## 日期 84 | 85 | 2018 年 9 月 25 日 —— 美好的一周又开始了,划重点,今天是周二 86 | -------------------------------------------------------------------------------- /1100-1199/1151. Minimum Swaps to Group All 1's Together 最少交换次数来组合所有的 1.md: -------------------------------------------------------------------------------- 1 | - 作者: 负雪明烛 2 | - id: fuxuemingzhu 3 | - 个人博客:[http://fuxuemingzhu.cn/](http://fuxuemingzhu.cn/) 4 | 5 | --- 6 | @[TOC](目录) 7 | 8 | 题目地址:https://leetcode-cn.com/problems/minimum-swaps-to-group-all-1s-together/ 9 | 10 | ## 题目描述 11 | 12 | Given a binary array data, return the **minimum** number of swaps required to group all 1’s present in the array together in any place in the array. 13 | 14 | Example 1: 15 | 16 | Input: [1,0,1,0,1] 17 | Output: 1 18 | Explanation: 19 | There are 3 ways to group all 1's together: 20 | [1,1,1,0,0] using 1 swap. 21 | [0,1,1,1,0] using 2 swaps. 22 | [0,0,1,1,1] using 1 swap. 23 | The minimum is 1. 24 | 25 | Example 2: 26 | 27 | Input: [0,0,0,1,0] 28 | Output: 0 29 | Explanation: 30 | Since there is only one 1 in the array, no swaps needed. 31 | 32 | Example 3: 33 | 34 | Input: [1,0,1,0,1,0,0,1,1,0,1] 35 | Output: 3 36 | Explanation: 37 | One possible solution that uses 3 swaps is [0,0,0,0,0,1,1,1,1,1,1]. 38 | 39 | Note: 40 | 41 | 1 <= data.length <= 10^5 42 | 0 <= data[i] <= 1 43 | 44 | ## 题目大意 45 | 46 | 给出一个二进制数组 data,你需要通过交换位置,将数组中 任何位置 上的 1 组合到一起,并返回所有可能中所需 最少的交换次数。 47 | 48 | ## 解题方法 49 | 50 | ### 滑动窗口 51 | 52 | 1. 首先统计总的有N个1 53 | 2. 设置大小为N的滑动窗口,统计该滑动窗口中的1的个数最大值是K 54 | 3. 需要交换N - K次使得该滑动窗口内的0变成1 55 | 56 | C++代码如下: 57 | 58 | ```cpp 59 | class Solution { 60 | public: 61 | int minSwaps(vector& data) { 62 | int N = accumulate(data.begin(), data.end(), 0); 63 | int left = -N; 64 | int right = 0; 65 | int one_counts = 0; 66 | int K = 0; 67 | while (right < data.size()) { 68 | if (data[right] == 1) { 69 | one_counts ++; 70 | } 71 | if (left >= 0 && data[left] == 1) { 72 | one_counts --; 73 | } 74 | K = max(K, one_counts); 75 | left ++; 76 | right ++; 77 | } 78 | return N - K; 79 | } 80 | }; 81 | ``` 82 | 83 | ## 日期 84 | 85 | 2019 年 9 月 23 日 —— 昨夜睡的早,错过了北京的烟火 86 | -------------------------------------------------------------------------------- /1-99/16. 3Sum Closest 最接近的三数之和.md: -------------------------------------------------------------------------------- 1 | 2 | - 作者: 负雪明烛 3 | - id: fuxuemingzhu 4 | - 个人博客:[http://fuxuemingzhu.cn/](http://fuxuemingzhu.cn/) 5 | - 个人公众号:负雪明烛 6 | - 本文关键词:3sum, three sum, 三数之和,题解,leetcode, 力扣,Python, C++, Java 7 | 8 | --- 9 | 10 | 题目地址: https://leetcode.com/problems/3sum-closest/description/ 11 | 12 | ## 题目描述: 13 | 14 | Given an array ``nums`` of n integers and an integer ``target``, find three integers in ``nums`` such that the sum is closest to ``target``. Return the sum of the three integers. You may assume that each input would have exactly one solution. 15 | 16 | Example: 17 | 18 | Given array nums = [-1, 2, 1, -4], and target = 1. 19 | 20 | The sum that is closest to the target is 2. (-1 + 2 + 1 = 2). 21 | 22 | ## 题目大意 23 | 24 | 在给定的数组中判断是否存在三个数的和是0,返回所有的组合,但是返回的组合中不能有重复。 25 | 26 | ## 解题方法 27 | 28 | ### 方法:原数组排序+双指针 29 | 30 | 这个题和[15. 3Sum][1]基本一样,而且这个题更简单一点。 31 | 32 | 想要得到三个数字的和,要求这个和尽可能的靠近target,那么同样需要先排序,然后使用一个指针遍历,另外两个指针分别指向下一个元素和最后一个元素然后向中间靠拢的方式。在靠拢的过程中如果当前的和与target的差距比要返回的结果与target更小,那么更新要返回的结果。 33 | 34 | 指针的移动策略是如果和比目标值大,说明我们需要把这个和调小一点;如果和比目标小,那么需要把和调大一点。如果相等那么就返回结果。 35 | 36 | 时间复杂度是O(N^2),空间复杂度是O(1)。 37 | 38 | ```python 39 | class Solution(object): 40 | def threeSumClosest(self, nums, target): 41 | """ 42 | :type nums: List[int] 43 | :type target: int 44 | :rtype: int 45 | """ 46 | N = len(nums) 47 | nums.sort() 48 | res = float('inf') # sum of 3 number 49 | for t in range(N): 50 | i, j = t + 1, N - 1 51 | while i < j: 52 | _sum = nums[t] + nums[i] + nums[j] 53 | if abs(_sum - target) < abs(res - target): 54 | res = _sum 55 | if _sum > target: 56 | j -= 1 57 | elif _sum < target: 58 | i += 1 59 | else: 60 | return target 61 | return res 62 | ``` 63 | 64 | 65 | 66 | 参考资料: 67 | 68 | 69 | ## 日期 70 | 71 | 2018 年 10 月 17 日 —— 今又重阳,战地黄花分外香 72 | 73 | 74 | [1]: https://blog.csdn.net/fuxuemingzhu/article/details/83115850 75 | -------------------------------------------------------------------------------- /500-599/521. Longest Uncommon Subsequence I 最长特殊序列 Ⅰ.md: -------------------------------------------------------------------------------- 1 | 2 | 作者: 负雪明烛 3 | id: fuxuemingzhu 4 | 个人博客: http://fuxuemingzhu.cn/ 5 | 6 | --- 7 | @[TOC](目录) 8 | 9 | 题目地址:https://leetcode.com/problems/longest-uncommon-subsequence-i/description/ 10 | 11 | 12 | ## 题目描述 13 | 14 | Given a group of two strings, you need to find the longest uncommon subsequence of this group of two strings. The longest uncommon subsequence is defined as the longest subsequence of one of these strings and this subsequence should not be any subsequence of the other strings. 15 | 16 | A subsequence is a sequence that can be derived from one sequence by deleting some characters without changing the order of the remaining elements. Trivially, any string is a subsequence of itself and an empty string is a subsequence of any string. 17 | 18 | The input will be two strings, and the output needs to be the length of the longest uncommon subsequence. If the longest uncommon subsequence doesn't exist, return -1. 19 | 20 | Example 1: 21 | Input: "aba", "cdc" 22 | Output: 3 23 | Explanation: The longest uncommon subsequence is "aba" (or "cdc"), 24 | because "aba" is a subsequence of "aba", 25 | but not a subsequence of any other strings in the group of two strings. 26 | 27 | Note: 28 | 29 | 1. Both strings' lengths will not exceed 100. 30 | 1. Only letters from a ~ z will appear in input strings. 31 | 32 | ## 题目大意 33 | 34 | 题意很重要啊!这个题目有点长,看了几遍没看太懂,所以一直没做。 35 | 36 | 给定一组两个的字符串,您需要找到这组两个字符串中最长的不常见的子序列。 最长的不常见的子序列被定义为这些字符串之一的最长子序列,并且该子序列不应该是其他字符串的任何子序列。 37 | 子序列是可以通过删除一些字符而不改变剩余元素的顺序从一个序列导出的序列。 简而言之,任何字符串本身都是一个子序列,空字符串是任何字符串的子序列。 38 | 输入将是两个字符串,输出需要是最长的不常见子序列的长度。 如果最长不常见的子序列不存在,则返回-1。 39 | 40 | ## 解题方法 41 | 42 | 题意简而言之就是求两个字符串的最长不常见子序列的长度。如果两个字符串相等,那么不存在!如果不等,长度最长的那个字符串就是最长不常见子序列。 43 | 44 | 脑筋急转弯的题目!怪不得大家对这个题踩了那么多。 45 | 46 | ```python 47 | class Solution(object): 48 | def findLUSlength(self, a, b): 49 | """ 50 | :type a: str 51 | :type b: str 52 | :rtype: int 53 | """ 54 | return max(len(a), len(b)) if a != b else -1 55 | ``` 56 | 57 | ## 日期 58 | 59 | 2018 年 2 月 28 日 60 | 2018 年 11 月 9 日 —— 睡眠可以 61 | -------------------------------------------------------------------------------- /600-699/645. Set Mismatch 错误的集合.md: -------------------------------------------------------------------------------- 1 | 2 | 作者: 负雪明烛 3 | id: fuxuemingzhu 4 | 个人博客: http://fuxuemingzhu.cn/ 5 | 6 | --- 7 | @[TOC](目录) 8 | 题目地址:[https://leetcode.com/problems/set-mismatch/description/][1] 9 | 10 | 11 | ## 题目描述 12 | 13 | The set ``S`` originally contains numbers from ``1 to n``. But unfortunately, due to the data error, one of the numbers in the set got duplicated to another number in the set, which results in repetition of one number and loss of another number. 14 | 15 | Given an array ``nums`` representing the data status of this set after the error. Your task is to firstly find the number occurs twice and then find the number that is missing. Return them in the form of an array. 16 | 17 | Example 1: 18 | 19 | Input: nums = [1,2,2,4] 20 | Output: [2,3] 21 | 22 | Note: 23 | 24 | - The given array size will in the range [2, 10000]. 25 | - The given array's numbers won't have any order. 26 | 27 | ## 题目大意 28 | 29 | 数组正常的状态是1~N,但是有个数字重复出现了,导致覆盖了另外一个数字,现在要求重复出现的数字,和缺失的数字。 30 | 31 | ## 解题方法 32 | 33 | ### Hash方法 34 | 35 | 这个题明显使用hash的思想。把每个位置出现的次数统计一下,找出出现了2次和0次的数字的位置即可。 36 | 37 | ```python 38 | class Solution(object): 39 | def findErrorNums(self, nums): 40 | """ 41 | :type nums: List[int] 42 | :rtype: List[int] 43 | """ 44 | hashs = [0] * len(nums) 45 | missing = -1 46 | for i in range(len(nums)): 47 | hashs[nums[i] - 1] += 1 48 | return [hashs.index(2) + 1, hashs.index(0) + 1] 49 | ``` 50 | 51 | ### 直接计算 52 | 53 | 和[268. Missing Number](https://blog.csdn.net/fuxuemingzhu/article/details/70332471)很像,直接计算出来也可以,速度稍快点。 54 | 55 | ```python 56 | class Solution(object): 57 | def findErrorNums(self, nums): 58 | """ 59 | :type nums: List[int] 60 | :rtype: List[int] 61 | """ 62 | N = len(nums) 63 | nset = set(nums) 64 | missing = N * (N + 1) / 2 - sum(nset) 65 | duplicated = sum(nums) - sum(nset) 66 | return [duplicated, missing] 67 | ``` 68 | 69 | ## 日期 70 | 71 | 2018 年 2 月 3 日 72 | 2018 年 11 月 21 日 —— 又是一个美好的开始 73 | 74 | [1]: https://leetcode.com/problems/set-mismatch/description/ 75 | -------------------------------------------------------------------------------- /500-599/581. Shortest Unsorted Continuous Subarray 最短无序连续子数组.md: -------------------------------------------------------------------------------- 1 | 2 | 作者: 负雪明烛 3 | id: fuxuemingzhu 4 | 个人博客: http://fuxuemingzhu.cn/ 5 | 6 | --- 7 | @[TOC](目录) 8 | 9 | 题目地址:https://leetcode.com/problems/shortest-unsorted-continuous-subarray/description/ 10 | 11 | 12 | ## 题目描述 13 | 14 | Given an integer array, you need to find one continuous subarray that if you only sort this subarray in ascending order, then the whole array will be sorted in ascending order, too. 15 | 16 | You need to find the shortest such subarray and output its length. 17 | 18 | Example 1: 19 | 20 | Input: [2, 6, 4, 8, 10, 9, 15] 21 | Output: 5 22 | Explanation: You need to sort [6, 4, 8, 10, 9] in ascending order to make the whole array sorted in ascending order. 23 | 24 | Note: 25 | 26 | 1. Then length of the input array is in range [1, 10,000]. 27 | 1. The input array may contain duplicates, so ascending order here means <=. 28 | 29 | ## 解题方法 30 | 31 | ### 方法一:排序比较 32 | 33 | 这个题竟然真的是排序之后,然后和原来的数组进行比较得到的。 34 | 35 | 因为题目中的数组的长度最大只有1000,所以排序的时间不算很高。排序后的数组和之前的数组进行比较,找出最小的不相等的数字位置和最大不相等的数字的位置,两者的差相减+1即为所求。 36 | 37 | ```python 38 | class Solution(object): 39 | def findUnsortedSubarray(self, nums): 40 | """ 41 | :type nums: List[int] 42 | :rtype: int 43 | """ 44 | _len, _nums = len(nums), sorted(nums) 45 | if nums == _nums: 46 | return 0 47 | l = min([i for i in range(_len) if nums[i] != _nums[i]]) 48 | r = max([i for i in range(_len) if nums[i] != _nums[i]]) 49 | return r - l + 1 50 | ``` 51 | 52 | 二刷用到C++,代码如下: 53 | 54 | ```cpp 55 | class Solution { 56 | public: 57 | int findUnsortedSubarray(vector& nums) { 58 | const int N = nums.size(); 59 | auto t = nums; 60 | sort(t.begin(), t.end()); 61 | int l = N, r = 0; 62 | for (int i = 0; i < N; ++i) { 63 | if (t[i] != nums[i]) { 64 | l = min(l, i); 65 | r = max(r, i); 66 | } 67 | } 68 | return r >= l ? r - l + 1 : 0; 69 | } 70 | }; 71 | ``` 72 | 73 | ## 日期 74 | 75 | 2018 年 2 月 4 日 76 | 2018 年 11 月 27 日 —— 最近的雾霾太可怕 77 | -------------------------------------------------------------------------------- /1400-1499/1409. Queries on a Permutation With Key 查询带键的排列.md: -------------------------------------------------------------------------------- 1 | - 作者: 负雪明烛 2 | - id: fuxuemingzhu 3 | - 个人博客:[http://fuxuemingzhu.cn/](http://fuxuemingzhu.cn/) 4 | 5 | --- 6 | @[TOC](目录) 7 | 8 | 9 | 题目地址:https://leetcode-cn.com/problems/string-matching-in-an-array/ 10 | 11 | # 题目描述 12 | 13 | 给你一个待查数组 `queries` ,数组中的元素为 1 到 m 之间的正整数。 请你根据以下规则处理所有待查项 `queries[i]`(从 i=0 到 `i=queries.length-1`): 14 | 15 | 一开始,排列 `P=[1,2,3,...,m]`。 16 | 对于当前的 i ,请你找出待查项 `queries[i]` 在排列 P 中的位置(下标从 0 开始),然后将其从原位置移动到排列 P 的起始位置(即下标为 0 处)。注意, queries[i] 在 P 中的位置就是 `queries[i]` 的查询结果。 17 | 请你以数组形式返回待查数组 `queries` 的查询结果。 18 | 19 | 20 | 21 | 示例 1: 22 | 23 | 输入:queries = [3,1,2,1], m = 5 24 | 输出:[2,1,2,1] 25 | 解释:待查数组 queries 处理如下: 26 | 对于 i=0: queries[i]=3, P=[1,2,3,4,5], 3 在 P 中的位置是 2,接着我们把 3 移动到 P 的起始位置,得到 P=[3,1,2,4,5] 。 27 | 对于 i=1: queries[i]=1, P=[3,1,2,4,5], 1 在 P 中的位置是 1,接着我们把 1 移动到 P 的起始位置,得到 P=[1,3,2,4,5] 。 28 | 对于 i=2: queries[i]=2, P=[1,3,2,4,5], 2 在 P 中的位置是 2,接着我们把 2 移动到 P 的起始位置,得到 P=[2,1,3,4,5] 。 29 | 对于 i=3: queries[i]=1, P=[2,1,3,4,5], 1 在 P 中的位置是 1,接着我们把 1 移动到 P 的起始位置,得到 P=[1,2,3,4,5] 。 30 | 因此,返回的结果数组为 [2,1,2,1] 。 31 | 32 | 示例 2: 33 | 34 | 输入:queries = [4,1,2,2], m = 4 35 | 输出:[3,1,2,0] 36 | 37 | 示例 3: 38 | 39 | 输入:queries = [7,5,5,8,3], m = 8 40 | 输出:[6,5,0,7,5] 41 | 42 | 43 | 提示: 44 | 45 | 1. `1 <= m <= 10^3` 46 | 1. `1 <= queries.length <= m` 47 | 1. `1 <= queries[i] <= m` 48 | 49 | # 题目大意 50 | 51 | 给出了一段查询串,并且查到谁就把谁放在前面,问每次命中的位置是什么。 52 | 53 | # 解题方法 54 | 55 | ## 模拟 56 | 57 | 数据的规模并不大,可以直接进行模拟。 58 | 59 | Python代码如下: 60 | 61 | ```python 62 | class Solution: 63 | def processQueries(self, queries: List[int], m: int) -> List[int]: 64 | P = list(range(1, m + 1)) 65 | res = [] 66 | for q in queries: 67 | idx = P.index(q) 68 | P = [q] + P[:idx] + P[idx+1:] 69 | res.append(idx) 70 | return res 71 | ``` 72 | 73 | 74 | **欢迎关注[负雪明烛的刷题博客](https://blog.csdn.net/fuxuemingzhu),leetcode刷题800多,每道都讲解了详细写法!** 75 | 76 | # 日期 77 | 78 | 2020 年 4 月 12 日 —— dp问题还是不太会 79 | 80 | 81 | [1]: https://blog.csdn.net/fuxuemingzhu/article/details/79451733 82 | -------------------------------------------------------------------------------- /1400-1499/1410. HTML Entity Parser HTML 实体解析器.md: -------------------------------------------------------------------------------- 1 | - 作者: 负雪明烛 2 | - id: fuxuemingzhu 3 | - 个人博客:[http://fuxuemingzhu.cn/](http://fuxuemingzhu.cn/) 4 | 5 | --- 6 | @[TOC](目录) 7 | 8 | 9 | 题目地址:https://leetcode-cn.com/problems/html-entity-parser/ 10 | 11 | # 题目描述 12 | 13 | 「HTML 实体解析器」 是一种特殊的解析器,它将 HTML 代码作为输入,并用字符本身替换掉所有这些特殊的字符实体。 14 | 15 | HTML 里这些特殊字符和它们对应的字符实体包括: 16 | 17 | - 双引号:字符实体为 `"`; ,对应的字符是 " 。 18 | - 单引号:字符实体为 `&apos`; ,对应的字符是 ' 。 19 | - 与符号:字符实体为 `&`; ,对应对的字符是 & 。 20 | - 大于号:字符实体为 `>`; ,对应的字符是 > 。 21 | - 小于号:字符实体为 `<`; ,对应的字符是 < 。 22 | - 斜线号:字符实体为 `&frasl`; ,对应的字符是 / 。 23 | 24 | 给你输入字符串 text ,请你实现一个 HTML 实体解析器,返回解析器解析后的结果。 25 | 26 | 示例 1: 27 | 28 | 输入:text = "& is an HTML entity but &ambassador; is not." 29 | 输出:"& is an HTML entity but &ambassador; is not." 30 | 解释:解析器把字符实体 & 用 & 替换 31 | 32 | 示例 2: 33 | 34 | 输入:text = "and I quote: "..."" 35 | 输出:"and I quote: \"...\"" 36 | 37 | 示例 3: 38 | 39 | 输入:text = "Stay home! Practice on Leetcode :)" 40 | 输出:"Stay home! Practice on Leetcode :)" 41 | 42 | 示例 4: 43 | 44 | 输入:text = "x > y && x < y is always false" 45 | 输出:"x > y && x < y is always false" 46 | 47 | 示例 5: 48 | 49 | 输入:text = "leetcode.com⁄problemset⁄all" 50 | 输出:"leetcode.com/problemset/all" 51 | 52 | 53 | 提示: 54 | 55 | 1. `1 <= text.length <= 10^5` 56 | 1. 字符串可能包含 256 个ASCII 字符中的任意字符。 57 | 58 | # 题目大意 59 | 60 | 把给出的文本中的字符进行替换。 61 | 62 | # 解题方法 63 | 64 | ## 替换 65 | 66 | 直接按照题目要求进行替换。 67 | 68 | Python代码如下: 69 | 70 | ```python 71 | class Solution: 72 | def entityParser(self, text: str) -> str: 73 | d = {""": '"', 74 | "'": "'", 75 | "&": "&", 76 | ">": ">", 77 | "<": "<", 78 | "⁄": "/"} 79 | for k, v in d.items(): 80 | text = text.replace(k, v) 81 | return text 82 | ``` 83 | 84 | 85 | **欢迎关注[负雪明烛的刷题博客](https://blog.csdn.net/fuxuemingzhu),leetcode刷题800多,每道都讲解了详细写法!** 86 | 87 | # 日期 88 | 89 | 2020 年 4 月 12 日 —— dp问题还是不太会 90 | 91 | 92 | [1]: https://blog.csdn.net/fuxuemingzhu/article/details/79451733 93 | -------------------------------------------------------------------------------- /500-599/598. Range Addition II 范围求和 II.md: -------------------------------------------------------------------------------- 1 | 2 | 作者: 负雪明烛 3 | id: fuxuemingzhu 4 | 个人博客: http://fuxuemingzhu.cn/ 5 | 6 | --- 7 | @[TOC](目录) 8 | 9 | 题目地址:https://leetcode.com/problems/range-addition-ii/description/ 10 | 11 | 12 | ## 题目描述 13 | 14 | Given an ``m * n`` matrix M initialized with all 0's and several update operations. 15 | 16 | Operations are represented by a 2D array, and each operation is represented by an array with two positive integers a and b, which means ``M[i][j]`` should be added by one for all ``0 <= i < a`` and ``0 <= j < b``. 17 | 18 | You need to count and return the number of maximum integers in the matrix after performing all the operations. 19 | 20 | Example 1: 21 | Input: 22 | m = 3, n = 3 23 | operations = [[2,2],[3,3]] 24 | Output: 4 25 | Explanation: 26 | Initially, M = 27 | [[0, 0, 0], 28 | [0, 0, 0], 29 | [0, 0, 0]] 30 | 31 | After performing [2,2], M = 32 | [[1, 1, 0], 33 | [1, 1, 0], 34 | [0, 0, 0]] 35 | 36 | After performing [3,3], M = 37 | [[2, 2, 1], 38 | [2, 2, 1], 39 | [1, 1, 1]] 40 | 41 | So the maximum integer in M is 2, and there are four of it in M. So return 4. 42 | 43 | Note: 44 | 45 | 1. The range of m and n is [1,40000]. 46 | 1. The range of a is [1,m], and the range of b is [1,n]. 47 | 1. The range of operations size won't exceed 10,000. 48 | 49 | 50 | ## 题目大意 51 | 52 | 对于一个初始全部为零的二维数组,经过一串操作后,找出数组中最大的数字出现的``次数``。操作是指,把二维数组中小于(m,n)左上角的元素都 + 1. 53 | 54 | ## 解题方法 55 | 56 | 首先要明白,要求的结果是最终二维数组中最大值出现的``次数``。那么,被重复加的最多的数组元素一定最大,其出现次数就是答案。 57 | 58 | 每次操作都是对左上角部分区域进行操作的,并且,a,b的范围都是大于1的,即每次都会有元素改变。那么,最终二维数组中最大值出现的次数一定是操作中最小范围中的那批元素构成的矩形区域面积。 59 | 60 | 如果没有进行操作,那么,返回的应该是全部0的个数。 61 | 62 | ```python 63 | class Solution(object): 64 | def maxCount(self, m, n, ops): 65 | """ 66 | :type m: int 67 | :type n: int 68 | :type ops: List[List[int]] 69 | :rtype: int 70 | """ 71 | if not ops: 72 | return m * n 73 | return min([op[0] for op in ops]) * min([op[1] for op in ops]) 74 | ``` 75 | 76 | ## 日期 77 | 78 | 2018 年 2 月 28 日 79 | 2018 年 11 月 15 日 —— 时间太快,不忍直视 80 | -------------------------------------------------------------------------------- /1400-1499/1436. Destination City 旅行终点站.md: -------------------------------------------------------------------------------- 1 | - 作者: 负雪明烛 2 | - id: fuxuemingzhu 3 | - 个人博客:[http://fuxuemingzhu.cn/](http://fuxuemingzhu.cn/) 4 | 5 | --- 6 | @[TOC](目录) 7 | 8 | 9 | 题目地址:https://leetcode-cn.com/problems/destination-city/ 10 | 11 | # 题目描述 12 | 给你一份旅游线路图,该线路图中的旅行线路用数组 `paths` 表示,其中 `paths[i] = [cityAi, cityBi]` 表示该线路将会从 `cityAi` 直接前往 `cityBi` 。请你找出这次旅行的终点站,即没有任何可以通往其他城市的线路的城市。 13 | 14 | 题目数据保证线路图会形成一条不存在循环的线路,因此只会有一个旅行终点站。 15 | 16 | 17 | 示例 1: 18 | 19 | 输入:paths = [["London","New York"],["New York","Lima"],["Lima","Sao Paulo"]] 20 | 输出:"Sao Paulo" 21 | 解释:从 "London" 出发,最后抵达终点站 "Sao Paulo" 。本次旅行的路线是 "London" -> "New York" -> "Lima" -> "Sao Paulo" 。 22 | 23 | 示例 2: 24 | 25 | 输入:paths = [["B","C"],["D","B"],["C","A"]] 26 | 输出:"A" 27 | 解释:所有可能的线路是: 28 | "D" -> "B" -> "C" -> "A". 29 | "B" -> "C" -> "A". 30 | "C" -> "A". 31 | "A". 32 | 显然,旅行终点站是 "A" 。 33 | 34 | 示例 3: 35 | 36 | 输入:paths = [["A","Z"]] 37 | 输出:"Z" 38 | 39 | 40 | 提示: 41 | 42 | 1. `1 <= paths.length <= 100` 43 | 1. `paths[i].length == 2` 44 | 1. `1 <= cityAi.length, cityBi.length <= 10` 45 | 1. `cityAi != cityBi` 46 | 1. 所有字符串均由大小写英文字母和空格字符组成。 47 | 48 | 49 | # 题目大意 50 | 给出的是一个有向无环图,找出旅行的终点站。 51 | 52 | # 解题方法 53 | 54 | ## set 55 | 56 | 第一个感觉是 拓扑排序,但这个是周赛的 Easy 题,应该很简单。 57 | 58 | 注意题目给出的条件:**只会有一个旅行终点站。** 59 | 60 | 所以,我们找出 哪个站 没有**出度**就行了。说人话:只有一个站不会出现在出发点上。 61 | 62 | 所以,对所有的站进行统计,如果一个站没有出现在出发点上,那这个站就是最终的旅行终点站。 63 | 64 | Python 代码如下: 65 | 66 | ```python 67 | class Solution(object): 68 | def destCity(self, paths): 69 | """ 70 | :type paths: List[List[str]] 71 | :rtype: str 72 | """ 73 | starts = set() 74 | ends = set() 75 | for path in paths: 76 | starts.add(path[0]) 77 | ends.add(path[1]) 78 | for end in ends: 79 | if end not in starts: 80 | return end 81 | return "" 82 | ``` 83 | 84 | **欢迎关注[负雪明烛的刷题博客](https://blog.csdn.net/fuxuemingzhu),leetcode刷题800多,每道都讲解了详细写法!** 85 | 86 | # 日期 87 | 88 | 2020 年 5 月 3 日 —— 天气好热,瞬间入夏 89 | 90 | 91 | [1]: https://blog.csdn.net/fuxuemingzhu/article/details/79451733 92 | -------------------------------------------------------------------------------- /600-699/657. Robot Return to Origin 机器人能否返回原点.md: -------------------------------------------------------------------------------- 1 | # 【LeetCode】657. Judge Route Circle 2 | 3 | 标签(空格分隔): LeetCode 4 | 5 | --- 6 | 7 | 题目地址:[https://leetcode.com/problems/judge-route-circle/description/][1] 8 | 9 | 10 | ## 题目描述: 11 | 12 | Initially, there is a Robot at position (0, 0). Given a sequence of its moves, judge if this robot makes a circle, which means it moves back to the original place. 13 | 14 | The move sequence is represented by a string. And each move is represent by a character. The valid robot moves are R (Right), L (Left), U (Up) and D (down). The output should be true or false representing whether the robot makes a circle. 15 | 16 | Example 1: 17 | Input: "UD" 18 | Output: true 19 | Example 2: 20 | Input: "LL" 21 | Output: false 22 | 23 | ## Ways 24 | 25 | python里面表达坐标比较简单,直接用列表就可以。 26 | 27 | 这个题就是判断移动了几次之后是否在原来的位置,只要每步都去修改一次即可。 28 | 29 | 方法一,O(n): 30 | ```python 31 | class Solution: 32 | def judgeCircle(self, moves): 33 | """ 34 | :type moves: str 35 | :rtype: bool 36 | """ 37 | position = [0, 0] 38 | for move in moves: 39 | if move == 'R': 40 | position[0] += 1 41 | if move == 'L': 42 | position[0] -= 1 43 | if move == 'U': 44 | position[1] += 1 45 | if move == 'D': 46 | position[1] -= 1 47 | return position == [0, 0] 48 | ``` 49 | 50 | 方法二,数左右移动的次数和上下移动的次数是否相等: 51 | ```python 52 | class Solution: 53 | def judgeCircle(self, moves): 54 | """ 55 | :type moves: str 56 | :rtype: bool 57 | """ 58 | return moves.count('L') == moves.count('R') and moves.count('U') == moves.count('D') 59 | ``` 60 | 61 | 方法三,看了Discuss才知道,python原来也可以用复数! 62 | ```python 63 | class Solution: 64 | def judgeCircle(self, moves): 65 | """ 66 | :type moves: str 67 | :rtype: bool 68 | """ 69 | directs = {'L':-1, 'R':1, 'U':1j, 'D':-1j} 70 | return 0 == sum(directs[move] for move in moves) 71 | ``` 72 | 73 | ## Date 74 | 75 | 2018 年 1 月 13 日 76 | 77 | 78 | [1]: https://leetcode.com/problems/judge-route-circle/description/ -------------------------------------------------------------------------------- /900-999/984. String Without AAA or BBB 不含 AAA 或 BBB 的字符串.md: -------------------------------------------------------------------------------- 1 | 2 | 作者: 负雪明烛 3 | id: fuxuemingzhu 4 | 个人博客: http://fuxuemingzhu.cn/ 5 | 6 | --- 7 | @[TOC](目录) 8 | 9 | 10 | 题目地址:https://leetcode.com/problems/string-without-aaa-or-bbb/ 11 | 12 | 13 | ## 题目描述 14 | 15 | Given two integers A and B, return any string S such that: 16 | 17 | - S has length A + B and contains exactly A 'a' letters, and exactly B 'b' letters; 18 | - The substring 'aaa' does not occur in S; 19 | - The substring 'bbb' does not occur in S. 20 | 21 | 22 | Example 1: 23 | 24 | Input: A = 1, B = 2 25 | Output: "abb" 26 | Explanation: "abb", "bab" and "bba" are all correct answers. 27 | 28 | Example 2: 29 | 30 | Input: A = 4, B = 1 31 | Output: "aabaa" 32 | 33 | 34 | Note: 35 | 36 | 1. 0 <= A <= 100 37 | 1. 0 <= B <= 100 38 | 1. It is guaranteed such an S exists for the given A and B. 39 | 40 | 41 | ## 题目大意 42 | 43 | 构造出来一个字符串,要求出现A个a和B个b,同时要求不能出现连续三个的a或者b. 44 | 45 | 46 | ## 解题方法 47 | 48 | ### 字符串构造 49 | 50 | 有不少人第一题就扑街了……我虽然一遍过了,但是也花了不少时间。 51 | 52 | 首先为了简化判断我做了一个设定就是A>B,如果不满足这个条件,就把A和B进行翻转,这里需要注意的是如果翻转A和B,那么需要把A和B对应的'a'和'b'也翻转。这步之后就能保证了A代表的字符是出现多的字符,B代表的是出现次数少的字符。 53 | 54 | 那么如何构造呢?我想了一个比较巧妙的方法:先构造出成对出现的'a','b',然后把剩余的字符进行插空。 55 | 56 | 具体的说,我们保证了构造出的ab是'ab',当A>B;ab是'ba',当B>A.即出现次数多的字符在前面。然后我们统计一下剩余的字符还有多少个,很显然是A - B个。然后把剩余的A-B个a插入到ab中间,会构成了aabaab...abab的样子。如果还有剩余的ab对放到后面即可。 57 | 58 | 这个思路的好处在于,我们优先构造出ab对,在插空的时候不会产生连续aaa或者bbb,而且剩余的一定是abab的形式,因为题目已经保证了可以构造出来,所以不会出现A>>B导致不能构造。 59 | 60 | 61 | ```python 62 | class Solution(object): 63 | def strWithout3a3b(self, A, B): 64 | """ 65 | :type A: int 66 | :type B: int 67 | :rtype: str 68 | """ 69 | _len = A + B 70 | # to make A > B 71 | a, b = ('a', 'b') if A > B else ('b', 'a') 72 | A, B = (A, B) if A > B else (B, A) 73 | ab = [a + b] * B 74 | A -= B 75 | res = [] 76 | while A: 77 | res.append(a) 78 | if ab: 79 | res.append(ab.pop()) 80 | A -= 1 81 | res += ab 82 | return "".join(res) 83 | ``` 84 | 85 | 86 | ## 日期 87 | 88 | 2019 年 1 月 27 日 —— 这个周赛不太爽 89 | -------------------------------------------------------------------------------- /1-99/28. Implement strStr() 实现 strStr().md: -------------------------------------------------------------------------------- 1 | 2 | 作者: 负雪明烛 3 | id: fuxuemingzhu 4 | 个人博客: http://fuxuemingzhu.cn/ 5 | 6 | --- 7 | @[TOC](目录) 8 | 9 | 题目地址:https://leetcode.com/problems/implement-strstr/description/ 10 | 11 | 12 | ## 题目描述 13 | 14 | Implement strStr(). 15 | 16 | Return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack. 17 | 18 | Example 1: 19 | 20 | Input: haystack = "hello", needle = "ll" 21 | Output: 2 22 | 23 | Example 2: 24 | 25 | Input: haystack = "aaaaa", needle = "bba" 26 | Output: -1 27 | 28 | ## 题目大意 29 | 30 | 实现在haystack中找出needle第一次出现的位置,如果不存在,那么就返回-1. 31 | 32 | ## 解题方法 33 | 34 | ### find函数 35 | 36 | 找出一个长串中小串的位置。这样太简单了。。 37 | 38 | Python中,find()函数就是实现这个功能,如果找不到子串的话,返回-1. 39 | 40 | 另外,index()会在找不到的时候报错,这是两个函数的区别。 41 | 42 | ```python 43 | class Solution(object): 44 | def strStr(self, haystack, needle): 45 | """ 46 | :type haystack: str 47 | :type needle: str 48 | :rtype: int 49 | """ 50 | return haystack.find(needle) 51 | ``` 52 | 53 | ### 遍历+切片 54 | 55 | 这个题这么考就没意思了,自己实现了一下find函数。这里有个需要注意的点,i的变动范围是[0,M-N]闭区间, 56 | 57 | 时间复杂度是O(M),空间复杂度是O(1)。超过96%. 58 | 59 | ```python3 60 | class Solution: 61 | def strStr(self, haystack, needle): 62 | """ 63 | :type haystack: str 64 | :type needle: str 65 | :rtype: int 66 | """ 67 | M, N = len(haystack), len(needle) 68 | for i in range(M - N + 1): 69 | if haystack[i : i + N] == needle: 70 | return i 71 | return -1 72 | ``` 73 | 74 | C++写法: 75 | 76 | 要注意的是string的substr方法第一个参数是起始位置,第二个参数是切片长度。 77 | 78 | ```cpp 79 | class Solution { 80 | public: 81 | int strStr(string haystack, string needle) { 82 | int M = haystack.size(); 83 | int N = needle.size(); 84 | for (int i = 0; i < M - N + 1; i ++){ 85 | if (haystack.substr(i, N) == needle){ 86 | return i; 87 | } 88 | } 89 | return -1; 90 | } 91 | }; 92 | ``` 93 | 94 | ## 日期 95 | 96 | 2018 年 2 月 4 日 97 | 2018 年 11 月 3 日 —— 雾霾的周六 98 | 2018 年 11 月 26 日 —— 11月最后一周! 99 | -------------------------------------------------------------------------------- /400-499/458. Poor Pigs 可怜的小猪.md: -------------------------------------------------------------------------------- 1 | 2 | 作者: 负雪明烛 3 | id: fuxuemingzhu 4 | 个人博客: http://fuxuemingzhu.cn/ 5 | 6 | --- 7 | @[TOC](目录) 8 | 9 | 题目地址:https://leetcode.com/problems/poor-pigs/description/ 10 | 11 | ## 题目描述 12 | 13 | There are 1000 buckets, one and only one of them contains poison, the rest are filled with water. They all look the same. If a pig drinks that poison it will die within 15 minutes. What is the minimum amount of pigs you need to figure out which bucket contains the poison within one hour. 14 | 15 | Answer this question, and write an algorithm for the follow-up general case. 16 | 17 | **Follow-up:** 18 | 19 | If there are n buckets and a pig drinking poison will die within m minutes, how many pigs (x) you need to figure out the "poison" bucket within p minutes? There is exact one bucket with poison. 20 | 21 | ## 题目大意 22 | 23 | 有1000个桶,其中有一个桶里有毒药,其他的都是正常的。一头猪喝了毒药之后,过了15分钟会上天。只给了60分钟,问至少需要多少头猪来找出有毒的桶? 24 | 25 | 下面给了一个Follow-up,是桶数(n),上天时间为m,在p分钟内检测出来,求猪数x。 26 | 27 | ## 解题方法 28 | 29 | 这个题让我想起来本科的时候的微机原理,那个时候有题目是拨号键盘。通过监测拨号键盘行和列有哪些有电平,来检测出按下了哪个键。 30 | 31 | 一只猪在一个小时内最多验多少桶呢?这个猪可以喝4桶水,如果有毒就会死亡,否则说明这4桶没问题。如果只有5桶水,那么第5桶一定有问题。 32 | 33 | 两只猪呢?那就是拨号键盘了,每15分钟喝一个行或者列的所有5桶水,根据两只猪死亡时间,按照拨号键盘的思路,知道了毒水在几行几列。也就是两头猪最多验出来25个桶。 34 | 35 | 1 2 3 4 5 36 | 37 | 6 7 8 9 10 38 | 39 | 11 12 13 14 15 40 | 41 | 16 17 18 19 20 42 | 43 | 21 22 23 24 25 44 | 45 | 46 | 更多的猪,不难看出,就是一个多维的空间了,当有N只的时候,求出5^N>=1000,就能得出了N。 47 | 48 | 49 | 代码如下: 50 | 51 | ```python 52 | class Solution(object): 53 | def poorPigs(self, buckets, minutesToDie, minutesToTest): 54 | """ 55 | :type buckets: int 56 | :type minutesToDie: int 57 | :type minutesToTest: int 58 | :rtype: int 59 | """ 60 | tests = minutesToTest / minutesToDie + 1 61 | pigs = 0 62 | while tests ** pigs < buckets: 63 | pigs += 1 64 | return pigs 65 | ``` 66 | 67 | 参考资料:https://blog.csdn.net/wilschan0201/article/details/72519147 68 | 69 | ## 日期 70 | 71 | 2018 年 7 月 17 日 —— 连天大雨,这种情况很少见,但是很舒服 72 | 2018 年 11 月 19 日 —— 周一又开始了 73 | 74 | [1]: http://www.cnblogs.com/grandyang/p/7500082.html 75 | -------------------------------------------------------------------------------- /400-499/452. Minimum Number of Arrows to Burst Balloons 用最少数量的箭引爆气球.md: -------------------------------------------------------------------------------- 1 | # 【LeetCode】452. Minimum Number of Arrows to Burst Balloons 解题报告(Python) 2 | 3 | 标签(空格分隔): LeetCode 4 | 5 | --- 6 | 7 | 题目地址:https://leetcode.com/problems/minimum-number-of-arrows-to-burst-balloons/description/ 8 | 9 | ## 题目描述: 10 | 11 | There are a number of spherical balloons spread in two-dimensional space. For each balloon, provided input is the start and end coordinates of the horizontal diameter. Since it's horizontal, y-coordinates don't matter and hence the x-coordinates of start and end of the diameter suffice. Start is always smaller than end. There will be at most 104 balloons. 12 | 13 | An arrow can be shot up exactly vertically from different points along the x-axis. A balloon with xstart and xend bursts by an arrow shot at x if xstart ≤ x ≤ xend. There is no limit to the number of arrows that can be shot. An arrow once shot keeps travelling up infinitely. The problem is to find the minimum number of arrows that must be shot to burst all balloons. 14 | 15 | Example: 16 | 17 | Input: 18 | [[10,16], [2,8], [1,6], [7,12]] 19 | 20 | Output: 21 | 2 22 | 23 | Explanation: 24 | One way is to shoot one arrow for example at x = 6 (bursting the balloons [2,8] and [1,6]) and another arrow at x = 11 (bursting the other two balloons). 25 | 26 | 27 | ## 题目大意 28 | 29 | 给出了一组气球的起始和结束的坐标,现在用箭去沿着y轴方向射。最少需要多少个箭才能把所有的气球打破? 30 | 31 | ## 解题方法 32 | 33 | 这个题是贪心算法的题目,看到这种问区间重叠情况的,一般都能想到是贪心。我们把所有的区间按照右边界进行排序,因为每个气球都要被打破,因此排序得到的第一组数据我们一定要使用。可以想到,只要沿着该数据最右边界的位置进行射箭一定能打破尽可能多的气球。然后依次移动射箭的位置,进行统计即可。 34 | 35 | ```python 36 | class Solution(object): 37 | def findMinArrowShots(self, points): 38 | """ 39 | :type points: List[List[int]] 40 | :rtype: int 41 | """ 42 | if not points: return 0 43 | points.sort(key = lambda x : x[1]) 44 | curr_pos = points[0][1] 45 | ans = 1 46 | for i in range(len(points)): 47 | if curr_pos >= points[i][0]: 48 | continue 49 | curr_pos = points[i][1] 50 | ans += 1 51 | return ans 52 | ``` 53 | 54 | ## 日期 55 | 56 | 2018 年 4 月 10 日 ———— 风很大,很舒服~~ -------------------------------------------------------------------------------- /1000-1099/1018. Binary Prefix Divisible By 5 可被 5 整除的二进制前缀.md: -------------------------------------------------------------------------------- 1 | 作者: 负雪明烛 2 | id: fuxuemingzhu 3 | 个人博客: http://fuxuemingzhu.cn/ 4 | 5 | --- 6 | @[TOC](目录) 7 | 8 | 9 | 题目地址:https://leetcode.com/problems/binary-prefix-divisible-by-5/ 10 | 11 | ## 题目描述 12 | 13 | Given an array ``A`` of ``0``s and ``1``s, consider ``N_i``: the ``i-th`` subarray from ```A[0]`` to ``A[i]`` interpreted as a binary number (from most-significant-bit to least-significant-bit.) 14 | 15 | Return a list of booleans ``answer``, where ``answer[i]`` is true if and only if N_i is divisible by 5. 16 | 17 | Example 1: 18 | 19 | Input: [0,1,1] 20 | Output: [true,false,false] 21 | Explanation: 22 | The input numbers in binary are 0, 01, 011; which are 0, 1, and 3 in base-10. Only the first number is divisible by 5, so answer[0] is true. 23 | 24 | Example 2: 25 | 26 | Input: [1,1,1] 27 | Output: [false,false,false] 28 | 29 | Example 3: 30 | 31 | Input: [0,1,1,1,1,1] 32 | Output: [true,false,false,false,true,false] 33 | 34 | Example 4: 35 | 36 | Input: [1,1,1,0,1] 37 | Output: [false,false,false,false,false] 38 | 39 | 40 | Note: 41 | 42 | 1. ``1 <= A.length <= 30000`` 43 | 1. ``A[i] is 0 or 1`` 44 | 45 | 46 | ## 题目大意 47 | 48 | 给出一个数组,判断数组的每个位置构成的前缀能不能被5整除。 49 | 50 | ## 解题方法 51 | 52 | 这个题肯定不能蛮力求解,最简单的方法就是利用求余的性质。我们每次只用保存前缀对5的余数,在求下一个位置的时候把``上一次的前缀×2 + 当前的数字``再模5. 53 | 54 | 求余的性质: 55 | 56 | ((a +b)mod p × c) mod p = ((a × c) mod p + (b × c) mod p) mod p 57 | (a×b) mod c=((a mod c) * (b mod c)) mod c 58 | (a+b) mod c=((a mod c)+ (b mod c)) mod c 59 | (a-b) mod c=((a mod c)- (b mod c)) mod c 60 | 61 | 所以,a扩大x倍之后模一个数字,等于((a % 5) * (x % 5)) % 5. 62 | 63 | Python代码如下: 64 | 65 | ```python 66 | class Solution(object): 67 | def prefixesDivBy5(self, A): 68 | """ 69 | :type A: List[int] 70 | :rtype: List[bool] 71 | """ 72 | res = [] 73 | prefix = 0 74 | for a in A: 75 | prefix = (prefix * 2 + a) % 5 76 | res.append(prefix == 0) 77 | return res 78 | ``` 79 | 80 | ## 日期 81 | 82 | 2019 年 4 月 5 日 —— 清明节休息一下~ 83 | 84 | 85 | [1]: https://blog.csdn.net/fuxuemingzhu/article/details/82716042 86 | -------------------------------------------------------------------------------- /1000-1099/1065. Index Pairs of a String 字符串的索引对.md: -------------------------------------------------------------------------------- 1 | 2 | - 作者: 负雪明烛 3 | - id: fuxuemingzhu 4 | - 个人博客:[http://fuxuemingzhu.cn/](http://fuxuemingzhu.cn/) 5 | 6 | --- 7 | @[TOC](目录) 8 | 9 | 10 | 题目地址:https://leetcode-cn.com/problems/index-pairs-of-a-string/ 11 | 12 | ## 题目描述 13 | 14 | Given a text string and words (a list of strings), return all index pairs `[i, j]` so that the substring `text[i]...text[j]` is in the list of words. 15 | 16 | Example 1: 17 | 18 | Input: text = "thestoryofleetcodeandme", words = ["story","fleet","leetcode"] 19 | Output: [[3,7],[9,13],[10,17]] 20 | 21 | Example 2: 22 | 23 | Input: text = "ababa", words = ["aba","ab"] 24 | Output: [[0,1],[0,2],[2,3],[2,4]] 25 | Explanation: 26 | Notice that matches can overlap, see "aba" is found in [0,2] and [2,4]. 27 | 28 | Note: 29 | 30 | 1. All strings contains only lowercase English letters. 31 | 1. It's guaranteed that all strings in words are different. 32 | 1. `1 <= text.length <= 100` 33 | 1. `1 <= words.length <= 20` 34 | 1. `1 <= words[i].length <= 50` 35 | Return the pairs [i,j] in sorted order (i.e. sort them by their first coordinate in case of ties sort them by their second coordinate). 36 | 37 | ## 题目大意 38 | 39 | 给出 字符串 `text` 和 字符串列表 `words`, 返回所有的索引对 `[i, j]` 使得在索引对范围内的子字符串 `text[i]...text[j]`(包括 i 和 j)属于字符串列表 words。 40 | 41 | 42 | ## 解题方法 43 | 44 | ### 遍历 45 | 46 | 暴力遍历所有的字符串子串,看其是否在words中。为了加速查找效率,使用的set。 47 | 48 | C++代码如下: 49 | 50 | ```cpp 51 | class Solution { 52 | public: 53 | vector> indexPairs(string text, vector& words) { 54 | unordered_set wordset(words.begin(), words.end()); 55 | const int N = text.size(); 56 | vector> res; 57 | for (int i = 0; i < N; ++i) { 58 | for (int j = i; j < N; ++j) { 59 | string cur = text.substr(i, j - i + 1); 60 | if (wordset.count(cur)) { 61 | res.push_back({i, j}); 62 | } 63 | } 64 | } 65 | return res; 66 | } 67 | }; 68 | ``` 69 | 70 | ## 日期 71 | 72 | 2019 年 9 月 18 日 —— 今日又是九一八 73 | 74 | 75 | [1]: https://blog.csdn.net/fuxuemingzhu/article/details/100977773 76 | -------------------------------------------------------------------------------- /1700-1799/1768. Merge Strings Alternately 交替合并字符串.md: -------------------------------------------------------------------------------- 1 | 2 | - 作者: 负雪明烛 3 | - id: fuxuemingzhu 4 | - 公众号:负雪明烛 5 | - 本文关键词:LeetCode,力扣,算法,算法题,交替合并字符串,Merge Strings Alternately,刷题群 6 | 7 | --- 8 | @[TOC](目录) 9 | 10 | 11 | 题目地址:https://leetcode-cn.com/problems/merge-strings-alternately/ 12 | 13 | # 题目描述 14 | 15 | 16 | 给你两个字符串 `word1` 和 `word2` 。请你从 `word1` 开始,通过交替添加字母来合并字符串。如果一个字符串比另一个字符串长,就将多出来的字母追加到合并后字符串的末尾。 17 | 18 | 返回 合并后的字符串 。 19 | 20 | 21 | 22 | 示例 1: 23 | 24 | 输入:word1 = "abc", word2 = "pqr" 25 | 输出:"apbqcr" 26 | 解释:字符串合并情况如下所示: 27 | word1: a b c 28 | word2: p q r 29 | 合并后: a p b q c r 30 | 31 | 示例 2: 32 | 33 | 输入:word1 = "ab", word2 = "pqrs" 34 | 输出:"apbqrs" 35 | 解释:注意,word2 比 word1 长,"rs" 需要追加到合并后字符串的末尾。 36 | word1: a b 37 | word2: p q r s 38 | 合并后: a p b q r s 39 | 40 | 示例 3: 41 | 42 | 输入:word1 = "abcd", word2 = "pq" 43 | 输出:"apbqcd" 44 | 解释:注意,word1 比 word2 长,"cd" 需要追加到合并后字符串的末尾。 45 | word1: a b c d 46 | word2: p q 47 | 合并后: a p b q c d 48 | 49 | 50 | 提示: 51 | 52 | 1. `1 <= word1.length, word2.length <= 100` 53 | 1. `word1` 和 `word2` 由小写英文字母组成 54 | 55 | 56 | # 解题思路 57 | 58 | 59 | ## 合并 60 | 61 | 交替合并两个字符串,也就是每次分别从 `word1` 和 `word2` 获取一个字符。当一个字符串用完了之后,while 循环停止,然后把另外一个字符串的剩余部分,也补充到结果中。 62 | 63 | 时间复杂度:$O(M + N)$。 64 | 65 | ```python 66 | class Solution: 67 | def mergeAlternately(self, word1: str, word2: str) -> str: 68 | cur1 = 0 69 | cur2 = 0 70 | res = "" 71 | while cur1 < len(word1) and cur2 < len(word2): 72 | res += word1[cur1] + word2[cur2] 73 | cur1 += 1 74 | cur2 += 1 75 | if cur1 != len(word1): 76 | res += word1[cur1:] 77 | if cur2 != len(word2): 78 | res += word2[cur2:] 79 | return res 80 | ``` 81 | 82 | 83 | 84 | # 欢迎加入组织 85 | 86 | 算法每日一题是个互相帮助、互相监督的力扣打卡网站,其地址是 [https://www.ojeveryday.com/](https://www.ojeveryday.com/) 87 | 88 | 想加入千人刷题群的朋友,可以复制上面的链接到浏览器,然后在左侧点击“加入组织”,提交力扣个人主页,即可进入刷题群。期待你早日加入。 89 | 90 | **欢迎关注我的公众号:负雪明烛** 91 | 92 | ![在这里插入图片描述](https://img-blog.csdnimg.cn/20210129111056950.jpg#pic_center) 93 | 94 | 95 | # 日期 96 | 97 | 2021 年 2 月 21 日 —— 好久不打周赛了,发现手已经非常生。 98 | -------------------------------------------------------------------------------- /1000-1099/1008. Construct Binary Search Tree from Preorder Traversal 前序遍历构造二叉搜索树.md: -------------------------------------------------------------------------------- 1 | 2 | 作者: 负雪明烛 3 | id: fuxuemingzhu 4 | 个人博客: http://fuxuemingzhu.cn/ 5 | 6 | --- 7 | @[TOC](目录) 8 | 9 | 10 | 题目地址:https://leetcode.com/problems/construct-binary-search-tree-from-preorder-traversal/ 11 | 12 | ## 题目描述 13 | 14 | Return the root node of a binary search tree that matches the given ``preorder`` traversal. 15 | 16 | (Recall that a binary search tree is a binary tree where for every node, any descendant of ``node.left`` has a ``value < node.val``, and any descendant of node.right has a ``value > node.val``. Also recall that a preorder traversal displays the value of the node first, then traverses ``node.left``, then traverses ``node.right``.) 17 | 18 | Example 1: 19 | 20 | Input: [8,5,1,7,10,12] 21 | Output: [8,5,10,1,7,null,12] 22 | 23 | ![此处输入图片的描述][1] 24 | 25 | Note: 26 | 27 | 1. 1 <= preorder.length <= 100 28 | 1. The values of preorder are distinct. 29 | 30 | ## 题目大意 31 | 32 | 给出了一个BST的先序遍历,求该BST。 33 | 34 | ## 解题方法 35 | 36 | ### 递归 37 | 38 | 先序遍历一定先遍历了根节点,所以出现的第一个数字一定是根。那么BST的左子树都比根节点小,而先序遍历要把左子树遍历结束才遍历右子树,所以向后找第一个大于根节点数字位置,该位置就是右子树的根节点。 39 | 40 | 做一个递归即可。 41 | 42 | Python代码如下: 43 | 44 | ```python 45 | # Definition for a binary tree node. 46 | # class TreeNode(object): 47 | # def __init__(self, x): 48 | # self.val = x 49 | # self.left = None 50 | # self.right = None 51 | 52 | class Solution(object): 53 | def bstFromPreorder(self, preorder): 54 | """ 55 | :type preorder: List[int] 56 | :rtype: TreeNode 57 | """ 58 | if not preorder: return None 59 | root = TreeNode(preorder[0]) 60 | N = len(preorder) 61 | i = 1 62 | while i < N: 63 | if preorder[i] > preorder[0]: 64 | break 65 | i += 1 66 | root.left = self.bstFromPreorder(preorder[1:i]) 67 | root.right = self.bstFromPreorder(preorder[i:]) 68 | return root 69 | ``` 70 | 71 | 72 | ## 日期 73 | 74 | 2019 年 3 月 10 日 —— 周赛进了第一页! 75 | 76 | 77 | [1]: https://assets.leetcode.com/uploads/2019/03/06/1266.png 78 | [2]: https://assets.leetcode.com/uploads/2019/03/08/domino.png 79 | -------------------------------------------------------------------------------- /1400-1499/1413. Minimum Value to Get Positive Step by Step Sum 逐步求和得到正数的最小值.md: -------------------------------------------------------------------------------- 1 | 2 | - 作者: 负雪明烛 3 | - id: fuxuemingzhu 4 | - 个人博客:[http://fuxuemingzhu.cn/](http://fuxuemingzhu.cn/) 5 | 6 | --- 7 | @[TOC](目录) 8 | 9 | 10 | 题目地址:https://leetcode-cn.com/contest/biweekly-contest-24/problems/minimum-value-to-get-positive-step-by-step-sum/ 11 | 12 | # 题目描述 13 | 14 | 给你一个整数数组 nums 。你可以选定任意的 正数 startValue 作为初始值。 15 | 16 | 你需要从左到右遍历 nums 数组,并将 startValue 依次累加上 nums 数组中的值。 17 | 18 | 请你在确保累加和始终大于等于 1 的前提下,选出一个最小的 正数 作为 startValue 。 19 | 20 | 21 | 22 | 示例 1: 23 | 24 | 输入:nums = [-3,2,-3,4,2] 25 | 输出:5 26 | 解释:如果你选择 startValue = 4,在第三次累加时,和小于 1 。 27 | 累加求和 28 | startValue = 4 | startValue = 5 | nums 29 | (4 -3 ) = 1 | (5 -3 ) = 2 | -3 30 | (1 +2 ) = 3 | (2 +2 ) = 4 | 2 31 | (3 -3 ) = 0 | (4 -3 ) = 1 | -3 32 | (0 +4 ) = 4 | (1 +4 ) = 5 | 4 33 | (4 +2 ) = 6 | (5 +2 ) = 7 | 2 34 | 35 | 示例 2: 36 | 37 | 输入:nums = [1,2] 38 | 输出:1 39 | 解释:最小的 startValue 需要是正数。 40 | 41 | 示例 3: 42 | 43 | 输入:nums = [1,-2,-3] 44 | 输出:5 45 | 46 | 47 | 提示: 48 | 49 | 1. `1 <= nums.length <= 100` 50 | 1. `-100 <= nums[i] <= 100` 51 | 52 | 53 | # 题目大意 54 | 55 | 让你找个最小的正数startValue,使得startValue从左到右累加一遍的时候保证和至少为1. 56 | 57 | # 解题方法 58 | 59 | ## 求和 60 | 61 | 让我们求最小的 startValue,就是让我们求从左到右累加所有数字的时候,出现的最小的和 min_sum。 62 | 63 | 1. 当 min_sum > 0 的时候,比如示例2,我们让startValue设置为1. 64 | 2. 当 min_sum <= 0 的时候,让 startValue + min_sum >= 1,就让 startValue 为 1 - min_sum即可。 65 | 66 | Python代码如下: 67 | 68 | ```python 69 | class Solution: 70 | def minStartValue(self, nums: List[int]) -> int: 71 | min_sum = 0 72 | cur_sum = 0 73 | for num in nums: 74 | cur_sum += num 75 | min_sum = min(min_sum, cur_sum) 76 | return 1 if min_sum > 0 else 1 - min_sum 77 | ``` 78 | 79 | 80 | **欢迎关注[负雪明烛的刷题博客](https://blog.csdn.net/fuxuemingzhu),leetcode刷题800多,每道都讲解了详细写法!** 81 | 82 | # 日期 83 | 84 | 2020 年 4 月 18 日 —— 周赛死于第4题 85 | 86 | 87 | [1]: https://blog.csdn.net/fuxuemingzhu/article/details/79451733 88 | --------------------------------------------------------------------------------