diff --git a/.github/PULL_REQUEST_TEMPLATE.md b/.github/PULL_REQUEST_TEMPLATE.md index ed30b68824b3c..e69de29bb2d1d 100644 --- a/.github/PULL_REQUEST_TEMPLATE.md +++ b/.github/PULL_REQUEST_TEMPLATE.md @@ -1 +0,0 @@ -None. diff --git a/README.md b/README.md index c96b472a6b262..e6b99d369a66f 100644 --- a/README.md +++ b/README.md @@ -8,6 +8,8 @@ issues stars forks +

## Introduction @@ -26,13 +28,6 @@ I'm looking for long-term contributors/partners to this repo! Send me [PRs](http ![how-to-contribute](/img/how-to-contribute-yanglbme.png) ## Contributors +This project exists thanks to all the people who contribute. -" If you want to go fast, go alone. If you want to go far, go together. And that's the spirit of [teamwork](https://github.com/doocs/leetcode/graphs/contributors) ". - - -|
[](https://github.com/yanglbme)
|
[](https://github.com/chakyam)
|
[](https://github.com/zhkmxx9302013)
|
[](https://github.com/MarkKuang1991)
|
[](https://github.com/fonxian)
|
[](https://github.com/zhanary)
|
[](https://github.com/ZhouTingZhaobiu)
|
[](https://github.com/zouwx2cs)
| -|---|---|---|---|---|---|---|---| -|
[](https://github.com/Mrzhudky)
|
[](https://github.com/KongJHong)
|
[](https://github.com/limbowandering)
|
[](https://github.com/jxdeng3989)
|
[](https://github.com/igayhub)
|
[](https://github.com/MCN1998)
|
[](https://github.com/Fairyhead)
|
[](https://github.com/zhng1456)
| -|
[](https://github.com/xiapengchng)
|
[](https://github.com/Mcnwork2018)
|
[](https://github.com/bluesword12350)
|
[](https://github.com/ashwek)
|
[](https://github.com/Mrtj2016)
| - - \ No newline at end of file + \ No newline at end of file diff --git a/SOLUTION_TREE.md b/SOLUTION_TREE.md index a2f2322004c71..5dc3d2da27114 100644 --- a/SOLUTION_TREE.md +++ b/SOLUTION_TREE.md @@ -1,47 +1,49 @@ - ## Solution Tree - ``` . ├── 0001.Two Sum │   ├── README.md -│   ├── Solution2.js -│   ├── Solution2.py │   ├── Solution.cpp │   ├── Solution.go │   ├── Solution.java │   ├── Solution.js │   ├── Solution.py │   ├── Solution.rb -│   └── Solution.scala +│   ├── Solution.scala +│   └── Solution2.py ├── 0002.Add Two Numbers │   ├── README.md │   ├── Solution.cpp │   ├── Solution.java │   ├── Solution.js │   ├── Solution.py -│   └── Solution.rb +│   ├── Solution.rb +│   └── Solution2.js ├── 0003.Longest Substring Without Repeating Characters │   ├── README.md -│   └── Solution.java +│   ├── Solution.java +│   └── Solution.js ├── 0004.Median of Two Sorted Arrays │   ├── README.md │   ├── Solution.cpp -│   └── Solution.java +│   ├── Solution.java +│   └── Solution.js ├── 0005.Longest Palindromic Substring │   ├── README.md -│   └── Solution.java +│   ├── Solution.java +│   └── Solution.js ├── 0006.ZigZag Conversion │   ├── Solution.cpp │   ├── Solution.java +│   ├── Solution.js │   └── Solution.py ├── 0007.Reverse Integer │   ├── README.md -│   ├── Solution2.py │   ├── Solution.java │   ├── Solution.js │   ├── Solution.py -│   └── Solution.rb +│   ├── Solution.rb +│   └── Solution2.py ├── 0008.String to Integer (atoi) │   ├── Solution.java │   ├── Solution.js @@ -49,36 +51,38 @@ ├── 0009.Palindrome Number │   ├── README.md │   ├── Solution.java +│   ├── Solution.js │   └── Solution.py ├── 0010.Regular Expression Matching │   └── Solution.java ├── 0011.Container With Most Water +│   ├── Solution.cpp │   ├── Solution.java │   └── Solution.js ├── 0012.Integer to Roman │   └── Solution.java ├── 0013.Roman to Integer │   ├── README.md -│   ├── Solution2.py │   ├── Solution.java │   ├── Solution.js │   ├── Solution.py -│   └── Solution.rb +│   ├── Solution.rb +│   └── Solution2.py ├── 0014.Longest Common Prefix │   ├── README.md -│   ├── Solution2.py │   ├── Solution.cpp │   ├── Solution.java │   ├── Solution.js │   ├── Solution.py -│   └── Solution.rb +│   ├── Solution.rb +│   └── Solution2.py ├── 0015.3Sum │   ├── README.md -│   ├── solution.cpp │   ├── Solution.cpp │   ├── Solution.java │   ├── Solution.py -│   └── Solution.rb +│   ├── Solution.rb +│   └── solution.cpp ├── 0016.3Sum Closest │   └── Solution.java ├── 0017.Letter Combinations of a Phone Number @@ -96,19 +100,20 @@ │   └── Solution.rb ├── 0020.Valid Parentheses │   ├── README.md -│   ├── Solution2.py │   ├── Solution.cpp │   ├── Solution.java │   ├── Solution.js │   ├── Solution.py -│   └── Solution.rb +│   ├── Solution.rb +│   └── Solution2.py ├── 0021.Merge Two Sorted Lists │   ├── README.md │   ├── Solution.cpp │   ├── Solution.java │   ├── Solution.js │   ├── Solution.py -│   └── Solution.rb +│   ├── Solution.rb +│   └── Solution2.js ├── 0022.Generate Parentheses │   └── Solution.java ├── 0023.Merge k Sorted Lists @@ -122,7 +127,8 @@ │   ├── Solution.cpp │   ├── Solution.java │   ├── Solution.py -│   └── Solution.rb +│   ├── Solution.rb +│   └── Solution2.cpp ├── 0025.Reverse Nodes in k-Group │   ├── README.md │   └── Solution.java @@ -140,6 +146,7 @@ │   ├── README.md │   ├── Solution.cpp │   ├── Solution.java +│   ├── Solution.js │   └── Solution.py ├── 0029.Divide Two Integers │   ├── README.md @@ -158,7 +165,8 @@ ├── 0033.Search in Rotated Sorted Array │   ├── README.md │   ├── Solution.cpp -│   └── Solution.java +│   ├── Solution.java +│   └── Solution.js ├── 0034.Find First and Last Position of Element in Sorted Array │   ├── README.md │   ├── Solution.cpp @@ -206,12 +214,14 @@ │   ├── README.md │   ├── Solution.cpp │   ├── Solution.java -│   └── Solution.py +│   ├── Solution.py +│   └── Solution2.cpp ├── 0047.Permutations II │   ├── README.md │   ├── Solution.cpp │   ├── Solution.java -│   └── Solution.py +│   ├── Solution.py +│   └── Solution2.cpp ├── 0048.Rotate Image │   ├── README.md │   ├── Solution.cpp @@ -220,7 +230,8 @@ ├── 0049.Group Anagrams │   └── Solution.java ├── 0050.Pow(x, n) -│   └── Solution.java +│   ├── Solution.java +│   └── Solution.js ├── 0051.N-Queens │   └── Solution.java ├── 0052.N-Queens II @@ -267,45 +278,70 @@ ├── 0064.Minimum Path Sum │   ├── README.md │   ├── Solution.cpp -│   └── Solution.java +│   ├── Solution.java +│   └── Solution2.cpp ├── 0065.Valid -│   └── Solution.java +│   ├── Solution.java +│   └── Solution.py ├── 0066.Plus One │   ├── README.md -│   ├── Solution2.py │   ├── Solution.cpp │   ├── Solution.java │   ├── Solution.js -│   └── Solution.py +│   ├── Solution.py +│   ├── Solution2.js +│   └── Solution2.py ├── 0067.Add Binary │   └── Solution.java +├── 0068.Text Justification +│   └── Solution.java ├── 0069.Sqrt(x) │   ├── README.md -│   ├── Solution2.py -│   └── Solution.py +│   ├── Solution.java +│   ├── Solution.js +│   ├── Solution.py +│   └── Solution2.py ├── 0070.Climbing Stairs │   ├── README.md │   ├── Solution.cpp │   ├── Solution.java │   ├── Solution.js │   └── Solution.py +├── 0071.Simplify Path +│   └── Solution.java +├── 0072.Edit Distance +│   └── Solution.java ├── 0073.Set Matrix Zeroes │   ├── README.md │   ├── Solution.cpp +│   ├── Solution.java │   └── Solution.py ├── 0074.Search a 2D Matrix │   ├── README.md │   ├── Solution.cpp +│   ├── Solution.java │   └── Solution.py ├── 0075.Sort Colors │   ├── README.md -│   ├── Solution2.py │   ├── Solution.cpp │   ├── Solution.java -│   └── Solution.py +│   ├── Solution.py +│   ├── Solution2.cpp +│   └── Solution2.py +├── 0076.Minimum Window Substring +│   └── Solution.java +├── 0077.Combinations +│   └── Solution.java +├── 0078.Subsets +│   └── Solution.java +├── 0079.Word Search +│   └── Solution.java ├── 0080.Remove Duplicates from Sorted Array II │   ├── README.md -│   └── Solution.cpp +│   ├── Solution.cpp +│   └── Solution.java +├── 0081.Search in Rotated Sorted Array II +│   └── Solution.java ├── 0082.Remove Duplicates from Sorted List II │   ├── README.md │   ├── Solution.java @@ -313,35 +349,69 @@ ├── 0083.Remove Duplicates from Sorted List │   ├── README.md │   ├── Solution.java +│   ├── Solution.js │   └── Solution.py ├── 0084.Largest Rectangle in Histogram │   ├── README.md │   ├── Solution.cpp │   └── Solution.java +├── 0085.Maximal Rectangle +│   └── Solution.java ├── 0086.Partition List │   ├── README.md +│   ├── Solution.cpp │   ├── Solution.java │   └── Solution.py +├── 0087.Scramble String +│   └── Solution.java ├── 0088.Merge Sorted Array +│   ├── Solution.java │   └── Solution.js +├── 0089.Gray Code +│   └── Solution.java ├── 0090.Subsets II │   ├── README.md -│   └── Solution.cpp +│   ├── Solution.cpp +│   ├── Solution.java +│   └── Solution2.cpp +├── 0091.Decode Ways +│   └── Solution.java ├── 0092.Reverse Linked List II │   ├── README.md +│   ├── Solution.cpp +│   └── Solution.java +├── 0093.Restore IP Addresses +│   ├── Solution.cpp │   └── Solution.java ├── 0094.Binary Tree Inorder Traversal │   ├── README.md │   ├── Solution.java │   └── Solution.py +├── 0095.Unique Binary Search Trees II +│   └── Solution.java ├── 0096.Unique Binary Search Trees │   ├── README.md │   ├── Solution.java │   └── Solution.py +├── 0097.Interleaving String +│   └── Solution.java +├── 0098.Validate Binary Search Tree +│   ├── Solution.cpp +│   └── Solution.java +├── 0099.Recover Binary Search Tree +│   └── Solution.java +├── 0100.Same Tree +│   └── Solution.java +├── 0101.Symmetric Tree +│   └── Solution.java ├── 0102.Binary Tree Level Order Traversal │   ├── README.md │   ├── Solution.java │   └── Solution.py +├── 0103.Binary Tree Zigzag Level Order Traversal +│   └── Solution.java +├── 0104.Maximum Depth of Binary Tree +│   └── Solution.java ├── 0105.Construct Binary Tree from Preorder and Inorder Traversal │   ├── README.md │   ├── Solution.cpp @@ -349,34 +419,82 @@ ├── 0106.Construct Binary Tree from Inorder and Postorder Traversal │   ├── README.md │   └── Solution.java +├── 0107.Binary Tree Level Order Traversal II +│   └── Solution.java +├── 0108.Convert Sorted Array to Binary Search Tree +│   └── Solution.java +├── 0109.Convert Sorted List to Binary Search Tree +│   └── Solution.java +├── 0110.Balanced Binary Tree +│   └── Solution.java +├── 0111.Minimum Depth of Binary Tree +│   └── Solution.java ├── 0112.Path Sum │   ├── README.md -│   └── Solution.cpp +│   ├── Solution.cpp +│   └── Solution.java +├── 0113.Path Sum II +│   └── Solution.java +├── 0114.Flatten Binary Tree to Linked List +│   └── Solution.java +├── 0115.Distinct Subsequences +│   └── Solution.java +├── 0116.Populating Next Right Pointers in Each Node +│   └── Solution.java +├── 0117.Populating Next Right Pointers in Each Node II +│   └── Solution.java ├── 0118.Pascal's Triangle │   ├── README.md │   ├── Solution.cpp +│   ├── Solution.java │   └── Solution.js ├── 0119.Pascal's Triangle II │   ├── README.md -│   └── Solution.cpp +│   ├── Solution.cpp +│   └── Solution.java ├── 0120.Triangle │   ├── README.md -│   └── Solution.cpp +│   ├── Solution.cpp +│   ├── Solution.java +│   └── Solution2.cpp ├── 0121.Best Time to Buy and Sell Stock +│   ├── Solution.java │   └── Solution.js ├── 0122.Best Time to Buy and Sell Stock II │   ├── Solution.cpp +│   ├── Solution.java │   └── Solution.js ├── 0123.Best Time to Buy and Sell Stock III │   ├── README.md -│   └── Solution.cpp +│   ├── Solution.cpp +│   └── Solution.java +├── 0124.Binary Tree Maximum Path Sum +│   └── Solution.java ├── 0125.Valid Palindrome +│   ├── Solution.java │   └── Solution.js +├── 0126.Word Ladder II +│   └── Solution.java ├── 0127.Word Ladder │   ├── README.md │   └── Solution.java +├── 0128.Longest Consecutive Sequence +│   └── Solution.java +├── 0129.Sum Root to Leaf Numbers +│   └── Solution.java ├── 0130.Surrounded Regions │   ├── README.md +│   ├── Solution.cpp +│   └── Solution.java +├── 0131.Palindrome Partitioning +│   └── Solution.java +├── 0132.Palindrome Partitioning II +│   └── Solution.java +├── 0133.Clone Graph +│   └── Solution.java +├── 0134.Gas Station +│   └── Solution.java +├── 0135.Candy │   └── Solution.java ├── 0136.Single Number │   ├── README.md @@ -390,9 +508,14 @@ ├── 0138.Copy List with Random Pointer │   ├── README.md │   └── Solution.java +├── 0139.Word Break +│   └── Solution.java +├── 0140.Word Break II +│   └── Solution.java ├── 0141.Linked List Cycle │   ├── README.md │   ├── Solution.java +│   ├── Solution.js │   └── Solution.py ├── 0142.Linked List Cycle II │   ├── README.md @@ -416,6 +539,7 @@ │   └── Solution.py ├── 0153.Find Minimum in Rotated Sorted Array │   ├── README.md +│   ├── Solution.cpp │   ├── Solution.java │   └── Solution.py ├── 0155.Min Stack @@ -469,19 +593,29 @@ ├── 0200.Number of Islands │   ├── README.md │   └── Solution.py +├── 0202.Happy Number +│   ├── README.md +│   └── Solution.java ├── 0203.Remove Linked List Elements │   ├── README.md │   ├── Solution.java │   └── Solution.py ├── 0204.Count Primes +│   ├── Solution.cpp │   └── Solution.js ├── 0206.Reverse Linked List │   └── Solution.js +├── 0207.Course Schedule +│   ├── README.md +│   └── Solution.java ├── 0215.Kth Largest Element in an Array │   ├── README.md +│   ├── Solution.cpp │   └── Solution.java ├── 0217.Contains Duplicate │   └── Solution.js +├── 0218.The Skyline Problem +│   └── Solution.cpp ├── 0228.Summary Ranges │   ├── README.md │   ├── Solution.cpp @@ -504,19 +638,23 @@ ├── 0242.Valid Anagram │   └── Solution.js ├── 0268.Missing Number -│   └── Solution.js +│   ├── Solution.js +│   └── Solution2.js ├── 0278.First Bad Version │   └── Solution.js ├── 0283.Move Zeroes │   ├── README.md │   ├── Solution.cpp -│   └── Solution.js +│   ├── Solution.js +│   └── Solution2.js ├── 0295.Find Median from Data Stream │   ├── README.md │   └── Solution.java ├── 0300.Longest Increasing Subsequence │   ├── README.md -│   └── Solution.java +│   ├── Solution.cpp +│   ├── Solution.java +│   └── Solution2.cpp ├── 0312.Burst Balloons │   ├── README.md │   └── Solution.java @@ -527,6 +665,8 @@ ├── 0328.Odd Even Linked List │   ├── README.md │   └── Solution.java +├── 0329.Longest Increasing Path in a Matrix +│   └── Solution.cpp ├── 0343.Integer Break │   ├── README.md │   └── Solution.java @@ -535,6 +675,8 @@ │   ├── Solution.java │   ├── Solution.js │   └── Solution.py +├── 0349.Intersection of Two Arrays +│   └── Solution.py ├── 0350.Intersection of Two Arrays II │   └── Solution.js ├── 0384.Shuffle an Array @@ -542,6 +684,8 @@ ├── 0387.First Unique Character in a String │   ├── Solution.cpp │   └── Solution.js +├── 0393.UTF-8 Validation +│   └── Solution.cpp ├── 0394.Decode String │   ├── README.md │   └── Solution.py @@ -549,12 +693,16 @@ │   ├── Solution.cpp │   ├── Solution.js │   └── Solution.py +├── 0423.Reconstruct Original Digits from English +│   └── Solution.cpp ├── 0427.Construct Quad Tree │   └── Solution.cpp ├── 0434.Number of Segments in a String │   └── Solution.cpp ├── 0438.Find All Anagrams in a String -│   └── Solution.cpp +│   ├── README.md +│   ├── Solution.cpp +│   └── Solution.py ├── 0443.String Compression │   └── Solution.cpp ├── 0448.Find All Numbers Disappeared in an Array @@ -562,9 +710,32 @@ │   └── Solution.cpp ├── 0461.Hamming Distance │   └── Solution.js +├── 0476.Number Complement +│   └── Solution.cpp +├── 0485. Max Consecutive Ones +│   └── Solution.js +├── 0493.Reverse Pairs +│   └── Solution.cpp +├── 0500.Keyboard Row +│   └── Solution.py +├── 0509.Fibonacci +│   ├── README.md +│   ├── Solution.cpp +│   └── Solution.js ├── 0521.Longest Uncommon Subsequence I │   ├── README.md │   └── Solution.py +├── 0554.Brick Wall +│   ├── README.md +│   └── Solution.py +├── 0561.Array Partition I +│   ├── README.md +│   └── Solution.js +├── 0567.Permutation in String +│   ├── README.md +│   └── Solution.py +├── 0572.Subtree of Another Tree +│   └── Solution.cpp ├── 0581.Shortest Unsorted Continuous Subarray │   ├── README.md │   ├── Solution.cpp @@ -582,6 +753,8 @@ │   └── README.md ├── 0627.Swap Salary │   └── README.md +├── 0657.Robot Return to Origin +│   └── Solution.py ├── 0665.Non-decreasing Array │   ├── README.md │   └── Solution.py @@ -592,6 +765,9 @@ │   ├── README.md │   ├── Solution.cpp │   └── Solution.java +├── 0700.Search in a Binary Search Tree +│   ├── Solution.cpp +│   └── Solution.py ├── 0701.Insert into a Binary Search Tree │   ├── README.md │   └── Solution.py @@ -601,12 +777,28 @@ ├── 0707.Design Linked List │   ├── README.md │   └── Solution.java +├── 0728.Self Dividing Numbers +│   └── Solution.cpp ├── 0735.Asteroid Collision │   ├── README.md │   └── Solution.py +├── 0762.Prime Number of Set Bits in Binary Representation +│   ├── README.md +│   └── Solution.py +├── 0769.Max Chunks To Make Sorted +│   ├── README.md +│   └── Solution.py +├── 0771.Jewels and Stones +│   └── Solution.py ├── 0789.Escape The Ghosts │   ├── README.md │   └── Solution.py +├── 0797.All Paths From Source to Target +│   └── Solution.cpp +├── 0804.Unique Morse Code Words +│   └── Solution.py +├── 0807.Max Increase to Keep City Skyline +│   └── Solution.cpp ├── 0817.Linked List Components │   ├── README.md │   ├── Solution.java @@ -614,8 +806,22 @@ ├── 0826.Most Profit Assigning Work │   ├── README.md │   └── Solution.py +├── 0832.Flipping an Image +│   ├── README.md +│   ├── Solution.cpp +│   ├── Solution.js +│   └── Solution.py ├── 0836.Rectangle Overlap │   └── Solution.cpp +├── 0848.Shifting Letters +│   ├── README.md +│   └── Solution.py +├── 0853.Car Fleet +│   ├── README.md +│   └── Solution.py +├── 0867.Transpose Matrix +│   ├── README.md +│   └── Solution.js ├── 0874.Walking Robot Simulation │   └── Solution.cpp ├── 0876.Middle of the Linked List @@ -628,18 +834,66 @@ ├── 0889.Construct Binary Tree from Preorder and Postorder Traversal │   ├── README.md │   └── Solution.py +├── 0905.Sort Array By Parity +│   ├── README.md +│   ├── Solution.js +│   └── Solution.py ├── 0915.Partition Array into Disjoint Intervals │   ├── README.md │   └── Solution.py +├── 0917.Reverse Only Letters +│   ├── Solution.cpp +│   └── Solution.py +├── 0922.Sort Array By Parity II +│   ├── README.md +│   └── Solution.js ├── 0926.Flip String to Monotone Increasing │   └── Solution.js ├── 0929.Unique Email Addresses -│   └── Solution.js +│   ├── Solution.js +│   └── Solution.py ├── 0930.Binary Subarrays With Sum │   └── Solution.js -└── 0938.Range Sum of BST +├── 0938.Range Sum of BST +│   ├── README.md +│   ├── Solution.cpp +│   ├── Solution.java +│   └── Solution.py +├── 0941.Valid Mountain Array +│   └── Solution.cpp +├── 0944.Delete Columns to Make Sorted +│   └── Solution.py +├── 0950.Reveal Cards In Increasing Order +│   └── Solution.cpp +├── 0952.Largest Component Size by Common Factor +│   ├── README.md +│   └── Solution.java +├── 0953.Verifying an Alien Dictionary +│   ├── Solution.cpp +│   └── Solution.py +├── 0955.Delete Columns to Make Sorted II +│   ├── README.md +│   └── Solution.java +├── 0961.N-Repeated Element in Size 2N Array +│   ├── README.md +│   ├── Solution.cpp +│   ├── Solution.java +│   ├── Solution.js +│   ├── Solution.py +│   ├── Solution2.cpp +│   └── Solution2.py +├── 0965.Univalued Binary Tree +│   └── Solution.cpp +├── 0976.Largest Perimeter Triangle +│   └── Solution.cpp +├── 0977.Squares of a Sorted Array +│   ├── README.md +│   ├── Solution.cpp +│   ├── Solution.java +│   └── Solution.js +└── 0985.Sum of Even Numbers After Queries ├── README.md - ├── Solution.java + ├── Solution.cpp + ├── Solution.js └── Solution.py - ``` \ No newline at end of file diff --git a/img/Largest-Component-Size-by-Common-Factor1.png b/img/Largest-Component-Size-by-Common-Factor1.png index 259ef1e9f78a2..28b6ade1e1c62 100644 Binary files a/img/Largest-Component-Size-by-Common-Factor1.png and b/img/Largest-Component-Size-by-Common-Factor1.png differ diff --git a/img/Largest-Component-Size-by-Common-Factor2.png b/img/Largest-Component-Size-by-Common-Factor2.png index 94789480719e6..d49b9c151c009 100644 Binary files a/img/Largest-Component-Size-by-Common-Factor2.png and b/img/Largest-Component-Size-by-Common-Factor2.png differ diff --git a/img/Largest-Component-Size-by-Common-Factor3.png b/img/Largest-Component-Size-by-Common-Factor3.png index bc9678c6cd86d..fca5996ac96a4 100644 Binary files a/img/Largest-Component-Size-by-Common-Factor3.png and b/img/Largest-Component-Size-by-Common-Factor3.png differ diff --git a/img/brick_wall.png b/img/brick_wall.png new file mode 100644 index 0000000000000..e162d08fc6ed6 Binary files /dev/null and b/img/brick_wall.png differ diff --git a/img/clone-fork-doocs-leetcode.jpg b/img/clone-fork-doocs-leetcode.jpg index 01e7a88c5c018..38655ecfc4f20 100644 Binary files a/img/clone-fork-doocs-leetcode.jpg and b/img/clone-fork-doocs-leetcode.jpg differ diff --git a/img/create-pull-request.png b/img/create-pull-request.png index 90ca37a93e0fc..34321e6f4e070 100644 Binary files a/img/create-pull-request.png and b/img/create-pull-request.png differ diff --git a/img/dev-pull-request.png b/img/dev-pull-request.png index b72792e570f4e..316e5ae5cc0f3 100644 Binary files a/img/dev-pull-request.png and b/img/dev-pull-request.png differ diff --git a/img/email-of-pull-request.jpg b/img/email-of-pull-request.jpg index 981b44e734165..6f29fd1137932 100644 Binary files a/img/email-of-pull-request.jpg and b/img/email-of-pull-request.jpg differ diff --git a/img/how-to-contribute-yanglbme.png b/img/how-to-contribute-yanglbme.png index d240410a3d1d7..cbaac0ebf4573 100644 Binary files a/img/how-to-contribute-yanglbme.png and b/img/how-to-contribute-yanglbme.png differ diff --git a/img/leetcode-github-yanglbme.png b/img/leetcode-github-yanglbme.png index e1219be111087..2a8d938f68495 100644 Binary files a/img/leetcode-github-yanglbme.png and b/img/leetcode-github-yanglbme.png differ diff --git a/img/random-list-step1.png b/img/random-list-step1.png index 701e37f29166e..9c37d10fbc341 100644 Binary files a/img/random-list-step1.png and b/img/random-list-step1.png differ diff --git a/img/random-list-step2.png b/img/random-list-step2.png index 3316254e9830d..04d2fe8787d6a 100644 Binary files a/img/random-list-step2.png and b/img/random-list-step2.png differ diff --git a/img/random-list-step3.png b/img/random-list-step3.png index a8e36ee04f137..2c805aecaec2a 100644 Binary files a/img/random-list-step3.png and b/img/random-list-step3.png differ diff --git a/img/random-list.png b/img/random-list.png index 4b9b4b485e1c3..83e472048e125 100644 Binary files a/img/random-list.png and b/img/random-list.png differ diff --git a/img/robot_maze.png b/img/robot_maze.png index ebcd2dce41643..1b672b7a51340 100644 Binary files a/img/robot_maze.png and b/img/robot_maze.png differ diff --git a/solution/0001.Two Sum/Solution.js b/solution/0001.Two Sum/Solution.js index ff5d195926f06..b0bd22cd58491 100644 --- a/solution/0001.Two Sum/Solution.js +++ b/solution/0001.Two Sum/Solution.js @@ -1,6 +1,9 @@ +/** + * Author: limbowandering + */ + const twoSum = function(nums, target) { const map = {}; - for (let i = 0; i < nums.length; i++) { if (map[nums[i]] !== undefined) { return [map[nums[i]], i] @@ -8,4 +11,33 @@ const twoSum = function(nums, target) { map[target - nums[i]] = i } } +}; + +/** + * Author: Mcnwork2018 + */ + +var twoSum = function(nums, target) { + let len = nums.length; + let n = {}; + for (let i = 0; i < len; i++) { + if (n[target - nums[i]] !== undefined) { + return [n[target - nums[i]], i]; + } + n[nums[i]] = i; + } +}; + +/** + * Author: rookie + */ + +var twoSum = function(nums, target) { + const map = new Map(); + for (let i = 0; i < nums.length; i++) { + if (map.has(target - nums[i])) { + return [ map.get(target - nums[i]), i ] + } + map.set(nums[i], i); + } }; \ No newline at end of file diff --git a/solution/0001.Two Sum/Solution2.js b/solution/0001.Two Sum/Solution2.js deleted file mode 100644 index 3c4b7abb4f047..0000000000000 --- a/solution/0001.Two Sum/Solution2.js +++ /dev/null @@ -1,10 +0,0 @@ -var twoSum = function(nums, target) { - var len = nums.length; - var n = {}; - for(var i = 0; i < len; i++){ - if(n[target - nums[i]] !== undefined){ - return [n[target - nums[i]], i]; - } - n[nums[i]] = i; - } -}; diff --git a/solution/0002.Add Two Numbers/Solution.js b/solution/0002.Add Two Numbers/Solution.js index 624c4a12e6acc..c9fc0b9898542 100644 --- a/solution/0002.Add Two Numbers/Solution.js +++ b/solution/0002.Add Two Numbers/Solution.js @@ -10,27 +10,31 @@ * @param {ListNode} l2 * @return {ListNode} */ -var addTwoNumbers = function(l1, l2) { - var c1 = l1,c2 = l2,c3,l3,carry = 0; - while(c1 || c2 || carry){ - var v1 = 0,v2 = 0; - if(c1){ - v1 = c1.val; - c1 = c1.next; - } - if(c2){ - v2 = c2.val; - c2 = c2.next; - } - var sum = v1 + v2 + carry; - carry = (sum - sum % 10) / 10; - if(!c3){ - l3 = new ListNode(sum%10); - c3 = l3; - }else{ - c3.next = new ListNode(sum%10); - c3 = c3.next; - } - } - return l3; + +/** + * Author: Mcnwork2018 + */ +var addTwoNumbers = function (l1, l2) { + let c1 = l1, c2 = l2, c3 = 0, l3 = 0, carry = 0; + while (c1 || c2 || carry) { + var v1 = 0, v2 = 0; + if (c1) { + v1 = c1.val; + c1 = c1.next; + } + if (c2) { + v2 = c2.val; + c2 = c2.next; + } + var sum = v1 + v2 + carry; + carry = (sum - sum % 10) / 10; + if (!c3) { + l3 = new ListNode(sum % 10); + c3 = l3; + } else { + c3.next = new ListNode(sum % 10); + c3 = c3.next; + } + } + return l3; } \ No newline at end of file diff --git a/solution/0002.Add Two Numbers/Solution2.js b/solution/0002.Add Two Numbers/Solution2.js new file mode 100644 index 0000000000000..2d488981100a1 --- /dev/null +++ b/solution/0002.Add Two Numbers/Solution2.js @@ -0,0 +1,46 @@ +/** + * Definition for singly-linked list. + * function ListNode(val) { + * this.val = val; + * this.next = null; + * } + */ +/** + * @param {ListNode} l1 + * @param {ListNode} l2 + * @return {ListNode} + */ +var addTwoNumbers = function(l1, l2) { + let head = new ListNode(0) + let cur = head + let curry = 0 + + while (true) { + let sum = curry + sum += l1 ? l1.val : 0 + sum += l2 ? l2.val : 0 + cur.val = sum % 10 + curry = parseInt(sum / 10) + if (l1) l1 = l1.next + if (l2) l2 = l2.next + if (l1 != null || l2 != null) { + cur.next = new ListNode(0) + cur = cur.next + } else { + break + } + } + if (curry != 0) { + cur.next = new ListNode(0) + cur = cur.next + cur.val = curry + } + return head + }; + + var l1 = new ListNode(1) + l1.next = new ListNode(8) + + var l2 = new ListNode(0) + + console.log(addTwoNumbers(l1, l2)) \ No newline at end of file diff --git a/solution/0003.Longest Substring Without Repeating Characters/Solution.js b/solution/0003.Longest Substring Without Repeating Characters/Solution.js new file mode 100644 index 0000000000000..d63cafcb8e123 --- /dev/null +++ b/solution/0003.Longest Substring Without Repeating Characters/Solution.js @@ -0,0 +1,22 @@ +/** + * @param {string} s + * @return {number} + */ +var lengthOfLongestSubstring = function(s) { + var start = 0; // 非重复字符串开始索引 + var max = 0; // 最长字符串长度 + var visitedCharByPosition = {}; + for (var position = 0; position < s.length; position++) { + var nextChar = s[position]; + if (nextChar in visitedCharByPosition && visitedCharByPosition[nextChar] >= start) { + // 有重复,非重复字符串索引从下一个 index 开始 + start = visitedCharByPosition[nextChar] + 1; + visitedCharByPosition[nextChar] = position; + } else { + visitedCharByPosition[nextChar] = position; + // 非重复,求非重复值 + max = Math.max(max, position + 1 - start); + } + } + return max; +}; \ No newline at end of file diff --git a/solution/0004.Median of Two Sorted Arrays/Solution.js b/solution/0004.Median of Two Sorted Arrays/Solution.js new file mode 100644 index 0000000000000..82afa8c8fa27e --- /dev/null +++ b/solution/0004.Median of Two Sorted Arrays/Solution.js @@ -0,0 +1,74 @@ +/** + * @param {number[]} nums1 + * @param {number[]} nums2 + * @return {number} 012345 + */ +var findMedianSortedArrays = function (nums1, nums2) { + if (nums1.length == 0 || nums2.length == 0) { + if ((nums1.length + nums2.length) % 2 == 1) { + const index = parseInt((nums1.length + nums2.length) / 2) + return nums2.length == 0 ? nums1[index] : nums2[index] + } else { + let nums = nums2.length == 0 ? nums1 : nums2 + const index = nums.length / 2 + return (nums[index - 1] + nums[index]) / 2 + } + } + + if (nums1.length > nums2.length) { + swap(nums1, nums2) + } + const M = nums1.length, N = nums2.length + let min = 0, max = M, half = parseInt((M + N + 1) / 2) // 连个数组合并的中间值 + while (min <= max) { + let i = parseInt((min + max) / 2) // nums1 的索引值 + let j = half - i // num2 的索引值 + if (i < max && nums2[j - 1] > nums1[i]) { + min++ + } else if (i > min && nums1[i - 1] > nums2[j]) { + max-- + } else { + let maxLeft = 0 + if (i == 0) { + maxLeft = nums2[j - 1] + } else if (j == 0) { + maxLeft = nums1[i - 1] + } else { + maxLeft = Math.max(nums1[i - 1], nums2[j - 1]) + } + if ((M + N) % 2 == 1) { + return maxLeft + } + let minRight = 0 + if (i == M) { + minRight = nums2[j] + } else if (j == N) { + minRight = nums1[i] + } else { + minRight = Math.min(nums1[i], nums2[j]) + } + return (maxLeft + minRight) / 2 + } + } + return 0 +}; + +function swap(a, b) { + let tmp = a + a = b + b = tmp +} + +const nums1 = [4, 5] +const nums2 = [1, 2, 3] +findMedianSortedArrays(nums1, nums2) + +/** + * 实现思路 + * 先排除空数组的情况 + * 数组从小到大排序 + * 取小数组的中间值 + * 取大数组的索引 = 总中间值-小数组中间值 + * 循环直到符合条件 + * 如果都不符合条件,那么说明中间值在两个数组的左边或者右边 + */ \ No newline at end of file diff --git a/solution/0005.Longest Palindromic Substring/Solution.js b/solution/0005.Longest Palindromic Substring/Solution.js new file mode 100644 index 0000000000000..3371f06d57ebf --- /dev/null +++ b/solution/0005.Longest Palindromic Substring/Solution.js @@ -0,0 +1,36 @@ +/** + * @param {string} s + * @return {string} + */ +var longestPalindrome = function (s) { + let maxLength = 0, left = 0, right = 0 + for (let i = 0; i < s.length; i++) { + let singleCharLength = getPalLenByCenterChar(s, i, i) + let doubleCharLength = getPalLenByCenterChar(s, i, i + 1) + let max = Math.max(singleCharLength, doubleCharLength) + if (max > maxLength) { + maxLength = max + left = i - parseInt((max - 1) / 2) + right = i + parseInt(max / 2) + } + } + return s.slice(left, right + 1) +}; + +function getPalLenByCenterChar(s, left, right) { + // 中间值为两个字符,确保两个字符相等 + if (s[left] != s[right]){ + return right - left // 不相等返回为1个字符串 + } + while (left > 0 && right < s.length - 1) { + // 先加减再判断 + left-- + right++ + if (s[left] != s[right]){ + return right - left - 1 + } + } + return right - left + 1 +} + +console.log(longestPalindrome("cbbd")) \ No newline at end of file diff --git a/solution/0006.ZigZag Conversion/Solution.js b/solution/0006.ZigZag Conversion/Solution.js new file mode 100644 index 0000000000000..68ea0f89c2a72 --- /dev/null +++ b/solution/0006.ZigZag Conversion/Solution.js @@ -0,0 +1,32 @@ +/** + * @param {string} s + * @param {number} numRows + * @return {string} + */ +var convert = function (s, numRows) { + if (numRows == 1) return s + let arr = new Array(numRows) + for (let i = 0; i < numRows; i++) arr[i] = [] + let index = 0, len = s.length, mi = 0, isDown = true + while (index < len) { + arr[mi].push(s[index]) + index++ + + if (mi >= numRows - 1) + isDown = false + else if (mi <= 0) + isDown = true + + if (isDown) mi++ + else mi-- + } + let ans = [] + for (let item of arr) { + ans = ans.concat(item) + } + return ans.join("") +}; + +const s = "AB", numRows = 1 + +console.log(convert(s, numRows)) \ No newline at end of file diff --git a/solution/0007.Reverse Integer/Solution.js b/solution/0007.Reverse Integer/Solution.js index 2c2acac2bfb25..4edeb7ff76deb 100644 --- a/solution/0007.Reverse Integer/Solution.js +++ b/solution/0007.Reverse Integer/Solution.js @@ -2,50 +2,50 @@ * @param {number} x * @return {number} */ -const reverse1 = function(x){ - let s = String(x); - let isNegative = false; - if(s[0] === '-'){ - isNegative = true; - } - s = parseInt(s.split('').reverse().join('')); - return isNegative ? (s > Math.pow(2,31) ? 0 : -s) : (s > Math.pow(2,31) - 1 ? 0 : s); -} -const reverse = function(x){ - let result = parseInt(x.toString().split('').reverse().join('')); - if(result > Math.pow(2,31) - 1 || -result < Math.pow(-2,31)) return 0; - return x > 0 ? result: -result; -} -/** - * author:mcn date:2018/10/25 +/** + * Author: mcnwork2018 */ -/** - * First Way:将数字转化为字符串的处理 - */ var reverse = function(x) { - const min = -Math.pow(2,31),max = Math.pow(2,31) - 1; - let sign = 1; - if(x < 0){ - sign = -sign; - x = sign * x; + let min = -Math.pow(2,31), max = Math.pow(2,31) - 1; + let rev = 0; + while (x != 0) { + let pop = x % 10; + x = (x - pop) / 10; + if (rev > max / 10 || (rev == max / 10 && pop > 7)) return 0; + if (rev < min / 10 || (rev == min / 10 && pop < -8)) return 0; + rev = rev * 10 + pop; } - let a = x.toString(); - let len = a.length,b=''; - for(let i = len - 1;i >= 0;i--)b += a[i]; - b = sign * Number(b); - if(b > max || b < min) return 0; - return b; + return rev; }; + /** - * Second Way: 弹出和推入数字 + * Author: rookie */ -let reverse = function(x) { - let res = 0; - while (x !== 0) { - res = res * 10 + x % 10; - x = x < 0 ? Math.ceil(x / 10) : Math.floor(x / 10); + +var reverse = function (x) { + const s = x + "" + let i = 0 + let sign = 1 + if (s[i] == "-") { + i++ + sign = -1 + } + if (s[i] == "+") { + i++ + } + let num = 0 + for (let j = s.length - 1; j >= i; j--) { + num = num * 10 + parseInt(s[j]) + } + num *= sign + let max = 2 + for (let n = 0; n < 30; n++) { + max *= 2 + } + if (num > max || num < -max) { + return 0 } - return res < -(2**31) || res > 2**31 - 1 ? 0 : res; + return num }; \ No newline at end of file diff --git a/solution/0009.Palindrome Number/Solution.js b/solution/0009.Palindrome Number/Solution.js new file mode 100644 index 0000000000000..9876d699cc70d --- /dev/null +++ b/solution/0009.Palindrome Number/Solution.js @@ -0,0 +1,14 @@ +/** + * @param {number} x + * @return {boolean} + */ +var isPalindrome = function(x) { + let str = x + "" + let left = 0,right = str.length - 1 + while(left < right){ + if (str[left] != str[right]) return false + left++ + right-- + } + return true +}; \ No newline at end of file diff --git a/solution/0011.Container With Most Water/Solution.cpp b/solution/0011.Container With Most Water/Solution.cpp new file mode 100644 index 0000000000000..50d2b7b750cd4 --- /dev/null +++ b/solution/0011.Container With Most Water/Solution.cpp @@ -0,0 +1,20 @@ +class Solution { +public: + int maxArea(vector& height) { + int Max = -1, Min, area; + int s = 0, e = height.size()-1; + + while( s < e ){ + if( height[s] < height[e] ){ + area = (e-s) * height[s]; + s++; + } + else{ + area = (e-s) * height[e]; + e--; + } + if( area > Max ) Max = area; + } + return Max; + } +}; diff --git a/solution/0021.Merge Two Sorted Lists/Solution2.js b/solution/0021.Merge Two Sorted Lists/Solution2.js new file mode 100644 index 0000000000000..09eec85be3462 --- /dev/null +++ b/solution/0021.Merge Two Sorted Lists/Solution2.js @@ -0,0 +1,24 @@ +/** + * Definition for singly-linked list. + * function ListNode(val) { + * this.val = val; + * this.next = null; + * } + */ +/** + * @param {ListNode} l1 + * @param {ListNode} l2 + * @return {ListNode} + */ +var mergeTwoLists = function (l1, l2) { + if (l1 == null) return l2; + if (l2 == null) return l1; + // 排序插入 + if (l1.val < l2.val) { + l1.next = mergeTwoLists(l1.next, l2); + return l1; + } else { + l2.next = mergeTwoLists(l1, l2.next); + return l2; + } +}; \ No newline at end of file diff --git a/solution/0024.Swap Nodes in Pairs/Solution2.cpp b/solution/0024.Swap Nodes in Pairs/Solution2.cpp new file mode 100644 index 0000000000000..9afadc01373a0 --- /dev/null +++ b/solution/0024.Swap Nodes in Pairs/Solution2.cpp @@ -0,0 +1,31 @@ +// 非递归版本 +/** + * Definition for singly-linked list. + * struct ListNode { + * int val; + * ListNode *next; + * ListNode(int x) : val(x), next(NULL) {} + * }; + */ +class Solution { +public: + ListNode* swapPairs(ListNode* head) { + ListNode *pPre, *p1, *p2 ; + // 建立一个头结点就不用特殊处理第一个工作节点了 + ListNode node(0) ; + node.next = head ; + p2 = &node ; + + while ( (pPre = p2) + && (p1 = pPre->next) + && (p2 = p1->next) ) + { + pPre->next = p2 ; + p1->next = p2->next ; + p2->next = p1 ; + swap(p1, p2) ; // p1、p2 实质上已经交换了位置,所以指针也要交换一下以保证循环条件顺序 + } + + return node.next ; + } +}; \ No newline at end of file diff --git a/solution/0028.Implement strStr()/Solution.js b/solution/0028.Implement strStr()/Solution.js new file mode 100644 index 0000000000000..54dd21355df5d --- /dev/null +++ b/solution/0028.Implement strStr()/Solution.js @@ -0,0 +1,22 @@ +/** + * @param {string} haystack + * @param {string} needle + * @return {number} + */ +var strStr = function (haystack, needle) { + const slen = haystack.length + const plen = needle.length + if (slen == plen) { + return haystack == needle ? 0 : -1 + } + for (let i = 0; i <= slen - plen; i++) { + let j + for (j = 0; j < plen; j++) { + if (haystack[i + j] != needle[j]) { + break + } + } + if (j == plen) return i + } + return -1 +}; diff --git a/solution/0033.Search in Rotated Sorted Array/Solution.js b/solution/0033.Search in Rotated Sorted Array/Solution.js new file mode 100644 index 0000000000000..21c2bccae9806 --- /dev/null +++ b/solution/0033.Search in Rotated Sorted Array/Solution.js @@ -0,0 +1,13 @@ +/** + * @param {number[]} nums + * @param {number} target + * @return {number} + */ +var search = function (nums, target) { + for (let i = 0; i < nums.length; i++) { + if (nums[i] == target) { + return i + } + } + return -1 +}; \ No newline at end of file diff --git a/solution/0046.Permutations/Solution2.cpp b/solution/0046.Permutations/Solution2.cpp new file mode 100644 index 0000000000000..3a5a03743e97f --- /dev/null +++ b/solution/0046.Permutations/Solution2.cpp @@ -0,0 +1,44 @@ +class Solution { +private: + void my_next_permutation(vector::iterator b, vector::iterator e) + { + // 指针从后往前移动找到第一个下降值, (如 1, 3, 2 的1为下降值) + // 在这个下降值(1)后面找一个比下降值大的最小值(2),与下降值(1)交换 + // 交换后原来下降值之后的位置做排序(2, 1, 3) + vector::iterator p = e-2 ; + while (p >= b && *p > *(p+1)) + --p ; + + if (p >= b) + { + int M = *p ; + vector::iterator pnindex = p ; + for (vector::iterator pn = p+1 ; pn < e; ++pn) + if (*pn > *p) + { + M = min(M, *pn) ; + pnindex = pn ; + } + swap(*p, *pnindex) ; + sort(p+1, e) ; + } + else + sort(b, e) ; + } +public: + vector> permute(vector& nums) { + int n = nums.size() ; + int cnt = n ; + while (--n) + cnt *= n ; + + vector> res ; + while (cnt--) + { + res.push_back(nums) ; + // next_permutation(nums.begin(), nums.end()) ; + my_next_permutation(nums.begin(), nums.end()) ; + } + return res ; + } +}; diff --git a/solution/0047.Permutations II/Solution2.cpp b/solution/0047.Permutations II/Solution2.cpp new file mode 100644 index 0000000000000..9f7a877a47c86 --- /dev/null +++ b/solution/0047.Permutations II/Solution2.cpp @@ -0,0 +1,49 @@ +class Solution { +private: + void my_next_permutation(vector::iterator b, vector::iterator e) + { + // 指针从后往前移动找到第一个下降值, (如 1, 3, 2 的1为下降值) + // 在这个下降值(1)后面找一个比下降值大的最小值(2),与下降值(1)交换 + // 交换后原来下降值之后的位置做排序(2, 1, 3) + vector::iterator p = e-2 ; + while (p >= b && *p >= *(p+1)) + --p ; + + if (p >= b) + { + int M = *p ; + vector::iterator pnindex = p ; + for (vector::iterator pn = p+1 ; pn < e; ++pn) + if (*pn > *p) + { + M = min(M, *pn) ; + pnindex = pn ; + } + swap(*p, *pnindex) ; + sort(p+1, e) ; + } + else + sort(b, e) ; + } + inline bool IsSample(vector &a, vector &b) + { + // 长度肯定一样,就不用比较长度了 + for (int i = a.size()-1; i >= 0; --i) + if (a[i] != b[i]) + return false ; + return true ; + } +public: + vector> permuteUnique(vector& nums) { + vector nums_bak(nums) ; + vector> res ; + + do + { + res.push_back(nums) ; + my_next_permutation(nums.begin(), nums.end()) ; + } while ( !IsSample(nums, nums_bak) ) ; + + return res ; + } +}; diff --git a/solution/0050.Pow(x, n)/Solution.js b/solution/0050.Pow(x, n)/Solution.js new file mode 100644 index 0000000000000..8dfd15f5a101a --- /dev/null +++ b/solution/0050.Pow(x, n)/Solution.js @@ -0,0 +1,13 @@ +/** + * @param {number} x + * @param {number} n + * @return {number} + */ +var myPow = function(x, n) { + if (n == 0) return 1 + if (n < 0) { + n = -n + x = 1 / x + } + return (n % 2 == 0) ? Math.pow(x * x, parseInt(n / 2)) : x*Math.pow(x * x, parseInt(n / 2)); + }; \ No newline at end of file diff --git a/solution/0064.Minimum Path Sum/Solution2.cpp b/solution/0064.Minimum Path Sum/Solution2.cpp new file mode 100644 index 0000000000000..954158c2f210b --- /dev/null +++ b/solution/0064.Minimum Path Sum/Solution2.cpp @@ -0,0 +1,25 @@ +class Solution { +private: + void dfs(vector> &g, + vector> &dis, + int i, int j, int d) + { + if (i >= dis.size() || j >= dis[0].size()) + return ; + + d += g[i][j] ; + if (dis[i][j] >= 0 && d >= dis[i][j]) + return ; + + dis[i][j] = d ; + + dfs(g, dis, i+1, j, d) ; + dfs(g, dis, i, j+1, d) ; + } +public: + int minPathSum(vector>& grid) { + vector> dis(grid.size(), vector(grid.at(0).size(), -1)) ; + dfs(grid, dis, 0, 0, 0) ; + return dis.back().back() ; + } +}; diff --git a/solution/0065.Valid/Solution.py b/solution/0065.Valid/Solution.py new file mode 100644 index 0000000000000..2d0c1e35984e5 --- /dev/null +++ b/solution/0065.Valid/Solution.py @@ -0,0 +1,17 @@ +class Solution: + def isNumber(self, s): + """ + :type s: str + :rtype: bool + """ + + NumberRE = "[\+\-]?((\d+\.?\d*|\d*\.?\d+)(e[\+\-]?\d+)?)" + + s = s.strip() + + Ans = re.match(NumberRE, s) + + if Ans and len(s) == Ans.regs[0][1] : + return True + + return False diff --git a/solution/0066.Plus One/Solution2.js b/solution/0066.Plus One/Solution2.js new file mode 100644 index 0000000000000..4041fdb3835e9 --- /dev/null +++ b/solution/0066.Plus One/Solution2.js @@ -0,0 +1,18 @@ +/** + * @param {number[]} digits + * @return {number[]} + */ +var plusOne = function(digits) { + for (let i = digits.length - 1; i >= 0; i--) { + if (digits[i] < 9) { + digits[i]++ + break + } else { + digits[i] = 0 + } + } + if (digits[0] == 0) { + digits.unshift(1) + } + return digits +}; diff --git a/solution/0069.Sqrt(x)/Solution.java b/solution/0069.Sqrt(x)/Solution.java new file mode 100644 index 0000000000000..26cbcb7160490 --- /dev/null +++ b/solution/0069.Sqrt(x)/Solution.java @@ -0,0 +1,8 @@ +class Solution { + public int mySqrt(int x) { + if(x==0)return 0; + long i=x; + while(i>x/i) i = (i + x / i) / 2; + return (int)i; + } +} \ No newline at end of file diff --git a/solution/0069.Sqrt(x)/Solution.js b/solution/0069.Sqrt(x)/Solution.js new file mode 100644 index 0000000000000..49c3dd5eeb1a5 --- /dev/null +++ b/solution/0069.Sqrt(x)/Solution.js @@ -0,0 +1,18 @@ +/** + * @param {number} x + * @return {number} + */ +var mySqrt = function(x) { + var left = 1 + var right = x + var middle = Math.floor((left + right) / 2) + while( middle !== left ) { + if (middle * middle <= x) { + left = middle + } else { + right = middle + } + middle = Math.floor((left + right) / 2) + } + return middle +}; diff --git a/solution/0071.Simplify Path/Solution.java b/solution/0071.Simplify Path/Solution.java new file mode 100644 index 0000000000000..357a883e21233 --- /dev/null +++ b/solution/0071.Simplify Path/Solution.java @@ -0,0 +1,26 @@ +class Solution { + public String simplifyPath(String path) { + List dirs = new ArrayList<>(); + int dirStart = 0, len = path.length(); + while (dirStart < len) { + while (dirStart < len && path.charAt(dirStart) == '/') dirStart++; + int dirEnd = dirStart; + while (dirEnd < len && path.charAt(dirEnd) != '/') dirEnd++; + String dir = path.substring(dirStart, dirEnd); + if (!".".equals(dir)) { + if ("..".equals(dir)) { + if (! dirs.isEmpty()) dirs.remove(dirs.size() - 1); + } else if (dir.length() > 0) { + dirs.add(dir); + } + } + dirStart = ++dirEnd; + } + StringBuilder sb = new StringBuilder("/"); + for (int i = 0; i < dirs.size(); i++) { + if (i == dirs.size() - 1) sb.append(dirs.get(i)); + else sb.append(dirs.get(i)).append("/"); + } + return sb.toString(); + } +} \ No newline at end of file diff --git a/solution/0072.Edit Distance/Solution.java b/solution/0072.Edit Distance/Solution.java new file mode 100644 index 0000000000000..afa7cf33a08da --- /dev/null +++ b/solution/0072.Edit Distance/Solution.java @@ -0,0 +1,15 @@ +class Solution { + public int minDistance(String word1, String word2) { + return edit(word1.length(),word2.length(),word1,word2,new int[word1.length()+1][word2.length()+1]); + } + private int edit(int l, int r, String w1, String w2, int[][] dp){ + if(l==0) return r; + if(r==0) return l; + if(dp[l][r]!=0) return dp[l][r]; + int min = (w1.charAt(l-1)!=w2.charAt(r-1)) ? + Math.min(edit(l-1,r-1,w1,w2,dp)+1,Math.min(edit(l-1,r,w1,w2,dp)+1,edit(l,r-1,w1,w2,dp)+1)) + : edit(l - 1, r - 1, w1, w2, dp); + dp[l][r] = min; + return min; + } +} \ No newline at end of file diff --git a/solution/0073.Set Matrix Zeroes/Solution.java b/solution/0073.Set Matrix Zeroes/Solution.java new file mode 100644 index 0000000000000..07a49f29b6204 --- /dev/null +++ b/solution/0073.Set Matrix Zeroes/Solution.java @@ -0,0 +1,20 @@ +class Solution { + public void setZeroes(int[][] matrix) { + int matrixRow = matrix.length, matrixCol = matrix[0].length; + boolean[] row = new boolean[matrixRow], col = new boolean[matrixCol]; + for (int i = 0; i < matrixRow; i++) { + for (int j = 0; j < matrixCol; j++) { + if (matrix[i][j] == 0) { + row[i] = true; + col[j] = true; + } + } + } + for (int i = 0; i < matrixRow; i++) { + if (row[i]) for (int k = 0; k < matrixCol; k++) matrix[i][k] = 0; + } + for (int j = 0; j < matrixCol; j++) { + if (col[j]) for (int k = 0; k < matrixRow; k++) matrix[k][j] = 0; + } + } +} \ No newline at end of file diff --git a/solution/0074.Search a 2D Matrix/Solution.java b/solution/0074.Search a 2D Matrix/Solution.java new file mode 100644 index 0000000000000..ada311d7701c5 --- /dev/null +++ b/solution/0074.Search a 2D Matrix/Solution.java @@ -0,0 +1,14 @@ +class Solution { + public boolean searchMatrix(int[][] matrix, int target) { + int x = 0,y = matrix.length-1; + if(y<0) return false; + int maxX = matrix[0].length-1; + while ((x <= maxX) && (y >= 0)) { + int cur = matrix[y][x]; + if (cur == target) return false; + if (cur < target) x++; + else y--; + } + return false; + } +} \ No newline at end of file diff --git a/solution/0075.Sort Colors/Solution2.cpp b/solution/0075.Sort Colors/Solution2.cpp new file mode 100644 index 0000000000000..81272de3ef3cb --- /dev/null +++ b/solution/0075.Sort Colors/Solution2.cpp @@ -0,0 +1,19 @@ +// 三路partition算法(0ms) +class Solution { +public: + void sortColors(vector& nums) { + vector::iterator next_lower = nums.begin() ; + vector::iterator next_cmp = nums.begin() ; + vector::iterator next_bigger = nums.end()-1 ; + + while (next_cmp <= next_bigger) + { + if (*next_cmp < 1) + swap(*next_lower++, *next_cmp++) ; + else if (*next_cmp > 1) + swap(*next_bigger--, *next_cmp) ; + else + ++next_cmp ; + } + } +}; diff --git a/solution/0076.Minimum Window Substring/Solution.java b/solution/0076.Minimum Window Substring/Solution.java new file mode 100644 index 0000000000000..6d9ffff906548 --- /dev/null +++ b/solution/0076.Minimum Window Substring/Solution.java @@ -0,0 +1,28 @@ +class Solution { + public String minWindow(String s, String t) { + int[] count = new int['z' - 'A' + 1]; + int uniq = 0; + for (int i = 0; i < t.length(); ++i) { + if (++count[t.charAt(i) - 'A'] == 1) uniq++; + } + int found = 0,i = 0,j = 0; + int minLen = Integer.MAX_VALUE; + int minJ = Integer.MAX_VALUE; + while (found < uniq) { + while (i < s.length()) { + if (found >= uniq) break; + if (--count[s.charAt(i) - 'A'] == 0) found++; + i++; + } + if (found < uniq) break; + while (j < i && count[s.charAt(j) - 'A'] < 0) count[s.charAt(j++) - 'A']++; + if (i - j < minLen) { + minLen = i - j; + minJ = j; + } + count[s.charAt(j++) - 'A']++; + found--; + } + return minLen < Integer.MAX_VALUE ? s.substring(minJ, minJ + minLen) : ""; + } +} \ No newline at end of file diff --git a/solution/0077.Combinations/Solution.java b/solution/0077.Combinations/Solution.java new file mode 100644 index 0000000000000..eff0327dbefab --- /dev/null +++ b/solution/0077.Combinations/Solution.java @@ -0,0 +1,21 @@ +class Solution { + + private List> result; + + public List> combine(int n, int k) { + result = new ArrayList<>(); + combine(n-k+1,k,0,1,new Integer[k]); + return result; + } + + private void combine(int n, int k, int i, int start, Integer[] list) { + if (i==k) { + result.add(new ArrayList<>(Arrays.asList(list))); + return; + } + for (int j = start; j <= n+i; j++) { + list[i] = j; + combine(n,k,i+1,j+1,list); + } + } +} \ No newline at end of file diff --git a/solution/0078.Subsets/Solution.java b/solution/0078.Subsets/Solution.java new file mode 100644 index 0000000000000..000aa6e87f700 --- /dev/null +++ b/solution/0078.Subsets/Solution.java @@ -0,0 +1,18 @@ +class Solution { + public List> subsets(int[] nums) { + List> list = new ArrayList<>(); + for (int num : nums) { + int size = list.size(); + for (int j = 0; j < size; j++) { + List temp = new ArrayList<>(list.get(j)); + temp.add(num); + list.add(temp); + } + List one = new ArrayList<>(); + one.add(num); + list.add(one); + } + list.add(new ArrayList<>()); + return list; + } +} \ No newline at end of file diff --git a/solution/0079.Word Search/Solution.java b/solution/0079.Word Search/Solution.java new file mode 100644 index 0000000000000..4e72dbccb9a0a --- /dev/null +++ b/solution/0079.Word Search/Solution.java @@ -0,0 +1,30 @@ +class Solution { + private char[] cs; + private char[][] board; + public boolean exist(char[][] board, String word) { + this.cs = word.toCharArray(); + this.board = board; + for (int i = 0; i < board.length; i++) { + for (int j = 0; j < board[i].length; j++) { + if (board[i][j] == cs[0] && backtrack(i, j, 0)) return true; + } + } + return false; + } + private boolean backtrack(int i, int j, int k) { + if (board[i][j] == cs[k]) { + if (k == cs.length - 1) return true; + char cache = board[i][j]; + board[i][j] = 0; + k++; + if ( i > 0 && backtrack(i - 1, j, k) + || i < board.length - 1 && backtrack(i + 1, j, k) + || j > 0 && backtrack(i, j - 1, k) + || j < board[i].length - 1 && backtrack(i, j + 1, k)) { + return true; + } + board[i][j] = cache; + } + return false; + } +} \ No newline at end of file diff --git a/solution/0080.Remove Duplicates from Sorted Array II/Solution.java b/solution/0080.Remove Duplicates from Sorted Array II/Solution.java new file mode 100644 index 0000000000000..94d98aff807bc --- /dev/null +++ b/solution/0080.Remove Duplicates from Sorted Array II/Solution.java @@ -0,0 +1,15 @@ +class Solution { + public int removeDuplicates(int[] nums) { + if (nums.length<3) return nums.length; + int pos = 1,flag = 1,last = nums[0]; + for(int i = 1;i nums[mid] && target <= nums[end]) start = mid + 1; + else end = mid - 1; + } else if (nums[mid] > nums[start] || nums[mid] > nums[end]) { + if (target < nums[mid] && target >= nums[start]) end = mid - 1; + else start = mid + 1; + } else end--; + } + return false; + } +} \ No newline at end of file diff --git a/solution/0083.Remove Duplicates from Sorted List/Solution.js b/solution/0083.Remove Duplicates from Sorted List/Solution.js new file mode 100644 index 0000000000000..a7236a1b8f10c --- /dev/null +++ b/solution/0083.Remove Duplicates from Sorted List/Solution.js @@ -0,0 +1,23 @@ +/** + * Definition for singly-linked list. + * function ListNode(val) { + * this.val = val; + * this.next = null; + * } + */ +/** + * @param {ListNode} head + * @return {ListNode} + */ +var deleteDuplicates = function(head) { + var p = head; + while (p && p.next) { + if (p.val == p.next.val) { + p.next = p.next.next; + } else { + p = p.next; + } + } + return head; + +}; diff --git a/solution/0085.Maximal Rectangle/Solution.java b/solution/0085.Maximal Rectangle/Solution.java new file mode 100644 index 0000000000000..e5c3d41328e46 --- /dev/null +++ b/solution/0085.Maximal Rectangle/Solution.java @@ -0,0 +1,32 @@ +class Solution { + public int maximalRectangle(char[][] matrix) { + if(matrix==null || matrix.length==0) return 0; + int result = 0; + int[] row = new int[matrix[0].length]; + for(char[] line : matrix){ + update(line,row); + result = Math.max(result, largestRectangleArea(row)); + } + return result; + } + private int largestRectangleArea(int[] heights) { + int[] stack = new int[1 << 10]; + int length = heights.length; + int j, stackSize= 0, ma = 0, a; + for (int i = 0; i <= length; i++) { + while (stackSize > 0 &&( i==length || heights[i] < heights[stack[stackSize - 1]])) { + j = stack[--stackSize]; + a = (i - (stackSize == 0 ? 0 : stack[stackSize - 1] + 1)) * (heights[j]); + if (a > ma) ma = a; + } + stack[stackSize++] = i; + } + return ma; + } + private void update(char[] line, int[] row){ + for (int i = 0; i < row.length; i++) { + if (line[i] == '0') row[i] = 0; + else row[i]++; + } + } +} \ No newline at end of file diff --git a/solution/0086.Partition List/Solution.cpp b/solution/0086.Partition List/Solution.cpp new file mode 100644 index 0000000000000..20aa01cabe101 --- /dev/null +++ b/solution/0086.Partition List/Solution.cpp @@ -0,0 +1,34 @@ +/** + * Definition for singly-linked list. + * struct ListNode { + * int val; + * ListNode *next; + * ListNode(int x) : val(x), next(NULL) {} + * }; + */ +class Solution { +public: + ListNode* partition(ListNode* head, int x) { + ListNode headSmaller(0), headBigger(0) ; + ListNode *pSmaller = &headSmaller ; + ListNode *pBigger = &headBigger ; + ListNode *p = head ; + while (nullptr != p) + { + if (p->val < x) + { + pSmaller->next = p ; + pSmaller = p ; + } + else + { + pBigger->next = p ; + pBigger = p ; + } + p = p->next ; + } + pBigger->next = nullptr ; + pSmaller->next = headBigger.next ; + return headSmaller.next ; + } +}; diff --git a/solution/0087.Scramble String/Solution.java b/solution/0087.Scramble String/Solution.java new file mode 100644 index 0000000000000..a308f6ecd4ae3 --- /dev/null +++ b/solution/0087.Scramble String/Solution.java @@ -0,0 +1,21 @@ +class Solution { + public boolean isScramble(String s1, String s2) { + if(s1.equals(s2)) return true; + if(s1.length()!=s2.length()) return false; + int len = s1.length(); + int[] count = new int[26]; + for(int i = 0; i < len; i++){ + count[s1.charAt(i) - 'a']++; + count[s2.charAt(i) - 'a']--; + } + for(int item : count) if (item != 0) return false; + for(int i = 1; i <= len - 1; i++){ + if(isScramble(s1.substring(0, i), s2.substring(0, i)) && isScramble(s1.substring(i), s2.substring(i))) + return true; + if (isScramble(s1.substring(0, i), s2.substring(len - i)) && + isScramble(s1.substring(i), s2.substring(0, len - i))) + return true; + } + return false; + } +} \ No newline at end of file diff --git a/solution/0088.Merge Sorted Array/Solution.java b/solution/0088.Merge Sorted Array/Solution.java new file mode 100644 index 0000000000000..96e4660207a8c --- /dev/null +++ b/solution/0088.Merge Sorted Array/Solution.java @@ -0,0 +1,12 @@ +class Solution { + public void merge(int[] nums1, int m, int[] nums2, int n) { + int index = m+n-1; + int index1 = m-1; + int index2 = n-1; + while(index1>=0&&index2>=0){ + if (nums1[index1]=0) nums1[index--] = nums2[index2--]; + } +} \ No newline at end of file diff --git a/solution/0089.Gray Code/Solution.java b/solution/0089.Gray Code/Solution.java new file mode 100644 index 0000000000000..49fb61c6aa79a --- /dev/null +++ b/solution/0089.Gray Code/Solution.java @@ -0,0 +1,7 @@ +class Solution { + public List grayCode(int n) { + List re = new ArrayList<>(); + for (int i = 0; i < (1 << n); i++) re.add(i ^ (i >> 1)); + return re; + } +} \ No newline at end of file diff --git a/solution/0090.Subsets II/Solution.java b/solution/0090.Subsets II/Solution.java new file mode 100644 index 0000000000000..1b17b5398381f --- /dev/null +++ b/solution/0090.Subsets II/Solution.java @@ -0,0 +1,19 @@ +class Solution { + public List> subsetsWithDup(int[] nums) { + List> res = new ArrayList<>(); + if(nums==null||nums.length==0) return res; + Arrays.sort(nums); + backTrack(res, nums, 0, new ArrayList<>()); + return res; + } + private void backTrack(List> res, int[] nums, int index, List ls){ + res.add(new ArrayList<>(ls)); + if(index>=nums.length) return; + for(int i=index;i Fun(vector &keys, int counts[]) + { + vector item ; + for (int i = 0; i < keys.size(); ++i) + { + for (int j = 0; j < counts[i]; ++j) + item.push_back(keys[i]) ; + } + return item ; + } +public: + vector> subsetsWithDup(vector& nums) { + if (nums.size() == 0) + return {} ; + vector> res ; + + sort(nums.begin(), nums.end()) ; + const int len = nums.size() ; + nums.push_back(nums[0] - 1) ; //哨兵 + + vector cnts ; + vector keys ; + for (int i = 0, cnt = 1; i < len; ++i) + { + if (nums[i] != nums[i+1]) + { + keys.push_back(nums[i]) ; + cnts.push_back(cnt) ; + // cout << "[" << nums[i] << "]: " << cnt << endl ; + cnt = 1 ; + } + else + ++cnt ; + } + + int counts[cnts.size()] = {0, } ; + int i ; + while (true) + { + res.push_back(Fun(keys, counts)); + ++counts[0] ; + for (i = 0; i < cnts.size(); ++i) + { + if (counts[i] > cnts[i]) + { + if (i+1 == cnts.size()) + { + ++i ; + break ; + } + ++counts[i+1] ; + counts[i] = 0 ; + } + else + break ; + } + if (i >= cnts.size()) + break ; + } + return res ; + } +}; diff --git a/solution/0091.Decode Ways/Solution.java b/solution/0091.Decode Ways/Solution.java new file mode 100644 index 0000000000000..ed64fc4ce1e9f --- /dev/null +++ b/solution/0091.Decode Ways/Solution.java @@ -0,0 +1,19 @@ +class Solution { + public int numDecodings(String s) { + int len = s.length(); + if (len == 0) return 0; + int current = s.charAt(0) == '0' ? 0 : 1; + int last = 1; + for (int i = 1; i < len; i++) { + int tmp = current; + if(s.charAt(i) == '0'){ + if(s.charAt(i-1) == '1' || s.charAt(i-1) == '2') current = last; + else return 0; + }else if(s.charAt(i-1) == '1' || s.charAt(i-1) == '2' && s.charAt(i) <= '6') { + current += last; + } + last = tmp; + } + return current; + } +} \ No newline at end of file diff --git a/solution/0092.Reverse Linked List II/Solution.cpp b/solution/0092.Reverse Linked List II/Solution.cpp new file mode 100644 index 0000000000000..089c5bf8d8d8f --- /dev/null +++ b/solution/0092.Reverse Linked List II/Solution.cpp @@ -0,0 +1,40 @@ +/** + * Definition for singly-linked list. + * struct ListNode { + * int val; + * ListNode *next; + * ListNode(int x) : val(x), next(NULL) {} + * }; + */ +class Solution { +public: + ListNode* reverseBetween(ListNode* head, int m, int n) { + ListNode headNode(0) ; + headNode.next = head ; + + n = n-m+1 ; + + ListNode *p = &headNode ; + while (--m) // 移动m-1次,故--m + p = p->next ; + + ListNode revNode(0) ; + ListNode *pRev = &revNode ; + pRev->next = nullptr ; + ListNode *pN = p->next ; + + ListNode *pTmp ; + while (n--) + { + pTmp = p->next ; + p->next = p->next->next ; + pTmp->next = pRev->next ; + pRev->next = pTmp ; + } + + pN->next = p->next ; + p->next = revNode.next ; + + return headNode.next ; + } +}; diff --git a/solution/0093.Restore IP Addresses/Solution.cpp b/solution/0093.Restore IP Addresses/Solution.cpp new file mode 100644 index 0000000000000..86376c5a0fbab --- /dev/null +++ b/solution/0093.Restore IP Addresses/Solution.cpp @@ -0,0 +1,54 @@ +class Solution { +private: + inline string Check(string &s, int widths[]) + { + widths[1] += widths[0] ; + widths[2] += widths[1] ; + widths[3] = s.length() - widths[2] ; + + if (widths[3] < 1 || widths[3] > 3 ) + return "" ; + + widths[3] = s.length() ; + + for (int seg = 0; seg < 4; ++seg) + { + int num = 0 ; + for (int i = (seg == 0? 0: widths[seg-1]); i < widths[seg]; ++i) + { + num *= 10 ; + num += s[i] - '0' ; + } + if (num > 255) + return "" ; + + int w = widths[seg] - (seg == 0? 0: widths[seg-1]) ; + if (w == 3 && num < 100) + return "" ; + if (w == 2 && num < 10) + return "" ; + } + string res = s ; + for (int i = 2; i >= 0; --i) + res.insert(widths[i], ".") ; + + return res ; + } +public: + vector restoreIpAddresses(string s) { + int widths[4] ; + vector res ; + for (int i = 0; i < 27; ++i) + { + widths[0] = 1 + i%3 ; + widths[1] = 1 + i/3%3 ; + widths[2] = 1 + i/9 ; + + string tmp = Check(s, widths) ; + if (tmp.size() != 0) + res.push_back(tmp) ; + } + + return res; + } +}; diff --git a/solution/0093.Restore IP Addresses/Solution.java b/solution/0093.Restore IP Addresses/Solution.java new file mode 100644 index 0000000000000..e826d75fd0627 --- /dev/null +++ b/solution/0093.Restore IP Addresses/Solution.java @@ -0,0 +1,33 @@ +class Solution { + private List result; + private int length; + public List restoreIpAddresses(String s) { + result = new ArrayList<>(); + length = s.length(); + int[] ip = new int[4]; + restoreIpAddresses(s,0,ip,0); + return result; + } + private void restoreIpAddresses(String s, int si, int[] ip, int pi) { + int sl = length - si , pl = 3 - pi , i = -1; + String pfx = null; + while (si< length){ + int num = s.charAt(si++) - '1' + 1; + if (i==0) break; + i = i == -1 ? num : i * 10 + num; + sl--; + if (i>255) break; + if (sl < pl || sl > pl * 3) continue; + if (pi==3){ + if (pfx==null){ + StringBuilder pfxBuilder = new StringBuilder(); + for (int j = 0; j < ip.length-1; j++) pfxBuilder.append(ip[j]).append('.'); + pfx = pfxBuilder.toString(); + } + result.add(pfx + i); + } + ip[pi] = i; + restoreIpAddresses(s,si,ip,pi+1); + } + } +} \ No newline at end of file diff --git a/solution/0095.Unique Binary Search Trees II/Solution.java b/solution/0095.Unique Binary Search Trees II/Solution.java new file mode 100644 index 0000000000000..5301b02faeba1 --- /dev/null +++ b/solution/0095.Unique Binary Search Trees II/Solution.java @@ -0,0 +1,26 @@ +class Solution { + public List generateTrees(int n) { + if (n <= 0) return new ArrayList<>(); + return generateTrees(1, n); + } + private List generateTrees(int left, int right) { + List list = new ArrayList<>(); + if (left > right) { + list.add(null); + } else { + for (int i = left; i <= right; i++) { + List leftTrees = generateTrees(left, i - 1); + List rightTrees = generateTrees(i + 1, right); + for (TreeNode l : leftTrees) { + for (TreeNode r : rightTrees) { + TreeNode root = new TreeNode(i); + root.left = l; + root.right = r; + list.add(root); + } + } + } + } + return list; + } +} \ No newline at end of file diff --git a/solution/0097.Interleaving String/Solution.java b/solution/0097.Interleaving String/Solution.java new file mode 100644 index 0000000000000..2c01f30e26973 --- /dev/null +++ b/solution/0097.Interleaving String/Solution.java @@ -0,0 +1,16 @@ +public class Solution { + public boolean isInterleave(String s1, String s2, String s3) { + char[] c1 = s1.toCharArray(), c2 = s2.toCharArray(), c3 = s3.toCharArray(); + int m = s1.length(), n = s2.length(); + if(m + n != s3.length()) return false; + return dfs(c1, c2, c3, 0, 0, 0, new boolean[m + 1][n + 1]); + } + private boolean dfs(char[] c1, char[] c2, char[] c3, int i, int j, int k, boolean[][] invalid) { + if(invalid[i][j]) return false; + if(k == c3.length) return true; + boolean valid = i < c1.length && c1[i] == c3[k] && dfs(c1, c2, c3, i + 1, j, k + 1, invalid) || + j < c2.length && c2[j] == c3[k] && dfs(c1, c2, c3, i, j + 1, k + 1, invalid); + if(!valid) invalid[i][j] = true; + return valid; + } +} \ No newline at end of file diff --git a/solution/0098.Validate Binary Search Tree/Solution.cpp b/solution/0098.Validate Binary Search Tree/Solution.cpp new file mode 100644 index 0000000000000..8fffd05a31ffb --- /dev/null +++ b/solution/0098.Validate Binary Search Tree/Solution.cpp @@ -0,0 +1,38 @@ +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode(int x) : val(x), left(NULL), right(NULL) {} + * }; + */ +class Solution { +public: + + void traverse(TreeNode* root, vector &elements){ + + if( root->left != NULL ) + traverse(root->left, elements); + + elements.push_back(root->val); + + if( root->right != NULL ) + traverse(root->right, elements); + } + + bool isValidBST(TreeNode* root) { + + if( root == NULL ) + return true; + + vector elements; + traverse(root, elements); + + for(int i = 0 ; i < elements.size() - 1 ; i++) + if( elements[i] >= elements[i + 1] ) + return false; + + return true; + } +}; diff --git a/solution/0098.Validate Binary Search Tree/Solution.java b/solution/0098.Validate Binary Search Tree/Solution.java new file mode 100644 index 0000000000000..8835f3f767610 --- /dev/null +++ b/solution/0098.Validate Binary Search Tree/Solution.java @@ -0,0 +1,13 @@ +class Solution { + + private long current = Long.MIN_VALUE; + + public boolean isValidBST(TreeNode root) { + if (root == null) return true; + if (isValidBST(root.left) && current < root.val) { + current = root.val; + return isValidBST(root.right); + } + return false; + } +} \ No newline at end of file diff --git a/solution/0099.Recover Binary Search Tree/Solution.java b/solution/0099.Recover Binary Search Tree/Solution.java new file mode 100644 index 0000000000000..0ba46b97e406f --- /dev/null +++ b/solution/0099.Recover Binary Search Tree/Solution.java @@ -0,0 +1,19 @@ +class Solution { + private TreeNode first,second,pre; + public void recoverTree(TreeNode root) { + traverse(root); + int temp = first.val; + first.val = second.val; + second.val = temp; + } + private void traverse(TreeNode root) { + if (root == null) return; + traverse(root.left); + if (pre != null) { + if (first == null && pre.val > root.val) first = pre; + if (first != null && pre.val > root.val) second = root; + } + pre = root; + traverse(root.right); + } +} \ No newline at end of file diff --git a/solution/0100.Same Tree/Solution.java b/solution/0100.Same Tree/Solution.java new file mode 100644 index 0000000000000..c7200b7d6225b --- /dev/null +++ b/solution/0100.Same Tree/Solution.java @@ -0,0 +1,7 @@ +class Solution { + public boolean isSameTree(TreeNode p, TreeNode q) { + if (p==null && q==null) return true; + if (p==null || q==null || p.val!=q.val) return false; + return isSameTree(p.left,q.left) && isSameTree(p.right,q.right); + } +} \ No newline at end of file diff --git a/solution/0101.Symmetric Tree/Solution.java b/solution/0101.Symmetric Tree/Solution.java new file mode 100644 index 0000000000000..f8e82632c5b09 --- /dev/null +++ b/solution/0101.Symmetric Tree/Solution.java @@ -0,0 +1,12 @@ +class Solution { + public boolean isSymmetric(TreeNode root) { + if(root == null) return true; + return isSymmetric(root.left, root.right); + } + public boolean isSymmetric(TreeNode leftNode, TreeNode rightNode) { + if(leftNode == null && rightNode == null) return true; + if(leftNode == null || rightNode == null) return false; + return leftNode.val == rightNode.val && isSymmetric(leftNode.left, rightNode.right) && + isSymmetric(leftNode.right, rightNode.left); + } +} \ No newline at end of file diff --git a/solution/0103.Binary Tree Zigzag Level Order Traversal/Solution.java b/solution/0103.Binary Tree Zigzag Level Order Traversal/Solution.java new file mode 100644 index 0000000000000..97561dfd56018 --- /dev/null +++ b/solution/0103.Binary Tree Zigzag Level Order Traversal/Solution.java @@ -0,0 +1,21 @@ +class Solution { + private List> list; + public List> zigzagLevelOrder(TreeNode root) { + list = new ArrayList<>(); + lever(root, 0); + for (int i = 1; i < list.size(); i = i + 2) { + List nList = list.get(i); + List nnl = new ArrayList<>(); + for (int j = nList.size() - 1; j >= 0; j--) nnl.add(nList.get(j)); + list.set(i, nnl); + } + return list; + } + private void lever(TreeNode root, int l) { + if (root == null) return; + while (l > list.size() - 1) list.add(new ArrayList<>()); + list.get(l++).add(root.val); + lever(root.left, l); + lever(root.right, l); + } +} \ No newline at end of file diff --git a/solution/0104.Maximum Depth of Binary Tree/Solution.java b/solution/0104.Maximum Depth of Binary Tree/Solution.java new file mode 100644 index 0000000000000..b04ecfbc6beb9 --- /dev/null +++ b/solution/0104.Maximum Depth of Binary Tree/Solution.java @@ -0,0 +1,6 @@ +class Solution { + public int maxDepth(TreeNode root) { + if (root == null) return 0; + return Integer.max(maxDepth(root.left), maxDepth(root.right)) + 1; + } +} \ No newline at end of file diff --git a/solution/0107.Binary Tree Level Order Traversal II/Solution.java b/solution/0107.Binary Tree Level Order Traversal II/Solution.java new file mode 100644 index 0000000000000..a848c93c7f91f --- /dev/null +++ b/solution/0107.Binary Tree Level Order Traversal II/Solution.java @@ -0,0 +1,23 @@ +class Solution { + List> lists; + public List> levelOrderBottom(TreeNode root) { + lists = new ArrayList<>(); + levelOrderBottom(root,0); + List> result = new ArrayList<>(); + for (int i = lists.size() - 1; i >= 0; i--) result.add(lists.get(i)); + return result; + } + private void levelOrderBottom(TreeNode root, int i) { + if (root==null) return; + List list; + if (i==lists.size()){ + list = new ArrayList<>(); + lists.add(list); + }else { + list = lists.get(i); + } + list.add(root.val); + levelOrderBottom(root.left,i+1); + levelOrderBottom(root.right,i+1); + } +} \ No newline at end of file diff --git a/solution/0108.Convert Sorted Array to Binary Search Tree/Solution.java b/solution/0108.Convert Sorted Array to Binary Search Tree/Solution.java new file mode 100644 index 0000000000000..66726b6054e1e --- /dev/null +++ b/solution/0108.Convert Sorted Array to Binary Search Tree/Solution.java @@ -0,0 +1,15 @@ +class Solution { + public TreeNode sortedArrayToBST(int[] nums) { + int len = nums.length; + if (len == 0) return null; + return helper(nums, 0, len - 1); + } + private TreeNode helper(int[] arr, int start, int end) { + if (start > end) return null; + int middle = (end + start) / 2; + TreeNode helperRoot = new TreeNode(arr[middle]); + helperRoot.left = helper(arr, start, middle - 1); + helperRoot.right = helper(arr, middle + 1, end); + return helperRoot; + } +} \ No newline at end of file diff --git a/solution/0109.Convert Sorted List to Binary Search Tree/Solution.java b/solution/0109.Convert Sorted List to Binary Search Tree/Solution.java new file mode 100644 index 0000000000000..f6693a30d8c3a --- /dev/null +++ b/solution/0109.Convert Sorted List to Binary Search Tree/Solution.java @@ -0,0 +1,19 @@ +class Solution { + public TreeNode sortedListToBST(ListNode head) { + if(head==null) return null; + if(head.next==null) return new TreeNode(head.val); + ListNode slow = head; + ListNode fast = head; + ListNode prev = null; + while(fast!=null && fast.next!=null){ + prev = slow; + slow=slow.next; + fast=fast.next.next; + } + TreeNode root = new TreeNode(Objects.requireNonNull(prev).next.val); + prev.next = null; + root.left = sortedListToBST(head); + root.right = sortedListToBST(slow.next); + return root; + } +} \ No newline at end of file diff --git a/solution/0110.Balanced Binary Tree/Solution.java b/solution/0110.Balanced Binary Tree/Solution.java new file mode 100644 index 0000000000000..c63d5e80d615c --- /dev/null +++ b/solution/0110.Balanced Binary Tree/Solution.java @@ -0,0 +1,13 @@ +class Solution { + public boolean isBalanced(TreeNode root) { + return depth(root) != -1; + } + private int depth(TreeNode root) { + if (root == null) return 0; + int left = depth(root.left); + if (left == -1) return -1; + int right = depth(root.right); + if (right == -1 || Math.abs(left - right) > 1) return -1; + return Math.max(left, right) + 1; + } +} \ No newline at end of file diff --git a/solution/0111.Minimum Depth of Binary Tree/Solution.java b/solution/0111.Minimum Depth of Binary Tree/Solution.java new file mode 100644 index 0000000000000..7dcdb2c7dee9b --- /dev/null +++ b/solution/0111.Minimum Depth of Binary Tree/Solution.java @@ -0,0 +1,11 @@ +class Solution { + public int minDepth(TreeNode root) { + if(root == null) return 0; + if(root.left==null && root.right==null) return 1; + int leftDepth = minDepth(root.left); + if(leftDepth==0) leftDepth = Integer.MAX_VALUE; + int rightDepth = minDepth(root.right); + if(rightDepth==0) rightDepth = Integer.MAX_VALUE; + return Math.min(leftDepth,rightDepth)+1; + } +} \ No newline at end of file diff --git a/solution/0112.Path Sum/Solution.java b/solution/0112.Path Sum/Solution.java new file mode 100644 index 0000000000000..17d54d03bb417 --- /dev/null +++ b/solution/0112.Path Sum/Solution.java @@ -0,0 +1,8 @@ +class Solution { + public boolean hasPathSum(TreeNode root, int sum) { + if (root == null) return false; + sum -= root.val; + return (root.left == null && root.right == null && sum == 0) || + hasPathSum(root.left, sum) || hasPathSum(root.right, sum); + } +} \ No newline at end of file diff --git a/solution/0113.Path Sum II/Solution.java b/solution/0113.Path Sum II/Solution.java new file mode 100644 index 0000000000000..37ce2cfc9ffcf --- /dev/null +++ b/solution/0113.Path Sum II/Solution.java @@ -0,0 +1,20 @@ +class Solution { + private List> result = new ArrayList<>(); + public List> pathSum(TreeNode root, int sum) { + pathSum(root,new ArrayList<>(),sum); + return result; + } + private void pathSum(TreeNode root, List list, int sum) { + if (root==null) return; + sum = sum - root.val; + list.add(root.val); + if (root.left==null && root.right==null){ + ArrayList integers = new ArrayList<>(list); + if (sum==0) result.add(integers); + } else { + pathSum(root.left,list,sum); + pathSum(root.right,list,sum); + } + list.remove(list.size()-1); + } +} \ No newline at end of file diff --git a/solution/0114.Flatten Binary Tree to Linked List/Solution.java b/solution/0114.Flatten Binary Tree to Linked List/Solution.java new file mode 100644 index 0000000000000..72a752b70d9bd --- /dev/null +++ b/solution/0114.Flatten Binary Tree to Linked List/Solution.java @@ -0,0 +1,13 @@ +class Solution { + public void flatten(TreeNode root) { + if (root==null) return; + TreeNode right = root.right; + flatten(right); + flatten(root.left); + root.right = root.left; + root.left = null; + TreeNode cache = root; + while (cache.right!=null) cache = cache.right; + cache.right = right; + } +} \ No newline at end of file diff --git a/solution/0115.Distinct Subsequences/Solution.java b/solution/0115.Distinct Subsequences/Solution.java new file mode 100644 index 0000000000000..89be0bdba114c --- /dev/null +++ b/solution/0115.Distinct Subsequences/Solution.java @@ -0,0 +1,17 @@ +class Solution { + public int numDistinct(String s, String t) { + int[][] hash = new int[256][t.length() + 1]; + int[] cnt = new int[t.length() + 1]; + cnt[0] = 1; + for (int i = 0; i < t.length();) { + char c = t.charAt(i); + hash[c][++hash[c][0]] = ++i; + } + for(char c : s.toCharArray()) { + for(int i = hash[c][0]; i > 0; i--) { + cnt[hash[c][i]] += cnt[hash[c][i] - 1]; + } + } + return cnt[t.length()]; + } +} \ No newline at end of file diff --git a/solution/0116.Populating Next Right Pointers in Each Node/Solution.java b/solution/0116.Populating Next Right Pointers in Each Node/Solution.java new file mode 100644 index 0000000000000..a289983691a74 --- /dev/null +++ b/solution/0116.Populating Next Right Pointers in Each Node/Solution.java @@ -0,0 +1,10 @@ +class Solution { + public void connect(TreeLinkNode root) { + if (root == null || root.left == null) return; + root.left.next = root.right; + if (root.next == null) root.right.next = null; + else root.right.next = root.next.left; + connect(root.left); + connect(root.right); + } +} \ No newline at end of file diff --git a/solution/0117.Populating Next Right Pointers in Each Node II/Solution.java b/solution/0117.Populating Next Right Pointers in Each Node II/Solution.java new file mode 100644 index 0000000000000..0961a1d1999de --- /dev/null +++ b/solution/0117.Populating Next Right Pointers in Each Node II/Solution.java @@ -0,0 +1,28 @@ +public class Solution { + public void connect(TreeLinkNode root) { + if (root == null) return; + TreeLinkNode first_node_next_layer = null; + TreeLinkNode preNode = null; + for (TreeLinkNode curNode = root; curNode != null; curNode = curNode.next) { + if (curNode.left != null) { + if (preNode == null) { + preNode = curNode.left; + first_node_next_layer = curNode.left; + } else { + preNode.next = curNode.left; + preNode = preNode.next; + } + } + if (curNode.right != null) { + if (preNode == null) { + preNode = curNode.right; + first_node_next_layer = curNode.right; + } else { + preNode.next = curNode.right; + preNode = preNode.next; + } + } + } + connect(first_node_next_layer); + } +} \ No newline at end of file diff --git a/solution/0118.Pascal's Triangle/Solution.java b/solution/0118.Pascal's Triangle/Solution.java new file mode 100644 index 0000000000000..f8850bdae52de --- /dev/null +++ b/solution/0118.Pascal's Triangle/Solution.java @@ -0,0 +1,17 @@ +class Solution { + public List> generate(int numRows) { + List> re = new ArrayList<>(); + if (numRows == 0) return re; + re.add(Collections.singletonList(1)); + for (int i = 1; i < numRows; i++) { + List list = new ArrayList<>(); + re.add(list); + for (int j = 0; j < i + 1; j++) { + int l = j - 1 < 0 ? 0 : re.get(i - 1).get(j - 1); + int r = j > i - 1 ? 0 : re.get(i - 1).get(j); + list.add(l + r); + } + } + return re; + } +} \ No newline at end of file diff --git a/solution/0118.Pascal's Triangle/Solution.js b/solution/0118.Pascal's Triangle/Solution.js index 42c8522983df0..389a05a3cee30 100644 --- a/solution/0118.Pascal's Triangle/Solution.js +++ b/solution/0118.Pascal's Triangle/Solution.js @@ -4,7 +4,6 @@ const generate = function(numRows){ let row = []; row[0]=1; row[i] = 1; - for(let j = 1; j < row.length - 1; j++){ row[j] = arr[i-1][j-1] + arr[i-1][j]; } @@ -12,3 +11,25 @@ const generate = function(numRows){ } return arr; } + +/** + * Author: Mcnwork2018 + */ + +var generate = function(numRows) { + if (numRows === 0) return []; + if (numRows === 1) return [[1]]; + if (numRows === 2) return [[1],[1,1]]; + let triangleArray = [[1],[1,1]]; + for ( let i = 2; i < numRows; ++i ) { + triangleArray[i] = []; + for ( let j = 0; j < i + 1; ++j ) { + if ( j === 0 || j === i ) { + triangleArray[i][j] = 1; + } else { + triangleArray[i][j] = triangleArray[i-1][j-1] + triangleArray[i-1][j]; + } + } + } + return triangleArray; +}; diff --git a/solution/0119.Pascal's Triangle II/Solution.java b/solution/0119.Pascal's Triangle II/Solution.java new file mode 100644 index 0000000000000..4c37826556059 --- /dev/null +++ b/solution/0119.Pascal's Triangle II/Solution.java @@ -0,0 +1,11 @@ +class Solution { + public List getRow(int rowIndex) { + List ret = new LinkedList<>(); + long nk = 1; + for (int i = 0; i <= rowIndex; i++) { + ret.add((int) nk); + nk = nk * (rowIndex - i) / (i + 1); + } + return ret; + } +} \ No newline at end of file diff --git a/solution/0120.Triangle/Solution.java b/solution/0120.Triangle/Solution.java new file mode 100644 index 0000000000000..edba20ad2c1cd --- /dev/null +++ b/solution/0120.Triangle/Solution.java @@ -0,0 +1,18 @@ +class Solution { + private int[][] cache = null; + public int minimumTotal(List> triangle) { + int n = triangle.size(); + cache = new int[n][triangle.get(n - 1).size()]; + for (int[] row : cache) Arrays.fill(row, -1); + return dfs(triangle,0,0); + } + private int dfs(List> triangle, int row, int col) { + if (row == triangle.size()) return 0; + if (cache[row][col] != -1) return cache[row][col]; + int l = dfs(triangle,row+1,col); + int r = dfs(triangle,row+1,col+1); + int res = Math.min(l,r)+triangle.get(row).get(col); + cache[row][col] = res; + return res; + } +} \ No newline at end of file diff --git a/solution/0120.Triangle/Solution2.cpp b/solution/0120.Triangle/Solution2.cpp new file mode 100644 index 0000000000000..374ef3163a4df --- /dev/null +++ b/solution/0120.Triangle/Solution2.cpp @@ -0,0 +1,12 @@ +class Solution { +public: + int minimumTotal(vector>& triangle) { + vector dp(triangle.back()) ; + + for (int i = triangle.size()-2; i >= 0; --i) + for (int j = 0; j <= i; ++j) + dp[j] = triangle[i][j] + min(dp[j], dp[j+1]) ; + + return dp[0] ; + } +}; diff --git a/solution/0121.Best Time to Buy and Sell Stock/Solution.java b/solution/0121.Best Time to Buy and Sell Stock/Solution.java new file mode 100644 index 0000000000000..804d536b7301b --- /dev/null +++ b/solution/0121.Best Time to Buy and Sell Stock/Solution.java @@ -0,0 +1,16 @@ +class Solution { + public int maxProfit(int[] prices) { + if (prices.length == 0) return 0; + int m = prices[0] , l = 0; + for (int i = 1; i < prices.length; i++) { + int d = prices[i]; + if (d < m) { + m = d; + } else { + int n = d - m; + l = n > l ? n : l; + } + } + return l; + } +} \ No newline at end of file diff --git a/solution/0122.Best Time to Buy and Sell Stock II/Solution.java b/solution/0122.Best Time to Buy and Sell Stock II/Solution.java new file mode 100644 index 0000000000000..24ac92d267104 --- /dev/null +++ b/solution/0122.Best Time to Buy and Sell Stock II/Solution.java @@ -0,0 +1,11 @@ +class Solution { + public int maxProfit(int[] prices) { + int maxProfit = 0; + for (int i = 0; i < prices.length; i++) { + if (i + 1 < prices.length && prices[i + 1] - prices[i] > 0) { + maxProfit += prices[i + 1] - prices[i]; + } + } + return maxProfit; + } +} \ No newline at end of file diff --git a/solution/0123.Best Time to Buy and Sell Stock III/Solution.java b/solution/0123.Best Time to Buy and Sell Stock III/Solution.java new file mode 100644 index 0000000000000..40a093240e086 --- /dev/null +++ b/solution/0123.Best Time to Buy and Sell Stock III/Solution.java @@ -0,0 +1,15 @@ +class Solution { + public int maxProfit(int[] prices) { + if (prices.length <= 1) return 0; + int m = 2 , n = prices.length; + int[][] dp = new int[m+1][n]; + for (int i = 1; i <= m; i++) { + int maxdiff = Integer.MIN_VALUE; + for (int j = 1; j < n; j++) { + maxdiff = Math.max(maxdiff, dp[i-1][j-1] - prices[j-1]); + dp[i][j] = Math.max(dp[i][j-1], prices[j] + maxdiff); + } + } + return dp[m][n-1]; + } +} \ No newline at end of file diff --git a/solution/0124.Binary Tree Maximum Path Sum/Solution.java b/solution/0124.Binary Tree Maximum Path Sum/Solution.java new file mode 100644 index 0000000000000..78ed300882aab --- /dev/null +++ b/solution/0124.Binary Tree Maximum Path Sum/Solution.java @@ -0,0 +1,19 @@ +class Solution { + private int max = Integer.MIN_VALUE; + public int maxPathSum(TreeNode root) { + helper(root); + return max; + } + private int helper(TreeNode root) { + if (root == null) return 0; + if (root.left == null && root.right == null) { + max = Math.max(max, root.val); + return root.val; + } + int left = helper(root.left); + int right = helper(root.right); + int currSum = Math.max(Math.max(left + root.val, right + root.val), root.val); + max = Math.max(Math.max(currSum, left + right + root.val), max); + return currSum; + } +} \ No newline at end of file diff --git a/solution/0125.Valid Palindrome/Solution.java b/solution/0125.Valid Palindrome/Solution.java new file mode 100644 index 0000000000000..b11baef00a699 --- /dev/null +++ b/solution/0125.Valid Palindrome/Solution.java @@ -0,0 +1,34 @@ +class Solution { + public boolean isPalindrome(String s) { + if (s == null || s.length() == 0) return true; + int start = 0 , end = s.length() - 1; + while (start < end) { + char c = ' '; + while (start < end) { + c = s.charAt(start); + if (c >= 'a' && c <= 'z' || c >= '0' && c <= '9') break; + if (c >= 'A' && c <= 'Z') { + c = (char) (c - 'A' + 'a'); + break; + } + start++; + } + char b = ' '; + while (start < end) { + b = s.charAt(end); + if (b >= 'a' && b <= 'z' || b >= '0' && b <= '9') break; + if (b >= 'A' && b <= 'Z') { + b = (char) (b - 'A' + 'a'); + break; + } + end--; + } + if (start < end) { + if (c != b) return false; + start++; + end--; + } + } + return true; + } +} \ No newline at end of file diff --git a/solution/0126.Word Ladder II/Solution.java b/solution/0126.Word Ladder II/Solution.java new file mode 100644 index 0000000000000..8a8bbd943d4f4 --- /dev/null +++ b/solution/0126.Word Ladder II/Solution.java @@ -0,0 +1,64 @@ +class Solution { + private boolean isConnected = false; + private Map> hs; + public List> findLadders(String beginWord, String endWord, List wordList) { + hs = new HashMap<>(16); + List> result = new ArrayList<>(); + if(!wordList.contains(endWord)) + return result; + HashSet dict = new HashSet<>(wordList); + Set fwd = new HashSet<>(); + fwd.add(beginWord); + Set bwd = new HashSet<>(); + bwd.add(endWord); + bfs(fwd, bwd, dict, false); + if(!isConnected) return result; + List temp = new ArrayList<>(); + temp.add(beginWord); + dfs(result, temp, beginWord, endWord); + return result; + } + private void bfs(Set forward, Set backward, Set dict, boolean swap){ + if(forward.isEmpty() || backward.isEmpty()) return; + if(forward.size() > backward.size()){ + bfs(backward, forward, dict, !swap); + return; + } + dict.removeAll(forward); + dict.removeAll(backward); + Set set3 = new HashSet<>(); + for(String str : forward) + for (int i = 0; i < str.length(); i++) { + char[] ary = str.toCharArray(); + for (char j = 'a'; j <= 'z'; j++) { + ary[i] = j; + String temp = new String(ary); + if (!backward.contains(temp) && !dict.contains(temp)) continue; + String key = !swap ? str : temp; + String val = !swap ? temp : str; + if (!hs.containsKey(key)) hs.put(key, new ArrayList<>()); + if (backward.contains(temp)) { + hs.get(key).add(val); + isConnected = true; + } + if (!isConnected && dict.contains(temp)) { + hs.get(key).add(val); + set3.add(temp); + } + } + } + if(!isConnected) bfs(set3, backward, dict, swap); + } + private void dfs(List> result, List temp, String start, String end){ + if(start.equals(end)){ + result.add(new ArrayList<>(temp)); + return; + } + if(!hs.containsKey(start)) return; + for(String s : hs.get(start)){ + temp.add(s); + dfs(result, temp, s, end); + temp.remove(temp.size()-1); + } + } +} \ No newline at end of file diff --git a/solution/0128.Longest Consecutive Sequence/Solution.java b/solution/0128.Longest Consecutive Sequence/Solution.java new file mode 100644 index 0000000000000..06edbbd1fb32d --- /dev/null +++ b/solution/0128.Longest Consecutive Sequence/Solution.java @@ -0,0 +1,18 @@ +class Solution { + public int longestConsecutive(int[] nums) { + if (nums.length == 0) return 0; + Arrays.sort(nums); + int start = 0, casch = nums[0], longest = 0; + for (int i = 1; i < nums.length; i++) { + int nc = nums[i] , con = nc - casch; + if (con == 0) { + start++; + } else if (con != 1) { + longest = Math.max(i - start, longest); + start = i; + } + casch = nc; + } + return Math.max(nums.length - start, longest); + } +} \ No newline at end of file diff --git a/solution/0129.Sum Root to Leaf Numbers/Solution.java b/solution/0129.Sum Root to Leaf Numbers/Solution.java new file mode 100644 index 0000000000000..4434a2bfaac59 --- /dev/null +++ b/solution/0129.Sum Root to Leaf Numbers/Solution.java @@ -0,0 +1,11 @@ +class Solution { + public int sumNumbers(TreeNode root) { + return sumNumbers(root,0); + } + private int sumNumbers(TreeNode root, int sum) { + if (root==null) return 0; + sum = sum *10 + root.val; + if (root.left==null && root.right==null) return sum; + return sumNumbers(root.left,sum)+sumNumbers(root.right,sum); + } +} \ No newline at end of file diff --git a/solution/0130.Surrounded Regions/Solution.cpp b/solution/0130.Surrounded Regions/Solution.cpp new file mode 100644 index 0000000000000..1d4758973fb82 --- /dev/null +++ b/solution/0130.Surrounded Regions/Solution.cpp @@ -0,0 +1,50 @@ +class Solution { +private: + void dfs(vector>& b, + vector>& m, + int i, int j) + { + if (i < 0 || i >= b.size() + || j < 0 || j >= b[0].size()) + return ; + + if (b[i][j] != 'O' || m[i][j]) + return ; + + m[i][j] = true ; + dfs(b, m, i-1, j) ; + dfs(b, m, i+1, j) ; + dfs(b, m, i, j-1) ; + dfs(b, m, i, j+1) ; + } +public: + void solve(vector>& board) { + if (board.size() == 0 || board[0].size() == 0) + return ; + + vector> marks(board.size(), vector(board[0].size(), false)) ; + const int w_1 = board[0].size() - 1 ; + for (int i = 0; i < w_1; ++i) + { + if (board[0][i] == 'O') + dfs(board, marks, 0, i) ; + if (board[board.size()-1][i] == 'O') + dfs(board, marks, board.size()-1, i) ; + } + + const int h_1 = board.size() - 1 ; + for (int i = 1; i < h_1; ++i) + { + if (board[i][0] == 'O') + dfs(board, marks, i, 0) ; + if (board[i][board[0].size()-1] == 'O') + dfs(board, marks, i, board[0].size()-1) ; + } + + for (int i = 1; i < h_1; ++i) + for (int j = 1; j < w_1; ++j) + if (board[i][j] == 'O' && !marks[i][j]) + board[i][j] = 'X' ; + + } +}; diff --git a/solution/0131.Palindrome Partitioning/Solution.java b/solution/0131.Palindrome Partitioning/Solution.java new file mode 100644 index 0000000000000..dcc46aae5075d --- /dev/null +++ b/solution/0131.Palindrome Partitioning/Solution.java @@ -0,0 +1,38 @@ +class Solution { + private List> res; + public List> partition(String s) { + res= new ArrayList<>(); + func(new ArrayList<>(),0,s); + return res; + } + private void func(List temp, int start, String str){ + if(start>=str.length()){ + res.add(new ArrayList<>(temp)); + return; + } + int ed=str.indexOf(str.charAt(start),start+1); + while(ed>0){ + int s=start; + int e=ed; + boolean flag=false; + while(s=0 && j cache; + public Node cloneGraph(Node node) { + cache = new HashMap<>(16); + return helper(node); + } + private Node helper(Node node) { + if (node == null) return null; + else if (cache.containsKey(node)) return cache.get(node); + Node nodeCopy = new Node(node.val,new ArrayList<>()); + cache.put(node, nodeCopy); + for (Node neighbor : node.neighbors) nodeCopy.neighbors.add(helper(neighbor)); + return nodeCopy; + } +} \ No newline at end of file diff --git a/solution/0134.Gas Station/Solution.java b/solution/0134.Gas Station/Solution.java new file mode 100644 index 0000000000000..07ce12e4cd540 --- /dev/null +++ b/solution/0134.Gas Station/Solution.java @@ -0,0 +1,17 @@ +class Solution { + public int canCompleteCircuit(int[] gas, int[] cost) { + if(gas.length!=cost.length) return -1; + int sum=0,total=0,index=0; + for(int i=0;i wordDict) { + int wordMaxLen = Integer.MIN_VALUE; + for (String word : wordDict){ + wordMaxLen = Math.max(wordMaxLen, word.length()); + } + Set wordSet = new HashSet<>(wordDict); + int len = s.length(); + boolean[] dp = new boolean[len + 1]; + dp[0] = true; + for(int i = 1; i <= len; i++){ + for(int l = 1; l <= wordMaxLen && i - l >= 0; l++){ + if(dp[i-l] && wordSet.contains(s.substring(i-l, i))){ + dp[i] = true; + break; + } + } + } + return dp[len]; + } +} \ No newline at end of file diff --git a/solution/0140.Word Break II/Solution.java b/solution/0140.Word Break II/Solution.java new file mode 100644 index 0000000000000..7bdc27f3a5868 --- /dev/null +++ b/solution/0140.Word Break II/Solution.java @@ -0,0 +1,23 @@ +class Solution { + public List wordBreak(String s, List wordDict) { + return wordBreak(s,wordDict,new HashMap<>(16)); + } + private List wordBreak(String s, List wordDict, HashMap> map) { + List list=new ArrayList<>(); + if(map.containsKey(s)) return map.get(s); + if("".equals(s)){ + list.add(""); + return list; + } + for(String word:wordDict){ + if(s.startsWith(word)){ + List res=wordBreak(s.substring(word.length()),wordDict,map); + for(String str:res){ + list.add(word+("".equals(str) ?"":" ")+str); + } + } + } + map.put(s,list); + return list; + } +} \ No newline at end of file diff --git a/solution/0141.Linked List Cycle/Solution.js b/solution/0141.Linked List Cycle/Solution.js new file mode 100644 index 0000000000000..b2203e08904d7 --- /dev/null +++ b/solution/0141.Linked List Cycle/Solution.js @@ -0,0 +1,38 @@ +/** + * Definition for singly-linked list. + * function ListNode(val) { + * this.val = val; + * this.next = null; + * } + */ + +/** + * @param {ListNode} head + * @return {boolean} + */ +var hasCycle = function(head) { + flag = false; + + dfs(head); + + return flag; +}; +function dfs(node) { + if (flag) + return; + + if (node === null) + return; + + if (node.flag) { + flag = true; + return; + } + + if (node.next === null) + return; + + node.flag = true; + + dfs(node.next); +} \ No newline at end of file diff --git a/solution/0147.Insertion Sort List/README.md b/solution/0147.Insertion Sort List/README.md new file mode 100644 index 0000000000000..6740189e12279 --- /dev/null +++ b/solution/0147.Insertion Sort List/README.md @@ -0,0 +1,78 @@ +## 对链表进行插入排序 +### 题目描述 + +对链表进行插入排序。 + +插入排序的动画演示如上。从第一个元素开始,该链表可以被认为已经部分排序(用黑色表示)。 +每次迭代时,从输入数据中移除一个元素(用红色表示),并原地将其插入到已排好序的链表中。 + +插入排序算法: +1. 插入排序是迭代的,每次只移动一个元素,直到所有元素可以形成一个有序的输出列表。 +2. 每次迭代中,插入排序只从输入数据中移除一个待排序的元素,找到它在序列中适当的位置,并将其插入。 +3. 重复直到所有输入数据插入完为止。 + +示例1: +``` +输入: 4->2->1->3 +输出: 1->2->3->4 +``` + +示例2: +``` +输入: -1->5->3->4->0 +输出: -1->0->3->4->5 +``` +### 解法 +从链表头部开始遍历,记录当前已完成插入排序的最后一个节点。然后进行以下操作: +- 获得要插入排序的节点 curNode 、其上一个节点 perNode 、其下一个节点 nextNode; +- 判断 curNode 是否应插入在 perNode 之后,若否,将 curNode 从链表中移除准备插入,若是,无需进一步操作,此时已排序的最后一个节点为 curNode; +- 在链表头节点前增加一个节点,应对 curNode 插入位置在 头节点之前的情况; +- 从头节点开始遍历,找到curNode 的插入位置,进行插入; +- 此时已排序的最后一个节点仍为 perNode ,重复以上操作直至链表末尾。 + +```java +/** + * Definition for singly-linked list. + * public class ListNode { + * int val; + * ListNode next; + * ListNode(int x) { val = x; } + * } + */ +class Solution { + public ListNode insertionSortList(ListNode head) { + if (head == null) { + return null; + } + return insertionOneNode(head, head); + } + + private ListNode insertionOneNode(ListNode head, ListNode node) { + if (head == null || node == null || node.next == null) { + return head; + } + + ListNode perNode = node; + ListNode curNode = node.next; + ListNode nextNode = curNode.next; + + if (node.val <= curNode.val) { + return insertionOneNode(head, curNode); + } else { + node.next = nextNode; + } + + ListNode pNode = new ListNode(0); + pNode.next = head; + head = pNode; + while (pNode.next.val <= curNode.val) { + pNode = pNode.next; + } + ListNode nNode = pNode.next; + pNode.next = curNode; + curNode.next = nNode; + + return insertionOneNode(head.next, perNode); + } +} +``` \ No newline at end of file diff --git a/solution/0147.Insertion Sort List/Solution.java b/solution/0147.Insertion Sort List/Solution.java new file mode 100644 index 0000000000000..f2a7229c7a696 --- /dev/null +++ b/solution/0147.Insertion Sort List/Solution.java @@ -0,0 +1,45 @@ +/** + * Definition for singly-linked list. + * public class ListNode { + * int val; + * ListNode next; + * ListNode(int x) { val = x; } + * } + */ +class Solution { + public ListNode insertionSortList(ListNode head) { + if (head == null) { + return null; + } + return insertionOneNode(head, head); + } + + private ListNode insertionOneNode(ListNode head, ListNode node) { + if (head == null || node == null || node.next == null) { + return head; + } + + ListNode perNode = node; + ListNode curNode = node.next; + ListNode nextNode = curNode.next; + + if (node.val <= curNode.val) { + return insertionOneNode(head, curNode); + } else { + node.next = nextNode; + } + + ListNode pNode = new ListNode(0); + pNode.next = head; + head = pNode; + while (pNode.next.val <= curNode.val) { + pNode = pNode.next; + } + ListNode nNode = pNode.next; + pNode.next = curNode; + curNode.next = nNode; + + return insertionOneNode(head.next, perNode); + } +} + diff --git a/solution/0153.Find Minimum in Rotated Sorted Array/Solution.cpp b/solution/0153.Find Minimum in Rotated Sorted Array/Solution.cpp new file mode 100644 index 0000000000000..7eb666d68d7cf --- /dev/null +++ b/solution/0153.Find Minimum in Rotated Sorted Array/Solution.cpp @@ -0,0 +1,20 @@ +class Solution { +public: + int findMin(vector& nums) { + if (nums[0] <= nums.back()) + return nums[0] ; + + int l = 0, r = nums.size() - 1 ; + + while (l+1 < r) + { + const int mid = l + ((r-l) >> 1) ; + if (nums[l] <= nums[mid]) + l = mid ; + else + r = mid ; + } + + return nums.at(r) ; + } +}; diff --git a/solution/0202.Happy Number/README.md b/solution/0202.Happy Number/README.md new file mode 100644 index 0000000000000..3c9e4444b090a --- /dev/null +++ b/solution/0202.Happy Number/README.md @@ -0,0 +1,43 @@ +## 快乐数 +### 题目描述 + +编写一个算法来判断一个数是不是“快乐数”。 + +一个“快乐数”定义为: + +对于一个正整数,每一次将该数替换为它每个位置上的数字的平方和,然后重复这个过程直到这个数变为 1,也可能是无限循环但始终变不到 1。如果可以变为 1,那么这个数就是快乐数。 + +**示例**: +``` +输入: 19 +输出: true +解释: +1² + 9² = 82 +8² + 2² = 68 +6² + 8² = 100 +1² + 0² + 0² = 1 +``` + +### 解法 +在进行验算的过程中,发现一个规律,只要过程中得到任意一个结果和为 4,那么就一定会按 `4 → 16 → 37 → 58 → 89 → 145 → 42 → 20 → 4` +进行循环,这样的数就不为快乐数;此外,结果和与若是与输入 n 或者上一轮结果和 n 相同,那也不为快乐数。 + +```java +class Solution { + public boolean isHappy(int n) { + if (n <= 0) return false; + int sum = 0; + while (sum != n) { + while (n > 0) { + sum += Math.pow(n % 10, 2); + n /= 10; + } + if (sum == 1) return true; + if (sum == 4) return false; + n = sum; + sum = 0; + } + return false; + } +} +``` \ No newline at end of file diff --git a/solution/0202.Happy Number/Solution.java b/solution/0202.Happy Number/Solution.java new file mode 100644 index 0000000000000..f6ee86fe82f6c --- /dev/null +++ b/solution/0202.Happy Number/Solution.java @@ -0,0 +1,33 @@ +class Solution { + public boolean isHappy(int n) { + if (n <= 0) return false; + int sum = 0; + while (sum != n) { + while (n > 0) { + sum += Math.pow(n % 10, 2); + n /= 10; + } + if (sum == 1) return true; + if (sum == 4) return false; + n = sum; + sum = 0; + } + return false; + } +} + + +// 递归 +class Solution { + public boolean isHappy(int n) { + if (n <= 0) return false; + int sum = 0; + while (n > 0) { + sum += Math.pow(n % 10, 2); + n /= 10; + } + if (sum == 1) return true; + if (sum == 4) return false; + return isHappy(sum); + } +} \ No newline at end of file diff --git a/solution/0204.Count Primes/Solution.cpp b/solution/0204.Count Primes/Solution.cpp new file mode 100644 index 0000000000000..2ecb07bde6878 --- /dev/null +++ b/solution/0204.Count Primes/Solution.cpp @@ -0,0 +1,29 @@ +class Solution { + public: + + vector primes; + + int isPrime(int num){ + + int i = 1; + while( i < primes.size() && sqrt(num) >= primes[i] ){ + if( num % primes[i] == 0 ) return 0; + i++; + } + return 1; + } + + int countPrimes(int n) { + + if( n <= 2 ) return 0; + + primes.push_back(2); + + for(int i = 3; i < n; i += 2){ + if( isPrime(i) ) + primes.push_back(i); + } + + return primes.size(); + } +}; diff --git a/solution/0207.Course Schedule/README.md b/solution/0207.Course Schedule/README.md index d403a8fbee92d..a44a44bfb3538 100644 --- a/solution/0207.Course Schedule/README.md +++ b/solution/0207.Course Schedule/README.md @@ -36,6 +36,11 @@ 如果存在拓扑排序,那么就可以完成所有课程的学习。 +**说明:** + +- 拓扑排序的本质是不断输出入度为 0 的点,该算法可**用于判断图中是否存在环**; +- 可以用队列(或者栈)保存入度为 0 的点,避免每次遍历所有的点。 + ```java class Solution { public boolean canFinish(int numCourses, int[][] prerequisites) { diff --git a/solution/0215.Kth Largest Element in an Array/Solution.cpp b/solution/0215.Kth Largest Element in an Array/Solution.cpp new file mode 100644 index 0000000000000..849874c94ce30 --- /dev/null +++ b/solution/0215.Kth Largest Element in an Array/Solution.cpp @@ -0,0 +1,44 @@ +class Solution { +public: + int findKthLargest(vector& nums, int k) { + --k ; + int ii = 0, jj = nums.size()-1 ; + int i, j ; + while (true) + { + i = ii, j = jj ; + if (i + 63 < j) + { + const int mid = i + (j-i)/2 ; + if (nums[j] >= nums[mid] && nums[j] <= nums[i] + || nums[j] <= nums[mid] && nums[j] >= nums[i]) + { + swap(nums[i], nums[j]) ; + } + else if (nums[mid] >= nums[i] && nums[mid] <= nums[j] + || nums[mid] <= nums[i] && nums[mid] >= nums[j]) + { + swap(nums[i], nums[mid]) ; + } + } + while (i < j) + { + while (i < j && nums.at(i) >= nums.at(j)) + --j ; + swap(nums[i], nums[j]) ; + while (i < j && nums.at(i) >= nums.at(j)) + ++i ; + swap(nums[i], nums[j]) ; + } + + if (i > k) + jj = i-1 ; + else if (i < k) + ii = i+1 ; + else + return nums[k] ; + } + + return nums.at(k) ; + } +}; diff --git a/solution/0218.The Skyline Problem/Solution.cpp b/solution/0218.The Skyline Problem/Solution.cpp new file mode 100644 index 0000000000000..a22db24dabf02 --- /dev/null +++ b/solution/0218.The Skyline Problem/Solution.cpp @@ -0,0 +1,41 @@ +// 区间离散化解法(低效 120ms) +class Solution { +public: + vector> getSkyline(vector>& buildings) { + set poss ; + map m ; + for (auto v: buildings) + { + poss.insert(v[0]) ; + poss.insert(v[1]) ; + } + + int i = 0 ; + for (int pos: poss) + m.insert(pair(pos, i++)) ; + + vector highs(m.size(), 0) ; + for (auto v: buildings) + { + const int b = m[v[0]], e = m[v[1]] ; + for (int i = b; i < e; ++i) + highs[i] = max(highs[i], v[2]) ; + } + + vector> res ; + vector mm(poss.begin(), poss.end()) ; + for (int i = 0; i < highs.size(); ++i) + { + if (highs[i] != highs[i+1]) + res.push_back(pair(mm[i], highs[i])) ; + else + { + const int start = i ; + res.push_back(pair(mm[start], highs[i])) ; + while (highs[i] == highs[i+1]) + ++i ; + } + } + return res ; + } +}; diff --git a/solution/0268.Missing Number/Solution2.js b/solution/0268.Missing Number/Solution2.js new file mode 100644 index 0000000000000..32dc0dff470a5 --- /dev/null +++ b/solution/0268.Missing Number/Solution2.js @@ -0,0 +1,19 @@ +/** + * @param {number[]} nums + * @return {number} + */ +var missingNumber = function(nums) { + var flags = [] + for(var i = 0; i <= nums.length; i++) { + flags[i] = 0 + } + for(var i = 0; i& nums) { + if (nums.size() == 0) + return 0 ; + int M[nums.size()] = {0, } ; + int MM = -1 ; + for (int i = nums.size()-1; i >= 0; --i) + { + for (int j = i+1; j < nums.size(); ++j) + if (nums[i] < nums[j]) + M[i] = max(M[i], M[j]) ; + MM = max(++M[i], MM) ; + } + return MM ; + } +}; diff --git a/solution/0300.Longest Increasing Subsequence/Solution2.cpp b/solution/0300.Longest Increasing Subsequence/Solution2.cpp new file mode 100644 index 0000000000000..0de9bea439651 --- /dev/null +++ b/solution/0300.Longest Increasing Subsequence/Solution2.cpp @@ -0,0 +1,31 @@ +class Solution { +// dp[i] 表示当前长度为i+1的最大升序左侧子序列的最小末尾值 +// 可以知道dp[]一定是递增的,每多加一个元素就可以用折半查找更新dp +public: + int lengthOfLIS(vector& nums) { + if (nums.size() == 0) + return 0 ; + int dp[nums.size()] = {nums[0], }; + int maxLen = 1 ; // 刚开始找到的最大左侧子串是第一个元素,长度为1 + for (int i = 1; i < nums.size(); ++i) + { + int l = 0, r = maxLen ; + while (l < r) + { + const int mid = l + (r-l)/2 ; + if (dp[mid] < nums[i]) + l = mid+1 ; + else + r = mid ; + } + + // 长度为l+1的最大上升子序列的最小末尾值可以更新为该元素了 + dp[l] = nums[i] ; + + // 如果当前元素比dp中所有元素都大,最大长度就可以+1,并以该元素结尾 + if (l == maxLen) + ++maxLen ; + } + return maxLen ; + } +}; diff --git a/solution/0329.Longest Increasing Path in a Matrix/Solution.cpp b/solution/0329.Longest Increasing Path in a Matrix/Solution.cpp new file mode 100644 index 0000000000000..99dc31c7ad46d --- /dev/null +++ b/solution/0329.Longest Increasing Path in a Matrix/Solution.cpp @@ -0,0 +1,54 @@ +class Solution { +private: + int Dfs(vector> &m, vector> &v, + int i, int j, + bool first, int lastNum) + { + if (i < 0 || i >= m.size() + || j < 0 || j >= m[0].size()) + return 0 ; + + if (!first && lastNum >= m[i][j]) + return 0 ; + + if (v[i][j] >= 0) + return v[i][j] ; + + int d1 = Dfs(m, v, i-1, j, false, m[i][j]) ; + int d2 = Dfs(m, v, i+1, j, false, m[i][j]) ; + int d3 = Dfs(m, v, i, j-1, false, m[i][j]) ; + int d4 = Dfs(m, v, i, j+1, false, m[i][j]) ; + v[i][j] = 1 + max(max(d1, d2), max(d3, d4)) ; + + return v[i][j] ; + } +public: + int longestIncreasingPath(vector>& matrix) { + if (matrix.size() == 0) + return 0 ; + const int h = matrix.size(), w = matrix[0].size() ; + vector> visited(h, vector(w, -1)) ; + + int M = 0 ; + for (int i = 0; i < h; ++i) + for (int j = 0; j < w; ++j) + { + if (j + 1 < w && matrix[i][j] > matrix[i][j+1] + || i + 1 < h && matrix[i][j] > matrix[i+1][j]) + { + continue ; + } + else + { + M = max(M, Dfs(matrix, visited, i, j, true, 0)) ; + } + } + return M ; + } +}; + +static const auto __ = []() { + std::ios::sync_with_stdio(false); + std::cin.tie(nullptr); + return nullptr; +}(); \ No newline at end of file diff --git a/solution/0349.Intersection of Two Arrays/Solution.py b/solution/0349.Intersection of Two Arrays/Solution.py new file mode 100644 index 0000000000000..c250d9e4a4c27 --- /dev/null +++ b/solution/0349.Intersection of Two Arrays/Solution.py @@ -0,0 +1,4 @@ +class Solution: + def intersection(self, nums1: 'List[int]', nums2: 'List[int]') -> 'List[int]': + + return list(set(nums1).intersection(set(nums2))) diff --git a/solution/0393.UTF-8 Validation/Solution.cpp b/solution/0393.UTF-8 Validation/Solution.cpp new file mode 100644 index 0000000000000..d1a3cf6eff3e1 --- /dev/null +++ b/solution/0393.UTF-8 Validation/Solution.cpp @@ -0,0 +1,33 @@ +class Solution { +public: + bool validUtf8(vector& data) { + const unsigned modeContinue = 0xc0 ; + + int conti = 0 ; + for (auto it = data.begin(); it < data.end(); ++it) + { + + if (0 == conti) // 首字节 + { + if (*it < 0x80) + continue ; + else if (*it < 0xe0) + conti = 1 ; + else if (*it < 0xf0) + conti = 2 ; + else if (*it < 0xf8) + conti = 3 ; + else + return false ; + } + else // 后续字节 + { + --conti ; + if ((*it & modeContinue) != 0x80) + return false ; + } + } + + return 0 == conti ; + } +}; \ No newline at end of file diff --git a/solution/0423.Reconstruct Original Digits from English/Solution.cpp b/solution/0423.Reconstruct Original Digits from English/Solution.cpp new file mode 100644 index 0000000000000..2349f4f38d0cf --- /dev/null +++ b/solution/0423.Reconstruct Original Digits from English/Solution.cpp @@ -0,0 +1,99 @@ +class Solution { +public: + string originalDigits(string s) { + vector chs(26, 0) ; + vector nums(10, 0) ; + for (char ch: s) + ++chs[ch-'a'] ; + + if (chs['z' - 'a'] != 0) + { + const int cnt = chs['z' - 'a'] ; + chs['e' - 'a'] -= cnt ; + chs['r' - 'a'] -= cnt ; + chs['o' - 'a'] -= cnt ; + nums[0] = cnt ; + } + + if (chs['w' - 'a'] != 0) + { + const int cnt = chs['w' - 'a'] ; + chs['t' - 'a'] -= cnt ; + chs['o' - 'a'] -= cnt ; + nums[2] = cnt ; + } + + if (chs['u' - 'a'] != 0) + { + const int cnt = chs['u' - 'a'] ; + chs['f' - 'a'] -= cnt ; + chs['o' - 'a'] -= cnt ; + chs['r' - 'a'] -= cnt ; + nums[4] = cnt ; + } + + if (chs['x' - 'a'] != 0) + { + const int cnt = chs['x' - 'a'] ; + chs['s' - 'a'] -= cnt ; + chs['i' - 'a'] -= cnt ; + nums[6] = cnt ; + } + + if (chs['g' - 'a'] != 0) + { + const int cnt = chs['g' - 'a'] ; + chs['e' - 'a'] -= cnt ; + chs['i' - 'a'] -= cnt ; + chs['h' - 'a'] -= cnt ; + chs['t' - 'a'] -= cnt ; + nums[8] = cnt ; + } + + if (chs['o' - 'a'] != 0) + { + const int cnt = chs['o' - 'a'] ; + chs['n' - 'a'] -= cnt ; + chs['e' - 'a'] -= cnt ; + nums[1] = cnt ; + } + + if (chs['t' - 'a'] != 0) + { + const int cnt = chs['t' - 'a'] ; + chs['h' - 'a'] -= cnt ; + chs['r' - 'a'] -= cnt ; + chs['e' - 'a'] -= cnt*2 ; + nums[3] = cnt ; + } + + if (chs['f' - 'a'] != 0) + { + const int cnt = chs['f' - 'a'] ; + chs['i' - 'a'] -= cnt ; + chs['v' - 'a'] -= cnt ; + chs['e' - 'a'] -= cnt ; + nums[5] = cnt ; + } + + if (chs['s' - 'a'] != 0) + { + const int cnt = chs['s' - 'a'] ; + chs['v' - 'a'] -= cnt ; + chs['n' - 'a'] -= cnt ; + chs['e' - 'a'] -= cnt*2 ; + nums[7] = cnt ; + } + + nums[9] = chs['i' - 'a'] ; + + stringstream ss ; + for (int i = 0; i < 10; ++i) + while (nums[i]--) + ss << char('0' + i) ; + + string res ; + ss >> res ; + return res ; + } +}; diff --git a/solution/0438.Find All Anagrams in a String/README.md b/solution/0438.Find All Anagrams in a String/README.md new file mode 100644 index 0000000000000..961f3f4e1e218 --- /dev/null +++ b/solution/0438.Find All Anagrams in a String/README.md @@ -0,0 +1,61 @@ +## 找到字符串中所有字母异位词 + +### 问题描述 + +给定一个字符串 `s` 和一个非空字符串 `p`,找到 `s` 中所有是 `p` 的字母异位词的子串,返回这些子串的起始索引。 + +字符串只包含小写英文字母,并且字符串 `s` 和 `p` 的长度都不超过 20100。 + +**示例1:** +``` +输入: +s: "cbaebabacd" p: "abc" + +输出: +[0, 6] + +解释: +起始索引等于 0 的子串是 "cba", 它是 "abc" 的字母异位词。 +起始索引等于 6 的子串是 "bac", 它是 "abc" 的字母异位词。 +``` +**示例2:** +``` +输入: +s: "abab" p: "ab" + +输出: +[0, 1, 2] + +解释: +起始索引等于 0 的子串是 "ab", 它是 "ab" 的字母异位词。 +起始索引等于 1 的子串是 "ba", 它是 "ab" 的字母异位词。 +起始索引等于 2 的子串是 "ab", 它是 "ab" 的字母异位词。 +``` +**提示:** +- 字母异位词指字母相同,但排列不同的字符串。 +- 不考虑答案输出的顺序。 + +### 解法 +同`第0567`题。 +使用滑动窗口。窗口宽为`p`的长度,从左到右在`s`上滑动,若窗口内的字母出现频率和`p`中字母出现的频率一样,则此窗口的起始位置为一个起始索引。 + +```python +class Solution: + def findAnagrams(self, s, p): + lens = len(s) + lenp = len(p) + if lens < lenp: + return [] + flag1 = [0] * 26 + flag2 = [0] * 26 + for i, x in enumerate(p): + flag1[ord(x) - 97] += 1 + ans = [] + for i, x in enumerate(s): + flag2[ord(x) - 97] += 1 + if i >= lenp: + flag2[ord(s[i - lenp]) - 97] -= 1 + if flag1 == flag2: + ans.append(i - lenp + 1) + return ans +``` diff --git a/solution/0438.Find All Anagrams in a String/Solution.py b/solution/0438.Find All Anagrams in a String/Solution.py new file mode 100644 index 0000000000000..17b2b481a10f4 --- /dev/null +++ b/solution/0438.Find All Anagrams in a String/Solution.py @@ -0,0 +1,23 @@ +class Solution: + def findAnagrams(self, s, p): + """ + :type s: str + :type p: str + :rtype: List[int] + """ + lens=len(s) + lenp=len(p) + if lens < lenp: + return [] + flag1 = [0] * 26 + flag2 = [0] * 26 + for i, x in enumerate(p): + flag1[ord(x) - 97] += 1 + ans = [] + for i, x in enumerate(s): + flag2[ord(x)- 97] += 1 + if i >= lenp: + flag2[ord(s[i - lenp]) - 97] -= 1 + if flag1 == flag2: + ans.append(i-lenp+1) + return ans diff --git a/solution/0476.Number Complement/Solution.cpp b/solution/0476.Number Complement/Solution.cpp new file mode 100644 index 0000000000000..8bb2645b08e76 --- /dev/null +++ b/solution/0476.Number Complement/Solution.cpp @@ -0,0 +1,7 @@ +class Solution { + public: + int findComplement(int num) { + int full = pow(2, int(log2(num)) + 1) - 1; + return full ^ num; + } +}; \ No newline at end of file diff --git a/solution/0485. Max Consecutive Ones/Solution.js b/solution/0485. Max Consecutive Ones/Solution.js new file mode 100644 index 0000000000000..becea6643df10 --- /dev/null +++ b/solution/0485. Max Consecutive Ones/Solution.js @@ -0,0 +1,20 @@ +/** + * @param {number[]} nums + * @return {number} + */ +var findMaxConsecutiveOnes = function(nums) { + var max = 0 + var n = 0 + for(var i = 0; i < nums.length; i++) { + if (nums[i] == 0) { + n = 0 + } else { + n++ + } + max = n > max ? n : max + if (n > max) { + max = n + } + } + return max +}; diff --git a/solution/0493.Reverse Pairs/Solution.cpp b/solution/0493.Reverse Pairs/Solution.cpp new file mode 100644 index 0000000000000..2194505d5087a --- /dev/null +++ b/solution/0493.Reverse Pairs/Solution.cpp @@ -0,0 +1,79 @@ +class Solution { +private: + inline bool cmp1(vector::iterator a, + vector::iterator b) + { + if (*a >= 0 && *b >= 0) + { + const unsigned ua = *a, ub = *b ; + return ua <= (ub << 1) ; + } + + if (*a < 0 && *b < 0) + { + const unsigned ua = -*a, ub = -*b ; + return ua >= (ub << 1) ; + } + + if (*a < 0 && *b >= 0) + return true ; + + if (*a >= 0 && *b < 0) + return false ; + } + + unsigned CountLRPairs(vector::iterator start, + vector::iterator end) + { + if (start + 1 >= end) + return 0 ; + if (start + 2 == end) + { + if (*start <= *(start+1)) + return !cmp1(start, start+1) ; // ҲҪ㣬ӦΪи + else // ҲҪҪرעa[i] < a[j]a[i] < 2*a[j] + { + swap(*start, *(start+1)) ; + return !cmp1(start+1, start) ; // λ + } + } + + vector::iterator mid = start + ((end-start) >> 1) ; + vector::iterator pF = start, pB = mid ; + int cnt = CountLRPairs(start, mid) + CountLRPairs(mid, end) ; + while (pF != mid) + { + while (pB != end && !cmp1(pF, pB)) + ++pB ; + cnt += pB-mid ; + ++pF ; + } + + vector tmp(start, mid) ; + pF = tmp.begin() ; + pB = mid ; + vector::iterator p = start ; + + auto size = end - start ; + if (size == 10) + ++size ; + + while (pF != tmp.end() && pB != end) + { + if (*pF <= *pB) + *p++ = *pF++ ; + else + *p++ = *pB++ ; + } + while (pF != tmp.end()) + *p++ = *pF++ ; + while (pB != end) + *p++ = *pB++ ; + + return cnt ; + } +public: + int reversePairs(vector& nums) { + return CountLRPairs(nums.begin(), nums.end()) ; + } +}; \ No newline at end of file diff --git a/solution/0500.Keyboard Row/Solution.py b/solution/0500.Keyboard Row/Solution.py new file mode 100644 index 0000000000000..dcc86221a5104 --- /dev/null +++ b/solution/0500.Keyboard Row/Solution.py @@ -0,0 +1,16 @@ +class Solution: + def findWords(self, words): + """ + :type words: List[str] + :rtype: List[str] + """ + + Rows={"q":0, "w":0, "e":0, "r":0, "t":0, "y":0, "u":0, "i":0, "o":0, "p":0, "a":1, "s":1, "d":1, "f":1, "g":1, "h":1, "j":1, "k":1, "l":1, "z":2, "x":2, "c":2, "v":2, "b":2, "n":2, "m":2} + + Final = [] + for each in words : + + if all([Rows[each[0].lower()]==Rows[ch] for ch in each.lower()]) : + Final.append(each) + + return Final diff --git a/solution/0509.Fibonacci/README.md b/solution/0509.Fibonacci/README.md new file mode 100644 index 0000000000000..7c38404131d6c --- /dev/null +++ b/solution/0509.Fibonacci/README.md @@ -0,0 +1,70 @@ +# 斐波那契数 + +### 题目描述 + +**斐波那契数**,通常用 `F(n)` 表示,形成的序列称为**斐波那契数列**。该数列由 `0` 和 `1` 开始,后面的每一项数字都是前面两项数字的和。也就是: + +``` +F(0) = 0, F(1) = 1 +F(N) = F(N - 1) + F(N - 2), 其中 N > 1. +``` + +给定 `N`,计算 `F(N)`。 + +**示例 1:** + +``` +输入:2 +输出:1 +解释:F(2) = F(1) + F(0) = 1 + 0 = 1. +``` + +**示例 2:** + +``` +输入:3 +输出:2 +解释:F(3) = F(2) + F(1) = 1 + 1 = 2. +``` + +**示例 3:** + +``` +输入:4 +输出:3 +解释:F(4) = F(3) + F(2) = 2 + 1 = 3. +``` + + + +**提示:** + +- 0 ≤ `N` ≤ 30 + +### 解题思路 + +**思路** + +利用递归思想,递归公式`F(n) = F(n - 1) + F(n - 2)`,递归的终止条件`F(1) = 1`,`F(2) = 2`。 + +**算法** + +```javascript +let preResult = {}; +var fib = function(N) { + if( N === 0 ) return 0; + if( N === 1 ) return 1; + if( preResult[N] ){ + return preResult[N]; + } else { + preResult[N] = fib(N-1) + fib(N-2); + } + return fib(N-1) + fib(N-2); +}; +``` + + + +**复杂度分析** + +暂无 \ No newline at end of file diff --git a/solution/0509.Fibonacci/Solution.cpp b/solution/0509.Fibonacci/Solution.cpp new file mode 100644 index 0000000000000..1ee394258dea8 --- /dev/null +++ b/solution/0509.Fibonacci/Solution.cpp @@ -0,0 +1,9 @@ +class Solution { +public: + int fib(int N) { + int a[2] = {0, 1} ; + for (int i = 2; i <= N; ++i) + a[i&1] += a[i&1^1] ; + return a[N&1] ; + } +}; \ No newline at end of file diff --git a/solution/0509.Fibonacci/Solution.js b/solution/0509.Fibonacci/Solution.js new file mode 100644 index 0000000000000..1ad863c2f0d3e --- /dev/null +++ b/solution/0509.Fibonacci/Solution.js @@ -0,0 +1,20 @@ +/** + * @param {number} N + * @return {number} + */ + +/** + * Author: Mcnwork2018 + */ + +let preResult = {}; +var fib = function(N) { + if ( N === 0 ) return 0; + if ( N === 1 ) return 1; + if ( preResult[N] ) { + return preResult[N]; + } else { + preResult[N] = fib(N-1) + fib(N-2); + } + return fib(N-1) + fib(N-2); +}; diff --git a/solution/0554.Brick Wall/README.md b/solution/0554.Brick Wall/README.md new file mode 100644 index 0000000000000..05ceda5db28fa --- /dev/null +++ b/solution/0554.Brick Wall/README.md @@ -0,0 +1,54 @@ +## 砖墙 + +### 问题描述 + +你的面前有一堵方形的、由多行砖块组成的砖墙。 这些砖块高度相同但是宽度不同。你现在要画一条自顶向下的、穿过最少砖块的垂线。 + +砖墙由行的列表表示。 每一行都是一个代表从左至右每块砖的宽度的整数列表。 + +如果你画的线只是从砖块的边缘经过,就不算穿过这块砖。你需要找出怎样画才能使这条线穿过的砖块数量最少,并且返回穿过的砖块数量。 + +你不能沿着墙的两个垂直边缘之一画线,这样显然是没有穿过一块砖的。 + +**示例1:** +``` +输入: [[1,2,2,1], + [3,1,2], + [1,3,2], + [2,4], + [3,1,2], + [1,3,1,1]] + +输出: 2 +``` + +![示例1](/img/brick_wall.png) + +**提示:** +- 每一行砖块的宽度之和应该相等,并且不能超过 `INT_MAX`。 +- 每一行砖块的数量在 [1,10,000] 范围内, 墙的高度在 [1,10,000] 范围内, 总的砖块数量不超过 20,000。 + +### 解法 + +记录每个长度(每个砖块右侧到最左侧的长度)出现的次数, 总层数减去出现次数最多的长度, 就是最少交叉的数量。每层最后一块砖的右侧是边缘,不考虑。 + +```python +class Solution: + def leastBricks(self, wall): + dic = {} + count = 0 + for hang in wall: + count = 0 + for j, ele in enumerate(hang): + if j == len(hang) - 1: + break + count += ele + if count not in dic: + dic[count] = 1 + else: + dic[count] += 1 + + if not dic: + return len(wall) + return len(wall) - dic[max(dic, key=dic.get)] +``` diff --git a/solution/0554.Brick Wall/Solution.py b/solution/0554.Brick Wall/Solution.py new file mode 100644 index 0000000000000..788d9e75b2f43 --- /dev/null +++ b/solution/0554.Brick Wall/Solution.py @@ -0,0 +1,22 @@ +class Solution: + def leastBricks(self, wall): + """ + :type wall: List[List[int]] + :rtype: int + """ + dic = {} + count = 0 + for hang in wall: + count = 0 + for j, ele in enumerate(hang): + if j == len(hang) - 1: + break + count += ele + if count not in dic: + dic[count] = 1 + else: + dic[count] += 1 + + if not dic: + return len(wall) + return len(wall) - dic[max(dic, key=dic.get)] diff --git a/solution/0561.Array Partition I/README.md b/solution/0561.Array Partition I/README.md new file mode 100644 index 0000000000000..b52f1644f6aae --- /dev/null +++ b/solution/0561.Array Partition I/README.md @@ -0,0 +1,139 @@ +# 数组拆分 I + +### 题目描述 + +给定长度为 **2n** 的数组, 你的任务是将这些数分成 **n** 对, 例如 (a1, b1), (a2, b2), ..., (an, bn) ,使得从1 到 n 的 min(ai, bi) 总和最大。 + +**示例 1** + +``` +输入: [1,4,3,2] +输出: 4 +解释: n 等于 2, 最大总和为 4 = min(1, 2) + min(3, 4). +``` + +**提示** + +1. **n** 是正整数,范围在 [1, 10000]. +2. 数组中的元素范围在 [-10000, 10000]. + +**提示1** + +Obviously, brute force won't help here. Think of something else, take some example like 1,2,3,4. + +显然,蛮力在这里无济于事。想想其他的东西,比如1,2,3,4。 + +**提示2** + +How will you make pairs to get the result? There must be some pattern. + +你将如何成对获得结果? 必须有一些模式。 + +**提示3** + +Did you observe that- Minimum element gets add into the result in sacrifice of maximum element. + +您是否观察到 - 最小元素会牺牲最大元素而添加到结果中。 + +**提示4** + +Still won't able to find pairs? Sort the array and try to find the pattern. + +仍然无法找到对? 对数组进行排序并尝试查找模式。 + +### 解题思路 + +**思路** + +先排序,在查找配对的两个数中最小值求和。这里使用的是归并排序和根据数组下标为奇数求和,有一些取巧,但有更快的算法(例如算法里使用C的解法,复杂度为O(n)),但还没想明白。 + +**算法** + +**JavaScript** + +```javascript +var arrayPairSum = function(nums) { + let result = merge_sort(nums); + let sum = 0; + for ( let i = 0; i < result.length; i += 2 ) { + sum += result[i]; + } + return sum; +}; +function merge_sort(A){ + let len = A.length; + if ( len === 1 ) return A; + let mid = ~~( len / 2 ); + let leftArray = A.slice(0, mid); + let rightArray = A.slice(mid, len); + return merge(merge_sort(leftArray), merge_sort(rightArray)); +} +function merge(left, right){ + let i = 0, j = 0, k = 0, tmp = []; + while ( i < left.length && j < right.length ) { + if ( left[i] <= right[j] ) { + tmp[k++] = left[i++]; + } else { + tmp[k++] = right[j++]; + } + } + while ( i < left.length ) { + tmp[k++] = left[i++]; + } + while ( j < right.length ) { + tmp[k++] = right[j++]; + } + return tmp; +} +``` + +**C** + +```c +nt arrayPairSum(vector& nums) { + if( nums.size() == 0) + return 0; + int min = nums[0], max= nums[0]; + + for( int i = 0; i < nums.size(); i++) + if( nums[i] < min) + min = nums[i]; + else if( nums[i] > max) + max = nums[i]; + + int *record = (int *)malloc( sizeof( int) * ( max - min +1)); + + for( int i = 0; i< max - min + 1; i++) + record[i] = 0; + + for( int i = 0; i < nums.size(); i++) + record[ nums[i] - min]++; + + int maxSum = 0, i = 0; + while(i < max-min+1){ + if( record[i] == 0){ + i++; + continue; + } + if( record[i] > 1){ + maxSum += i + min; + record[i] -=2; + continue; + } + if( record[i] == 1){ + for( int j = i+1; j < max-min+1; j++) + if( record[j] != 0){ + record[j]--, record[i]--; + maxSum += i + min; + i = j; + break; + } + continue; + } + + } + return maxSum; + } +``` +**复杂度分析** +暂无 \ No newline at end of file diff --git a/solution/0561.Array Partition I/Solution.js b/solution/0561.Array Partition I/Solution.js new file mode 100644 index 0000000000000..ad1a0d1f27bfa --- /dev/null +++ b/solution/0561.Array Partition I/Solution.js @@ -0,0 +1,42 @@ +/** + * @param {number[]} nums + * @return {number} + */ + +/** + * Author: Mcnwork2018 + */ + +var arrayPairSum = function(nums) { + let result = merge_sort(nums); + let sum = 0; + for ( let i = 0; i < result.length; i += 2 ) { + sum += result[i]; + } + return sum; +}; +function merge_sort(A){ + let len = A.length; + if ( len === 1 ) return A; + let mid = ~~( len / 2 ); + let leftArray = A.slice(0, mid); + let rightArray = A.slice(mid, len); + return merge(merge_sort(leftArray), merge_sort(rightArray)); +} +function merge(left, right){ + let i = 0, j = 0, k = 0, tmp = []; + while ( i < left.length && j < right.length ) { + if ( left[i] <= right[j] ) { + tmp[k++] = left[i++]; + } else { + tmp[k++] = right[j++]; + } + } + while ( i < left.length ) { + tmp[k++] = left[i++]; + } + while ( j < right.length ) { + tmp[k++] = right[j++]; + } + return tmp; +} \ No newline at end of file diff --git a/solution/0567.Permutation in String/README.md b/solution/0567.Permutation in String/README.md new file mode 100644 index 0000000000000..45042f46c09d3 --- /dev/null +++ b/solution/0567.Permutation in String/README.md @@ -0,0 +1,43 @@ +## 字符串的排列 + +### 问题描述 + +给定两个字符串 `s1` 和 `s2`,写一个函数来判断 `s2` 是否包含 `s1` 的排列。 + +换句话说,第一个字符串的排列之一是第二个字符串的子串。 + +**示例1:** +``` +输入: s1 = "ab" s2 = "eidbaooo" +输出: True +解释: s2 包含 s1 的排列之一 ("ba"). +``` +**示例2:** +``` +输入: s1= "ab" s2 = "eidboaoo" +输出: False +``` +**提示:** +- 输入的字符串只包含小写字母 +- 两个字符串的长度都在 [1, 10,000] 之间 + +### 解法 +使用滑动窗口,窗口宽为`s1`的长度,从左到右在`s2`上滑动,若窗口内的字母出现频率和`s1`中字母出现的频率一样,则`s2` 包含 `s1` 的排列。若不存在则`s2` 不包含 `s1` 的排列。 + +```python +class Solution: + def checkInclusion(self, s1, s2): + if len(s1) > len(s2): + return False + flag1 = [0] * 26 + flag2 = [0] * 26 + for i, x in enumerate(s1): + flag1[ord(x) - ord('a')] += 1 + for i, x in enumerate(s2): + flag2[ord(x) - ord('a')] += 1 + if i >= len(s1): + flag2[ord(s2[i - len(s1)]) - ord('a')] -= 1 + if flag1 == flag2: + return True + return False +``` diff --git a/solution/0567.Permutation in String/Solution.py b/solution/0567.Permutation in String/Solution.py new file mode 100644 index 0000000000000..86506381d454f --- /dev/null +++ b/solution/0567.Permutation in String/Solution.py @@ -0,0 +1,21 @@ +class Solution: + def checkInclusion(self, s1, s2): + """ + :type s1: str + :type s2: str + :rtype: bool + """ + if len(s1) > len(s2): + return False + flag1 = [0] * 26 + flag2 = [0] * 26 + for i, x in enumerate(s1): + flag1[ord(x) - ord('a')] += 1 + + for i, x in enumerate(s2): + flag2[ord(x) - ord('a')] += 1 + if i >= len(s1): + flag2[ord(s2[i - len(s1)]) - ord('a')] -= 1 + if flag1 == flag2: + return True + return False diff --git a/solution/0572.Subtree of Another Tree/Solution.cpp b/solution/0572.Subtree of Another Tree/Solution.cpp new file mode 100644 index 0000000000000..fae148dc038ad --- /dev/null +++ b/solution/0572.Subtree of Another Tree/Solution.cpp @@ -0,0 +1,37 @@ +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode(int x) : val(x), left(NULL), right(NULL) {} + * }; + */ +class Solution { +private: + bool IsSameTree(TreeNode *s, TreeNode *t) + { + if (nullptr == s && nullptr == t) + return true ; + if (nullptr == s || nullptr == t + || s->val != t->val) + return false ; + + return IsSameTree(s->left, t->left) + && IsSameTree(s->right, t->right) ; + } +public: + bool isSubtree(TreeNode* s, TreeNode* t) { + if (nullptr == s) + return false ; + + if (s->val == t->val && IsSameTree(s, t)) + return true ; + + if (!isSubtree(s->left, t) + && !isSubtree(s->right, t)) + return false ; + + return true ; + } +}; \ No newline at end of file diff --git a/solution/0657.Robot Return to Origin/Solution.py b/solution/0657.Robot Return to Origin/Solution.py new file mode 100644 index 0000000000000..18fb73c039a53 --- /dev/null +++ b/solution/0657.Robot Return to Origin/Solution.py @@ -0,0 +1,20 @@ +class Solution: + def judgeCircle(self, moves): + """ + :type moves: str + :rtype: bool + """ + + x = 0 + y = 0 + for each in moves: + if( each == 'U' ): + y += 1 + elif( each == 'D' ): + y -= 1 + elif( each == 'R' ): + x += 1 + elif( each == 'L' ): + x -= 1 + + return x == y == 0 diff --git a/solution/0700.Search in a Binary Search Tree/Solution.cpp b/solution/0700.Search in a Binary Search Tree/Solution.cpp new file mode 100644 index 0000000000000..5461901931b8a --- /dev/null +++ b/solution/0700.Search in a Binary Search Tree/Solution.cpp @@ -0,0 +1,30 @@ +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode(int x) : val(x), left(NULL), right(NULL) {} + * }; + */ +class Solution { + public: + TreeNode* searchBST(TreeNode* root, int val) { + + TreeNode* temp = root; + + while( temp != NULL ){ + if( temp->val == val ){ + return temp; + } + else if( val < temp->val ){ + temp = temp->left; + } + else{ + temp = temp->right; + } + } + + return NULL; + } +}; diff --git a/solution/0700.Search in a Binary Search Tree/Solution.py b/solution/0700.Search in a Binary Search Tree/Solution.py new file mode 100644 index 0000000000000..9dae363047096 --- /dev/null +++ b/solution/0700.Search in a Binary Search Tree/Solution.py @@ -0,0 +1,27 @@ +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, x): +# self.val = x +# self.left = None +# self.right = None + +class Solution: + def searchBST(self, root, val): + """ + :type root: TreeNode + :type val: int + :rtype: TreeNode + """ + + temp = root + + while temp != None : + + if temp.val == val : + return temp + elif val < temp.val : + temp = temp.left + else: + temp = temp.right + + return None diff --git a/solution/0728.Self Dividing Numbers/Solution.cpp b/solution/0728.Self Dividing Numbers/Solution.cpp new file mode 100644 index 0000000000000..b32036b56e992 --- /dev/null +++ b/solution/0728.Self Dividing Numbers/Solution.cpp @@ -0,0 +1,33 @@ +class Solution { + public: + int div(int num){ + + int temp = num, r; + + while( temp > 0 ){ + + r = temp % 10; + + if( r == 0 || num % r != 0){ + return 0; + } + + temp /= 10; + } + + return 1; + } + + vector selfDividingNumbers(int left, int right) { + + vector ret; + + for(int i = left; i <= right; i++){ + if( div(i) ){ + ret.push_back(i); + } + } + + return ret; + } +}; diff --git a/solution/0762.Prime Number of Set Bits in Binary Representation/README.md b/solution/0762.Prime Number of Set Bits in Binary Representation/README.md new file mode 100644 index 0000000000000..bf15f74398575 --- /dev/null +++ b/solution/0762.Prime Number of Set Bits in Binary Representation/README.md @@ -0,0 +1,53 @@ +## 二进制表示中质数个计算置位 + +### 问题描述 + +给定两个整数 L 和 R ,找到闭区间 [L, R] 范围内,计算置位位数为质数的整数个数。 + +(注意,计算置位代表二进制表示中1的个数。例如 21 的二进制表示 10101 有 3 个计算置位。还有,1 不是质数。) + +**示例1:** + +``` +输入: L = 6, R = 10 +输出: 4 +解释: +6 -> 110 (2 个计算置位,2 是质数) +7 -> 111 (3 个计算置位,3 是质数) +9 -> 1001 (2 个计算置位,2 是质数) +10-> 1010 (2 个计算置位,2 是质数) +``` + +**示例2:** + +``` +输入: L = 10, R = 15 +输出: 5 +解释: +10 -> 1010 (2 个计算置位, 2 是质数) +11 -> 1011 (3 个计算置位, 3 是质数) +12 -> 1100 (2 个计算置位, 2 是质数) +13 -> 1101 (3 个计算置位, 3 是质数) +14 -> 1110 (3 个计算置位, 3 是质数) +15 -> 1111 (4 个计算置位, 4 不是质数) +``` + + +**提示:** + +- L, R 是 L <= R 且在 [1, 10^6] 中的整数。 +- R - L 的最大值为 10000。 + +### 解法 +列举32中的质数,得到`ls`;遍历`L`到`R`之间的数,计算其计算置位的个数是否为质数(是否在`ls`中)即可。 + +```python +class Solution: + def countPrimeSetBits(self, L, R): + res = 0 + flag = [2, 3, 5, 7, 11, 13, 17, 19] + for i in range(L, R + 1): + if bin(i).count('1') in flag: + res += 1 + return res +``` diff --git a/solution/0762.Prime Number of Set Bits in Binary Representation/Solution.py b/solution/0762.Prime Number of Set Bits in Binary Representation/Solution.py new file mode 100644 index 0000000000000..06c0766ec4244 --- /dev/null +++ b/solution/0762.Prime Number of Set Bits in Binary Representation/Solution.py @@ -0,0 +1,13 @@ +class Solution: + def countPrimeSetBits(self, L, R): + """ + :type L: int + :type R: int + :rtype: int + """ + res = 0 + flag = [2, 3, 5, 7, 11, 13, 17, 19] + for i in range(L, R + 1): + if bin(i).count('1') in flag: + res += 1 + return res diff --git a/solution/0769.Max Chunks To Make Sorted/README.md b/solution/0769.Max Chunks To Make Sorted/README.md new file mode 100644 index 0000000000000..2e964e9caf1e3 --- /dev/null +++ b/solution/0769.Max Chunks To Make Sorted/README.md @@ -0,0 +1,43 @@ +## 最多能完成排序的块 + +### 问题描述 + +数组`arr`是``[0, 1, ..., arr.length - 1]``的一种排列,我们将这个数组分割成几个“块”,并将这些块分别进行排序。之后再连接起来,使得连接的结果和按升序排序后的原数组相同。 + +我们最多能将数组分成多少块? + +**示例1:** +``` +输入: arr = [4,3,2,1,0] +输出: 1 +解释: +将数组分成2块或者更多块,都无法得到所需的结果。 +例如,分成 [4, 3], [2, 1, 0] 的结果是 [3, 4, 0, 1, 2],这不是有序的数组。 +``` +**示例2:** +``` +输入: arr = [1,0,2,3,4] +输出: 4 +解释: +我们可以把它分成两块,例如 [1, 0], [2, 3, 4]。 +然而,分成 [1, 0], [2], [3], [4] 可以得到最多的块数。 +``` +**提示:** +- arr 的长度在 [1, 10] 之间。 +- arr[i]是 [0, 1, ..., arr.length - 1]的一种排列。 + +### 解法 +从左到右,在位置`i`处,只要位置`i`及之前的位置不包括比`i`大的值,就能分割成一个块。 + + +```python +class Solution: + def maxChunksToSorted(self, arr): + ans = 0 + loc = 0 + for i, val in enumerate(arr): + loc = val if loc < val else loc + if loc == i: + ans += 1 + return ans +``` diff --git a/solution/0769.Max Chunks To Make Sorted/Solution.py b/solution/0769.Max Chunks To Make Sorted/Solution.py new file mode 100644 index 0000000000000..e7325590ff73a --- /dev/null +++ b/solution/0769.Max Chunks To Make Sorted/Solution.py @@ -0,0 +1,13 @@ +class Solution: + def maxChunksToSorted(self, arr): + """ + :type arr: List[int] + :rtype: int + """ + ans = 0 + loc = 0 + for i, val in enumerate(arr): + loc = val if loc < val else loc + if loc == i: + ans += 1 + return ans diff --git a/solution/0771.Jewels and Stones/Solution.py b/solution/0771.Jewels and Stones/Solution.py new file mode 100644 index 0000000000000..af9010884884a --- /dev/null +++ b/solution/0771.Jewels and Stones/Solution.py @@ -0,0 +1,18 @@ +class Solution: + def numJewelsInStones(self, J, S): + """ + :type J: str + :type S: str + :rtype: int + """ + + D = {} + for each in J: + D[each] = 0 + + Sum = 0 + for each in S: + if D.get(each) is not None : + Sum += 1 + + return Sum diff --git a/solution/0797.All Paths From Source to Target/Solution.cpp b/solution/0797.All Paths From Source to Target/Solution.cpp new file mode 100644 index 0000000000000..ee20513212fbe --- /dev/null +++ b/solution/0797.All Paths From Source to Target/Solution.cpp @@ -0,0 +1,38 @@ +class Solution { +private: + vector> paths ; + vector visited = vector(16, false) ; + vector path ; + + void search(vector>& graph, int s, int e) + { + if (visited.at(s)) + return ; + + if (s == e) + { + path.push_back(e) ; + paths.push_back(path) ; + path.pop_back() ; + return ; + } + + visited[s] = true ; // visited + path.push_back(s) ; + for (auto to: graph[s]) + search(graph, to, e) ; + path.pop_back() ; + visited[s] = false ; + + } + +public: + vector> allPathsSourceTarget(vector>& graph) { + if (graph.size() == 0) + return {} ; + + search(graph, 0, graph.size()-1) ; + + return paths ; + } +}; \ No newline at end of file diff --git a/solution/0804.Unique Morse Code Words/Solution.py b/solution/0804.Unique Morse Code Words/Solution.py new file mode 100644 index 0000000000000..699cd8d0f1f4d --- /dev/null +++ b/solution/0804.Unique Morse Code Words/Solution.py @@ -0,0 +1,14 @@ +class Solution: + def uniqueMorseRepresentations(self, words): + """ + :type words: List[str] + :rtype: int + """ + + morse_code = [".-", "-...", "-.-.", "-..", ".", "..-.", "--.", "....", "..", ".---", "-.-", ".-..", "--", "-.", "---", ".--.", "--.-", ".-.", "...", "-", "..-", "...-", ".--", "-..-", "-.--", "--.."] + + unique = {} + for each in words: + unique["".join(morse_code[ord(ch)-97] for ch in each)] = 0 + + return len(unique) diff --git a/solution/0807.Max Increase to Keep City Skyline/Solution.cpp b/solution/0807.Max Increase to Keep City Skyline/Solution.cpp new file mode 100644 index 0000000000000..5791905517109 --- /dev/null +++ b/solution/0807.Max Increase to Keep City Skyline/Solution.cpp @@ -0,0 +1,29 @@ +class Solution { +public: + int maxIncreaseKeepingSkyline(vector>& grid) + { + + vector h(grid.size(), -1), w(grid[0]) ; + + for (int i = 0; i < grid.size(); ++i) + for (int j = 0; j < grid[i].size(); ++j) + { + if (grid[i][j] > h[i]) + h[i] = grid[i][j] ; + if (grid[i][j] > w[j]) + w[j] = grid[i][j] ; + } + int sum = 0 ; + + for (int i = 0; i < grid.size(); ++i) + for (int j = 0; j < grid.size(); ++j) + { + int m = h[i] < w[j]? h[i]: w[j] ; + if (grid[i][j] < m) + sum += m - grid[i][j] ; + } + + + return sum ; + } +}; diff --git a/solution/0832.Flipping an Image/README.md b/solution/0832.Flipping an Image/README.md new file mode 100644 index 0000000000000..726ef2536861a --- /dev/null +++ b/solution/0832.Flipping an Image/README.md @@ -0,0 +1,85 @@ +# 翻转图像 + +### 题目描述 + +给定一个二进制矩阵 `A`,我们想先水平翻转图像,然后反转图像并返回结果。 + +水平翻转图片就是将图片的每一行都进行翻转,即逆序。例如,水平翻转 `[1, 1, 0]` 的结果是 `[0, 1, 1]`。 + +反转图片的意思是图片中的 `0` 全部被 `1` 替换, `1` 全部被 `0` 替换。例如,反转 `[0, 1, 1]` 的结果是 `[1, 0, 0]`。 + +**示例 1** + +``` +输入: [[1,1,0],[1,0,1],[0,0,0]] +输出: [[1,0,0],[0,1,0],[1,1,1]] +解释: 首先翻转每一行: [[0,1,1],[1,0,1],[0,0,0]]; + 然后反转图片: [[1,0,0],[0,1,0],[1,1,1]] +``` + +**示例 2** + +``` +输入: [[1,1,0,0],[1,0,0,1],[0,1,1,1],[1,0,1,0]] +输出: [[1,1,0,0],[0,1,1,0],[0,0,0,1],[1,0,1,0]] +解释: 首先翻转每一行: [[0,0,1,1],[1,0,0,1],[1,1,1,0],[0,1,0,1]]; + 然后反转图片: [[1,1,0,0],[0,1,1,0],[0,0,0,1],[1,0,1,0]] +``` + +**说明** + +- `1 <= A.length = A[0].length <= 20` +- `0 <= A[i][j] <= 1` + +### 解法 + +**第一种解法** + +**思路** + +实际上,对数组进行翻转并取反,数组只需要对比对称位上的数组是否相同,如果相同,就进行取反,如果不同,则不去取反,以为当对称位数字不同,进行一次翻转后在取反和原先的数字是相同的。 + +**算法** + +```javascript +var flipAndInvertImage = function(A) { + const len = A.length; + for (let k = 0; k < len; k++ ) { + let j = len - 1; + for(let i = 0; i <= ~~( j / 2 ); i++){ + if ( A[k][i] === A[k][j - i] ) { + A[k][i] === 1 ? A[k][i] = A[k][j - i] = 0 : A[k][i] = A[k][j - i] = 1; + } + } + } + return A; +} +``` + +**复杂度分析** + +暂无 + +**第二种解法** + +**思路** + +正常的进行交换取反值。这个解法中双非~~和 按位异或 ^ 的用法非常棒。 + +**算法** + +```javascript +var flipAndInvertImage2 = function(A) { + for (let i = 0; i < A.length; ++i) { + let last = A[i].length - 1; + for (let j = 0; j <= ~~(last / 2); ++j) { + [ A[i][j], A[i][last - j] ] = [ A[i][last - j] ^ 1, A[i][j] ^ 1 ]; + } + } + return A; +}; +``` + +**复杂度分析** + +暂无 \ No newline at end of file diff --git a/solution/0832.Flipping an Image/Solution.cpp b/solution/0832.Flipping an Image/Solution.cpp new file mode 100644 index 0000000000000..f967fcca98ad5 --- /dev/null +++ b/solution/0832.Flipping an Image/Solution.cpp @@ -0,0 +1,18 @@ +class Solution { + public: + vector> flipAndInvertImage(vector> &A) { + + int temp, Len = A[0].size(); + + for (int i = 0; i < A.size(); i++) + { + for (int j = 0; j < ((Len + 1) / 2); j++) + { + temp = !A[i][j]; + A[i][j] = !A[i][Len - j - 1]; + A[i][Len - j - 1] = temp; + } + } + return A; + } +}; diff --git a/solution/0832.Flipping an Image/Solution.js b/solution/0832.Flipping an Image/Solution.js new file mode 100644 index 0000000000000..4d61110ac6741 --- /dev/null +++ b/solution/0832.Flipping an Image/Solution.js @@ -0,0 +1,32 @@ +/** + * @param {number[][]} A + * @return {number[][]} + */ + +/** + * Author: Mcnwork2018 + */ + +// 第一种思路,碰到相等的情况才进行取反 +var flipAndInvertImage = function(A) { + const len = A.length; + for (let k = 0; k < len; k++ ) { + let j = len - 1; + for(let i = 0; i <= ~~( j / 2 ); i++){ + if ( A[k][i] === A[k][j - i] ) { + A[k][i] === 1 ? A[k][i] = A[k][j - i] = 0 : A[k][i] = A[k][j - i] = 1; + } + } + } + return A; +} +// 第二种思路,无论是否相等,对每个值都进行交换并取反 +var flipAndInvertImage2 = function(A) { + for (let i = 0; i < A.length; ++i) { + let last = A[i].length - 1; + for (let j = 0; j <= ~~(last / 2); ++j) { + [ A[i][j], A[i][last - j] ] = [ A[i][last - j] ^ 1, A[i][j] ^ 1 ]; + } + } + return A; +}; \ No newline at end of file diff --git a/solution/0832.Flipping an Image/Solution.py b/solution/0832.Flipping an Image/Solution.py new file mode 100644 index 0000000000000..35a3121b9ffcb --- /dev/null +++ b/solution/0832.Flipping an Image/Solution.py @@ -0,0 +1,14 @@ +class Solution: + def flipAndInvertImage(self, A): + """ + :type A: List[List[int]] + :rtype: List[List[int]] + """ + + Len = len(A[0]) + + for row in A: + for i in range( (Len + 1) // 2 ): + row[i], row[Len - i - 1] = int(not row[Len - i - 1]), int(not row[i]) + + return A diff --git a/solution/0848.Shifting Letters/README.md b/solution/0848.Shifting Letters/README.md new file mode 100644 index 0000000000000..97a7c64b4e4ac --- /dev/null +++ b/solution/0848.Shifting Letters/README.md @@ -0,0 +1,44 @@ +## 字母移位 + +### 问题描述 + +有一个由小写字母组成的字符串 `S`,和一个整数数组 `shifts`。 + +我们将字母表中的下一个字母称为原字母的 移位(由于字母表是环绕的, `'z'` 将会变成 `'a'`)。 + +例如·,`shift('a') = 'b'`, `shift('t') = 'u'`,, 以及 `shift('z') = 'a'`。 + +对于每个 `shifts[i] = x`, 我们会将 `S` 中的前 `i+1` 个字母移位 `x` 次。 + +返回将所有这些移位都应用到 `S` 后最终得到的字符串。 + +**示例:** +``` +输入:S = "abc", shifts = [3,5,9] +输出:"rpl" +解释: +我们以 "abc" 开始。 +将 S 中的第 1 个字母移位 3 次后,我们得到 "dbc"。 +再将 S 中的前 2 个字母移位 5 次后,我们得到 "igc"。 +最后将 S 中的这 3 个字母移位 9 次后,我们得到答案 "rpl"。 +``` + +**提示:** +- 1 <= S.length = shifts.length <= 20000 +- 0 <= shifts[i] <= 10 ^ 9 + +### 解法 + +对于`S`中的每个字母,先将需要移动的长度求出,然后直接移位即可。从后往前遍历会比从前往后遍历快一点点,因为从前往后需要先求出`shifts`的和。 + +```python +class Solution: + def shiftingLetters(self, S, shifts): + mov = 0 + ans = list(S) + for i in range(len(S) - 1, -1, -1): + mov += shifts[i] + ans[i] = chr((ord(S[i]) - 97 + mov % 26) % 26 + 97) + return ''.join(ans) + +``` diff --git a/solution/0848.Shifting Letters/Solution.py b/solution/0848.Shifting Letters/Solution.py new file mode 100644 index 0000000000000..17dea0fe30e04 --- /dev/null +++ b/solution/0848.Shifting Letters/Solution.py @@ -0,0 +1,13 @@ +class Solution: + def shiftingLetters(self, S, shifts): + """ + :type S: str + :type shifts: List[int] + :rtype: str + """ + mov = 0 + ans = list(S) + for i in range(len(S) - 1, -1, -1): + mov += shifts[i] + ans[i] = chr((ord(S[i]) - 97 + mov % 26) % 26 + 97) + return ''.join(ans) diff --git a/solution/0867.Transpose Matrix/README.md b/solution/0867.Transpose Matrix/README.md new file mode 100644 index 0000000000000..ab453d03d6cfa --- /dev/null +++ b/solution/0867.Transpose Matrix/README.md @@ -0,0 +1,55 @@ +# 转置矩阵 + +### 题目描述 + +给定一个矩阵 `A`, 返回 `A` 的转置矩阵。 + +矩阵的转置是指将矩阵的主对角线翻转,交换矩阵的行索引与列索引。 + +**示例 1** + +``` +输入:[[1,2,3],[4,5,6],[7,8,9]] +输出:[[1,4,7],[2,5,8],[3,6,9]] +``` + +**示例 2** + +``` +输入:[[1,2,3],[4,5,6]] +输出:[[1,4],[2,5],[3,6]] +``` + +**提示** + +1. `1 <= A.length <= 1000` +2. `1 <= A[0].length <= 1000` + +### 解题思路 + +**思路** + +尺寸为 `R x C` 的矩阵 `A` 转置后会得到尺寸为 `C x R` 的矩阵 `ans`,对此有 `ans[c][r] = A[r][c]`。 + +让我们初始化一个新的矩阵 `ans` 来表示答案。然后,我们将酌情复制矩阵的每个条目。 + +**算法** + +```javascript +var transpose = function (A) { + if ( A.length === 1 && A[0].length === 1 ) return A; + let tran_matrix = []; + for ( let i = 0; i < A[0].length; ++i ) { + tran_matrix[i] = []; + for ( let j = 0; j < A.length; ++j ) { + tran_matrix[i][j] = A[j][i]; + } + } + return tran_matrix; +}; +``` + +**复杂度分析** + +- 时间复杂度:*O*(*R*∗*C*),其中 *R* 和 *C* 是给定矩阵 `A` 的行数和列数。 +- 空间复杂度:*O*(*R*∗*C*),也就是答案所使用的空间。 \ No newline at end of file diff --git a/solution/0867.Transpose Matrix/Solution.js b/solution/0867.Transpose Matrix/Solution.js new file mode 100644 index 0000000000000..372010f0c2036 --- /dev/null +++ b/solution/0867.Transpose Matrix/Solution.js @@ -0,0 +1,20 @@ +/** + * @param {number[][]} A + * @return {number[][]} + */ + +/** + * Author: Mcnwork2018 + */ + +var transpose = function (A) { + if ( A.length === 1 && A[0].length === 1 ) return A; + let tran_matrix = []; + for ( let i = 0; i < A[0].length; ++i ) { + tran_matrix[i] = []; + for ( let j = 0; j < A.length; ++j ) { + tran_matrix[i][j] = A[j][i]; + } + } + return tran_matrix; +}; \ No newline at end of file diff --git a/solution/0905.Sort Array By Parity/README.md b/solution/0905.Sort Array By Parity/README.md new file mode 100644 index 0000000000000..ac7b80074bbd4 --- /dev/null +++ b/solution/0905.Sort Array By Parity/README.md @@ -0,0 +1,127 @@ +# 按奇偶排序数组 + +### 题目描述 + +给定一个非负整数数组 `A`,返回一个由 `A` 的所有偶数元素组成的数组,后面跟 `A` 的所有奇数元素。 + +你可以返回满足此条件的任何数组作为答案。 + +**示例** + +``` +输入:[3,1,2,4] +输出:[2,4,3,1] +输出 [4,2,3,1],[2,4,1,3] 和 [4,2,1,3] 也会被接受。 +``` + +**提示** + +1. `1 <= A.length <= 5000` +2. `0 <= A[i] <= 5000` + +### 解法 + +官方题解缺失 + +**第一种解法** + +**思路** + +将数组`A`中的奇数和偶数都分别的提取到一个数组中,最后进行合并数组操作。 + +**算法** + +```javascript +var sortArrayByParity = function (A) { + const len = A.length; + if (len === 1) return A; + let evenNumber = [], oddNumber = []; + for (let i = 0; i < len; i++) { + if (A[i] % 2 === 0) { + evenNumber.push(A[i]); + } else { + oddNumber.push(A[i]); + } + } + return evenNumber.concat(oddNumber); +}; +``` + +**复杂度分析** + +暂无 + +**第二种解法** + +**思路** + +利用数组实现一个特殊的队列,队列两头都可以进,前面进偶数,后面进奇数。 + +**算法** + +```javascript +var sortArrayByParity = function (A) { + const len = A.length; + if (len === 1) return A; + let eoNum = []; + A.forEach((item, index, array) => { + if (item % 2 === 1) { + eoNum.push(item); + } else { + eoNum.unshift(item); + } + }); + return eoNum; +}; +``` + +**复杂度分析** + +暂无 + +**第三种解法** + +**思路** + +利用双指针`i`、`j`,`i`指向数组的开始,`j`指向数组的末尾,当`i` <`j`时,比较`A[i]`和`A[j]`,若`i`指向的为奇数,`j`指向的为偶数,交换`A[i]`和`A[j]`,`i`加一,`j`减一。若`A[i]`为偶数,`i`加一,不进行交换。若`A[j]`为奇数,`j`减一,不进行交换。 + +**算法** + +```javascript +// 第一种思路 +var sortArrayByParity = function (A) { + const len = A.length; + if (len === 1) return A; + let i = 0, j = len - 1; + while (i < j) { + if ((A[i] % 2 === 1) && (A[j] % 2 === 0)) { + let temp = A[j]; + A[j--] = A[i]; + A[i++] = temp; + } + if (A[i] % 2 === 0) i++; + if (A[j] % 2 === 1) j--; + } + return A; +}; +// 第二种思路 +var sortArrayByParity = function (A) { + const len = A.length; + if (len === 1) return A; + let i = 0, j = len - 1; + while (i < j) { + while ( A[i] % 2 === 0 ) i++; + while ( A[j] % 2 === 1 ) j--; + while( i < j && (A[i] % 2 === 1) && (A[j] % 2 === 0) ){ + let temp = A[j]; + A[j--] = A[i]; + A[i++] = temp; + } + } + return A; +}; +``` + +**复杂度分析** + +暂无 \ No newline at end of file diff --git a/solution/0905.Sort Array By Parity/Solution.js b/solution/0905.Sort Array By Parity/Solution.js new file mode 100644 index 0000000000000..4173defca9ec2 --- /dev/null +++ b/solution/0905.Sort Array By Parity/Solution.js @@ -0,0 +1,54 @@ +/** + * @param {number[]} A + * @return {number[]} + */ +// 第一次的做法 +var sortArrayByParity = function (A) { + const len = A.length; + if (len == 1) return A; + let evenNumber = []; + let oddNumber = []; + for (let i = 0; i < len; i++) { + if (A[i] % 2 == 0) { + evenNumber.push(A[i]); + } + if (A[i] % 2 != 0) { + oddNumber.push(A[i]); + } + } + return evenNumber.concat(oddNumber); +}; +// 修改第一次的代码,只使用一个数组,减少一次合并数组操作 +var sortArrayByParity = function (A) { + const len = A.length; + if (len == 1) return A; + let eoNum = []; + for (let i = 0; i < len; i++) { + if (A[i] % 2 == 1) { + eoNum.push(A[i]); + } + if (A[i] % 2 == 0) { + eoNum.unshift(A[i]); + } + } + return eoNum; +}; +// 双指针做法,无需新数组,push和unshift操作,利用第三个变量进行交换 +var sortArrayByParity = function (A) { + const len = A.length; + if (len == 1) return A; + let i = 0, + j = len - 1; + while (i < j) { + if ((A[i] % 2 == 1) && (A[j] % 2 == 0)) { + let temp = A[j]; + A[j] = A[i]; + A[i] = temp; + i++; + j--; + } + if (A[i] % 2 == 0) i++; + if (A[j] % 2 == 1) j--; + } + return A; +}; \ No newline at end of file diff --git a/solution/0905.Sort Array By Parity/Solution.py b/solution/0905.Sort Array By Parity/Solution.py new file mode 100644 index 0000000000000..6ece931651189 --- /dev/null +++ b/solution/0905.Sort Array By Parity/Solution.py @@ -0,0 +1,8 @@ +class Solution: + def sortArrayByParity(self, A): + """ + :type A: List[int] + :rtype: List[int] + """ + + return sorted(A, key = lambda i: i % 2) diff --git a/solution/0917.Reverse Only Letters/Solution.cpp b/solution/0917.Reverse Only Letters/Solution.cpp new file mode 100644 index 0000000000000..c9f0df4ed6471 --- /dev/null +++ b/solution/0917.Reverse Only Letters/Solution.cpp @@ -0,0 +1,22 @@ +class Solution { +public: + string reverseOnlyLetters(string S) { + + int start = 0, end = S.length()-1; + char temp; + + while( start < end ){ + + while( start < end && ! isalpha(S[start]) ) + start++; + while( start < end && ! isalpha(S[end]) ) + end--; + + swap(S[start], S[end]); + start++; + end--; + } + + return S; + } +}; diff --git a/solution/0917.Reverse Only Letters/Solution.py b/solution/0917.Reverse Only Letters/Solution.py new file mode 100644 index 0000000000000..bf08b86430096 --- /dev/null +++ b/solution/0917.Reverse Only Letters/Solution.py @@ -0,0 +1,24 @@ +class Solution: + def reverseOnlyLetters(self, S): + """ + :type S: str + :rtype: str + """ + + S = list(S) + + start = 0 + end = len(S)-1 + + while start < end : + + while start < end and S[start] not in string.ascii_letters : + start += 1 + while start < end and S[end] not in string.ascii_letters : + end -= 1 + + S[start], S[end] = S[end], S[start] + start += 1 + end -= 1 + + return ''.join(S) diff --git a/solution/0922.Sort Array By Parity II/README.md b/solution/0922.Sort Array By Parity II/README.md new file mode 100644 index 0000000000000..6d7ea48b85c68 --- /dev/null +++ b/solution/0922.Sort Array By Parity II/README.md @@ -0,0 +1,52 @@ +# 按奇偶排序数组 II + +### 题目描述 + +给定一个非负整数数组 `A`, A 中一半整数是奇数,一半整数是偶数。 + +对数组进行排序,以便当 `A[i]` 为奇数时,`i` 也是奇数;当 `A[i]` 为偶数时, `i` 也是偶数。 + +你可以返回任何满足上述条件的数组作为答案。 + +**示例** + +``` +输入:[4,2,5,7] +输出:[4,5,2,7] +解释:[4,7,2,5],[2,5,4,7],[2,7,4,5] 也会被接受。 +``` + +**提示** + +1. `2 <= A.length <= 20000` +2. `A.length % 2 == 0` +3. `0 <= A[i] <= 1000` + +### 解题思路 + +**思路** + +两个指针`i`、`j`分别指向偶数位和奇数位,当`A[i]`是奇数时,寻找最近的`A[j]`是偶数的位置,交换两个数字。直至遍历完整个数组的偶数位。 + +**算法** + +```javascript +var sortArrayByParityII = function(A) { + let index = A.length - 1, i = 0, j = 1; // index A的索引,i偶数位,j奇数位。 + for( ; i < index; i += 2 ){ + if( (A[i] & 1) != 0 ){ // 寻找A[i]是奇数的情况。 + while( (A[j] & 1) != 0 ){ // 寻找A[j]是偶数的情况。 + j += 2; + } + let temp = A[j]; + A[j] = A[i]; + A[i] = temp; + } + } + return A; +}; +``` + +**复杂度分析** + +暂无 \ No newline at end of file diff --git a/solution/0922.Sort Array By Parity II/Solution.js b/solution/0922.Sort Array By Parity II/Solution.js new file mode 100644 index 0000000000000..443f382136357 --- /dev/null +++ b/solution/0922.Sort Array By Parity II/Solution.js @@ -0,0 +1,23 @@ +/** + * @param {number[]} A + * @return {number[]} + */ + +/** + * Author: Mcnwork2018 + */ + +var sortArrayByParityII = function(A) { + let index = A.length - 1, i = 0, j = 1; // index A的索引, i偶数位, j奇数位。 + for ( ; i < index; i += 2 ) { + if ( (A[i] & 1) != 0 ) { // 寻找A[i]是奇数的情况。 + while ( (A[j] & 1) != 0 ) { // 寻找A[j]是偶数的情况。 + j += 2; + } + let temp = A[j]; + A[j] = A[i]; + A[i] = temp; + } + } + return A; +}; \ No newline at end of file diff --git a/solution/0929.Unique Email Addresses/Solution.py b/solution/0929.Unique Email Addresses/Solution.py new file mode 100644 index 0000000000000..0452142e37ad4 --- /dev/null +++ b/solution/0929.Unique Email Addresses/Solution.py @@ -0,0 +1,13 @@ +class Solution: + def numUniqueEmails(self, emails): + """ + :type emails: List[str] + :rtype: int + """ + E = {} + for each in emails: + local_name, domain = each.split('@') + local_name = local_name.split('+')[0].replace('.', '') + E[local_name + '@' + domain] = 0 + + return len(E) diff --git a/solution/0938.Range Sum of BST/Solution.cpp b/solution/0938.Range Sum of BST/Solution.cpp new file mode 100644 index 0000000000000..d0ae18840bb52 --- /dev/null +++ b/solution/0938.Range Sum of BST/Solution.cpp @@ -0,0 +1,47 @@ +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode(int x) : val(x), left(NULL), right(NULL) {} + * }; + */ +class Solution { +public: + int rangeSumBST(TreeNode* root, int L, int R) { + if (nullptr == root) + return 0 ; + stack s ; + s.push(root) ; + int sum = 0 ; + while (!s.empty()) + { + TreeNode *node = s.top() ; + s.pop() ; + + if (nullptr == node) + continue ; + + if (node->val > R) + s.push(node->left) ; + else if (node->val < L) + s.push(node->right) ; + else + { + sum += node->val ; + s.push(node->left) ; + s.push(node->right) ; + } + } + + return sum ; + } +}; + +static int x = []() +{ + ios::sync_with_stdio(false); + cin.tie(nullptr); + return 0; +}() ; diff --git a/solution/0941.Valid Mountain Array/Solution.cpp b/solution/0941.Valid Mountain Array/Solution.cpp new file mode 100644 index 0000000000000..68c431f9bed07 --- /dev/null +++ b/solution/0941.Valid Mountain Array/Solution.cpp @@ -0,0 +1,20 @@ +class Solution { +public: + bool validMountainArray(vector& A) { + if (A.size() < 3) + return false ; + + A.push_back(A[0]) ; + int lastIndex = A.size()-2 ; + int p ; + for (p = 0; A[p] < A[p+1]; ++p) + ; + if (p == lastIndex || 0 == p) + return false ; + A[A.size()-1] = A[p] ; + for (; A[p] > A[p+1]; ++p) + ; + + return p == lastIndex ; + } +}; diff --git a/solution/0944.Delete Columns to Make Sorted/Solution.py b/solution/0944.Delete Columns to Make Sorted/Solution.py new file mode 100644 index 0000000000000..dd607b374070c --- /dev/null +++ b/solution/0944.Delete Columns to Make Sorted/Solution.py @@ -0,0 +1,12 @@ +class Solution: + def minDeletionSize(self, A: 'List[str]') -> 'int': + + count = 0 + + for i in range(len(A[0])): + for j in range(len(A) - 1): + if A[j][i] > A[j + 1][i] : + count += 1 + break + + return count diff --git a/solution/0950.Reveal Cards In Increasing Order/Solution.cpp b/solution/0950.Reveal Cards In Increasing Order/Solution.cpp new file mode 100644 index 0000000000000..ad6d918d106d9 --- /dev/null +++ b/solution/0950.Reveal Cards In Increasing Order/Solution.cpp @@ -0,0 +1,33 @@ +class Solution { +public: + vector deckRevealedIncreasing(vector& deck) { + if (deck.size() == 0) + return {} ; + + sort(deck.begin(), deck.end()) ; + int len = deck.size() ; + + int flg = deck.at(0)-1 ; + vector o(len, flg) ; + + int i = 0, p = 0; + for ( ; ;) + { + o[p] = deck.at(i) ; + + if (++i < len) + { + do { + p = (p+1)%len ; + } while (o.at(p) != flg) ; + do { + p = (p+1)%len ; + } while (o.at(p) != flg) ; + } + else + break ; + } + + return o ; + } +}; \ No newline at end of file diff --git a/solution/0953.Verifying an Alien Dictionary/Solution.cpp b/solution/0953.Verifying an Alien Dictionary/Solution.cpp new file mode 100644 index 0000000000000..383dddf5d1055 --- /dev/null +++ b/solution/0953.Verifying an Alien Dictionary/Solution.cpp @@ -0,0 +1,35 @@ +class Solution { +private: + int ala[26] = {0, } ; +public: + bool isAlienSorted(vector& words, string order) + { + if (words.size() <= 1) + return true ; + + int i = 0 ; + for (i = 0; i < order.size(); ++i) + ala[order[i] - 'a'] = i ; + + for (i = 1; i < words.size(); ++i) + if (!cmp(words[i-1], words[i])) + return false ; + + return true ; + } + + bool cmp(string a, string b) + { + int i, len = min(a.size(), b.size()) ; + for (i = 0; i < len; ++i) + { + int c = ala[ a[i] - 'a' ] - ala[ b[i] - 'a' ] ; + if (c < 0) + return true ; + else if (c > 0) + return false ; + } + + return i == a.size() ; + } +}; \ No newline at end of file diff --git a/solution/0953.Verifying an Alien Dictionary/Solution.py b/solution/0953.Verifying an Alien Dictionary/Solution.py new file mode 100644 index 0000000000000..5a4d66d9ee864 --- /dev/null +++ b/solution/0953.Verifying an Alien Dictionary/Solution.py @@ -0,0 +1,24 @@ +class Solution: + def isAlienSorted(self, words, order): + """ + :type words: List[str] + :type order: str + :rtype: bool + """ + + order = {a: d for d, a in enumerate(order)} + + for i in range(1, len(words)): + j = 0 + while len(words[i - 1]) > j < len(words[i]): + + value = order[words[i - 1][j]] - order[words[i][j]] + + if value < 0: + break + elif value > 0 or (j + 1) == len(words[i]): + return False + + j += 1 + + return True diff --git a/solution/0961.N-Repeated Element in Size 2N Array/README.md b/solution/0961.N-Repeated Element in Size 2N Array/README.md new file mode 100644 index 0000000000000..b1e6e5488a30b --- /dev/null +++ b/solution/0961.N-Repeated Element in Size 2N Array/README.md @@ -0,0 +1,54 @@ +## 重复 N 次的元素 + +### 问题描述 + +在大小为 `2N` 的数组 `A` 中有 `N+1` 个不同的元素,其中有一个元素重复了 `N` 次。 + +返回重复了 `N` 次的那个元素。 + +**示例1:** + +``` +输入:[1,2,3,3] +输出:3 +``` + +**示例2:** + +``` +输入:[2,1,2,5,3,2] +输出:2 +``` + +**示例3:** + +``` +输入:[5,1,5,2,5,3,5,4] +输出:5 +``` + +**提示:** + +- `4 <= A.length <= 10000` +- `0 <= A[i] < 10000` +- `A.length` 为偶数 + +### 解法 +1. 直接用哈希表或者集合等数据结构就可解决。 +2. 由题意,只有一个元素是重复的,找到就行了。 + +```python +class Solution: + def repeatedNTimes(self, A): + if A[0] == A[1] or A[0] == A[2] or A[0] == A[3]: + return A[0] + elif A[1] == A[2] or A[1] == A[3]: + return A[1] + elif A[2] == A[3]: + return A[2] + i = 4 + while i < len(A): + if A[i] == A[i + 1]: + return A[i] + i += 2 +``` diff --git a/solution/0961.N-Repeated Element in Size 2N Array/Solution.cpp b/solution/0961.N-Repeated Element in Size 2N Array/Solution.cpp new file mode 100644 index 0000000000000..ac692420cc547 --- /dev/null +++ b/solution/0961.N-Repeated Element in Size 2N Array/Solution.cpp @@ -0,0 +1,12 @@ +class Solution { +public: + int repeatedNTimes(vector& A) { + unordered_set us(A[0]) ; + for(int i = (A.size() >> 1) - 1; i < A.size(); ++i) + if(us.find(A[i]) != us.end()) + return A[i] ; + else + us.insert(A[i]) ; + return A[0] ; + } +}; \ No newline at end of file diff --git a/solution/0961.N-Repeated Element in Size 2N Array/Solution.java b/solution/0961.N-Repeated Element in Size 2N Array/Solution.java new file mode 100644 index 0000000000000..969d85fa53767 --- /dev/null +++ b/solution/0961.N-Repeated Element in Size 2N Array/Solution.java @@ -0,0 +1,12 @@ +class Solution { + public int repeatedNTimes(int[] A) { + Set set = new HashSet<>(); + for (int e : A) { + if (set.contains(e)) { + return e; + } + set.add(e); + } + return 0; + } +} \ No newline at end of file diff --git a/solution/0961.N-Repeated Element in Size 2N Array/Solution.js b/solution/0961.N-Repeated Element in Size 2N Array/Solution.js new file mode 100644 index 0000000000000..76cac92e0da23 --- /dev/null +++ b/solution/0961.N-Repeated Element in Size 2N Array/Solution.js @@ -0,0 +1,10 @@ +const repeatedNTimes = function (A) { + let ss = new Set(); + for (let i = 0; i < A.length; i++) { + if (ss.has(A[i])) { + return A[i]; + } + ss.add(A[i]); + } + return null; +}; \ No newline at end of file diff --git a/solution/0961.N-Repeated Element in Size 2N Array/Solution.py b/solution/0961.N-Repeated Element in Size 2N Array/Solution.py new file mode 100644 index 0000000000000..6b6f8ac83c13a --- /dev/null +++ b/solution/0961.N-Repeated Element in Size 2N Array/Solution.py @@ -0,0 +1,17 @@ +class Solution: + def repeatedNTimes(self, A): + """ + :type A: List[int] + :rtype: int + """ + if A[0] == A[1] or A[0] == A[2] or A[0] == A[3]: + return A[0] + elif A[1] == A[2] or A[1] == A[3]: + return A[1] + elif A[2] == A[3]: + return A[2] + i = 4 + while i < len(A): + if A[i] == A[i + 1]: + return A[i] + i += 2 diff --git a/solution/0961.N-Repeated Element in Size 2N Array/Solution2.cpp b/solution/0961.N-Repeated Element in Size 2N Array/Solution2.cpp new file mode 100644 index 0000000000000..9c4463793a4d2 --- /dev/null +++ b/solution/0961.N-Repeated Element in Size 2N Array/Solution2.cpp @@ -0,0 +1,10 @@ +class Solution { +public: + int repeatedNTimes(vector& A) { + for(int i = (A.size() >> 1) - 1; i < A.size(); ++i) + for(int j = i+1; j < A.size(); ++j) + if(A[i] == A[j]) + return A[i]; + return A[0] ; + } +}; \ No newline at end of file diff --git a/solution/0961.N-Repeated Element in Size 2N Array/Solution2.py b/solution/0961.N-Repeated Element in Size 2N Array/Solution2.py new file mode 100644 index 0000000000000..5229b6c526a7e --- /dev/null +++ b/solution/0961.N-Repeated Element in Size 2N Array/Solution2.py @@ -0,0 +1,15 @@ +class Solution: + def repeatedNTimes(self, A): + """ + :type A: List[int] + :rtype: int + """ + + count = {} + for i in A: + try: + count[i] += 1 + return i + except KeyError: + count[i] = 0 + diff --git a/solution/0965.Univalued Binary Tree/Solution.cpp b/solution/0965.Univalued Binary Tree/Solution.cpp new file mode 100644 index 0000000000000..2af39cb5d4b9b --- /dev/null +++ b/solution/0965.Univalued Binary Tree/Solution.cpp @@ -0,0 +1,30 @@ +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode(int x) : val(x), left(NULL), right(NULL) {} + * }; + */ +class Solution { +private: + bool isUnivalVal(TreeNode* r, int val) + { + if (val != r->val) + return false ; + + if (r->left && !isUnivalVal(r->left, val)) + return false ; + if (r->right && !isUnivalVal(r->right, val)) + return false ; + + return true ; + } +public: + bool isUnivalTree(TreeNode* root) { + if (nullptr == root) + return true ; + return isUnivalVal(root, root->val) ; + } +} ; \ No newline at end of file diff --git a/solution/0976.Largest Perimeter Triangle/Solution.cpp b/solution/0976.Largest Perimeter Triangle/Solution.cpp new file mode 100644 index 0000000000000..20e4f4e538d9d --- /dev/null +++ b/solution/0976.Largest Perimeter Triangle/Solution.cpp @@ -0,0 +1,22 @@ +class Solution { +public: + int largestPerimeter(vector& A) { + priority_queue q(A.begin(), A.end()) ; // 大顶堆 + + int a, b, c ; + b = q.top() ; + q.pop() ; + c = q.top() ; + q.pop() ; + while ( !q.empty() ) + { + a = b ; + b = c ; + c = q.top() ; + q.pop() ; + if ( b + c > a ) + return a + b + c ; + } + return 0 ; + } +}; diff --git a/solution/0977.Squares of a Sorted Array/README.md b/solution/0977.Squares of a Sorted Array/README.md new file mode 100644 index 0000000000000..8e807d755d465 --- /dev/null +++ b/solution/0977.Squares of a Sorted Array/README.md @@ -0,0 +1,38 @@ +## 有序数组的平方 +### 题目描述 + +给定一个按非递减顺序排序的整数数组 A,返回每个数字的平方组成的新数组,要求也按非递减顺序排序。 + + +**示例 1:** +``` +输入:[-4,-1,0,3,10] +输出:[0,1,9,16,100] +``` + +**示例 2:** +``` +输入:[-7,-3,2,3,11] +输出:[4,9,9,49,121] +``` + +**提示:** + +1. 1 <= A.length <= 10000 +2. -10000 <= A[i] <= 10000 +3. A 已按非递减顺序排序。 + +### 解法 +先平方后排序。 + +```java +class Solution { + public int[] sortedSquares(int[] A) { + for (int i = 0, n = A.length; i < n; ++i) { + A[i] = A[i] * A[i]; + } + Arrays.sort(A); + return A; + } +} +``` diff --git a/solution/0977.Squares of a Sorted Array/Solution.cpp b/solution/0977.Squares of a Sorted Array/Solution.cpp new file mode 100644 index 0000000000000..03431b84b947b --- /dev/null +++ b/solution/0977.Squares of a Sorted Array/Solution.cpp @@ -0,0 +1,17 @@ +bool check(int x, int y){ + return abs(x) < abs(y); +} + +class Solution { +public: + + vector sortedSquares(vector& A) { + + sort(A.begin(), A.end(), check); + + for(int i = 0; i < A.size(); i++) + A[i] = pow(A[i], 2); + + return A; + } +}; diff --git a/solution/0977.Squares of a Sorted Array/Solution.java b/solution/0977.Squares of a Sorted Array/Solution.java new file mode 100644 index 0000000000000..c7bd148f2bd5a --- /dev/null +++ b/solution/0977.Squares of a Sorted Array/Solution.java @@ -0,0 +1,9 @@ +class Solution { + public int[] sortedSquares(int[] A) { + for (int i = 0, n = A.length; i < n; ++i) { + A[i] = A[i] * A[i]; + } + Arrays.sort(A); + return A; + } +} \ No newline at end of file diff --git a/solution/0977.Squares of a Sorted Array/Solution.js b/solution/0977.Squares of a Sorted Array/Solution.js new file mode 100644 index 0000000000000..9ea4908e7b4ce --- /dev/null +++ b/solution/0977.Squares of a Sorted Array/Solution.js @@ -0,0 +1,46 @@ +/** + * @param {number[]} A + * @return {number[]} + */ +/** + * Author: Mcnwork2018 + */ +// 第一种解法 +var sortedSquares = function(A) { + let results = A.map((item, index, array) => { + return item *= item; + }); + results.sort((v1, v2) => { + return v1 -v2; + }); + return results; +}; +// 第二种解法 +var sortedSquares = function(A){ + let len = A.length; // 数组长度 + let j = 0; // j 正数开始 + while ( j < len && A[j] < 0 ) { + j++; + } + let i = j - 1; // i 负数开始 + let results = []; // 存放最终结果 + let t = 0; // results下标 + while ( i >= 0 && j < len ) { + if ( A[i] * A[i] < A[j] * A[j] ) { + results[t++] = A[i] * A[i]; + i--; + } else { + results[t++] = A[j] * A[j]; + j++; + } + } + while ( i >= 0 ) { + results[t++] = A[i] * A[i]; + i--; + } + while ( j < len ) { + results[t++] = A[j] * A[j]; + j++; + } + return results; +} \ No newline at end of file diff --git a/solution/0985.Sum of Even Numbers After Queries/README.md b/solution/0985.Sum of Even Numbers After Queries/README.md new file mode 100644 index 0000000000000..57a269f5a1480 --- /dev/null +++ b/solution/0985.Sum of Even Numbers After Queries/README.md @@ -0,0 +1,85 @@ +# 查询后的偶数和 + +### 题目描述 + +给出一个整数数组 `A` 和一个查询数组 `queries`。 + +对于第 `i` 次查询,有 `val = queries[i][0], index = queries[i][1]`,我们会把 `val` 加到 `A[index]` 上。然后,第 `i` 次查询的答案是 `A` 中偶数值的和。 + +*(此处给定的 index = queries[i][1] 是从 0 开始的索引,每次查询都会永久修改数组 A。)* + +返回所有查询的答案。你的答案应当以数组 `answer` 给出,`answer[i]` 为第 `i` 次查询的答案。 + +**示例** + +``` +输入:A = [1,2,3,4], queries = [[1,0],[-3,1],[-4,0],[2,3]] +输出:[8,6,2,4] +解释: +开始时,数组为 [1,2,3,4]。 +将 1 加到 A[0] 上之后,数组为 [2,2,3,4],偶数值之和为 2 + 2 + 4 = 8。 +将 -3 加到 A[1] 上之后,数组为 [2,-1,3,4],偶数值之和为 2 + 4 = 6。 +将 -4 加到 A[0] 上之后,数组为 [-2,-1,3,4],偶数值之和为 -2 + 4 = 2。 +将 2 加到 A[3] 上之后,数组为 [-2,-1,3,6],偶数值之和为 -2 + 6 = 4。 +``` + +**提示** + +1. `1 <= A.length <= 10000` +2. `-10000 <= A[i] <= 10000` +3. `1 <= queries.length <= 10000` +4. `-10000 <= queries[i][0] <= 10000` +5. `0 <= queries[i][1] < A.length` + +### 解法 + +**第一种解法:调整数组和** + +**思路** + +让我们尝试不断调整 `S`,即每一步操作之后整个数组的偶数和。 + +我们操作数组中的某一个元素 `A[index]` 的时候,数组 `A` 其他位置的元素都应保持不变。如果 `A[index]` 是偶数,我们就从 `S` 中减去它,然后计算 `A[index] + val` 对 `S` 的影响(如果是偶数则在 `S` 中加上它)。 + +这里有一些例子: + +- 如果当前情况为 `A = [2,2,2,2,2]`、`S = 10`,并且需要执行 `A[0] += 4` 操作:我们应该先令 `S -= 2`,然后令 `S += 6`。最后得到 `A = [6,2,2,2,2]` 与 `S = 14`。 +- 如果当前情况为 `A = [1,2,2,2,2]`、`S = 8`,同时需要执行 `A[0] += 3` 操作:我们会跳过第一次更新 `S` 的步骤(因为 `A[0]` 是奇数),然后令 `S += 4`。 最后得到 `A = [4,2,2,2,2]` 与 `S = 12`。 +- 如果当前情况为 `A = [2,2,2,2,2]`、`S = 10`,同时需要执行 `A[0] += 1` 操作:我们先令 `S -= 2`,然后跳过第二次更新 `S` 的操作(因为 `A[0] + 1` 是奇数)。最后得到 `A = [3,2,2,2,2]` 与 `S = 8`。 +- 如果当前情况为 `A = [1,2,2,2,2]`、`S = 8`,同时需要执行 `A[0] += 2` 操作:我们跳过第一次更新 `S` 的操作(因为 `A[0]` 是奇数),然后再跳过第二次更新 `S` 的操作(因为 `A[0] + 2` 是奇数)。最后得到 `A = [3,2,2,2,2]` 与 `S = 8`。 + +这些例子充分展现了我们的算法在每一次询问操作之后应该如何调整 `S` 。 + +**算法** + +```javascript +var sumEvenAfterQueries = function (A, queries) { + const len = A.length; // A数组的长度 + const qlen = queries.length; // queries数组的长度 + let answer = []; + let S = 0; + for ( let i = 0; i < len; i++ ) { + if (A[i] % 2 == 0) { + S += A[i]; + } + } + for ( let j = 0; j < qlen; j++ ) { + let val = queries[j][0]; + let index = queries[j][1]; + if ( A[index] % 2 == 0 ) { + S -= A[index]; + } + A[index] += val; + if ( A[index] % 2 == 0 ) { + S += A[index] + } + answer.push(S); + } + return answer; +}; +``` + +**复杂度分析** + +- 时间复杂度:O(N+Q),其中 N 是数组 `A` 的长度, Q是询问 `queries` 的数量。 +- 空间复杂度:O(N+Q),事实上我们只使用了 O(1) 的额外空间。 diff --git a/solution/0985.Sum of Even Numbers After Queries/Solution.cpp b/solution/0985.Sum of Even Numbers After Queries/Solution.cpp new file mode 100644 index 0000000000000..532ef01e11e0b --- /dev/null +++ b/solution/0985.Sum of Even Numbers After Queries/Solution.cpp @@ -0,0 +1,33 @@ +class Solution { +public: + vector sumEvenAfterQueries(vector& A, vector>& queries) { + + vector ans; + + int Sum = 0; + for(int i = 0; i < A.size(); i++){ + if( ! ( A[i] & 1 ) ) + Sum += A[i]; + } + + int old; + + for(int i = 0; i < queries.size(); i++){ + + old = A[queries[i][1]]; + A[queries[i][1]] = A[queries[i][1]] + queries[i][0]; + + if( (old % 2 != 0) && (A[queries[i][1]] % 2 == 0) ) + Sum += A[queries[i][1]]; + else if( (old % 2 == 0) && (A[queries[i][1]] % 2 == 0) ) + Sum = Sum - old + A[queries[i][1]]; + else if( (old % 2 == 0) && (A[queries[i][1]] % 2 != 0) ) + Sum = Sum - old; + + ans.push_back(Sum); + + } + + return ans; + } +}; diff --git a/solution/0985.Sum of Even Numbers After Queries/Solution.js b/solution/0985.Sum of Even Numbers After Queries/Solution.js new file mode 100644 index 0000000000000..f08e6c7f9141c --- /dev/null +++ b/solution/0985.Sum of Even Numbers After Queries/Solution.js @@ -0,0 +1,34 @@ +/** + * @param {number[]} A + * @param {number[][]} queries + * @return {number[]} + */ + +/** + * Author: Mcnwork2018 + */ + +var sumEvenAfterQueries = function (A, queries) { + const len = A.length; // A数组的长度 + const qlen = queries.length; // queries数组的长度 + let answer = []; + let S = 0; + for ( let i = 0; i < len; i++ ) { + if (A[i] % 2 == 0) { + S += A[i]; + } + } + for ( let j = 0; j < qlen; j++ ) { + let val = queries[j][0]; + let index = queries[j][1]; + if ( A[index] % 2 == 0 ) { + S -= A[index]; + } + A[index] += val; + if ( A[index] % 2 == 0 ) { + S += A[index] + } + answer.push(S); + } + return answer; +}; \ No newline at end of file diff --git a/solution/0985.Sum of Even Numbers After Queries/Solution.py b/solution/0985.Sum of Even Numbers After Queries/Solution.py new file mode 100644 index 0000000000000..f321943580090 --- /dev/null +++ b/solution/0985.Sum of Even Numbers After Queries/Solution.py @@ -0,0 +1,16 @@ +class Solution: + def sumEvenAfterQueries(self, A: 'List[int]', queries: 'List[List[int]]') -> 'List[int]': + base = sum(filter(lambda x: x % 2 == 0, A)) + ans = [] + for val, index in queries: + if A[index] % 2 == 0: + base -= A[index] + A[index] += val + if A[index] % 2 == 0: + base += A[index] + else: + A[index] += val + if A[index] % 2 == 0: + base += A[index] + ans.append(base) + return ans