├── .vscode └── settings.json ├── 1. Two Sum.java ├── 10. Regular Expression Matching.java ├── 100. Same Tree.java ├── 1002. Find Common Characters.java ├── 1004. Max Consecutive Ones III.java ├── 1007. Minimum Domino Rotations For Equal Row.java ├── 1008. Construct Binary Search Tree from Preorder Traversal.java ├── 101. Symmetric Tree.java ├── 1010. Pairs of Songs With Total Durations Divisible by 60.java ├── 1011. Capacity To Ship Packages Within D Days.java ├── 1014. Best Sightseeing Pair.java ├── 1015. Smallest Integer Divisible by K.java ├── 1019. Next Greater Node In Linked List.java ├── 102. Binary Tree Level Order Traversal.java ├── 1021. Remove Outermost Parentheses.java ├── 1022. Sum of Root To Leaf Binary Numbers.java ├── 1025. Divisor Game.java ├── 1026. Maximum Difference Between Node and Ancestor.java ├── 1027. Longest Arithmetic Sequence.java ├── 1029. Two City Scheduling.java ├── 103. Binary Tree Zigzag Level Order Traversal.java ├── 1031. Maximum Sum of Two Non-Overlapping Subarrays.java ├── 104. Maximum Depth of Binary Tree.java ├── 1041. Robot Bounded In Circle.java ├── 1042. Flower Planting With No Adjacent.java ├── 1043. Partition Array for Maximum Sum.java ├── 1046. Last Stone Weight.java ├── 1047. Remove All Adjacent Duplicates In String.java ├── 1048. Longest String Chain.java ├── 1049. Last Stone Weight II.java ├── 105. Construct Binary Tree from Preorder and Inorder Traversal.java ├── 1054. Distant Barcodes.java ├── 1055. Shortest Way to Form String.java ├── 1056. Confusing Number.java ├── 1057. Campus Bikes.java ├── 106. Construct Binary Tree from Inorder and Postorder Traversal.java ├── 1060. Missing Element in Sorted Array.java ├── 1062. Longest Repeating Substring.java ├── 1064. Fixed Point.java ├── 1065. Index Pairs of a String.java ├── 1066. Campus Bikes II.java ├── 107. Binary Tree Level Order Traversal II.java ├── 1071. Greatest Common Divisor of Strings.java ├── 1073. Adding Two Negabinary Numbers.java ├── 108. Convert Sorted Array to Binary Search Tree.java ├── 1085. Sum of Digits in the Minimum Number.java ├── 1086. High Five.java ├── 1087. Brace Expansion.java ├── 1089. Duplicate Zeros.java ├── 109. Convert Sorted List to Binary Search Tree.java ├── 1091. Shortest Path in Binary Matrix.java ├── 1094. Car Pooling.java ├── 1099. Two Sum Less Than K.java ├── 11. Container With Most Water.java ├── 110. Balanced Binary Tree.java ├── 1101. The Earliest Moment When Everyone Become Friends.java ├── 1102. Path With Maximum Minimum Value.java ├── 1103. Distribute Candies to People.java ├── 1108. Defanging an IP Address.java ├── 111. Minimum Depth of Binary Tree.java ├── 1110. Delete Nodes And Return Forest.java ├── 1114. Print in Order.java ├── 1117. Building H2O.java ├── 1118. Number of Days in a Month.java ├── 1119. Remove Vowels from a String.java ├── 112. Path Sum.java ├── 1120. Maximum Average Subtree.java ├── 1122. Relative Sort Array.java ├── 1123. Lowest Common Ancestor of Deepest Leaves.java ├── 1124. Longest Well-Performing Interval.java ├── 1128. Number of Equivalent Domino Pairs.java ├── 1129. Shortest Path with Alternating Colors.java ├── 113. Path Sum II.java ├── 1130. Minimum Cost Tree From Leaf Values.java ├── 1133. Largest Unique Number.java ├── 1134. Armstrong Number.java ├── 1135. Connecting Cities With Minimum Cost.java ├── 1137. N-th Tribonacci Number.java ├── 1138. Alphabet Board Path.java ├── 1139. Largest 1-Bordered Square.java ├── 114. Flatten Binary Tree to Linked List.java ├── 1140. Stone Game II.java ├── 1143. Longest Common Subsequence.java ├── 1144. Decrease Elements To Make Array Zigzag.java ├── 1145. Binary Tree Coloring Game.java ├── 1146. Snapshot Array.java ├── 1147. Longest Chunked Palindrome Decomposition.java ├── 115. Distinct Subsequences.java ├── 1150. Check If a Number Is Majority Element in a Sorted Array.java ├── 1151. Minimum Swaps to Group All 1's Together.java ├── 1152. Analyze User Website Visit Pattern.java ├── 1154. Day of the Year.java ├── 1155. Number of Dice Rolls With Target Sus.java ├── 1156. Swap For Longest Repeated Character Substring.java ├── 1157. Online Majority Element In Subarray.java ├── 116. Populating Next Right Pointers in Each Node.java ├── 1160. Find Words That Can Be Formed by Characters.java ├── 1161. Maximum Level Sum of a Binary Tree.java ├── 1162. As Far from Land as Possible.java ├── 1163. Last Substring in Lexicographical Order.java ├── 1165. Single-Row Keyboard.java ├── 1166. Design File System.java ├── 1167. Minimum Cost to Connect Sticks.java ├── 1168. Optimize Water Distribution in a Village.java ├── 117. Populating Next Right Pointers in Each Node II.java ├── 1170. Compare Strings by Frequency of the Smallest Character.java ├── 1171. Remove Zero Sum Consecutive Nodes from Linked List.java ├── 1172. Dinner Plate Stacks.java ├── 1175. Prime Arrangements.java ├── 1176. Diet Plan Performance.java ├── 1177. Can Make Palindrome from Substring.java ├── 1180. Count Substrings with Only One Distinct Letter.java ├── 1181. Before and After Puzzle.java ├── 1184. Distance Between Bus Stops.java ├── 1185. Day of the Week.java ├── 1186. Maximum Subarray Sum with One Deletion.java ├── 1188. Design Bounded Blocking Queue.java ├── 1189. Maximum Number of Balloons.java ├── 119. Pascal's Triangle II.java ├── 1190. Reverse Substrings Between Each Pair of Parentheses.java ├── 1191. K-Concatenation Maximum Sum.java ├── 1192. Critical Connections in a Network.java ├── 1196. How Many Apples Can You Put into the Basket.java ├── 1197. Minimum Knight Moves.java ├── 1198. Find Smallest Common Element in All Rows.java ├── 1199. Minimum Time to Build Blocks.java ├── 12. Integer to Roman.java ├── 120. Triangle.java ├── 1200. Minimum Absolute Difference.java ├── 1201. Ugly Number III.java ├── 1202. Smallest String With Swaps.java ├── 1207. Unique Number of Occurrences.java ├── 1209. Remove All Adjacent Duplicates in String II.java ├── 121. Best Time to Buy and Sell Stock.java ├── 1213. Intersection of Three Sorted Arrays.java ├── 1214. Two Sum BSTs.java ├── 1215. Stepping Numbers.java ├── 1217. Play with Chips.java ├── 1218. Longest Arithmetic Subsequence of Given Difference.java ├── 1219. Path with Maximum Gold.java ├── 1220. Count Vowels Permutation.java ├── 1221. Split a String in Balanced Strings.java ├── 1222. Queens That Can Attack the King.java ├── 1223. Dice Roll Simulation.java ├── 1228. Missing Number In Arithmetic Progression.java ├── 1232. Check If It Is a Straight Line.java ├── 1233. Remove Sub-Folders from the Filesystem.java ├── 1234. Replace the Substring for Balanced String.java ├── 1235. Maximum Profit in Job Scheduling.java ├── 1236. Web Crawler.java ├── 1237. Find Positive Integer Solution for a Given Equation.java ├── 1239. Maximum Length of a Concatenated String with Unique Characters.java ├── 124. Binary Tree Maximum Path Sum.java ├── 1243. Array Transformation.java ├── 1244. Design A Leaderboard.java ├── 1245. Tree Diameter.java ├── 1249. Minimum Remove to Make Valid Parentheses.java ├── 125. Valid Palindrome.java ├── 1252. Cells with Odd Values in a Matrix.java ├── 1253. Reconstruct a 2-Row Binary Matrix.java ├── 1254. Number of Closed Islands.java ├── 1255. Maximum Score Words Formed by Letters.java ├── 1258. Synonymous Sentences.java ├── 126. Word Ladder II.java ├── 1260. Shift 2D Grid.java ├── 1261. Find Elements in a Contaminated Binary Tree.java ├── 1262. Greatest Sum Divisible by Three.java ├── 1263. Minimum Moves to Move a Box to Their Target Location.java ├── 1266. Minimum Time Visiting All Points.java ├── 1267. Count Servers that Communicate.java ├── 1268. Search Suggestions System.java ├── 127. Word Ladder.java ├── 1271. Hexspeak.java ├── 1272. Remove Interval.java ├── 1273. Delete Tree Nodes.java ├── 1275. Find Winner on a Tic Tac Toe Game.java ├── 1277. Count Square Submatrices with All Ones.java ├── 1279. Traffic Light Controlled Intersection.java ├── 128. Longest Consecutive Sequence.java ├── 1281. Subtract the Product and Sum of Digits of an Integer.java ├── 1282. Group the People Given the Group Size They Belong To.java ├── 1286. Iterator for Combination.java ├── 1287. Element Appearing More Than 25% In Sorted Array.java ├── 1288. Remove Covered Intervals.java ├── 1289. Minimum Falling Path Sum II.java ├── 129. Sum Root to Leaf Numbers.java ├── 1290. Convert Binary Number in a Linked List to Integer.java ├── 1291. Sequential Digits.java ├── 1292. Maximum Side Length of a Square with Sum Less than or Equal to Threshold.java ├── 1293. Shortest Path in a Grid with Obstacles Elimination.java ├── 1296. Divide Array in Sets of K Consecutive Numbers.java ├── 1299. Replace Elements with Greatest Element on Right Side.java ├── 13. Roman to Integer.java ├── 130. Surrounded Regions.java ├── 1300. Sum of Mutated Array Closest to Target.java ├── 1302. Deepest Leaves Sum.java ├── 1304. Find N Unique Integers Sum up to Zero.java ├── 1305. All Elements in Two Binary Search Trees.java ├── 1306. Jump Game III.java ├── 1309. Decrypt String from Alphabet to Integer Mapping.java ├── 131. Palindrome Partitioning.java ├── 1310. XOR Queries of a Subarray.java ├── 1311. Get Watched Videos by Your Friends.java ├── 1312. Minimum Insertion Steps to Make a String Palindrome.java ├── 1313. Decompress Run-Length Encoded List.java ├── 1314. Matrix Block Sum.java ├── 1315. Sum of Nodes with Even-Valued Grandparent.java ├── 1317. Convert Integer to the Sum of Two No-Zero Integers.java ├── 1318. Minimum Flips to Make a OR b Equal to c.java ├── 1319. Number of Operations to Make Network Connected.java ├── 132. Palindrome Partitioning II.java ├── 1326. Minimum Number of Taps to Open to Water a Garden.java ├── 1328. Break a Palindrome.java ├── 1329. Sort the Matrix Diagonally.java ├── 133. Clone Graph.java ├── 1331. Rank Transform of an Array.java ├── 1339. Maximum Product of Splitted Binary Tree.java ├── 134. Gas Station.java ├── 1342. Number of Steps to Reduce a Number to Zero.java ├── 1344. Angle Between Hands of a Clock.java ├── 135. Candy.java ├── 1352. Product of the Last K Numbers.java ├── 1353. Maximum Number of Events That Can Be Attended.java ├── 1358. Number of Substrings Containing All Three Characters.java ├── 136. Single Number.java ├── 1360. Number of Days Between Two Dates.java ├── 1365. How Many Numbers Are Smaller Than the Current Number.java ├── 137. Single Number II.java ├── 1374. Generate a String With Characters That Have Odd Counts.java ├── 1375. Bulb Switcher III.java ├── 1376. Time Needed to Inform All Employees.java ├── 138. Copy List with Random Pointer.java ├── 1381. Design a Stack With Increment Operation.java ├── 1382. Balance a Binary Search Tree.java ├── 1386. Cinema Seat Allocation.java ├── 139. Word Break.java ├── 1395. Count Number of Teams.java ├── 1396. Design Underground System.java ├── 14. Longest Common Prefix.java ├── 140. Word Break II.java ├── 1400. Construct K Palindrome Strings.java ├── 1403. Minimum Subsequence in Non-Increasing Order.java ├── 1404. Number of Steps to Reduce a Number in Binary Representation to One.java ├── 1405. Longest Happy String.java ├── 1408. String Matching in an Array.java ├── 1409. Queries on a Permutation With Key.java ├── 141. Linked List Cycle.java ├── 1413. Minimum Value to Get Positive Step by Step Sum.java ├── 1414. Find the Minimum Number of Fibonacci Numbers Whose Sum Is K.java ├── 1415. The k-th Lexicographical String of All Happy Strings of Length n.java ├── 142. Linked List Cycle II.java ├── 1422. Maximum Score After Splitting a String.java ├── 1423. Maximum Points You Can Obtain from Cards.java ├── 1426. Counting Elements.java ├── 1427. Perform String Shifts.java ├── 1428. Leftmost Column with at Least a One.java ├── 1429. First Unique Number.java ├── 143. Reorder List.java ├── 1430. Check If a String Is a Valid Sequence from Root to Leaves Path in a Binary Tree.java ├── 1431. Kids With the Greatest Number of Candies.java ├── 1432. Max Difference You Can Get From Changing an Integer.java ├── 1433. Check If a String Can Break Another String.java ├── 1436. Destination City.java ├── 1437. Check If All 1's Are at Least Length K Places Away.java ├── 1438. Longest Continuous Subarray With Absolute Diff Less Than or Equal to Limit.java ├── 1439. Find the Kth Smallest Sum of a Matrix With Sorted Rows.java ├── 144. Binary Tree Preorder Traversal.java ├── 1441. Build an Array With Stack Operations.java ├── 1442. Count Triplets That Can Form Two Arrays of Equal XOR.java ├── 1443. Minimum Time to Collect All Apples in a Tree.java ├── 1444. Number of Ways of Cutting a Pizza.java ├── 1446. Consecutive Characters.java ├── 1447. Simplified Fractions.java ├── 1448. Count Good Nodes in Binary Tree.java ├── 145. Binary Tree Postorder Traversal.java ├── 1450. Number of Students Doing Homework at a Given Time.java ├── 1451. Rearrange Words in a Sentence.java ├── 1452. People Whose List of Favorite Companies Is Not a Subset of Another List.java ├── 1455. Check If a Word Occurs As a Prefix of Any Word in a Sentence.java ├── 1456. Maximum Number of Vowels in a Substring of Given Length.java ├── 1457. Pseudo-Palindromic Paths in a Binary Tree.java ├── 146. LRU Cache.java ├── 1460. Make Two Arrays Equal by Reversing Sub-arrays.java ├── 1461. Check If a String Contains All Binary Codes of Size K.java ├── 1462. Course Schedule IV.java ├── 1464. Maximum Product of Two Elements in an Array.java ├── 1466. Reorder Routes to Make All Paths Lead to the City Zero.java ├── 1469. Find All The Lonely Nodes.java ├── 147. Insertion Sort List.java ├── 1470. Shuffle the Array.java ├── 1471. The k Strongest Values in an Array.java ├── 1472. Design Browser History.java ├── 1474. Delete N Nodes After M Nodes of a Linked List.java ├── 1475. Final Prices With a Special Discount in a Shop.java ├── 1477. Find Two Non-overlapping Sub-arrays Each With Target Sum.java ├── 148. Sort List.java ├── 1480. Running Sum of 1d Array.java ├── 1481. Least Number of Unique Integers after K Removals.java ├── 1482. Minimum Number of Days to Make m Bouquets.java ├── 1485. Clone Binary Tree With Random Pointer.java ├── 1486. XOR Operation in an Array.java ├── 1488. Avoid Flood in The City.java ├── 149. Max Points on a Line.java ├── 1490. Clone N-ary Tree.java ├── 1491. Average Salary Excluding the Minimum and Maximum Salary.java ├── 1492. The kth Factor of n.java ├── 1493. Longest Subarray of 1's After Deleting One Element.java ├── 1496. Path Crossing.java ├── 1497. Check If Array Pairs Are Divisible by k.java ├── 1498. Number of Subsequences That Satisfy the Given Sum Condition.java ├── 15. 3Sum.java ├── 150. Evaluate Reverse Polish Notation.java ├── 1500. Design a File Sharing System.java ├── 1502. Can Make Arithmetic Progression From Sequence.java ├── 1503. Last Moment Before All Ants Fall Out of a Plank.java ├── 1504. Count Submatrices With All Ones.java ├── 1506. Find Root of N-Ary Tree.java ├── 1508. Range Sum of Sorted Subarray Sums.java ├── 1509. Minimum Difference Between Largest and Smallest Value in Three Moves.java ├── 151. Reverse Words in a String.java ├── 1512. Number of Good Pairs.java ├── 1513. Number of Substrings With Only 1s.java ├── 1514. Path with Maximum Probability.java ├── 1518. Water Bottles.java ├── 1519. Number of Nodes in the Sub-Tree With the Same Label.java ├── 152. Maximum Product Subarray.java ├── 1520. Maximum Number of Non-Overlapping Substrings.java ├── 1523. Count Odd Numbers in an Interval Range.java ├── 1524. Number of Sub-arrays With Odd Sum.java ├── 1525. Number of Good Ways to Split a String.java ├── 1526. Minimum Number of Increments on Subarrays to Form a Target Array.java ├── 1528. Shuffle String.java ├── 1529. Bulb Switcher IV.java ├── 153. Find Minimum in Rotated Sorted Array.java ├── 1530. Number of Good Leaf Nodes Pairs.java ├── 1533. Find the Index of the Large Integer.java ├── 1534. Count Good Triplets.java ├── 1535. Find the Winner of an Array Game.java ├── 1536. Minimum Swaps to Arrange a Binary Grid.java ├── 1537. Get the Maximum Score.java ├── 1538. Guess the Majority in a Hidden Array.java ├── 1539. Kth Missing Positive Number.java ├── 154. Find Minimum in Rotated Sorted Array II.java ├── 1540. Can Convert String in K Moves.java ├── 1541. Minimum Insertions to Balance a Parentheses String.java ├── 1542. Find Longest Awesome Substring.java ├── 1544. Make The String Great.java ├── 1545. Find Kth Bit in Nth Binary String.java ├── 1546. Maximum Number of Non-Overlapping Subarrays With Sum Equals Target.java ├── 1547. Minimum Cost to Cut a Stick.java ├── 155. Min Stack.java ├── 1550. Three Consecutive Odds.java ├── 1551. Minimum Operations to Make Array Equal.java ├── 1552. Magnetic Force Between Two Balls.java ├── 1553. Minimum Number of Days to Eat N Oranges.java ├── 1556. Thousand Separator.java ├── 1557. Minimum Number of Vertices to Reach All Nodes.java ├── 1558. Minimum Numbers of Function Calls to Make Target Array.java ├── 1559. Detect Cycles in 2D Grid.java ├── 156. Binary Tree Upside Down.java ├── 1560. Most Visited Sector in a Circular Track.java ├── 1561. Maximum Number of Coins You Can Get.java ├── 1562. Find Latest Group of Size M.java ├── 1563. Stone Game V.java ├── 1564. Put Boxes Into the Warehouse I.java ├── 1566. Detect Pattern of Length M Repeated K or More Times.java ├── 1567. Maximum Length of Subarray With Positive Product.java ├── 157. Read N Characters Given Read4.java ├── 1570. Dot Product of Two Sparse Vectors.java ├── 1572. Matrix Diagonal Sum.java ├── 1573. Number of Ways to Split a String.java ├── 1574. Shortest Subarray to be Removed to Make Array Sorted.java ├── 1575. Count All Possible Routes.java ├── 1576. Replace All question marks to Avoid Consecutive Repeating Characters.java ├── 1577. Number of Ways Where Square of Number Is Equal to Product of Two Numbers.java ├── 1578. Minimum Deletion Cost to Avoid Repeating Letters.java ├── 1579. Remove Max Number of Edges to Keep Graph Fully Traversable.java ├── 158. Read N Characters Given Read4 II - Call multiple times.java ├── 1582. Special Positions in a Binary Matrix.java ├── 1583. Count Unhappy Friends.java ├── 1584. Min Cost to Connect All Points.java ├── 1586. Binary Search Tree Iterator II.java ├── 1588. Sum of All Odd Length Subarrays.java ├── 1589. Maximum Sum Obtained of Any Permutation.java ├── 159. Longest Substring with At Most Two Distinct Characters.java ├── 1590. Make Sum Divisible by P.java ├── 1592. Rearrange Spaces Between Words.java ├── 1593. Split a String Into the Max Number of Unique Substrings.java ├── 16. 3Sum Closest.java ├── 160. Intersection of Two Linked Lists.java ├── 1602. Find Nearest Right Node in Binary Tree.java ├── 1605. Find Valid Matrix Given Row and Column Sums.java ├── 1606. Find Servers That Handled Most Number of Requests.java ├── 161. One Edit Distance.java ├── 1612. Check If Two Expression Trees are Equivalent.java ├── 1614. Maximum Nesting Depth of the Parentheses.java ├── 1615. Maximal Network Rank.java ├── 1616. Split Two Strings to Make Palindrome.java ├── 1617. Count Subtrees With Max Distance Between Cities.java ├── 1618. Maximum Font to Fit a Sentence in a Screen.java ├── 1619. Mean of Array After Removing Some Elements.java ├── 162. Find Peak Element.java ├── 1624. Largest Substring Between Two Equal Characters.java ├── 1625. Lexicographically Smallest String After Applying Operations.java ├── 1626. Best Team With No Conflicts.java ├── 1627. Graph Connectivity With Threshold.java ├── 1629. Slowest Key.java ├── 163. Missing Ranges.java ├── 1630. Arithmetic Subarrays.java ├── 1631. Path With Minimum Effort.java ├── 1634. Add Two Polynomials Represented as Linked Lists.java ├── 1636. Sort Array by Increasing Frequency.java ├── 1637. Widest Vertical Area Between Two Points Containing No Points.java ├── 164. Maximum Gap.java ├── 1640. Check Array Formation Through Concatenation.java ├── 1641. Count Sorted Vowel Strings.java ├── 1642. Furthest Building You Can Reach.java ├── 1643. Kth Smallest Instructions.java ├── 1644. Lowest Common Ancestor of a Binary Tree II.java ├── 1647. Minimum Deletions to Make Character Frequencies Unique.java ├── 1648. Sell Diminishing-Valued Colored Balls.java ├── 165. Compare Version Numbers.java ├── 1652. Defuse the Bomb.java ├── 1653. Minimum Deletions to Make String Balanced.java ├── 1654. Minimum Jumps to Reach Home.java ├── 1656. Design an Ordered Stream.java ├── 1657. Determine if Two Strings Are Close.java ├── 166. Fraction to Recurring Decimal.java ├── 1660. Correct a Binary Tree.java ├── 1666. Change the Root of a Binary Tree.java ├── 1668. Maximum Repeating Substring.java ├── 1670. Design Front Middle Back Queue.java ├── 1673. Find the Most Competitive Subsequence.java ├── 1676. Lowest Common Ancestor of a Binary Tree IV.java ├── 1679. Max Number of K-Sum Pairs.java ├── 168. Excel Sheet Column Title.java ├── 1682. Longest Palindromic Subsequence II.java ├── 1685. Sum of Absolute Differences in a Sorted Array.java ├── 1686. Stone Game VI.java ├── 169. Majority Element.java ├── 17. Letter Combinations of a Phone Number.java ├── 170. Two Sum III - Data structure design.java ├── 171. Excel Sheet Column Number.java ├── 172. Factorial Trailing Zeroes.java ├── 173. Binary Search Tree Iterator.java ├── 174. Dungeon Game.java ├── 1769. Minimum Number of Operations to Move All Balls to Each Box.java ├── 179. Largest Number.java ├── 18. 4Sum.java ├── 1823. Find the Winner of the Circular Game.java ├── 1834. Single-Threaded CPU.java ├── 1858. Longest Word With All Prefixes.java ├── 186. Reverse Words in a String II.java ├── 187. Repeated DNA Sequences.java ├── 189. Rotate Array.java ├── 19. Remove Nth Node From End of List.java ├── 190. Reverse Bits.java ├── 1937. Maximum Number of Points with Cost.java ├── 198. House Robber.java ├── 199. Binary Tree Right Side View.java ├── 2. Add Two Numbers.java ├── 20. Valid Parentheses.java ├── 200. Number of Islands.java ├── 201. Bitwise AND of Numbers Range.java ├── 2013. Detect Squares.java ├── 202. Happy Number.java ├── 203. Remove Linked List Elements.java ├── 2034. Stock Price Fluctuation.java ├── 204. Count Primes.java ├── 205. Isomorphic Strings.java ├── 206. Reverse Linked List.java ├── 207. Course Schedule.java ├── 208. Implement Trie (Prefix Tree).java ├── 209. Minimum Size Subarray Sum.java ├── 21. Merge Two Sorted Lists.java ├── 210. Course Schedule II.java ├── 211. Add and Search Word - Data structure design.java ├── 2115. Find All Possible Recipes from Given Supplies.java ├── 212. Word Search II.java ├── 213. House Robber II.java ├── 2135. Count Words Obtained After Adding a Letter.java ├── 214. Shortest Palindrome.java ├── 215. Kth Largest Element in an Array.java ├── 2158. Amount of New Area Painted Each Day.java ├── 216. Combination Sum III.java ├── 217. Contains Duplicate.java ├── 218. The Skyline Problem.java ├── 219. Contains Duplicate II.java ├── 2196. Create Binary Tree From Descriptions.java ├── 22. Generate Parentheses.java ├── 220. Contains Duplicate III.java ├── 221. Maximal Square.java ├── 222. Count Complete Tree Nodes.java ├── 223. Rectangle Area.java ├── 224. Basic Calculator.java ├── 225. Implement Stack using Queues.java ├── 226. Invert Binary Tree.java ├── 227. Basic Calculator II.java ├── 228. Summary Ranges.java ├── 229. Majority Element II.java ├── 23. Merge k Sorted Lists.java ├── 230. Kth Smallest Element in a BST.java ├── 231. Power of Two.java ├── 232. Implement Queue using Stacks.java ├── 234. Palindrome Linked List.java ├── 235. Lowest Common Ancestor of a Binary Search Tree.java ├── 236. Lowest Common Ancestor of a Binary Tree.java ├── 237. Delete Node in a Linked List.java ├── 238. Product of Array Except Self.java ├── 239. Sliding Window Maximum.java ├── 24. Swap Nodes in Pairs.java ├── 240. Search a 2D Matrix II.java ├── 241. Different Ways to Add Parentheses.java ├── 242. Valid Anagram.java ├── 243. Shortest Word Distance.java ├── 244. Shortest Word Distance II.java ├── 245. Shortest Word Distance III.java ├── 246. Strobogrammatic Number.java ├── 247. Strobogrammatic Number II.java ├── 249. Group Shifted Strings.java ├── 25. Reverse Nodes in k-Group.java ├── 250. Count Univalue Subtrees.java ├── 251. Flatten 2D Vector.java ├── 252. Meeting Rooms.java ├── 253. Meeting Rooms II.java ├── 254. Factor Combinations.java ├── 255. Verify Preorder Sequence in Binary Search Tree.java ├── 256. Paint House.java ├── 257. Binary Tree Paths.java ├── 258. Add Digits.java ├── 259. 3Sum Smaller.java ├── 26. Remove Duplicates from Sorted Array.java ├── 260. Single Number III.java ├── 261. Graph Valid Tree.java ├── 263. Ugly Number.java ├── 264. Ugly Number II.java ├── 265. Paint House II.java ├── 266. Palindrome Permutation.java ├── 267. Palindrome Permutation II.java ├── 268. Missing Number.java ├── 269. Alien Dictionary.java ├── 27. Remove Element.java ├── 270. Closest Binary Search Tree Value.java ├── 271. Encode and Decode Strings.java ├── 272. Closest Binary Search Tree Value II.java ├── 273. Integer to English Words.java ├── 274. H-Index.java ├── 275. H-Index II.java ├── 276. Paint Fence.java ├── 277. Find the Celebrity.java ├── 278. First Bad Version.java ├── 279. Perfect Squares.java ├── 28. Implement strStr().java ├── 280. Wiggle Sort.java ├── 281. Zigzag Iterator.java ├── 282. Expression Add Operators.java ├── 283. Move Zeroes.java ├── 284. Peeking Iterator.java ├── 285. Inorder Successor in BST.java ├── 286. Walls and Gates.java ├── 287. Find the Duplicate Number.java ├── 288. Unique Word Abbreviation.java ├── 289. Game of Life.java ├── 29. Divide Two Integers.java ├── 290. Word Pattern.java ├── 291. Word Pattern II.java ├── 292. Nim Game.java ├── 293. Flip Game.java ├── 295. Find Median from Data Stream.java ├── 297. Serialize and Deserialize Binary Tree.java ├── 298. Binary Tree Longest Consecutive Sequence.java ├── 299. Bulls and Cows.java ├── 3. Longest Substring Without Repeating Characters.java ├── 30. Substring with Concatenation of All Words.java ├── 300. Longest Increasing Subsequence.java ├── 301. Remove Invalid Parentheses.java ├── 303. Range Sum Query - Immutable.java ├── 304. Range Sum Query 2D - Immutable.java ├── 305. Number of Islands II.java ├── 306. Additive Number.java ├── 307. Range Sum Query - Mutable.java ├── 31. Next Permutation.java ├── 310. Minimum Height Trees.java ├── 311. Sparse Matrix Multiplication.java ├── 312. Burst Balloons.java ├── 313. Super Ugly Number.java ├── 314. Binary Tree Vertical Order Traversal.java ├── 315. Count of Smaller Numbers After Self.java ├── 316. Remove Duplicate Letters.java ├── 317. Shortest Distance from All Buildings.java ├── 318. Maximum Product of Word Lengths.java ├── 319. Bulb Switcher.java ├── 32. Longest Valid Parentheses.java ├── 321. Create Maximum Number.java ├── 322. Coin Change.java ├── 323. Number of Connected Components in an Undirected Graph.java ├── 324. Wiggle Sort II.java ├── 325. Maximum Size Subarray Sum Equals k.java ├── 327. Count of Range Sum.java ├── 328. Odd Even Linked List.java ├── 329. Longest Increasing Path in a Matrix.java ├── 33. Search in Rotated Sorted Array.java ├── 330. Patching Array.java ├── 331. Verify Preorder Serialization of a Binary Tree.java ├── 332. Reconstruct Itinerary.java ├── 333. Largest BST Subtree.java ├── 334. Increasing Triplet Subsequence.java ├── 336. Palindrome Pairs.java ├── 337. House Robber III.java ├── 338. Counting Bits.java ├── 339. Nested List Weight Sum.java ├── 34. Find First and Last Position of Element in Sorted Array.java ├── 340. Longest Substring with At Most K Distinct Characters.java ├── 341. Flatten Nested List Iterator.java ├── 342. Power of Four.java ├── 343. Integer Break.java ├── 344. Reverse String.java ├── 345. Reverse Vowels of a String.java ├── 346. Moving Average from Data Stream.java ├── 347. Top K Frequent Elements.java ├── 348. Design Tic-Tac-Toe.java ├── 349. Intersection of Two Arrays.java ├── 35. Search Insert Position.java ├── 350. Intersection of Two Arrays II.java ├── 352. Data Stream as Disjoint Intervals.java ├── 353. Design Snake Game.java ├── 354. Russian Doll Envelopes.java ├── 355. Design Twitter.java ├── 356. Line Reflection.java ├── 357. Count Numbers with Unique Digits.java ├── 359. Logger Rate Limiter.java ├── 36. Valid Sudoku.java ├── 360. Sort Transformed Array.java ├── 361. Bomb Enemy.java ├── 362. Design Hit Counter.java ├── 363. Max Sum of Rectangle No Larger Than K.java ├── 364. Nested List Weight Sum II.java ├── 365. Water and Jug Problem.java ├── 366. Find Leaves of Binary Tree.java ├── 367. Valid Perfect Square.java ├── 368. Largest Divisible Subset.java ├── 369. Plus One Linked List.java ├── 37. Sudoku Solver.java ├── 370. Range Addition.java ├── 371. Sum of Two Integers.java ├── 373. Find K Pairs with Smallest Sums.java ├── 374. Guess Number Higher or Lower.java ├── 375. Guess Number Higher or Lower II.java ├── 376. Wiggle Subsequence.java ├── 377. Combination Sum IV.java ├── 378. Kth Smallest Element in a Sorted Matrix.java ├── 38. Count and Say.java ├── 380. Insert Delete GetRandom O(1).java ├── 381. Insert Delete GetRandom O(1) - Duplicates allowed.java ├── 382. Linked List Random Node.java ├── 383. Ransom Note.java ├── 384. Shuffle an Array.java ├── 385. Mini Parser.java ├── 386. Lexicographical Numbers.java ├── 387. First Unique Character in a String.java ├── 388. Longest Absolute File Path.java ├── 389. Find the Difference.java ├── 39. Combination Sum.java ├── 390. Elimination Game.java ├── 391. Perfect Rectangle.java ├── 392. Is Subsequence.java ├── 394. Decode String.java ├── 395. Longest Substring with At Least K Repeating Characters.java ├── 396. Rotate Function.java ├── 397. Integer Replacement.java ├── 398. Random Pick Index.java ├── 399. Evaluate Division.java ├── 4. Median of Two Sorted Arrays.java ├── 40. Combination Sum II.java ├── 400. Nth Digit.java ├── 402. Remove K Digits.java ├── 403. Frog Jump.java ├── 404. Sum of Left Leaves.java ├── 405. Convert a Number to Hexadecimal.java ├── 406. Queue Reconstruction by Height.java ├── 407. Trapping Rain Water II.java ├── 408. Valid Word Abbreviation.java ├── 409. Longest Palindrome.java ├── 41. First Missing Positive.java ├── 410. Split Array Largest Sum.java ├── 412. Fizz Buzz.java ├── 413. Arithmetic Slices.java ├── 414. Third Maximum Number.java ├── 415. Add Strings.java ├── 416. Partition Equal Subset Sum.java ├── 417. Pacific Atlantic Water Flow.java ├── 418. Sentence Screen Fitting.java ├── 42. Trapping Rain Water.java ├── 421. Maximum XOR of Two Numbers in an Array.java ├── 423. Reconstruct Original Digits from English.java ├── 424. Longest Repeating Character Replacement.java ├── 426. Convert Binary Search Tree to Sorted Doubly Linked List.java ├── 427. Construct Quad Tree.java ├── 428. Serialize and Deserialize N-ary Tree.java ├── 429. N-ary Tree Level Order Traversal.java ├── 43. Multiply Strings.java ├── 430. Flatten a Multilevel Doubly Linked List.java ├── 432. All O`one Data Structure.java ├── 433. Minimum Genetic Mutation.java ├── 434. Number of Segments in a String.java ├── 435. Non-overlapping Intervals.java ├── 436. Find Right Interval.java ├── 437. Path Sum III.java ├── 438. Find All Anagrams in a String.java ├── 44. Wildcard Matching.java ├── 440. K-th Smallest in Lexicographical Order.java ├── 441. Arranging Coins.java ├── 442. Find All Duplicates in an Array.java ├── 443. String Compression.java ├── 445. Add Two Numbers II.java ├── 446. Arithmetic Slices II - Subsequence.java ├── 447. Number of Boomerangs.java ├── 448. Find All Numbers Disappeared in an Array.java ├── 449. Serialize and Deserialize BST.java ├── 45. Jump Game II.java ├── 450. Delete Node in a BST.java ├── 451. Sort Characters By Frequency.java ├── 452. Minimum Number of Arrows to Burst Balloons.java ├── 453. Minimum Moves to Equal Array Elements.java ├── 454. 4Sum II.java ├── 455. Assign Cookies.java ├── 456. 132 Pattern.java ├── 457. Circular Array Loop.java ├── 458. Poor Pigs.java ├── 459. Repeated Substring Pattern.java ├── 46. Permutations.java ├── 460. LFU Cache.java ├── 461. Hamming Distance.java ├── 462. Minimum Moves to Equal Array Elements II.java ├── 463. Island Perimeter.java ├── 464. Can I Win.java ├── 465. Optimal Account Balancing.java ├── 467. Unique Substrings in Wraparound String.java ├── 47. Permutations II.java ├── 470. Implement Rand10() Using Rand7().java ├── 472. Concatenated Words.java ├── 473. Matchsticks to Square.java ├── 474. Ones and Zeroes.java ├── 475. Heaters.java ├── 476. Number Complement.java ├── 477. Total Hamming Distance.java ├── 478. Generate Random Point in a Circle.java ├── 48. Rotate Image.java ├── 480. Sliding Window Median.java ├── 481. Magical String.java ├── 482. License Key Formatting.java ├── 485. Max Consecutive Ones.java ├── 486. Predict the Winner.java ├── 488. Zuma Game.java ├── 489. Robot Room Cleaner.java ├── 49. Group Anagrams.java ├── 490. The Maze.java ├── 491. Increasing Subsequences.java ├── 492. Construct the Rectangle.java ├── 493. Reverse Pairs.java ├── 494. Target Sum.java ├── 496. Next Greater Element I.java ├── 497. Random Point in Non-overlapping Rectangles.java ├── 498. Diagonal Traverse.java ├── 5. Longest Palindromic Substring.java ├── 50. Pow(x, n).java ├── 500. Keyboard Row.java ├── 501. Find Mode in Binary Search Tree.java ├── 502. IPO.java ├── 503. Next Greater Element II.java ├── 504. Base 7.java ├── 505. The Maze II.java ├── 506. Relative Ranks.java ├── 507. Perfect Number.java ├── 508. Most Frequent Subtree Sum.java ├── 509. Fibonacci Number.java ├── 51. N-Queens.java ├── 510. Inorder Successor in BST II.java ├── 513. Find Bottom Left Tree Value.java ├── 514. Freedom Trail.java ├── 516. Longest Palindromic Subsequence.java ├── 517. Super Washing Machines.java ├── 518. Coin Change 2.java ├── 519. Random Flip Matrix.java ├── 52. N-Queens II.java ├── 520. Detect Capital.java ├── 521. Longest Uncommon Subsequence I.java ├── 523. Continuous Subarray Sum.java ├── 524. Longest Word in Dictionary through Deleting.java ├── 525. Contiguous Array.java ├── 526. Beautiful Arrangement.java ├── 528. Random Pick with Weight.java ├── 529. Minesweeper.java ├── 53. Maximum Subarray.java ├── 530. Minimum Absolute Difference in BST.java ├── 532. K-diff Pairs in an Array.java ├── 535. Encode and Decode TinyURL.java ├── 536. Construct Binary Tree from String.java ├── 537. Complex Number Multiplication.java ├── 538. Convert BST to Greater Tree.java ├── 539. Minimum Time Difference.java ├── 54. Spiral Matrix.java ├── 540. Single Element in a Sorted Array.java ├── 541. Reverse String II.java ├── 542. 01 Matrix.java ├── 543. Diameter of Binary Tree.java ├── 546. Remove Boxes.java ├── 547. Number of Provinces.java ├── 548. Split Array with Equal Sum.java ├── 549. Binary Tree Longest Consecutive Sequence II.java ├── 55. Jump Game.java ├── 551. Student Attendance Record I.java ├── 552. Student Attendance Record II.java ├── 553. Optimal Division.java ├── 554. Brick Wall.java ├── 556. Next Greater Element III.java ├── 557. Reverse Words in a String III.java ├── 559. Maximum Depth of N-ary Tree.java ├── 56. Merge Intervals.java ├── 560. Subarray Sum Equals K.java ├── 561. Array Partition I.java ├── 562. Longest Line of Consecutive One in Matrix.java ├── 563. Binary Tree Tilt.java ├── 564. Find the Closest Palindrome.java ├── 565. Array Nesting.java ├── 566. Reshape the Matrix.java ├── 567. Permutation in String.java ├── 57. Insert Interval.java ├── 572. Subtree of Another Tree.java ├── 573. Squirrel Simulation.java ├── 575. Distribute Candies.java ├── 576. Out of Boundary Paths.java ├── 58. Length of Last Word.java ├── 581. Shortest Unsorted Continuous Subarray.java ├── 582. Kill Process.java ├── 583. Delete Operation for Two Strings.java ├── 587. Erect the Fence.java ├── 588. Design In-Memory File System.java ├── 589. N-ary Tree Preorder Traversal.java ├── 59. Spiral Matrix II.java ├── 590. N-ary Tree Postorder Traversal.java ├── 591. Tag Validator.java ├── 592. Fraction Addition and Subtraction.java ├── 593. Valid Square.java ├── 594. Longest Harmonious Subsequence.java ├── 598. Range Addition II.java ├── 599. Minimum Index Sum of Two Lists.java ├── 6. ZigZag Conversion.java ├── 60. Permutation Sequence.java ├── 600. Non-negative Integers without Consecutive Ones.java ├── 605. Can Place Flowers.java ├── 606. Construct String from Binary Tree.java ├── 609. Find Duplicate File in System.java ├── 61. Rotate List.java ├── 611. Valid Triangle Number.java ├── 617. Merge Two Binary Trees.java ├── 62. Unique Paths.java ├── 621. Task Scheduler.java ├── 622. Design Circular Queue.java ├── 623. Add One Row to Tree.java ├── 624. Maximum Distance in Arrays.java ├── 628. Maximum Product of Three Numbers.java ├── 63. Unique Paths II.java ├── 630. Course Schedule III.java ├── 633. Sum of Square Numbers.java ├── 636. Exclusive Time of Functions.java ├── 637. Average of Levels in Binary Tree.java ├── 638. Shopping Offers.java ├── 64. Minimum Path Sum.java ├── 640. Solve the Equation.java ├── 641. Design Circular Deque.java ├── 642. Design Search Autocomplete System.java ├── 643. Maximum Average Subarray I.java ├── 645. Set Mismatch.java ├── 646. Maximum Length of Pair Chain.java ├── 647. Palindromic Substrings.java ├── 648. Replace Words.java ├── 650. 2 Keys Keyboard.java ├── 651. 4 Keys Keyboard.java ├── 652. Find Duplicate Subtrees.java ├── 655. Print Binary Tree.java ├── 657. Robot Return to Origin.java ├── 658. Find K Closest Elements.java ├── 659. Split Array into Consecutive Subsequences.java ├── 661. Image Smoother.java ├── 662. Maximum Width of Binary Tree.java ├── 663. Equal Tree Partition.java ├── 664. Strange Printer.java ├── 665. Non-decreasing Array.java ├── 669. Trim a Binary Search Tree.java ├── 67. Add Binary.java ├── 670. Maximum Swap.java ├── 673. Number of Longest Increasing Subsequence.java ├── 674. Longest Continuous Increasing Subsequence.java ├── 676. Implement Magic Dictionary.java ├── 677. Map Sum Pairs.java ├── 678. Valid Parenthesis String.java ├── 68. Text Justification.java ├── 680. Valid Palindrome II.java ├── 681. Next Closest Time.java ├── 682. Baseball Game.java ├── 683. K Empty Slots.java ├── 684. Redundant Connection.java ├── 685. Redundant Connection II.java ├── 686. Repeated String Match.java ├── 687. Longest Univalue Path.java ├── 688. Knight Probability in Chessboard.java ├── 69. Sqrt(x).java ├── 690. Employee Importance.java ├── 692. Top K Frequent Words.java ├── 693. Binary Number with Alternating Bits.java ├── 694. Number of Distinct Islands.java ├── 695. Max Area of Island.java ├── 696. Count Binary Substrings.java ├── 697. Degree of an Array.java ├── 698. Partition to K Equal Sum Subsets.java ├── 7. Reverse Integer.java ├── 70. Climbing Stairs.java ├── 700. Search in a Binary Search Tree.java ├── 701. Insert into a Binary Search Tree.java ├── 702. Search in a Sorted Array of Unknown Size.java ├── 703. Kth Largest Element in a Stream.java ├── 704. Binary Search.java ├── 705. Design HashSet.java ├── 706. Design HashMap.java ├── 707. Design Linked List.java ├── 708. Insert into a Sorted Circular Linked List.java ├── 71. Simplify Path.java ├── 712. Minimum ASCII Delete Sum for Two Strings.java ├── 713. Subarray Product Less Than K.java ├── 714. Best Time to Buy and Sell Stock with Transaction Fee.java ├── 716. Max Stack.java ├── 717. 1-bit and 2-bit Characters.java ├── 718. Maximum Length of Repeated Subarray.java ├── 72. Edit Distance.java ├── 721. Accounts Merge.java ├── 722. Remove Comments.java ├── 723. Candy Crush.java ├── 724. Find Pivot Index.java ├── 725. Split Linked List in Parts.java ├── 727. Minimum Window Subsequence.java ├── 729. My Calendar I.java ├── 73. Set Matrix Zeroes.java ├── 731. My Calendar II.java ├── 733. Flood Fill.java ├── 734. Sentence Similarity.java ├── 735. Asteroid Collision.java ├── 737. Sentence Similarity II.java ├── 739. Daily Temperatures.java ├── 74. Search a 2D Matrix.java ├── 740. Delete and Earn.java ├── 741. Cherry Pickup.java ├── 742. Closest Leaf in a Binary Tree.java ├── 743. Network Delay Time.java ├── 746. Min Cost Climbing Stairs.java ├── 75. Sort Colors.java ├── 752. Open the Lock.java ├── 755. Pour Water.java ├── 759. Employee Free Time.java ├── 76. Minimum Window Substring.java ├── 762. Prime Number of Set Bits in Binary Representation.java ├── 763. Partition Labels.java ├── 766. Toeplitz Matrix.java ├── 767. Reorganize String.java ├── 77. Combinations.java ├── 771. Jewels and Stones.java ├── 772. Basic Calculator III.java ├── 773. Sliding Puzzle.java ├── 777. Swap Adjacent in LR String.java ├── 778. Swim in Rising Water.java ├── 78. Subsets.java ├── 780. Reaching Points.java ├── 783. Minimum Distance Between BST Nodes.java ├── 784. Letter Case Permutation.java ├── 785. Is Graph Bipartite.java ├── 787. Cheapest Flights Within K Stops.java ├── 79. Word Search.java ├── 791. Custom Sort String.java ├── 792. Number of Matching Subsequences.java ├── 794. Valid Tic-Tac-Toe State.java ├── 796. Rotate String.java ├── 797. All Paths From Source to Target.java ├── 8. String to Integer (atoi).java ├── 801. Minimum Swaps To Make Sequences Increasing.java ├── 802. Find Eventual Safe States.java ├── 809. Expressive Words.java ├── 81. Search in Rotated Sorted Array II.java ├── 811. Subdomain Visit Count.java ├── 814. Binary Tree Pruning.java ├── 815. Bus Routes.java ├── 819. Most Common Word.java ├── 82. Remove Duplicates from Sorted List II.java ├── 821. Shortest Distance to a Character.java ├── 824. Goat Latin.java ├── 828. Unique Letter String.java ├── 829. Consecutive Numbers Sum.java ├── 83. Remove Duplicates from Sorted List.java ├── 832. Flipping an Image.java ├── 833. Find And Replace in String.java ├── 836. Rectangle Overlap.java ├── 84. Largest Rectangle in Histogram.java ├── 841. Keys and Rooms.java ├── 843. Guess the Word.java ├── 844. Backspace String Compare.java ├── 846. Hand of Straights.java ├── 847. Shortest Path Visiting All Nodes.java ├── 849. Maximize Distance to Closest Person.java ├── 85. Maximal Rectangle.java ├── 852. Peak Index in a Mountain Array.java ├── 855. Exam Room.java ├── 859. Buddy Strings.java ├── 86. Partition List.java ├── 862. Shortest Subarray with Sum at Least K.java ├── 863. All Nodes Distance K in Binary Tree.java ├── 867. Transpose Matrix.java ├── 87. Scramble String.java ├── 872. Leaf-Similar Trees.java ├── 875. Koko Eating Bananas.java ├── 876. Middle of the Linked List.java ├── 877. Stone Game.java ├── 88. Merge Sorted Array.java ├── 880. Decoded String at Index.java ├── 881. Boats to Save People.java ├── 887. Super Egg Drop.java ├── 888. Fair Candy Swap.java ├── 889. Construct Binary Tree from Preorder and Postorder Traversal.java ├── 89. Gray Code.java ├── 895. Maximum Frequency Stack.java ├── 896. Monotonic Array.java ├── 898. Bitwise ORs of Subarrays.java ├── 9. Palindrome Number.java ├── 90. Subsets II.java ├── 901. Online Stock Span.java ├── 904. Fruit Into Baskets.java ├── 905. Sort Array By Parity.java ├── 907. Sum of Subarray Minimums.java ├── 909. Snakes and Ladders.java ├── 91. Decode Ways.java ├── 912. Sort an Array.java ├── 915. Partition Array into Disjoint Intervals.java ├── 918. Maximum Sum Circular Subarray.java ├── 92. Reverse Linked List II.java ├── 921. Minimum Add to Make Parentheses Valid.java ├── 929. Unique Email Addresses.java ├── 93. Restore IP Addresses.java ├── 931. Minimum Falling Path Sum.java ├── 932. Beautiful Array.java ├── 933. Number of Recent Calls.java ├── 934. Shortest Bridge.java ├── 935. Knight Dialer.java ├── 937. Reorder Log Files.java ├── 938. Range Sum of BST.java ├── 939. Minimum Area Rectangle.java ├── 94. Binary Tree Inorder Traversal.java ├── 944. Delete Columns to Make Sorted.java ├── 945. Minimum Increment to Make Array Unique.java ├── 946. Validate Stack Sequences.java ├── 947. Most Stones Removed with Same Row or Column.java ├── 95. Unique Binary Search Trees II.java ├── 950. Reveal Cards In Increasing Order.java ├── 951. Flip Equivalent Binary Trees.java ├── 952. Largest Component Size by Common Factor.java ├── 953. Verifying an Alien Dictionary.java ├── 958. Check Completeness of a Binary Tree.java ├── 96. Unique Binary Search Trees.java ├── 961. N-Repeated Element in Size 2N Array.java ├── 962. Maximum Width Ramp.java ├── 963. Minimum Area Rectangle II.java ├── 965. Univalued Binary Tree.java ├── 969. Pancake Sorting.java ├── 97. Interleaving String.java ├── 973. K Closest Points to Origin.java ├── 974. Subarray Sums Divisible by K.java ├── 977. Squares of a Sorted Array.java ├── 978. Longest Turbulent Subarray.java ├── 979. Distribute Coins in Binary Tree.java ├── 98. Validate Binary Search Tree.java ├── 980. Unique Paths III.java ├── 981. Time Based Key-Value Store.java ├── 983. Minimum Cost For Tickets.java ├── 986. Interval List Intersections.java ├── 987. Vertical Order Traversal of a Binary Tree.java ├── 989. Add to Array-Form of Integer.java ├── 99. Recover Binary Search Tree.java ├── 990. Satisfiability of Equality Equations.java ├── 991. Broken Calculator.java ├── 993. Cousins in Binary Tree.java ├── 994. Rotting Oranges.java ├── 997. Find the Town Judge.java └── README.md /.vscode/settings.json: -------------------------------------------------------------------------------- 1 | { 2 | "files.exclude": { 3 | "**/.classpath": true, 4 | "**/.project": true, 5 | "**/.settings": true, 6 | "**/.factorypath": true 7 | } 8 | } -------------------------------------------------------------------------------- /1. Two Sum.java: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/two-sum/ 2 | 3 | // 思路:暴力解法,对每个数都遍历数组后面的所有数 4 | // 出现的问题:时间复杂度太高,为O(n^2) 5 | 6 | 7 | // 优化思路:One-pass HashMap 8 | // HashMap中key为nums数组每个数【被target减去后的剩下的数】,value为这个数在nums数组的位置。 9 | // 遍历nums数组,先判断HashMap中是否存在nums[i],如果有,那么说明和nums[i]相加为target的数在前面已经出现过, 10 | // 因此返回它们的index组成的数组。否则,将target - nums[i]和对应的i放进HashMap。 11 | // 时间复杂度:O(n) 12 | // 空间复杂度:O(n) 13 | 14 | class Solution { 15 | public int[] twoSum(int[] nums, int target) { 16 | Map map = new HashMap<>(); 17 | for (int i = 0; i < nums.length; i++) { 18 | if (map.containsKey(nums[i])) return new int[]{map.get(nums[i]), i}; 19 | map.put(target - nums[i], i); 20 | } 21 | return new int[0]; 22 | } 23 | } -------------------------------------------------------------------------------- /101. Symmetric Tree.java: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/symmetric-tree/ 2 | 3 | // 解法一:Recursion 4 | // 可知symmetric tree的性质是除root外,在root左右两边的子节点相同,且左子树的左子树和右子树的右子树互为镜像, 5 | // 左子树的右子树和右子树的左子树也互为镜像。 6 | // 或者这么看:如果两个树互为镜像,那么root节点相同,左子树和对方右子树互为镜像。 7 | 8 | class Solution { 9 | public boolean isSymmetric(TreeNode root) { 10 | /* 写法一 */ 11 | if (root == null) return true; 12 | return isMirror(root.left, root.right); 13 | 14 | /* 写法二 */ 15 | /*return isMirror(root, root);*/ 16 | } 17 | 18 | private boolean isMirror(TreeNode root1, TreeNode root2) { 19 | return (root1 == null && root2 == null) || 20 | (root1 != null && root2 != null && root1.val == root2.val && isMirror(root1.left, root2.right) && isMirror(root1.right, root2.left)); 21 | } 22 | } 23 | 24 | 25 | 解法二:Iteration -------------------------------------------------------------------------------- /1010. Pairs of Songs With Total Durations Divisible by 60.java: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/pairs-of-songs-with-total-durations-divisible-by-60/ 2 | 3 | 思路:Array模拟HashMap 4 | 时间复杂度:O(n) 5 | 空间复杂度:O(60) = O(1) 6 | 7 | class Solution { 8 | public int numPairsDivisibleBy60(int[] time) { 9 | int[] count = new int[60]; 10 | int res = 0; 11 | for (int t : time) { 12 | t = t % 60; 13 | res += count[(60 - t) % 60]; 14 | count[t]++; 15 | } 16 | 17 | return res; 18 | } 19 | } -------------------------------------------------------------------------------- /1014. Best Sightseeing Pair.java: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/best-sightseeing-pair/ 2 | 3 | // 思路:Dynamic Programming??? 参考答案:https://leetcode.com/problems/best-sightseeing-pair/discuss/260850/JavaC%2B%2BPython-One-Pass 4 | // 维护变量max,表示当前搜索到的最大的score;变量curr,表示当前元素左边范围的所有元素中“辐射”到当前位置时的最大值。 5 | // 当搜索到新的元素n,利用“辐射”的最大值curr和当前元素n的和更新max。 6 | // 然后,更新“辐射”的最大值curr为curr和当前元素n两者中的较大值,同时需要减去1,表示当“辐射”到达下一个元素时的值。 7 | // 时间复杂度:O(n) 8 | // 空间复杂度:O(1) 9 | 10 | class Solution { 11 | public int maxScoreSightseeingPair(int[] A) { 12 | int max = 0, curr = 0; 13 | for (int n: A) { 14 | max = Math.max(max, curr + n); 15 | curr = Math.max(curr, n) - 1; 16 | } 17 | 18 | return max; 19 | } 20 | } -------------------------------------------------------------------------------- /1015. Smallest Integer Divisible by K.java: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/smallest-integer-divisible-by-k/ 2 | 3 | idea: Math, pigeon holes problem. Referring to: https://leetcode.com/problems/smallest-integer-divisible-by-k/discuss/260852/JavaC%2B%2BPython-O(1)-Space-with-Proves-of-Pigeon-Holes 4 | time complexity: O(K) 5 | space complexity: O(1) 6 | 7 | class Solution { 8 | public int smallestRepunitDivByK(int k) { 9 | 10 | if (k == 2 || k == 5) { 11 | return -1; 12 | } 13 | 14 | int num = 0; 15 | for (int len = 1; len <= k; len++) { 16 | num = (num * 10 + 1) % k; 17 | if (num == 0) { 18 | return len; 19 | } 20 | } 21 | 22 | return -1; 23 | } 24 | } -------------------------------------------------------------------------------- /1026. Maximum Difference Between Node and Ancestor.java: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/maximum-difference-between-node-and-ancestor/ 2 | 3 | idea: DFS 4 | time complexity: O(n) 5 | space complexity: O(h) 6 | 7 | class Solution { 8 | int res = 0; 9 | 10 | private void dfs(TreeNode node, int min, int max) { 11 | if (node == null) { 12 | return; 13 | } 14 | 15 | int diff = Math.max(Math.abs(max - node.val), Math.abs(min - node.val)); 16 | res = Math.max(res, diff); 17 | min = Math.min(min, node.val); 18 | max = Math.max(max, node.val); 19 | 20 | dfs(node.left, min, max); 21 | dfs(node.right, min, max); 22 | } 23 | 24 | public int maxAncestorDiff(TreeNode root) { 25 | dfs(root, root.val, root.val); 26 | return res; 27 | } 28 | } -------------------------------------------------------------------------------- /1029. Two City Scheduling.java: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/two-city-scheduling/ 2 | 3 | idea: Greedy. Referring to: https://leetcode.com/problems/two-city-scheduling/solution/ 4 | time complexity: O(n log n) 5 | space complexity: O(n) for sorting, O(1) for iteration 6 | 7 | class Solution { 8 | public int twoCitySchedCost(int[][] costs) { 9 | // sort ascendingly by price diff between city A and city B 10 | Arrays.sort(costs, (a, b) -> (a[0] - a[1]) - (b[0] - b[1])); 11 | int n = costs.length / 2, total = 0; 12 | for (int i = 0; i < n; i++) { 13 | total += costs[i][0] + costs[i + n][1]; 14 | } 15 | 16 | return total; 17 | } 18 | } -------------------------------------------------------------------------------- /104. Maximum Depth of Binary Tree.java: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/maximum-depth-of-binary-tree/ 2 | 3 | // 写法一:Recursion 4 | // 时间复杂度:worst case O(n) 5 | // 空间复杂度:worst case O(n) 6 | 7 | class Solution { 8 | public int maxDepth(TreeNode root) { 9 | if (root == null) return 0; 10 | return 1 + Math.max(maxDepth(root.left), maxDepth(root.right)); 11 | } 12 | } 13 | 14 | 15 | 写法二:Iteration using Queue -------------------------------------------------------------------------------- /1046. Last Stone Weight.java: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/last-stone-weight/ 2 | 3 | 思路:Heap,类似huffman coding tree 4 | 时间复杂度:O(n log n) 5 | 空间复杂度:O(n) 6 | 7 | class Solution { 8 | public int lastStoneWeight(int[] stones) { 9 | PriorityQueue pq = new PriorityQueue<>(new Comparator() { 10 | @Override 11 | public int compare(Integer i1, Integer i2) { 12 | return i2 - i1; 13 | } 14 | }); 15 | 16 | for (int stone : stones) { 17 | pq.offer(stone); 18 | } 19 | 20 | while (pq.size() > 1) { 21 | int heavy = pq.poll(), light = pq.poll(); 22 | if (heavy - light > 0) { 23 | pq.offer(heavy - light); 24 | } 25 | } 26 | 27 | return pq.isEmpty() ? 0 : pq.poll(); 28 | } 29 | } -------------------------------------------------------------------------------- /1047. Remove All Adjacent Duplicates In String.java: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/remove-all-adjacent-duplicates-in-string/ 2 | 3 | 思路:Stack 4 | 时间复杂度:O(n), n=S.length() 5 | 空间复杂度:O(n) 6 | follow-up:1209. Remove All Adjacent Duplicates in String II 7 | 8 | class Solution { 9 | public String removeDuplicates(String S) { 10 | StringBuilder sb = new StringBuilder(); 11 | for (char c : S.toCharArray()) { 12 | if (sb.length() > 0 && sb.charAt(sb.length() - 1) == c) { 13 | sb.deleteCharAt(sb.length() - 1); 14 | } else { 15 | sb.append(c); 16 | } 17 | } 18 | 19 | return sb.toString(); 20 | } 21 | } -------------------------------------------------------------------------------- /1056. Confusing Number.java: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/confusing-number/ 2 | 3 | // 思路:Math 4 | // 时间复杂度:O(log N) 5 | // 空间复杂度:O(log N) 6 | 7 | class Solution { 8 | public boolean confusingNumber(int N) { 9 | Set set = new HashSet<>(Arrays.asList(0, 1, 6, 8, 9)); 10 | int rotate = 0; 11 | int temp = N; 12 | while (temp != 0) { 13 | int last = temp % 10; 14 | if (!set.contains(last)) { 15 | return false; 16 | } 17 | 18 | if (last == 6) { 19 | last = 9; 20 | } else if (last == 9) { 21 | last = 6; 22 | } 23 | 24 | rotate = rotate * 10 + last; 25 | temp = temp / 10; 26 | } 27 | 28 | return rotate != N; 29 | } 30 | } -------------------------------------------------------------------------------- /1062. Longest Repeating Substring.java: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/longest-repeating-substring/ 2 | 3 | idea: DP 4 | time complexity: O(n^2) 5 | space complexity: O(n^2) 6 | 7 | class Solution { 8 | public int longestRepeatingSubstring(String S) { 9 | if(S == null || S.length() == 0){ 10 | return 0; 11 | } 12 | 13 | int n = S.length(), res = 0; 14 | 15 | int [][] dp = new int[n+1][n+1]; 16 | for(int i = 1; i<=n; i++){ 17 | for(int j = 1; j= mid) { 14 | high = mid - 1; 15 | } else { 16 | low = mid + 1; 17 | } 18 | } 19 | 20 | return low < n && A[low] == low ? low : -1; 21 | } 22 | } -------------------------------------------------------------------------------- /1085. Sum of Digits in the Minimum Number.java: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/sum-of-digits-in-the-minimum-number/ 2 | 3 | // 思路:Math 4 | // 时间复杂度:O(len + log(num)), len=A.length, num=max(A) 5 | // 空间复杂度:O(1) 6 | 7 | class Solution { 8 | public int sumOfDigits(int[] A) { 9 | int num = A[0]; 10 | for (int n: A) { 11 | num = Math.min(num, n); 12 | } 13 | int sum = 0; 14 | while (num != 0) { 15 | sum += num % 10; 16 | num /= 10; 17 | } 18 | 19 | return (sum + 1) % 2; 20 | } 21 | } -------------------------------------------------------------------------------- /1089. Duplicate Zeros.java: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/duplicate-zeros/ 2 | 3 | // 思路:Queue 4 | // 利用Queue的FIFO特性,将当前元素arr[i]放进Queue。如果遇到0,那么再多放一个0。然后将arr[i]替换成 5 | // Queue的头部元素,Queue中剩下的元素将会在后续过程中取出。 6 | // 时间复杂度:O(n) 7 | // 空间复杂度:O(n) 8 | 9 | class Solution { 10 | public void duplicateZeros(int[] arr) { 11 | Queue queue = new LinkedList<>(); 12 | for (int i = 0; i < arr.length; i++) { 13 | queue.offer(arr[i]); 14 | if (arr[i] == 0) { 15 | queue.offer(arr[i]); 16 | } 17 | arr[i] = queue.poll(); 18 | } 19 | } 20 | } -------------------------------------------------------------------------------- /1094. Car Pooling.java: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/car-pooling/ 2 | 3 | idea: Sweeping Line 4 | time comp: O(n log n) 5 | space comp: O(n) 6 | 7 | class Solution { 8 | public boolean carPooling(int[][] trips, int capacity) { 9 | PriorityQueue pq = new PriorityQueue<>((a, b) -> a[0] == b[0] ? a[1] - b[1] : a[0] - b[0]); // {loc, start/end, #passenger} 10 | for (int[] trip: trips) { 11 | pq.offer(new int[]{trip[1], 1, trip[0]}); 12 | pq.offer(new int[]{trip[2], -1, trip[0]}); 13 | } 14 | 15 | int total = 0; 16 | while (!pq.isEmpty()) { 17 | int[] curr = pq.poll(); 18 | total += curr[1] * curr[2]; 19 | if (total > capacity) return false; 20 | } 21 | 22 | return true; 23 | } 24 | } -------------------------------------------------------------------------------- /11. Container With Most Water.java: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/container-with-most-water/ 2 | 3 | // Two pointers 4 | // 关键:当height[left] < height[right]时,left右移,反之更新right左移,因为根据短板原理,只有这样才有 5 | // 可能更新后的面积比原面积大 6 | 7 | class Solution { 8 | public int maxArea(int[] height) { 9 | int left = 0, right = height.length - 1, max = (right - left) * Math.min(height[left], height[right]); 10 | while (left < right) { 11 | if (height[left] < height[right]) left++; 12 | else right--; 13 | max = Math.max(max, (right - left) * Math.min(height[left], height[right])); 14 | } 15 | return max; 16 | } 17 | } -------------------------------------------------------------------------------- /110. Balanced Binary Tree.java: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/balanced-binary-tree/ 2 | 3 | // 思路:明显的Recursion。Iteration写起来比较麻烦。 4 | // 关键是了解height-balanced binary tree的性质:左右子树都为balanced binary tree,且左右子树的最大高度相差不超过1。 5 | 6 | class Solution { 7 | public boolean isBalanced(TreeNode root) { 8 | if (root == null) return true; 9 | return isBalanced(root.left) && isBalanced(root.right) && Math.abs(height(root.left) - height(root.right)) <= 1; 10 | } 11 | /** get the depth (maximum height) of a tree */ 12 | private int height(TreeNode root) { 13 | if (root == null) return 0; 14 | return 1 + Math.max(height(root.left), height(root.right)); 15 | } 16 | } -------------------------------------------------------------------------------- /1103. Distribute Candies to People.java: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/distribute-candies-to-people/ 2 | 3 | // 思路:Brute Force 4 | // 时间复杂度:O(sqrt(candies)),因为1+2+3+...+k = k*(k+1)/2 = candies,一共k步,k和sqrt(candies)有关。 5 | // 空间复杂度:O(n) 6 | 7 | class Solution { 8 | public int[] distributeCandies(int candies, int n) { 9 | int[] res = new int[n]; 10 | int pos = 0; 11 | while (candies > 0) { 12 | int index = pos % n; 13 | int curr = Math.min(candies, pos + 1);; 14 | res[index] += curr; 15 | candies -= curr; 16 | pos++; 17 | } 18 | 19 | return res; 20 | } 21 | } -------------------------------------------------------------------------------- /1108. Defanging an IP Address.java: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/defanging-an-ip-address/ 2 | 3 | // 思路:String.replaceAll() 4 | // 时间复杂度:O(n) 5 | // 空间复杂度:O(n) 6 | 7 | class Solution { 8 | public String defangIPaddr(String address) { 9 | return address.replaceAll("\\.", "[.]"); 10 | } 11 | } -------------------------------------------------------------------------------- /1118. Number of Days in a Month.java: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/number-of-days-in-a-month/ 2 | 3 | // 思路:常识题 4 | // 时间复杂度:O(1) 5 | // 空间复杂度:O(1) 6 | 7 | class Solution { 8 | public int numberOfDays(int Y, int M) { 9 | int[] months = new int[]{0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; 10 | if (isLeap(Y) && M == 2) { 11 | return 29; 12 | } 13 | 14 | return months[M]; 15 | } 16 | 17 | private boolean isLeap(int year) { 18 | return (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0); 19 | } 20 | } -------------------------------------------------------------------------------- /1119. Remove Vowels from a String.java: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/remove-vowels-from-a-string/ 2 | 3 | // 思路:遍历 + Java内置函数应用 4 | // 时间复杂度:O(n) 5 | // 空间复杂度:O(n) 6 | 7 | class Solution { 8 | public String removeVowels(String S) { 9 | StringBuilder sb = new StringBuilder(); 10 | String vowels = "aeiou"; 11 | for (char c: S.toCharArray()) { 12 | if (vowels.indexOf(c) < 0) { 13 | sb.append(c); 14 | } 15 | } 16 | return sb.toString(); 17 | } 18 | } -------------------------------------------------------------------------------- /1133. Largest Unique Number.java: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/largest-unique-number/ 2 | 3 | // 思路:HashMap 4 | // 时间复杂度:O(n) 5 | // 空间复杂度:O(n) 6 | 7 | class Solution { 8 | public int largestUniqueNumber(int[] A) { 9 | Map map = new HashMap<>(); 10 | for (int n: A) { 11 | map.put(n, map.getOrDefault(n, 0) + 1); 12 | } 13 | 14 | int maxNum = -1; 15 | for (int n: map.keySet()) { 16 | if (map.get(n) == 1) { 17 | maxNum = Math.max(maxNum, n); 18 | } 19 | } 20 | 21 | return maxNum; 22 | } 23 | } -------------------------------------------------------------------------------- /1134. Armstrong Number.java: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/armstrong-number/ 2 | 3 | // 思路:Math,相关api的调用。 4 | // 时间复杂度:O(k) 5 | // 空间复杂度:O(1) 6 | 7 | class Solution { 8 | public boolean isArmstrong(int N) { 9 | int k = String.valueOf(N).length(); // optimization, no need to manually iterate every digit to get k 10 | int temp = N; 11 | 12 | long sum = 0; 13 | while (temp > 0) { 14 | sum += Math.pow(temp % 10, k); 15 | temp = temp / 10; 16 | } 17 | 18 | return sum == N; 19 | } 20 | } -------------------------------------------------------------------------------- /1137. N-th Tribonacci Number.java: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/n-th-tribonacci-number/ 2 | 3 | // 思路:Fibonacci数列的进阶版,DP降维至常数个向量,用temp临时保存t2的值。 4 | 5 | class Solution { 6 | public int tribonacci(int n) { 7 | if (n == 0) return 0; 8 | if (n == 1) return 1; 9 | if (n == 2) return 1; 10 | int t0 = 0, t1 = 1, t2 = 1; 11 | for (int i = 2; i < n; i++) { 12 | int temp = t2; 13 | t2 += t1 + t0; 14 | t0 = t1; 15 | t1 = temp; 16 | } 17 | return t2; 18 | } 19 | } -------------------------------------------------------------------------------- /1150. Check If a Number Is Majority Element in a Sorted Array.java: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/check-if-a-number-is-majority-element-in-a-sorted-array/ 2 | 3 | // 解法一:Math 4 | // 时间复杂度:O(1) 5 | // 空间复杂度:O(1) 6 | // 犯错点:1.细节错误:如果nums数组有偶数个元素,那么nums[length / 2]仅仅是右半边的最左边元素,可能只包含右半边 7 | // length / 2个元素,不符合题意。因此,需要再确认nums[(length - 1) / 2],即左半边的最右边元素。 8 | // 对于奇数个元素的nums数组,nums[length / 2]和nums[(length - 1) / 2]是实际上同一个元素。 9 | 10 | class Solution { 11 | public boolean isMajorityElement(int[] nums, int target) { 12 | //return nums[nums.length / 2] == target; // {Mistake 1} 13 | return nums[nums.length / 2] == target && nums[(nums.length - 1) / 2] == target; // {Correction 1} 14 | } 15 | } 16 | 17 | 18 | 解法二:Binary Search 19 | 时间复杂度:O(log n) 20 | 空间复杂度:O(1) -------------------------------------------------------------------------------- /1165. Single-Row Keyboard.java: -------------------------------------------------------------------------------- 1 | https://leetcode.com/contest/biweekly-contest-7/problems/single-row-keyboard/ 2 | 3 | // 思路:常规遍历,利用indexOf() 4 | // 时间复杂度:O(n) 5 | // 空间复杂度:O(1) 6 | 7 | class Solution { 8 | public int calculateTime(String keyboard, String word) { 9 | int res = 0, pre = 0; 10 | for (char c: word.toCharArray()) { 11 | int curr = keyboard.indexOf(c); 12 | res += Math.abs(curr - pre); 13 | pre = curr; 14 | } 15 | 16 | return res; 17 | } 18 | } -------------------------------------------------------------------------------- /1167. Minimum Cost to Connect Sticks.java: -------------------------------------------------------------------------------- 1 | https://leetcode.com/contest/biweekly-contest-7/problems/minimum-cost-to-connect-sticks/ 2 | 3 | // 思路:minHeap 4 | // 根据题意,需要取当前所拥有的元素中的最小的两个,求和后放回去,然后再进行拿取,直到minHeap中的元素个数小于2。 5 | // 维护变量sum,记录每次两个元素求和的结果。初始化为0。 6 | // 时间复杂度:O(n log n) 7 | // 空间复杂度:O(n) 8 | 9 | class Solution { 10 | public int connectSticks(int[] sticks) { 11 | if (sticks.length < 2) { 12 | return 0; 13 | } 14 | 15 | int sum = 0; 16 | PriorityQueue pq = new PriorityQueue<>(); 17 | for (int n : sticks) { 18 | pq.offer(n); 19 | } 20 | 21 | while (pq.size() >= 2) { 22 | int curr = pq.poll(); 23 | curr += pq.poll(); 24 | sum += curr; 25 | pq.offer(curr); 26 | } 27 | 28 | return sum; 29 | } 30 | } -------------------------------------------------------------------------------- /1176. Diet Plan Performance.java: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/diet-plan-performance/ 2 | 3 | // 思路:Sliding window 4 | // 时间复杂度:O(n) 5 | // 空间复杂度:O(1) 6 | 7 | class Solution { 8 | public int dietPlanPerformance(int[] calories, int k, int lower, int upper) { 9 | int sum = 0, point = 0; 10 | for (int i = 0; i < calories.length; i++) { 11 | sum += calories[i]; 12 | if (i >= k - 1) { 13 | if (sum < lower) { 14 | point--; 15 | } else if (sum > upper) { 16 | point++; 17 | } 18 | sum -= calories[i - k + 1]; 19 | } 20 | } 21 | 22 | return point; 23 | } 24 | } -------------------------------------------------------------------------------- /1186. Maximum Subarray Sum with One Deletion.java: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/maximum-subarray-sum-with-one-deletion/ 2 | 3 | 思路:DP 4 | 5 | 时间复杂度:O(n) 6 | 空间复杂度:O(n) 7 | 8 | class Solution { 9 | public int maximumSum(int[] arr) { 10 | if (arr.length == 1) { 11 | return arr[0]; 12 | } 13 | 14 | int maxSum = Integer.MIN_VALUE; 15 | int[][] dp = new int[arr.length][2]; 16 | dp[0][0] = arr[0]; 17 | dp[0][1] = arr[0]; 18 | for (int i = 1; i < arr.length; i++) { 19 | dp[i][1] = Math.max(arr[i], arr[i] + dp[i - 1][1]); 20 | dp[i][0] = Math.max(dp[i - 1][1], arr[i] + dp[i - 1][0]); 21 | maxSum = Math.max(maxSum, Math.max(dp[i][0], dp[i][1])); 22 | } 23 | 24 | return maxSum; 25 | } 26 | } -------------------------------------------------------------------------------- /1189. Maximum Number of Balloons.java: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/maximum-number-of-balloons/ 2 | 3 | // 思路:HashMap,利用数组模拟。 4 | // 取'b'的个数,'a'的个数,'n'的个数,'l'的个数的一半,和'n'的个数的一半的最小值。 5 | // 时间复杂度:O(n) 6 | // 空间复杂度:O(1) 7 | 8 | class Solution { 9 | public int maxNumberOfBalloons(String text) { 10 | int[] count = new int[26]; 11 | 12 | for (char c: text.toCharArray()) { 13 | count[c - 'a']++; 14 | } 15 | 16 | int res = Integer.MAX_VALUE; 17 | for (char c: "balon".toCharArray()) { 18 | int temp = count[c - 'a'] / (c == 'l' || c == 'o' ? 2 : 1); 19 | res = Math.min(res, temp); 20 | } 21 | 22 | return res; 23 | } 24 | } -------------------------------------------------------------------------------- /119. Pascal's Triangle II.java: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/pascals-triangle-ii/ 2 | 3 | idea: DP? 4 | time comp: O(rowIndex^2) 5 | space comp: O(rowIndex) 6 | 7 | class Solution { 8 | public List getRow(int rowIndex) { 9 | List ret = new ArrayList<>(); 10 | for (int row = 0; row <= rowIndex; row++) { 11 | ret.add(ret.size(), 1); 12 | for (int col = row - 1; col >= 1; col--) { 13 | ret.set(col, ret.get(col) + ret.get(col - 1)); 14 | } 15 | } 16 | 17 | return ret; 18 | } 19 | } -------------------------------------------------------------------------------- /1196. How Many Apples Can You Put into the Basket.java: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/how-many-apples-can-you-put-into-the-basket/ 2 | 3 | // 思路:Sort + Greedy。注意:不是0/1背包问题。 4 | // 每次取重量最小的苹果,直到总重量超过限制5000. 5 | // 时间复杂度:O(n log n) 6 | // 空间复杂度:O(1) 7 | 8 | class Solution { 9 | public int maxNumberOfApples(int[] arr) { 10 | Arrays.sort(arr); 11 | int count = 0, sum = 0; 12 | for (int w: arr) { 13 | sum += w; 14 | if (sum > 5000) { 15 | break; 16 | } 17 | count++; 18 | } 19 | 20 | return count; 21 | } 22 | } -------------------------------------------------------------------------------- /120. Triangle.java: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/triangle/ 2 | 3 | // 总体思路:DP题,需要转变思维,从底层往上走,这样就可以在每一层遍历的时候进行选择。 4 | // 状态函数:dp[i]表示从最底层行走到当前行时第i列(0-based)的minimum path sum。初始长度定为triangle.size()+1是为了简化代码。 5 | // 状态转移方程:当前行的sum取决于下一行,当前列的sum在下一行同一列和相邻列(即i和i+1)取较小值来更新。 6 | // 初始值:dp[i] = 0 7 | 8 | class Solution { 9 | public int minimumTotal(List> triangle) { 10 | int dimension = triangle.size(); 11 | int[] dp = new int[dimension + 1]; 12 | for (int row = dimension - 1; row >= 0; row--) { 13 | for (int col = 0; col <= row; col++) { 14 | dp[col] = triangle.get(row).get(col) + Math.min(dp[col], dp[col + 1]); 15 | } 16 | } 17 | return dp[0]; 18 | } 19 | } -------------------------------------------------------------------------------- /1200. Minimum Absolute Difference.java: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/minimum-absolute-difference/ 2 | 3 | // 思路:Sort 4 | // 时间复杂度:O(n log n) 5 | // 空间复杂度:O(n) 6 | 7 | class Solution { 8 | public List> minimumAbsDifference(int[] arr) { 9 | Arrays.sort(arr); 10 | int minDiff = Integer.MAX_VALUE; 11 | for (int i = 0; i + 1 < arr.length; i++) { 12 | minDiff = Math.min(minDiff, arr[i + 1] - arr[i]); 13 | } 14 | 15 | List> res = new ArrayList<>(); 16 | for (int i = 0; i + 1 < arr.length; i++) { 17 | if (arr[i + 1] - arr[i] == minDiff) { 18 | res.add(Arrays.asList(arr[i], arr[i + 1])); 19 | } 20 | } 21 | 22 | return res; 23 | } 24 | } -------------------------------------------------------------------------------- /1207. Unique Number of Occurrences.java: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/unique-number-of-occurrences/ 2 | 3 | // 思路:HashMap + HashSet 4 | // 时间复杂度:O(n) 5 | // 空间复杂度:O(n) 6 | 7 | class Solution { 8 | public boolean uniqueOccurrences(int[] arr) { 9 | Map map = new HashMap<>(); 10 | for (int n: arr) { 11 | map.put(n, map.getOrDefault(n, 0) + 1); 12 | } 13 | 14 | Set set = new HashSet<>(map.values()); 15 | return map.size() == set.size(); 16 | } 17 | } -------------------------------------------------------------------------------- /121. Best Time to Buy and Sell Stock.java: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/best-time-to-buy-and-sell-stock/ 2 | 3 | idea: DP 4 | time comp: O(n) 5 | space comp: O(1) 6 | 7 | class Solution { 8 | public int maxProfit(int[] prices) { 9 | int max = 0; 10 | int buy = Integer.MAX_VALUE, sell = Integer.MIN_VALUE; 11 | for (int curr: prices) { 12 | if (curr < buy) { 13 | buy = curr; 14 | sell = curr; 15 | } else { 16 | sell = Math.max(sell, curr); 17 | max = Math.max(max, sell - buy); 18 | } 19 | } 20 | 21 | return max; 22 | } 23 | } -------------------------------------------------------------------------------- /1217. Play with Chips.java: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/play-with-chips/ 2 | 3 | // 思路:Math + Greedy 4 | // 根据题意,所有偶数元素可以0成本全部转移到某一特定偶数,奇数元素同理。因此,题目转化为取奇数和偶数元素的个数较小值, 5 | // 这样所用的成本最小。 6 | // 时间复杂度:O(n) 7 | // 空间复杂度:O(1) 8 | 9 | class Solution { 10 | public int minCostToMoveChips(int[] chips) { 11 | int odd = 0, even = 0; 12 | for (int n: chips) { 13 | if (n % 2 == 0) { 14 | even++; 15 | } else { 16 | odd++; 17 | } 18 | } 19 | 20 | return Math.min(odd, even); 21 | } 22 | } -------------------------------------------------------------------------------- /1221. Split a String in Balanced Strings.java: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/split-a-string-in-balanced-strings/ 2 | 3 | // 思路:Greedy 4 | // 依次遍历所有字符,统计'L'和'R'的出现次数,当次数相等时就可以进行切割,res++。最后返回res。 5 | // 时间复杂度:O(n) 6 | // 空间复杂度:O(1) 7 | 8 | class Solution { 9 | public int balancedStringSplit(String s) { 10 | int LCount = 0; 11 | int res = 0; 12 | for (char c : s.toCharArray()) { 13 | LCount += c == 'L' ? 1 : -1; 14 | if (LCount == 0) { 15 | res++; 16 | } 17 | } 18 | 19 | return res; 20 | } 21 | } -------------------------------------------------------------------------------- /1232. Check If It Is a Straight Line.java: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/check-if-it-is-a-straight-line/ 2 | 3 | // 思路:Math 4 | // 利用第三个点和两个基准点分别构成的直线的斜率是否相同来判断,即判断(y_curr - y_1) / (x_curr - x_1) 5 | // 是否等于(y_curr - y_2) / (x_curr - x_2)。为了避免除数为0,可以采用乘法的形式,即判断 6 | // (y_curr - y_1) * (x_curr - x_2)是否等于(y_curr - y_2) * (x_curr - x_1)。 7 | // 时间复杂度:O(n) 8 | // 空间复杂度:O(1) 9 | 10 | class Solution { 11 | public boolean checkStraightLine(int[][] coordinates) { 12 | int[] p1 = coordinates[0], p2 = coordinates[1]; 13 | for (int[] curr : coordinates) { 14 | if ((curr[1] - p1[1]) * (curr[0] - p2[0]) != (curr[1] - p2[1]) * (curr[0] - p1[0])) { 15 | return false; 16 | } 17 | } 18 | 19 | return true; 20 | } 21 | } -------------------------------------------------------------------------------- /1233. Remove Sub-Folders from the Filesystem.java: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/remove-sub-folders-from-the-filesystem/ 2 | 3 | 思路:遍历 + String.startsWith() 4 | 5 | 时间复杂度:O(n * k), n=folder.length, k=average length of each String 6 | 空间复杂度:O(n) 7 | 8 | class Solution { 9 | public List removeSubfolders(String[] folder) { 10 | List res = new ArrayList<>(); 11 | Arrays.sort(folder); 12 | int left = 0; 13 | while (left < folder.length) { 14 | int right = left + 1; 15 | while (right < folder.length && folder[right].startsWith(folder[left]) 16 | && folder[right].charAt(folder[left].length()) == '/') { 17 | right++; 18 | } 19 | 20 | res.add(folder[left]); 21 | left = right; 22 | } 23 | 24 | return res; 25 | } 26 | } -------------------------------------------------------------------------------- /1266. Minimum Time Visiting All Points.java: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/minimum-time-visiting-all-points/ 2 | 3 | // 思路:Math,找规律。 4 | // 实际上转化为连续两点间曼哈顿距离的横向距离和纵向距离的差值的绝对值。 5 | // 时间复杂度:O(n) 6 | // 空间复杂度:O(1) 7 | 8 | class Solution { 9 | public int minTimeToVisitAllPoints(int[][] points) { 10 | int n = points.length, res = 0; 11 | for (int i = 1; i < n; i++) { 12 | res += Math.max(Math.abs(points[i][0] - points[i - 1][0]), Math.abs(points[i][1] - points[i - 1][1])); 13 | } 14 | 15 | return res; 16 | } 17 | } -------------------------------------------------------------------------------- /1271. Hexspeak.java: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/hexspeak/ 2 | 3 | // 思路:Math + String 4 | // 时间复杂度:O(log n) 5 | // 空间复杂度:O(log n) 6 | 7 | class Solution { 8 | public String toHexspeak(String s) { 9 | char[] letters = new char[]{'O', 'I' ,'A', 'B', 'C', 'D', 'E', 'F'}; 10 | String res = ""; 11 | long num = Long.parseLong(s); 12 | while (num > 0) { 13 | int remainder = (int) (num % 16); 14 | if (remainder >= 2 && remainder <= 9) { 15 | return "ERROR"; 16 | } 17 | char letter = remainder < 2 ? letters[remainder] : letters[remainder - 8]; 18 | res = letter + res; 19 | num /= 16; 20 | } 21 | return res; 22 | } 23 | } -------------------------------------------------------------------------------- /1281. Subtract the Product and Sum of Digits of an Integer.java: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/subtract-the-product-and-sum-of-digits-of-an-integer/ 2 | 3 | 思路:Math 4 | 时间复杂度:O(log n) 5 | 空间复杂度:O(1) 6 | 7 | class Solution { 8 | public int subtractProductAndSum(int n) { 9 | int product = 1, sum = 0; 10 | while (n != 0) { 11 | int lastDigit = n % 10; 12 | n /= 10; 13 | product *= lastDigit; 14 | sum += lastDigit; 15 | } 16 | 17 | return product - sum; 18 | } 19 | } -------------------------------------------------------------------------------- /1287. Element Appearing More Than 25% In Sorted Array.java: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/element-appearing-more-than-25-in-sorted-array/ 2 | 3 | // 解法一:HashMap 4 | // 时间复杂度:O(n) 5 | // 空间复杂度:O(n) 6 | // 犯错点:1.思路错误:不能用vote algo 7 | 8 | class Solution { 9 | public int findSpecialInteger(int[] arr) { 10 | Map map = new HashMap<>(); 11 | int n = arr.length; 12 | for (int num : arr) { 13 | map.put(num, map.getOrDefault(num, 0) + 1); 14 | if (map.get(num) > n / 4) { 15 | return num; 16 | } 17 | } 18 | 19 | return -1; 20 | } 21 | } 22 | 23 | 24 | 解法二:Binary Search (in index) -------------------------------------------------------------------------------- /1290. Convert Binary Number in a Linked List to Integer.java: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/convert-binary-number-in-a-linked-list-to-integer/ 2 | 3 | // 思路:LinkedList + Math 4 | // 时间复杂度:O(n) 5 | // 空间复杂度:O(1) 6 | 7 | class Solution { 8 | public int getDecimalValue(ListNode head) { 9 | int res = 0; 10 | ListNode curr = head; 11 | while (curr != null) { 12 | res = res * 2 + curr.val; 13 | curr = curr.next; 14 | } 15 | return res; 16 | } 17 | } -------------------------------------------------------------------------------- /1299. Replace Elements with Greatest Element on Right Side.java: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/replace-elements-with-greatest-element-on-right-side/ 2 | 3 | // 思路:从右向左遍历,记录当前最大值。 4 | // 时间复杂度:O(n) 5 | // 空间复杂度:O(1) 6 | 7 | class Solution { 8 | public int[] replaceElements(int[] arr) { 9 | int max = -1, len = arr.length; 10 | for (int i = len - 1; i >= 0; i--) { 11 | int temp = arr[i]; 12 | arr[i] = max; 13 | max = Math.max(max, temp); 14 | } 15 | 16 | return arr; 17 | } 18 | } -------------------------------------------------------------------------------- /1304. Find N Unique Integers Sum up to Zero.java: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/find-n-unique-integers-sum-up-to-zero/ 2 | 3 | // 思路:找规律,只要每两个数是关于0对称即可。 4 | // 时间复杂度:O(n) 5 | // 空间复杂度:O(n) 6 | 7 | class Solution { 8 | public int[] sumZero(int n) { 9 | int[] res = new int[n]; 10 | int left = 0, right = n - 1; 11 | int rnum = n / 2, lnum = -rnum; 12 | while (left <= right) { 13 | res[left++] = lnum++; 14 | res[right--] = rnum--; 15 | } 16 | 17 | return res; 18 | } 19 | } -------------------------------------------------------------------------------- /1309. Decrypt String from Alphabet to Integer Mapping.java: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/decrypt-string-from-alphabet-to-integer-mapping/ 2 | 3 | 思路:常规扫描遍历,分类讨论(分两类) 4 | 时间复杂度:O(n) 5 | 空间复杂度:O(n) 6 | 7 | class Solution { 8 | public String freqAlphabets(String s) { 9 | StringBuilder sb = new StringBuilder(); 10 | int i = 0, len = s.length(); 11 | while (i < len) { 12 | if (i + 2 < len && s.charAt(i + 2) == '#') { 13 | int num = Integer.valueOf(s.substring(i, i + 2)) - 1; 14 | char c = (char) ('a' + num); 15 | sb.append(c); 16 | i += 3; 17 | } else { 18 | char c = (char) ('a' + s.charAt(i) - '1'); 19 | sb.append(c); 20 | i++; 21 | } 22 | } 23 | 24 | return sb.toString(); 25 | } 26 | } -------------------------------------------------------------------------------- /1310. XOR Queries of a Subarray.java: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/xor-queries-of-a-subarray/ 2 | 3 | 思路:Bit Manipulation,类似prefix sum 4 | 由于数字num ^ num结果为0,因此[i:j]的结果=[0:j]的结果^[0:i]的结果。 5 | 时间复杂度:O(n+m), n=arr.length, m=queries.length 6 | 空间复杂度:O(n+m), n=arr.length, m=queries.length 7 | 8 | class Solution { 9 | public int[] xorQueries(int[] arr, int[][] queries) { 10 | int[] res = new int[queries.length]; 11 | int[] xor = new int[arr.length + 1]; 12 | for (int i = 1; i <= arr.length; i++) { 13 | xor[i] = xor[i - 1] ^ arr[i - 1]; 14 | } 15 | for (int i = 0; i < queries.length; i++) { 16 | int left = queries[i][0], right = queries[i][1] + 1; 17 | res[i] = xor[left] ^ xor[right]; 18 | } 19 | 20 | return res; 21 | } 22 | } -------------------------------------------------------------------------------- /1313. Decompress Run-Length Encoded List.java: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/decompress-run-length-encoded-list/ 2 | 3 | 思路:按题意直接求 4 | 时间复杂度:O(sum(count)) 5 | 空间复杂度:O(sum(count)) 6 | 7 | class Solution { 8 | public int[] decompressRLElist(int[] nums) { 9 | int len = nums.length; 10 | List list = new ArrayList<>(); 11 | for (int i = 0; 2 * i + 1< len; i++) { 12 | int count = nums[2 * i], value = nums[2 * i + 1]; 13 | for (int j = 0; j < count; j++) { 14 | list.add(value); 15 | } 16 | } 17 | 18 | int[] res = new int[list.size()]; 19 | for (int i = 0; i < res.length; i++) { 20 | res[i] = list.get(i); 21 | } 22 | return res; 23 | } 24 | } -------------------------------------------------------------------------------- /1317. Convert Integer to the Sum of Two No-Zero Integers.java: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/convert-integer-to-the-sum-of-two-no-zero-integers/ 2 | 3 | 思路:转成String,检查是否含有'0' 4 | 时间复杂度:O(n log n), considering String construction and char search 5 | 空间复杂度:O(log n) 6 | 7 | class Solution { 8 | public int[] getNoZeroIntegers(int n) { 9 | for (int i = 1; i < n; i++) { 10 | int j = n - i; 11 | String s1 = String.valueOf(i), s2 = String.valueOf(j); 12 | if (s1.indexOf('0') >= 0 || s2.indexOf('0') >= 0) continue; 13 | 14 | return new int[]{i, j}; 15 | } 16 | 17 | return new int[2]; 18 | } 19 | } -------------------------------------------------------------------------------- /1318. Minimum Flips to Make a OR b Equal to c.java: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/minimum-flips-to-make-a-or-b-equal-to-c/ 2 | 3 | 思路:Bit Manipulation 4 | 只有当a和b的某个位置的bit和c对应位置的bit不相同时,才需要flip。有两种情况: 5 | 1)c的bit为1,而a和b的bit进行或运算结果为0,那么只要flip 1个bit即可。 6 | 2)c的bit为0,而a和b的bit进行或运算结果为1,那么需要flip的bit的个数等于a和b中1 bit的个数。 7 | 每次搜索完,将a,b和c右移一位。 8 | 时间复杂度:O(32) = O(1) 9 | 空间复杂度:O(1) 10 | 11 | class Solution { 12 | public int minFlips(int a, int b, int c) { 13 | int count = 0; 14 | while ((a | b) != c) { 15 | int alast = a & 1, blast = b & 1, clast = c & 1; 16 | if ((alast | blast) != clast) { 17 | count += clast == 1 ? 1 : alast + blast; 18 | } 19 | a = a >> 1; 20 | b = b >> 1; 21 | c = c >> 1; 22 | } 23 | 24 | return count; 25 | } 26 | } -------------------------------------------------------------------------------- /1331. Rank Transform of an Array.java: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/rank-transform-of-an-array/ 2 | 3 | 思路:HashMap + sort 4 | 时间复杂度:O(n log n) 5 | 空间复杂度:O(n) 6 | 7 | class Solution { 8 | public int[] arrayRankTransform(int[] arr) { 9 | int len = arr.length; 10 | int[] res = new int[len], copy = new int[len]; 11 | System.arraycopy(arr, 0, copy, 0, len); 12 | Arrays.sort(copy); 13 | Map map = new HashMap<>(); 14 | int rank = 1; 15 | for (int num : copy) { 16 | if (!map.containsKey(num)) { 17 | map.put(num, rank++); 18 | } 19 | } 20 | 21 | for (int i = 0; i < len; i++) { 22 | res[i] = map.get(arr[i]); 23 | } 24 | return res; 25 | } 26 | } -------------------------------------------------------------------------------- /134. Gas Station.java: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/gas-station/ 2 | 3 | 思路:Greedy 4 | 5 | 犯错点:1.当tank<0时,重新确定start后,tank要重置为0 6 | 2.最后判断是否有解要用sumGas和sumCost而不是tank 7 | 8 | class Solution { 9 | public int canCompleteCircuit(int[] gas, int[] cost) { 10 | int start = 0, tank = 0, sumCost = 0, sumGas = 0; 11 | for (int i = 0; i < gas.length; i++) { 12 | sumGas += gas[i]; 13 | sumCost += cost[i]; 14 | tank += gas[i] - cost[i]; 15 | if (tank < 0) { // fuel is not enough for [start:i] 16 | start = (i + 1) % gas.length; // set a new start 17 | tank = 0; // {Mistake 1} {Correction 1: reset tank for the next search} 18 | } 19 | } 20 | //return tank < 0 ? -1 : start; // {Mistake 2} 21 | return sumGas - sumCost < 0 ? -1 : start; // {Correction 2} 22 | } 23 | } -------------------------------------------------------------------------------- /1342. Number of Steps to Reduce a Number to Zero.java: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/number-of-steps-to-reduce-a-number-to-zero/ 2 | 3 | idea: Simulation + Bit Manipulation 4 | time complexity: O(log n) 5 | space complexity: O(1) 6 | 7 | class Solution { 8 | public int numberOfSteps (int num) { 9 | int count = 0; 10 | while (num > 0) { 11 | if ((num & 1) > 0) { 12 | num -= 1; 13 | } else { 14 | num >>= 1; 15 | 16 | } 17 | count++; 18 | } 19 | 20 | return count; 21 | } 22 | } -------------------------------------------------------------------------------- /1344. Angle Between Hands of a Clock.java: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/angle-between-hands-of-a-clock/ 2 | 3 | idea: Math 4 | time complexity: O(1) 5 | space complexity: O(1) 6 | 7 | class Solution { 8 | final double HOUR_PIECE = 30.0; 9 | 10 | public double angleClock(int hour, int minutes) { 11 | double portion = minutes / 60.0; 12 | double mDegree = portion * 360.0; 13 | double hDegree = (hour % 12) * HOUR_PIECE + portion * HOUR_PIECE; 14 | 15 | double d1 = Math.min(mDegree, hDegree), d2 = Math.max(mDegree, hDegree); 16 | 17 | return Math.min(d2 - d1, d1 + 360.0 - d2); 18 | } 19 | } -------------------------------------------------------------------------------- /136. Single Number.java: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/single-number/ 2 | 3 | // 经典的Bit Manipulation题,用到的是XOR。也可以用Hash Table。 4 | 5 | class Solution { 6 | public int singleNumber(int[] nums) { 7 | int res = 0; 8 | for (int n: nums) { 9 | res = res ^ n; 10 | } 11 | return res; 12 | } 13 | } -------------------------------------------------------------------------------- /1360. Number of Days Between Two Dates.java: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/number-of-days-between-two-dates/ 2 | 3 | import java.time.LocalDate; 4 | import java.time.temporal.ChronoUnit; 5 | 6 | class Solution { 7 | public int daysBetweenDates(String date1, String date2) { 8 | return Math.abs((int)ChronoUnit.DAYS.between(LocalDate.parse(date1), LocalDate.parse(date2))); 9 | } 10 | } -------------------------------------------------------------------------------- /1374. Generate a String With Characters That Have Odd Counts.java: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/generate-a-string-with-characters-that-have-odd-counts/ 2 | 3 | idea: String Simulation 4 | 5 | class Solution { 6 | public String generateTheString(int n) { 7 | int k = ((n & 1) == 0) ? n - 1 : n; 8 | StringBuilder sb = new StringBuilder(); 9 | for (int i = 0; i < k; i++) { 10 | sb.append('a'); 11 | } 12 | 13 | if (k == n - 1) { 14 | sb.append('b'); 15 | } 16 | 17 | return sb.toString(); 18 | } 19 | } -------------------------------------------------------------------------------- /1375. Bulb Switcher III.java: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/bulb-switcher-iii/ 2 | 3 | idea: Find the running max where max equals its index. 4 | time complexity: O(n) 5 | space complexity: O(1) 6 | 7 | class Solution { 8 | public int numTimesAllBlue(int[] light) { 9 | int res = 0, max = 0; 10 | for (int i = 0; i < light.length; i++) { 11 | max = Math.max(max, light[i]); 12 | if (max == i + 1) { 13 | res++; 14 | } 15 | } 16 | return res; 17 | } 18 | } -------------------------------------------------------------------------------- /1403. Minimum Subsequence in Non-Increasing Order.java: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/minimum-subsequence-in-non-increasing-order/ 2 | 3 | idea: Sort 4 | time complexity: O(n log n) 5 | space complexity: O(n) 6 | 7 | class Solution { 8 | public List minSubsequence(int[] nums) { 9 | int sum = 0, curr = 0, n = nums.length; 10 | Arrays.sort(nums); 11 | for (int num : nums) { 12 | sum += num; 13 | } 14 | List res = new ArrayList<>(); 15 | for (int i = n - 1; i >= 0 && curr <= sum / 2; i--) { 16 | curr += nums[i]; 17 | res.add(nums[i]); 18 | } 19 | 20 | return res; 21 | } 22 | } -------------------------------------------------------------------------------- /1404. Number of Steps to Reduce a Number in Binary Representation to One.java: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/number-of-steps-to-reduce-a-number-in-binary-representation-to-one/ 2 | 3 | idea: Simulation 4 | time complexity: O(n) 5 | space complexity: O(1) 6 | 7 | class Solution { 8 | public int numSteps(String s) { 9 | int ret = 0, n = s.length(), carry = 0; 10 | for (int i = n - 1; i >= 1; i--) { 11 | ret++; 12 | 13 | if (s.charAt(i) - '0' + carry == 1) { 14 | ret++; 15 | carry = 1; 16 | } 17 | } 18 | 19 | return ret + carry; 20 | } 21 | } -------------------------------------------------------------------------------- /1408. String Matching in an Array.java: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/string-matching-in-an-array/ 2 | 3 | idea: Brute force 4 | time complexity: O(n^2 * s) 5 | space complexity: O(1) 6 | 7 | class Solution { 8 | public List stringMatching(String[] words) { 9 | List ret = new ArrayList<>(); 10 | int n = words.length; 11 | for (int i = 0; i < n; i++) { 12 | for (int j = 0; j < n; j++) { 13 | if (i != j && words[j].indexOf(words[i]) >= 0) { 14 | ret.add(words[i]); 15 | break; 16 | } 17 | } 18 | } 19 | 20 | return ret; 21 | } 22 | } -------------------------------------------------------------------------------- /1409. Queries on a Permutation With Key.java: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/queries-on-a-permutation-with-key/ 2 | 3 | idea: Brute force 4 | time complexity: O(n*m) 5 | space complexity: O(m) 6 | 7 | class Solution { 8 | public int[] processQueries(int[] queries, int m) { 9 | int n = queries.length; 10 | int[] res = new int[n]; 11 | List list = new ArrayList<>(); 12 | for (int i = 0; i < m; i++) { 13 | list.add(i + 1); 14 | } 15 | 16 | for (int i = 0; i < n; i++) { 17 | int index = list.indexOf(queries[i]); 18 | int num = list.get(index); 19 | list.remove(index); 20 | list.add(0, num); 21 | res[i] = index; 22 | } 23 | 24 | return res; 25 | } 26 | } -------------------------------------------------------------------------------- /141. Linked List Cycle.java: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/linked-list-cycle/ 2 | 3 | // 经典的快慢指针题。注意:虽然两个指针都初始化为head,但实际上是先走了一步再进行if判断。可对比287. Find the Duplicate Number的快慢指针。 4 | 5 | /** 6 | * Definition for singly-linked list. 7 | * class ListNode { 8 | * int val; 9 | * ListNode next; 10 | * ListNode(int x) { 11 | * val = x; 12 | * next = null; 13 | * } 14 | * } 15 | */ 16 | public class Solution { 17 | public boolean hasCycle(ListNode head) { 18 | ListNode fast = head, slow = head; 19 | while (fast != null && fast.next != null) { 20 | fast = fast.next.next; 21 | slow = slow.next; 22 | if (slow == fast) return true; 23 | } 24 | return false; 25 | } 26 | } -------------------------------------------------------------------------------- /1413. Minimum Value to Get Positive Step by Step Sum.java: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/minimum-value-to-get-positive-step-by-step-sum/ 2 | 3 | idea: Prefix Sum 4 | time complexity: O(n) 5 | space complexity: O(1) 6 | 7 | class Solution { 8 | public int minStartValue(int[] nums) { 9 | int sum = 0, minSum = Integer.MAX_VALUE; 10 | for (int num : nums) { 11 | sum += num; 12 | minSum = Math.min(minSum, sum); 13 | } 14 | 15 | return Math.max(1 - minSum, 1); 16 | } 17 | } -------------------------------------------------------------------------------- /1422. Maximum Score After Splitting a String.java: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/maximum-score-after-splitting-a-string/ 2 | 3 | idea: Prefix Sum 4 | time complexity: O(n) 5 | space complexity: O(n) 6 | 7 | class Solution { 8 | public int maxScore(String s) { 9 | int n = s.length(); 10 | int[] zeroCount = new int[n + 1], oneCount = new int[n + 1]; 11 | for (int i = 1; i <= n; i++) { 12 | char c = s.charAt(i - 1); 13 | oneCount[i] = oneCount[i - 1] + (c == '1' ? 1 : 0); 14 | zeroCount[i] = zeroCount[i - 1] + (c == '0' ? 1 : 0); 15 | } 16 | 17 | int maxScore = 0; 18 | for (int i = 1; i < n; i++) { 19 | int score = zeroCount[i] + (oneCount[n] - oneCount[i]); 20 | maxScore = Math.max(maxScore, score); 21 | } 22 | 23 | return maxScore; 24 | } 25 | } -------------------------------------------------------------------------------- /1426. Counting Elements.java: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/counting-elements/ 2 | 3 | idea: HashSet 4 | time complexity: O(n) 5 | space complexity: O(n) 6 | 7 | class Solution { 8 | public int countElements(int[] arr) { 9 | Set set = new HashSet<>(); 10 | for (int num : arr) { 11 | set.add(num); 12 | } 13 | 14 | int count = 0; 15 | for (int num : arr) { 16 | if (set.contains(num + 1)) { 17 | count++; 18 | } 19 | } 20 | 21 | return count; 22 | } 23 | } -------------------------------------------------------------------------------- /1427. Perform String Shifts.java: -------------------------------------------------------------------------------- 1 | 2 | https://leetcode.com/problems/perform-string-shifts/ 3 | 4 | idea: Math 5 | time complexity: O(n+s), n=shift.length, s=s.length() 6 | space complexity: O(s) 7 | 8 | class Solution { 9 | public String stringShift(String s, int[][] shift) { 10 | int total = 0; // total num of left shift 11 | for (int[] op : shift) { 12 | total += (op[0] == 0 ? op[1] : -op[1]); 13 | } 14 | 15 | total %= s.length(); // avoid out of range 16 | if (total < 0) { 17 | total = s.length() + total; 18 | } 19 | 20 | return s.substring(total) + s.substring(0, total); 21 | } 22 | } -------------------------------------------------------------------------------- /1430. Check If a String Is a Valid Sequence from Root to Leaves Path in a Binary Tree.java: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/check-if-a-string-is-a-valid-sequence-from-root-to-leaves-path-in-a-binary-tree/ 2 | 3 | idea: DFS 4 | time complexity: O(n) 5 | space complexity: O(h) 6 | 7 | class Solution { 8 | private boolean dfs(TreeNode node, int[] arr, int idx) { 9 | int n = arr.length; 10 | if (node == null || idx == n || node.val != arr[idx]) { 11 | return false; 12 | } 13 | if (node.left == null && node.right == null) { 14 | return idx == n - 1; 15 | } 16 | 17 | return dfs(node.left, arr, idx + 1) || dfs(node.right, arr, idx + 1); 18 | } 19 | 20 | public boolean isValidSequence(TreeNode root, int[] arr) { 21 | return dfs(root, arr, 0); 22 | } 23 | } -------------------------------------------------------------------------------- /1431. Kids With the Greatest Number of Candies.java: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/kids-with-the-greatest-number-of-candies/ 2 | 3 | idea: Brute Force 4 | time complexity: O(n) 5 | space complexity: O(n) 6 | 7 | class Solution { 8 | public List kidsWithCandies(int[] candies, int extraCandies) { 9 | int max = 0; 10 | for (int num : candies) { 11 | max = Math.max(max, num); 12 | } 13 | 14 | List res = new ArrayList<>(); 15 | for (int num : candies) { 16 | res.add(num + extraCandies >= max); 17 | } 18 | 19 | return res; 20 | } 21 | } -------------------------------------------------------------------------------- /1433. Check If a String Can Break Another String.java: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/check-if-a-string-can-break-another-string/ 2 | 3 | idea: Greedy + Sort 4 | time complexity: O(n log n) 5 | space complexity: O(n) 6 | 7 | class Solution { 8 | private boolean check(char[] arr1, char[] arr2) { 9 | int n = arr1.length; 10 | for (int i = 0; i < n; i++) { 11 | if (arr1[i] > arr2[i]) return false; 12 | } 13 | 14 | return true; 15 | } 16 | 17 | public boolean checkIfCanBreak(String s1, String s2) { 18 | char[] arr1 = s1.toCharArray(); 19 | char[] arr2 = s2.toCharArray(); 20 | Arrays.sort(arr1); 21 | Arrays.sort(arr2); 22 | 23 | return check(arr1, arr2) || check(arr2, arr1); 24 | } 25 | } -------------------------------------------------------------------------------- /1436. Destination City.java: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/destination-city/ 2 | 3 | idea: HashMap 4 | Record outdegrees, and find the one with outdegree 0. 5 | time complexity: O(n) 6 | space complexity: O(n) 7 | 8 | class Solution { 9 | public String destCity(List> paths) { 10 | Map outdegree = new HashMap<>(); 11 | for (List edge : paths) { 12 | String from = edge.get(0), to = edge.get(1); 13 | outdegree.put(from, outdegree.getOrDefault(from, 0) + 1); 14 | outdegree.putIfAbsent(to, 0); 15 | } 16 | 17 | for (String key : outdegree.keySet()) { 18 | if (outdegree.get(key) == 0) { 19 | return key; 20 | } 21 | } 22 | 23 | return ""; 24 | } 25 | } -------------------------------------------------------------------------------- /1437. Check If All 1's Are at Least Length K Places Away.java: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/check-if-all-1s-are-at-least-length-k-places-away/ 2 | 3 | idea: Use a variable to record the nearest 1 to the left 4 | time complexity: O(n) 5 | space complexity: O(1) 6 | 7 | class Solution { 8 | public boolean kLengthApart(int[] nums, int k) { 9 | int preIdx = -1; 10 | for (int i = 0; i < nums.length; i++) { 11 | if (nums[i] == 0) continue; 12 | 13 | if (preIdx != -1 && i - preIdx <= k) { 14 | return false; 15 | } 16 | 17 | preIdx = i; 18 | } 19 | 20 | return true; 21 | } 22 | } -------------------------------------------------------------------------------- /1441. Build an Array With Stack Operations.java: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/build-an-array-with-stack-operations/ 2 | 3 | idea: Stack Simulation 4 | Add "Push" for elements that are kept in target array, and add both 5 | "Push" and "Pop" for those discarded. 6 | time complexity: O(n) 7 | space complexity: O(n) 8 | 9 | class Solution { 10 | public List buildArray(int[] target, int n) { 11 | List res = new ArrayList<>(); 12 | int curr = 1; 13 | for (int num : target) { 14 | while (curr != num) { 15 | res.add("Push"); 16 | res.add("Pop"); 17 | curr++; 18 | } 19 | 20 | res.add("Push"); 21 | curr++; 22 | } 23 | 24 | return res; 25 | } 26 | } -------------------------------------------------------------------------------- /1446. Consecutive Characters.java: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/consecutive-characters/ 2 | 3 | idea: Use variables to hold the previous char as well as its consecutive length. 4 | time complexity: O(n) 5 | space complexity: O(1) 6 | 7 | class Solution { 8 | public int maxPower(String s) { 9 | int maxLen = 0, currLen = 0; 10 | char pre = '.'; 11 | for (char c : s.toCharArray()) { 12 | if (c != pre) { 13 | currLen = 1; 14 | pre = c; 15 | } else { 16 | currLen++; 17 | } 18 | 19 | maxLen = Math.max(maxLen, currLen); 20 | } 21 | 22 | return maxLen; 23 | } 24 | } -------------------------------------------------------------------------------- /1447. Simplified Fractions.java: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/simplified-fractions/ 2 | 3 | idea: Math (GCD template) 4 | time complexity: O(n^2 * log n) 5 | space complexity: O(n^2) (or O(log n) or GCD recursion) 6 | 7 | class Solution { 8 | private int gcd(int a, int b) { 9 | if (b == 0) { 10 | return a; 11 | } 12 | 13 | return gcd(b, a % b); 14 | } 15 | 16 | public List simplifiedFractions(int n) { 17 | List res = new ArrayList<>(); 18 | 19 | for (int i = 2; i <= n; i++) { 20 | for (int j = 1; j < i; j++) { 21 | if (gcd(i, j) == 1) { 22 | res.add(j + "/" + i); 23 | } 24 | } 25 | 26 | } 27 | 28 | 29 | return res; 30 | } 31 | } -------------------------------------------------------------------------------- /1448. Count Good Nodes in Binary Tree.java: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/count-good-nodes-in-binary-tree/ 2 | 3 | idea: DFS (postorder traversal) 4 | time complexity: O(n) 5 | space complexity: O(n) 6 | 7 | class Solution { 8 | private int dfs(TreeNode node, int preMax) { 9 | if (node == null) { 10 | return 0; 11 | } 12 | 13 | int currMax = Math.max(node.val, preMax); 14 | int left = dfs(node.left, currMax); 15 | int right = dfs(node.right, currMax); 16 | 17 | return left + right + (currMax <= node.val ? 1 : 0); 18 | } 19 | 20 | public int goodNodes(TreeNode root) { 21 | return dfs(root, Integer.MIN_VALUE); 22 | } 23 | } -------------------------------------------------------------------------------- /1450. Number of Students Doing Homework at a Given Time.java: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/number-of-students-doing-homework-at-a-given-time/ 2 | 3 | idea: Brute Force 4 | time complexity: O(n) 5 | space complexity: O(1) 6 | 7 | class Solution { 8 | public int busyStudent(int[] startTime, int[] endTime, int queryTime) { 9 | int n = startTime.length; 10 | int count = 0; 11 | for (int i = 0; i < n; i++) { 12 | if (startTime[i] <= queryTime && endTime[i] >= queryTime) { 13 | count++; 14 | } 15 | } 16 | return count; 17 | } 18 | } -------------------------------------------------------------------------------- /1455. Check If a Word Occurs As a Prefix of Any Word in a Sentence.java: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/check-if-a-word-occurs-as-a-prefix-of-any-word-in-a-sentence/ 2 | 3 | time complexity: O(n * l), n=sentence.length, l=split[i].length 4 | space complexity: O(n * l) 5 | 6 | class Solution { 7 | public int isPrefixOfWord(String sentence, String searchWord) { 8 | String[] split = sentence.split("\\s+"); 9 | for (int i = 0; i < split.length; i++) { 10 | if (split[i].startsWith(searchWord)) { 11 | return i + 1; 12 | } 13 | } 14 | return -1; 15 | } 16 | } -------------------------------------------------------------------------------- /1460. Make Two Arrays Equal by Reversing Sub-arrays.java: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/make-two-arrays-equal-by-reversing-sub-arrays/ 2 | 3 | idea: Sort 4 | -Transform the question to whether two arrays are containing the same elements. 5 | time complexity: O(n log n) 6 | space complexity: O(n) for sorting 7 | 8 | class Solution { 9 | public boolean canBeEqual(int[] target, int[] arr) { 10 | Arrays.sort(target); 11 | Arrays.sort(arr); 12 | return Arrays.equals(target, arr); 13 | } 14 | } -------------------------------------------------------------------------------- /1461. Check If a String Contains All Binary Codes of Size K.java: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/check-if-a-string-contains-all-binary-codes-of-size-k/ 2 | 3 | idea: HashSet 4 | -Record all substring with length k, and finally check if the size of HashSet is 2^k 5 | time complexity: O(n*k) 6 | space complexity: O(n*k) 7 | optimization: Bit Manipulation 8 | 9 | class Solution { 10 | public boolean hasAllCodes(String s, int k) { 11 | Set set = new HashSet<>(); 12 | for (int i = 0; i + k <= s.length(); i++) { 13 | set.add(s.substring(i, i + k)); 14 | } 15 | 16 | return set.size() == (1 << k); 17 | } 18 | } -------------------------------------------------------------------------------- /1464. Maximum Product of Two Elements in an Array.java: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/maximum-product-of-two-elements-in-an-array/ 2 | 3 | idea: Sort 4 | time complexity: O(n log n) 5 | space complexity: O(n) 6 | 7 | class Solution { 8 | public int maxProduct(int[] nums) { 9 | int n = nums.length; 10 | Arrays.sort(nums); 11 | return (nums[n - 1] - 1) * (nums[n - 2] - 1); 12 | } 13 | } -------------------------------------------------------------------------------- /1469. Find All The Lonely Nodes.java: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/find-all-the-lonely-nodes/ 2 | 3 | idea: DFS 4 | time complexity: O(n) 5 | space complexity: O(h) 6 | 7 | class Solution { 8 | private void dfs(TreeNode node, List ret) { 9 | if (node == null) return; 10 | 11 | if (node.left != null && node.right != null) { 12 | dfs(node.left, ret); 13 | dfs(node.right, ret); 14 | } else if (node.left != null) { 15 | ret.add(node.left.val); 16 | dfs(node.left, ret); 17 | } else if (node.right != null) { 18 | ret.add(node.right.val); 19 | dfs(node.right, ret); 20 | } 21 | } 22 | 23 | public List getLonelyNodes(TreeNode root) { 24 | List ret = new ArrayList<>(); 25 | dfs(root, ret); 26 | return ret; 27 | } 28 | } -------------------------------------------------------------------------------- /1470. Shuffle the Array.java: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/shuffle-the-array/ 2 | 3 | solution1: 1-pass 4 | time complexity: O(n) 5 | space complexity: O(n) 6 | 7 | class Solution { 8 | public int[] shuffle(int[] nums, int n) { 9 | int[] ret = new int[2 * n]; 10 | for (int i = 0; i < 2 * n; i++) { 11 | ret[i] = i % 2 == 0 ? nums[i / 2] : nums[i / 2 + n]; 12 | } 13 | 14 | return ret; 15 | } 16 | } 17 | 18 | 19 | solution2: 2-pass Bit manipulaion -------------------------------------------------------------------------------- /1474. Delete N Nodes After M Nodes of a Linked List.java: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/delete-n-nodes-after-m-nodes-of-a-linked-list/ 2 | 3 | idea: Two pointers 4 | time complexity: in-place O(n) 5 | space complexity: O(1) 6 | 7 | class Solution { 8 | public ListNode deleteNodes(ListNode head, int m, int n) { 9 | ListNode dummy = new ListNode(0), pre = dummy, curr = head; 10 | dummy.next = head; 11 | while (curr != null) { 12 | for (int i = 0; i < m && curr != null; i++) { 13 | pre = curr; 14 | curr = curr.next; 15 | } 16 | 17 | for (int j = 0; j < n && curr != null; j++) { 18 | curr = curr.next; 19 | } 20 | 21 | pre.next = curr; 22 | } 23 | return dummy.next; 24 | } 25 | } -------------------------------------------------------------------------------- /1475. Final Prices With a Special Discount in a Shop.java: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/final-prices-with-a-special-discount-in-a-shop/ 2 | 3 | idea: Stack (monotonic queue) 4 | time complexity: O(n) 5 | space complexity: O(n) 6 | 7 | class Solution { 8 | public int[] finalPrices(int[] prices) { 9 | int n = prices.length; 10 | int[] ret = new int[n]; 11 | Stack stack = new Stack<>(); 12 | for (int i = n - 1; i >= 0; i--) { 13 | while (!stack.isEmpty() && prices[stack.peek()] > prices[i]) { 14 | stack.pop(); 15 | } 16 | ret[i] = prices[i] - (stack.isEmpty() ? 0 : prices[stack.peek()]); 17 | stack.push(i); 18 | } 19 | 20 | return ret; 21 | } 22 | } -------------------------------------------------------------------------------- /1480. Running Sum of 1d Array.java: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/running-sum-of-1d-array/ 2 | 3 | idea: Just prefix sum 4 | time complexity: O(n) 5 | space complexity: O(1) 6 | 7 | class Solution { 8 | public int[] runningSum(int[] nums) { 9 | int n = nums.length; 10 | int[] res = new int[n]; 11 | res[0] = nums[0]; 12 | for (int i = 1; i < nums.length; i++) { 13 | res[i] = nums[i] + res[i - 1]; 14 | } 15 | 16 | return res; 17 | } 18 | } -------------------------------------------------------------------------------- /1485. Clone Binary Tree With Random Pointer.java: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/GarhomLee/LeetCode/d69323b73a1bc7cb19ea955964f90ae29e86fdd6/1485. Clone Binary Tree With Random Pointer.java -------------------------------------------------------------------------------- /1486. XOR Operation in an Array.java: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/xor-operation-in-an-array/ 2 | 3 | idea: Simulation + Bit Manipulation 4 | time complexity: O(n) 5 | space complexity: O(1) 6 | 7 | class Solution { 8 | public int xorOperation(int n, int start) { 9 | int res = 0; 10 | for (int i = 0; i < n; i++) { 11 | res ^= start + 2 * i; 12 | } 13 | 14 | return res; 15 | } 16 | } -------------------------------------------------------------------------------- /1490. Clone N-ary Tree.java: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/clone-n-ary-tree/ 2 | 3 | idea: DFS 4 | time complexity: O(n) 5 | space complexity: O(n) 6 | 7 | class Solution { 8 | private Node dfs(Node node) { 9 | if (node == null) return null; 10 | 11 | Node copy = new Node(node.val); 12 | for (Node child : node.children) { 13 | copy.children.add(dfs(child)); 14 | } 15 | 16 | return copy; 17 | } 18 | 19 | public Node cloneTree(Node root) { 20 | return dfs(root); 21 | } 22 | } -------------------------------------------------------------------------------- /1491. Average Salary Excluding the Minimum and Maximum Salary.java: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/average-salary-excluding-the-minimum-and-maximum-salary/ 2 | 3 | idea: 1-pass iteration 4 | time complexity: O(n) 5 | space complexity: O(1) 6 | 7 | class Solution { 8 | public double average(int[] salary) { 9 | int max = 0, min = Integer.MAX_VALUE, sum = 0, n = salary.length; 10 | if (n < 3) return 0; 11 | 12 | for (int num : salary) { 13 | sum += num; 14 | max = Math.max(max, num); 15 | min = Math.min(min, num); 16 | } 17 | 18 | return (sum - max - min) / ((double) n - 2); 19 | } 20 | } -------------------------------------------------------------------------------- /1492. The kth Factor of n.java: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/the-kth-factor-of-n/ 2 | 3 | idea: Brute force 4 | time complexity: O(n) 5 | space complexity: O(n) 6 | 7 | class Solution { 8 | public int kthFactor(int n, int k) { 9 | List list = new ArrayList<>(); 10 | for (int i = 1; i<= n; i++) { 11 | if (n % i == 0) { 12 | list.add(i); 13 | } 14 | } 15 | 16 | return list.size() >= k ? list.get(k - 1) : -1; 17 | } 18 | } -------------------------------------------------------------------------------- /1497. Check If Array Pairs Are Divisible by k.java: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/check-if-array-pairs-are-divisible-by-k/ 2 | 3 | idea: Math 4 | time complexity: O(n + k) 5 | space complexity: O(k) 6 | 7 | class Solution { 8 | public boolean canArrange(int[] arr, int k) { 9 | int[] count = new int[k]; 10 | for (int num : arr) { 11 | num %= k; 12 | if (num < 0) { 13 | // transform the negative mod to a positive one 14 | num += k; 15 | } 16 | count[num]++; 17 | } 18 | 19 | if (count[0] % 2 != 0) { 20 | return false; 21 | } 22 | 23 | for (int i = 1; i < k; i++) { 24 | if (count[i] != count[k - i]) { 25 | return false; 26 | } 27 | } 28 | 29 | return true; 30 | } 31 | } -------------------------------------------------------------------------------- /1502. Can Make Arithmetic Progression From Sequence.java: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/can-make-arithmetic-progression-from-sequence/ 2 | 3 | idea: Sort 4 | time complexity: O(n log n) 5 | space complexity: O(n) 6 | 7 | class Solution { 8 | public boolean canMakeArithmeticProgression(int[] arr) { 9 | Arrays.sort(arr); 10 | int diff = arr[1] - arr[0]; 11 | for (int i = 1; i < arr.length; i++) { 12 | if (arr[i] - arr[i - 1] != diff) { 13 | return false; 14 | } 15 | } 16 | 17 | return true; 18 | } 19 | } -------------------------------------------------------------------------------- /1503. Last Moment Before All Ants Fall Out of a Plank.java: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/last-moment-before-all-ants-fall-out-of-a-plank/ 2 | 3 | idea: Math 4 | -Collision can actually be ignored. 5 | time complexity: O(n) 6 | space complexity: O(1) 7 | 8 | class Solution { 9 | public int getLastMoment(int n, int[] left, int[] right) { 10 | int res = 0; 11 | for (int i: left) 12 | res = Math.max(res, i); 13 | for (int i: right) 14 | res = Math.max(res, n - i); 15 | return res; 16 | } 17 | } -------------------------------------------------------------------------------- /1508. Range Sum of Sorted Subarray Sums.java: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/range-sum-of-sorted-subarray-sums/ 2 | 3 | idea: Sort 4 | time complexity: O(n^2 log(n^2)) 5 | space complexity: O(n^2) 6 | 7 | class Solution { 8 | final int MOD = 1_000_000_007; 9 | 10 | public int rangeSum(int[] nums, int n, int left, int right) { 11 | int[] sum = new int [n*(n+1)/2]; 12 | int k = 0; 13 | for (int i = 0; i < n; i++) { 14 | int curr = 0; 15 | for (int j = i; j >= 0; j--) { 16 | curr += nums[j]; 17 | sum[k++] = curr; 18 | } 19 | } 20 | 21 | Arrays.sort(sum); 22 | int ret = 0; 23 | for (int i = left - 1; i < right; i++) { 24 | ret += sum[i] % MOD; 25 | } 26 | return ret; 27 | } 28 | } -------------------------------------------------------------------------------- /1509. Minimum Difference Between Largest and Smallest Value in Three Moves.java: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/minimum-difference-between-largest-and-smallest-value-in-three-moves/ 2 | 3 | idea: Sort 4 | -The extreme values should be removed from the smallest end or/and largest end. 5 | time complexity: O(n log n) 6 | space complexity: O(n) 7 | 8 | class Solution { 9 | public int minDifference(int[] nums) { 10 | int n = nums.length; 11 | if (n <= 3) { 12 | return 0; 13 | } 14 | 15 | Arrays.sort(nums); 16 | int min = Integer.MAX_VALUE; 17 | for (int i = 0; i < 4; i++) { 18 | min = Math.min(min, nums[n - 4 + i] - nums[i]); 19 | } 20 | return min; 21 | } 22 | } -------------------------------------------------------------------------------- /1512. Number of Good Pairs.java: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/number-of-good-pairs/ 2 | 3 | idea: Count 4 | time complexity: O(n) 5 | space complexity: O(n) 6 | 7 | class Solution { 8 | public int numIdenticalPairs(int[] nums) { 9 | int[] count = new int[101]; 10 | int ret = 0; 11 | for (int num : nums) { 12 | ret += count[num]; 13 | count[num]++; 14 | } 15 | 16 | return ret; 17 | } 18 | } -------------------------------------------------------------------------------- /1513. Number of Substrings With Only 1s.java: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/number-of-substrings-with-only-1s/ 2 | 3 | idea: Count 4 | time complexity: O(n) 5 | space complexity: O(1) 6 | 7 | class Solution { 8 | final int MOD = 1_000_000_007; 9 | public int numSub(String s) { 10 | int ret = 0, curr = 0; 11 | for (char c : s.toCharArray()) { 12 | curr = c == '1' ? curr + 1 : 0; 13 | ret += curr; 14 | ret %= MOD; 15 | } 16 | 17 | return ret; 18 | } 19 | } -------------------------------------------------------------------------------- /1518. Water Bottles.java: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/water-bottles/ 2 | 3 | idea: Greedy 4 | time complexity: O(log n) 5 | space complexity: O(1) 6 | 7 | class Solution { 8 | public int numWaterBottles(int numBottles, int numExchange) { 9 | int full = numBottles, empty = 0, max = 0; 10 | while (full + empty >= numExchange) { 11 | max += full; 12 | int next = (full + empty) / numExchange; 13 | empty = (full + empty) - next * numExchange; 14 | full = next; 15 | } 16 | 17 | return max + full; 18 | } 19 | } -------------------------------------------------------------------------------- /1523. Count Odd Numbers in an Interval Range.java: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/count-odd-numbers-in-an-interval-range/ 2 | 3 | idea: Math 4 | time complexity: O(1) 5 | space complexity: O(1) 6 | 7 | class Solution { 8 | public int countOdds(int low, int high) { 9 | int ret = (high - low + 1) / 2; 10 | ret += low % 2 == 1 && high % 2 == 1 ? 1 : 0; 11 | return ret; 12 | } 13 | } -------------------------------------------------------------------------------- /1524. Number of Sub-arrays With Odd Sum.java: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/number-of-sub-arrays-with-odd-sum/ 2 | 3 | idea: Prefix Sum + Math 4 | -If current sum is even, only consider how many previous sums are odd; 5 | if current sum is odd, vice versa. 6 | time complexity: O(n) 7 | space complexity: O(1) 8 | 9 | class Solution { 10 | final int MOD = 1_000_000_007; 11 | 12 | public int numOfSubarrays(int[] arr) { 13 | int odd = 0, even = 1; 14 | int sum = 0, ret = 0; 15 | for (int num : arr) { 16 | sum += num; 17 | if (sum % 2 == 0) { 18 | ret += odd; 19 | even++; 20 | } else { 21 | ret += even; 22 | odd++; 23 | } 24 | ret %= MOD; 25 | } 26 | 27 | return ret; 28 | } 29 | } -------------------------------------------------------------------------------- /1526. Minimum Number of Increments on Subarrays to Form a Target Array.java: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/minimum-number-of-increments-on-subarrays-to-form-a-target-array/ 2 | 3 | idea: Segment Tree? Referring to: https://leetcode.com/problems/minimum-number-of-increments-on-subarrays-to-form-a-target-array/discuss/754674/JavaC%2B%2BPython-Comparison-of-Consecutive-Elements 4 | time complexity: O(n) 5 | space complexity: O(1) 6 | 7 | class Solution { 8 | public int minNumberOperations(int[] target) { 9 | int ret = 0, pre = 0; 10 | for (int num : target) { 11 | ret += Math.max(0, num - pre); 12 | pre = num; 13 | } 14 | 15 | return ret; 16 | } 17 | } -------------------------------------------------------------------------------- /1528. Shuffle String.java: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/shuffle-string/ 2 | 3 | idea: Brute Force 4 | time complexity: O(n) 5 | space complexity: O(n) 6 | 7 | class Solution { 8 | public String restoreString(String s, int[] indices) { 9 | int n = indices.length; 10 | char[] res = new char[n]; 11 | for (int i = 0; i < n; i++) { 12 | int idx = indices[i]; 13 | res[idx] = s.charAt(i); 14 | } 15 | 16 | return new String(res); 17 | } 18 | } -------------------------------------------------------------------------------- /1529. Bulb Switcher IV.java: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/bulb-switcher-iv/ 2 | 3 | idea: Greedy 4 | time complexity: O(n) 5 | space complexity: O(1) 6 | 7 | class Solution { 8 | public int minFlips(String target) { 9 | int n = target.length(), ret = 0; 10 | char prev = '0'; 11 | for (int i = 0; i < n; i++) { 12 | char curr = target.charAt(i); 13 | if (curr != prev) { 14 | ret++; 15 | } 16 | prev = curr; 17 | } 18 | 19 | return ret; 20 | } 21 | } -------------------------------------------------------------------------------- /1534. Count Good Triplets.java: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/count-good-triplets/ 2 | 3 | idea: Brute Force 4 | time complexity: O(n^3) 5 | space complexity: O(1) 6 | 7 | class Solution { 8 | public int countGoodTriplets(int[] arr, int a, int b, int c) { 9 | int n = arr.length, ret = 0; 10 | for (int i = 0; i + 2 < n; i++) { 11 | for (int j = i + 1; j + 1 < n; j++) { 12 | for (int k = j + 1; k < n; k++) { 13 | if (Math.abs(arr[i] - arr[j]) <= a 14 | && Math.abs(arr[j] - arr[k]) <= b 15 | && Math.abs(arr[i] - arr[k]) <= c) { 16 | ret++; 17 | } 18 | } 19 | } 20 | } 21 | 22 | return ret; 23 | } 24 | } -------------------------------------------------------------------------------- /1535. Find the Winner of an Array Game.java: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/find-the-winner-of-an-array-game/ 2 | 3 | idea: Simulation 4 | time complexity: O(n) 5 | space complexity: O(1) 6 | 7 | class Solution { 8 | public int getWinner(int[] arr, int k) { 9 | int n = arr.length; 10 | int max = arr[0], count = 0; 11 | for (int i = 1; i < n && count < k; i++) { 12 | if (max > arr[i]) { 13 | count++; 14 | } else if (max < arr[i]) { 15 | count = 1; 16 | max = arr[i]; 17 | } 18 | } 19 | 20 | return max; 21 | } 22 | } -------------------------------------------------------------------------------- /1544. Make The String Great.java: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/make-the-string-great/ 2 | 3 | idea: Stack 4 | time complexity: O(n) 5 | space complexity: O(n) 6 | 7 | class Solution { 8 | public String makeGood(String s) { 9 | Stack stack = new Stack<>(); 10 | for (char c : s.toCharArray()) { 11 | if (!stack.isEmpty() && Math.abs(stack.peek() - c) == 32) { 12 | stack.pop(); 13 | } else { 14 | stack.push(c); 15 | } 16 | 17 | } 18 | 19 | StringBuilder sb = new StringBuilder(); 20 | while (!stack.isEmpty()) { 21 | sb.insert(0, stack.pop()); 22 | } 23 | 24 | return sb.toString(); 25 | } 26 | } -------------------------------------------------------------------------------- /1545. Find Kth Bit in Nth Binary String.java: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/find-kth-bit-in-nth-binary-string/ 2 | 3 | idea: DFS 4 | time complexity: O(n) 5 | space complexity: O(n) 6 | 7 | class Solution { 8 | private int dfs(int n, int k) { 9 | if (n == 1) { 10 | return 0; 11 | } 12 | int mid = (1 << (n - 1)); 13 | if (k == mid) { 14 | return 1; 15 | } 16 | 17 | if (k > mid) { 18 | return 1 - dfs(n - 1, 2 * mid - k); 19 | } 20 | 21 | return dfs(n - 1, k); 22 | } 23 | 24 | 25 | public char findKthBit(int n, int k) { 26 | return (char) (dfs(n, k) + '0'); 27 | } 28 | } -------------------------------------------------------------------------------- /1550. Three Consecutive Odds.java: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/three-consecutive-odds/ 2 | 3 | idea: Brute Force (info cache) 4 | time complexity: O(n) 5 | space complexity: O(1) 6 | 7 | class Solution { 8 | public boolean threeConsecutiveOdds(int[] arr) { 9 | int count = 0; 10 | for (int num : arr) { 11 | int curr = num % 2; 12 | if (curr == 0) { 13 | count = 0; 14 | } else { 15 | count++; 16 | } 17 | 18 | if (count >= 3) { 19 | return true; 20 | } 21 | } 22 | 23 | return false; 24 | } 25 | } -------------------------------------------------------------------------------- /1551. Minimum Operations to Make Array Equal.java: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/minimum-operations-to-make-array-equal/ 2 | 3 | solution1: Simulation + Greedy 4 | time complexity: O(n) 5 | space complexity: O(1) 6 | 7 | class Solution { 8 | public int minOperations(int n) { 9 | int low = 1, high = 2 * (n - 1) + 1; 10 | int res = 0; 11 | while (low < high) { 12 | res += (high - low) / 2; 13 | low += 2; 14 | high -= 2; 15 | } 16 | 17 | return res; 18 | } 19 | } 20 | 21 | 22 | solution2: Math 23 | time complexity: O(1) 24 | space complexity: O(1) 25 | 26 | public int minOperations(int n) { 27 | int cnt = n / 2; 28 | return cnt * (cnt + n % 2); 29 | } -------------------------------------------------------------------------------- /1556. Thousand Separator.java: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/thousand-separator/ 2 | 3 | idea: Math 4 | time complexity: O(log n) 5 | space complexity: O(log n) 6 | 7 | class Solution { 8 | public String thousandSeparator(int n) { 9 | if (n == 0) { 10 | return "0"; 11 | } 12 | 13 | StringBuilder sb = new StringBuilder(); 14 | int count = 0; 15 | while (n != 0) { 16 | sb.insert(0, n % 10); 17 | n /= 10; 18 | count++; 19 | if (count % 3 == 0) { 20 | sb.insert(0, '.'); 21 | } 22 | } 23 | 24 | if (sb.charAt(0) == '.') { 25 | sb.deleteCharAt(0); 26 | } 27 | 28 | return sb.toString(); 29 | } 30 | } -------------------------------------------------------------------------------- /1557. Minimum Number of Vertices to Reach All Nodes.java: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/minimum-number-of-vertices-to-reach-all-nodes/ 2 | 3 | idea: Count indegree of each node, and the result is the ones with 0 indegree. 4 | time complexity: O(V + E) 5 | space complexity: O(V) 6 | 7 | class Solution { 8 | public List findSmallestSetOfVertices(int n, List> edges) { 9 | List res = new ArrayList<>(); 10 | 11 | int[] indegree = new int[n]; 12 | for (List edge : edges) { 13 | int from = edge.get(0), to = edge.get(1); 14 | indegree[to]++; 15 | } 16 | 17 | for (int i = 0; i < n; i++) { 18 | if (indegree[i] == 0) { 19 | res.add(i); 20 | } 21 | } 22 | 23 | return res; 24 | } 25 | } -------------------------------------------------------------------------------- /1561. Maximum Number of Coins You Can Get.java: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/maximum-number-of-coins-you-can-get/ 2 | 3 | idea: Greedy + Sort 4 | -Use greedy algo, so that the largest is for Alice, the second largest for myself, and the smallest 5 | for Bob which will be all 1/3 smallest elements after sorting. 6 | time complexity: O(n log n) 7 | space complexity: O(n) for sorting 8 | 9 | class Solution { 10 | public int maxCoins(int[] piles) { 11 | int n = piles.length, res = 0; 12 | Arrays.sort(piles); 13 | for (int count = 1, idx = n - 2; count <= n / 3; count++, idx -= 2) { 14 | res += piles[idx]; 15 | } 16 | 17 | return res; 18 | } 19 | } -------------------------------------------------------------------------------- /1564. Put Boxes Into the Warehouse I.java: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/put-boxes-into-the-warehouse-i/ 2 | 3 | idea: Sort + Greedy 4 | time complexity: O(m + n log n), m=warehouse.length, n=boxes.length 5 | space complexity: O(m + n) 6 | 7 | class Solution { 8 | public int maxBoxesInWarehouse(int[] boxes, int[] warehouse) { 9 | Stack stack = new Stack<>(); 10 | for (int height : warehouse) { 11 | int curr = stack.isEmpty() ? height : Math.min(height, stack.peek()); 12 | stack.push(curr); 13 | } 14 | 15 | Arrays.sort(boxes); 16 | int res = 0, n = boxes.length; 17 | for (int i = 0; i < n && !stack.isEmpty(); stack.pop()) { 18 | if (boxes[i] <= stack.peek()) { 19 | res++; 20 | i++; 21 | } 22 | } 23 | 24 | return res; 25 | } 26 | } -------------------------------------------------------------------------------- /1566. Detect Pattern of Length M Repeated K or More Times.java: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/detect-pattern-of-length-m-repeated-k-or-more-times/ 2 | 3 | idea: Brute Force 4 | time complexity: O(n*m) 5 | space complexity: O(1) 6 | 7 | class Solution { 8 | public boolean containsPattern(int[] arr, int m, int k) { 9 | int n = arr.length; 10 | for (int i = 0; i + k*m - 1 < n; i++) { 11 | boolean isMatch = true; 12 | for (int j = i; j < i + k*m; j++) { 13 | isMatch = isMatch && (arr[j] == arr[i + (j - i) % m]); 14 | } 15 | 16 | if (isMatch) { 17 | return true; 18 | } 19 | } 20 | 21 | return false; 22 | } 23 | } -------------------------------------------------------------------------------- /1570. Dot Product of Two Sparse Vectors.java: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/dot-product-of-two-sparse-vectors/ 2 | 3 | idea: HashMap 4 | 5 | class SparseVector { 6 | Map map; 7 | 8 | SparseVector(int[] nums) { 9 | map = new HashMap<>(); 10 | for (int i = 0; i < nums.length; i++) { 11 | if (nums[i] != 0) { 12 | map.put(i, nums[i]); 13 | } 14 | } 15 | } 16 | 17 | // Return the dotProduct of two sparse vectors 18 | public int dotProduct(SparseVector vec) { 19 | int ret = 0; 20 | for (int idx: map.keySet()) { 21 | ret += map.get(idx) * vec.map.getOrDefault(idx, 0); 22 | } 23 | return ret; 24 | } 25 | } -------------------------------------------------------------------------------- /1572. Matrix Diagonal Sum.java: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/matrix-diagonal-sum/ 2 | 3 | idea: Brute Force 4 | time complexity: O(n) 5 | space complexity: O(1) 6 | 7 | class Solution { 8 | public int diagonalSum(int[][] mat) { 9 | int n = mat.length; 10 | int sum = 0; 11 | for (int row = 0; row < n; row++) { 12 | int col1 = row, col2 = n - 1 - row; 13 | sum += mat[row][col1] + mat[row][col2]; 14 | if (col1 == col2) { 15 | sum -= mat[row][col1]; 16 | } 17 | } 18 | 19 | return sum; 20 | } 21 | } -------------------------------------------------------------------------------- /1588. Sum of All Odd Length Subarrays.java: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/sum-of-all-odd-length-subarrays/ 2 | 3 | idea: Prefix Sum 4 | time complexity: O(n^2) 5 | space complexity: O(n) 6 | 7 | class Solution { 8 | public int sumOddLengthSubarrays(int[] arr) { 9 | int n = arr.length; 10 | int[] sum = new int[n + 1]; 11 | for (int i = 1; i <= n; i++) { 12 | sum[i] = sum[i - 1] + arr[i - 1]; 13 | } 14 | 15 | int res = 0; 16 | for (int i = 1; i <= n; i++) { 17 | for (int j = i - 1; j >= 0; j -= 2) { 18 | res += sum[i] - sum[j]; 19 | } 20 | } 21 | 22 | return res; 23 | } 24 | } -------------------------------------------------------------------------------- /1614. Maximum Nesting Depth of the Parentheses.java: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/maximum-nesting-depth-of-the-parentheses/ 2 | 3 | idea: Count maximum left parentheses 4 | time complexity: O(n) 5 | space complexity: O(1) 6 | 7 | class Solution { 8 | public int maxDepth(String s) { 9 | int left = 0; 10 | int max = 0; 11 | for (char c : s.toCharArray()) { 12 | if (c == '(') { 13 | left++; 14 | } else if (c == ')') { 15 | left--; 16 | } 17 | max = Math.max(max, left); 18 | } 19 | 20 | return max; 21 | } 22 | } -------------------------------------------------------------------------------- /1619. Mean of Array After Removing Some Elements.java: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/mean-of-array-after-removing-some-elements/ 2 | 3 | idea: Sort 4 | time complexity: O(n log n) 5 | space complexity: O(n) for mergesort 6 | 7 | class Solution { 8 | public double trimMean(int[] arr) { 9 | Arrays.sort(arr); 10 | int n = arr.length, m = n / 20; 11 | double sum = 0.0; 12 | for (int i = m; i + m < n; i++) { 13 | sum += arr[i]; 14 | } 15 | 16 | return sum / (n - 2*m); 17 | } 18 | } -------------------------------------------------------------------------------- /162. Find Peak Element.java: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/find-peak-element/ 2 | 3 | // 总体思路:852. Peak Index in a Mountain Array的follow-up,同样可以用Binary Search模版。 4 | // 还是常规g(m),关键点在于理解题意。因为只需要找到其中一个peak,而且题目规定任意nums[i]!=nums[i+1], 5 | // 所以只要满足nums[mid] > nums[mid + 1]条件的mid都可以返回。 6 | 7 | class Solution { 8 | public int findPeakElement(int[] nums) { 9 | int low = 0, high = nums.length - 1; 10 | while (low <= high) { 11 | int mid = low + (high - low) / 2; 12 | if (mid < nums.length - 1 && nums[mid] > nums[mid + 1]) high = mid - 1; 13 | else low = mid + 1; 14 | } 15 | return low < nums.length ? low : nums.length - 1; 16 | } 17 | } -------------------------------------------------------------------------------- /1624. Largest Substring Between Two Equal Characters.java: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/largest-substring-between-two-equal-characters/ 2 | 3 | idea: Info Cache 4 | time complexity: O(n) 5 | space complexity: O(n) 6 | 7 | class Solution { 8 | public int maxLengthBetweenEqualCharacters(String s) { 9 | int[] indices = new int[26]; 10 | Arrays.fill(indices, -1); 11 | int res = -1; 12 | for (int i = 0; i < s.length(); i++) { 13 | char c = s.charAt(i); 14 | if (indices[c - 'a'] == -1) { 15 | indices[c - 'a'] = i; 16 | } else { 17 | res = Math.max(res, i - indices[c - 'a'] - 1); 18 | } 19 | } 20 | 21 | return res; 22 | } 23 | } -------------------------------------------------------------------------------- /1629. Slowest Key.java: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/slowest-key/ 2 | 3 | idea: Info Cache 4 | time complexity: O(n) 5 | space complexity: O(1) 6 | 7 | class Solution { 8 | public char slowestKey(int[] releaseTimes, String keysPressed) { 9 | int n = keysPressed.length(); 10 | int maxDuration = releaseTimes[0]; 11 | char maxKey = keysPressed.charAt(0); 12 | for (int i = 1; i < n; i++) { 13 | int duration = releaseTimes[i] - releaseTimes[i-1]; 14 | char curr = keysPressed.charAt(i); 15 | if (duration > maxDuration) { 16 | maxDuration = duration; 17 | maxKey = curr; 18 | } else if (duration == maxDuration && maxKey < curr) { 19 | maxKey = curr; 20 | } 21 | } 22 | 23 | return maxKey; 24 | } 25 | } -------------------------------------------------------------------------------- /1636. Sort Array by Increasing Frequency.java: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/sort-array-by-increasing-frequency/ 2 | 3 | idea: Sort (use stream function) 4 | time complexity: O(n log n) 5 | space complexity: O(n) for sorting 6 | 7 | class Solution { 8 | public int[] frequencySort(int[] nums) { 9 | Map map = new HashMap<>(); 10 | for (int num : nums) { 11 | map.put(num, map.getOrDefault(num, 0) + 1); 12 | } 13 | 14 | nums = Arrays.stream(nums). 15 | boxed(). 16 | sorted((a, b) -> map.get(a) == map.get(b) ? b - a : map.get(a) - map.get(b)). // customized sort 17 | mapToInt(i -> i). 18 | toArray(); 19 | return nums; 20 | } 21 | } -------------------------------------------------------------------------------- /1637. Widest Vertical Area Between Two Points Containing No Points.java: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/widest-vertical-area-between-two-points-containing-no-points/ 2 | 3 | idea: TreeSet 4 | time complexity: O(n log n) 5 | space complexity: O(n) 6 | 7 | class Solution { 8 | public int maxWidthOfVerticalArea(int[][] points) { 9 | TreeSet treeSet = new TreeSet<>(); 10 | for (int[] p : points) { 11 | treeSet.add(p[0]); 12 | } 13 | 14 | int prev = Integer.MAX_VALUE; 15 | int maxWidth = Integer.MIN_VALUE; 16 | for (int curr : treeSet) { 17 | maxWidth = Math.max(maxWidth, curr - prev); 18 | prev = curr; 19 | } 20 | 21 | return maxWidth; 22 | } 23 | } -------------------------------------------------------------------------------- /1641. Count Sorted Vowel Strings.java: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/count-sorted-vowel-strings/ 2 | 3 | idea: DP 4 | time complexity: O(n*5)=O(n) 5 | space complexity: O(5) 6 | 7 | class Solution { 8 | public int countVowelStrings(int n) { 9 | int[] dp = new int[5]; // dp[j] indicates, for given length i, the number of 10 | // non-decreasing string with the first char j={'a','e','i','o','u'} 11 | Arrays.fill(dp, 1); 12 | for (int i = 2; i <= n; i++) { 13 | for (int j = 3; j >= 0; j--) { 14 | dp[j] += dp[j+1]; 15 | } 16 | } 17 | return Arrays.stream(dp).sum(); 18 | } 19 | } -------------------------------------------------------------------------------- /1647. Minimum Deletions to Make Character Frequencies Unique.java: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/minimum-deletions-to-make-character-frequencies-unique/ 2 | 3 | idea: Sort + Greedy 4 | time complexity: O(n log n) 5 | space complexity: O(n) for sort 6 | 7 | class Solution { 8 | public int minDeletions(String s) { 9 | int[] count = new int[26]; 10 | for (char c : s.toCharArray()) { 11 | count[c - 'a']++; 12 | } 13 | 14 | int res = 0; 15 | Arrays.sort(count); 16 | 17 | // iterate from big to small count 18 | int curr = count[25] - 1; 19 | for (int i = 24; i >= 0; i--) { 20 | int diff = Math.max(count[i] - curr, 0); 21 | res += diff; 22 | count[i] -= diff; 23 | curr = Math.max(count[i] - 1, 0); 24 | } 25 | 26 | return res; 27 | } 28 | } -------------------------------------------------------------------------------- /165. Compare Version Numbers.java: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/compare-version-numbers/ 2 | 3 | // 总体思路:将字符以"."分隔,取其Integer的表示形式,然后比较。 4 | 5 | // 关键优化步骤:1)如果超出边界,根据题意,可以赋值为0,便于后续的比较 6 | // 2)将compareTo()的结果存在临时变量,简化代码 7 | 8 | class Solution { 9 | public int compareVersion(String version1, String version2) { 10 | String[] v1 = version1.split("\\."), v2 = version2.split("\\."); 11 | int i = 0, j = 0; 12 | while (i < v1.length || j < v2.length) { 13 | Integer num1 = i < v1.length ? Integer.valueOf(v1[i++]) : 0; 14 | Integer num2 = j < v2.length ? Integer.valueOf(v2[j++]) : 0; 15 | int compare = num1.compareTo(num2); 16 | if (compare != 0) return compare; 17 | } 18 | return 0; 19 | } 20 | } -------------------------------------------------------------------------------- /1652. Defuse the Bomb.java: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/defuse-the-bomb/ 2 | 3 | solution1: Brute Force 4 | time complexity: O(n*k) 5 | space complexity: O(1) 6 | 7 | class Solution { 8 | public int[] decrypt(int[] code, int k) { 9 | int n = code.length; 10 | int[] res = new int[n]; 11 | if (k == 0) { 12 | return res; 13 | } 14 | 15 | for (int i = 0; i < n; i++) { 16 | int sum = 0; 17 | for (int j = 1; j <= Math.abs(k); j++) { 18 | int idx = k < 0 ? (i + n - j) % n : (i + n + j) % n; 19 | sum += code[idx]; 20 | } 21 | res[i] = sum; 22 | } 23 | 24 | return res; 25 | } 26 | } 27 | 28 | solution2: Sliding Window 29 | time complexity: O(n) 30 | space complexity: O(1) -------------------------------------------------------------------------------- /1656. Design an Ordered Stream.java: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/design-an-ordered-stream/ 2 | 3 | idea: Record the start idx of the next chunk 4 | time complexity: O(n) 5 | space complexity: O(1) 6 | 7 | class OrderedStream { 8 | String[] arr; 9 | int n; 10 | int currIdx; 11 | 12 | public OrderedStream(int n) { 13 | this.arr = new String[n+1]; 14 | this.n = n; 15 | this.currIdx = 1; 16 | } 17 | 18 | public List insert(int id, String value) { 19 | this.arr[id] = value; 20 | List res = new ArrayList<>(); 21 | if (id == this.currIdx) { 22 | while (this.currIdx <= this.n && this.arr[this.currIdx] != null) { 23 | res.add(this.arr[this.currIdx++]); 24 | } 25 | } 26 | return res; 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /1668. Maximum Repeating Substring.java: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/maximum-repeating-substring/discuss/952025/C%2B%2B-short-easy-using-find 2 | 3 | idea: String built-in indexOf() 4 | time complexity: O(n log n) 5 | space complexity: O(n) 6 | 7 | class Solution { 8 | public int maxRepeating(String sequence, String word) { 9 | int n = word.length(), repeat = 0; 10 | String w = word; 11 | while (sequence.indexOf(w) >= 0) { 12 | repeat++; 13 | w += word; 14 | } 15 | 16 | return repeat; 17 | } 18 | } -------------------------------------------------------------------------------- /1673. Find the Most Competitive Subsequence.java: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/find-the-most-competitive-subsequence/ 2 | 3 | idea: Constrained Stack/Monotonoic Queue 4 | time complexity: O(n) 5 | space complexity: O(k) 6 | 7 | class Solution { 8 | public int[] mostCompetitive(int[] nums, int k) { 9 | int n = nums.length; 10 | int[] res = new int[k]; 11 | Stack stack = new Stack<>(); 12 | for (int i = 0; i < n; i++) { 13 | while (!stack.isEmpty() && nums[stack.peek()] > nums[i] && stack.size() + n - i > k) { 14 | stack.pop(); 15 | } 16 | if (stack.size() < k) { 17 | stack.push(i); 18 | } 19 | } 20 | 21 | for (int i = k - 1; i >= 0; i--) { 22 | res[i] = nums[stack.pop()]; 23 | } 24 | return res; 25 | } 26 | } -------------------------------------------------------------------------------- /1679. Max Number of K-Sum Pairs.java: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/max-number-of-k-sum-pairs/ 2 | 3 | idea: HashMap. Two Sum follow-up. 4 | time complexity: O(n) 5 | space complexity: O(n) 6 | 7 | class Solution { 8 | public int maxOperations(int[] nums, int k) { 9 | int res = 0; 10 | Map map = new HashMap<>(); 11 | for (int num : nums) { 12 | int comp = k - num; 13 | if (map.containsKey(comp) && map.get(comp) > 0) { 14 | res++; 15 | map.put(comp, map.get(comp) - 1); 16 | } else { 17 | map.put(num, map.getOrDefault(num, 0) + 1); 18 | } 19 | } 20 | 21 | return res; 22 | } 23 | } -------------------------------------------------------------------------------- /168. Excel Sheet Column Title.java: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/excel-sheet-column-title/ 2 | 3 | // 实际上考察的是【进制转换】:十进制转换成26进制。 4 | // 1)类似十进制转换成二进制,先转换出最低位,最后转换出最高位 5 | // 2)要利用n % 26作为index的性质,需要将n变成0-based,所以需要n-- 6 | // 3)n除以进制的基数(即26)来更新n 7 | 8 | class Solution { 9 | public String convertToTitle(int n) { 10 | StringBuilder sb = new StringBuilder(); 11 | while (n > 0) { 12 | n--; 13 | sb.insert(0, (char)('A' + n % 26)); 14 | n /= 26; 15 | } 16 | 17 | return sb.toString(); 18 | } 19 | } -------------------------------------------------------------------------------- /1685. Sum of Absolute Differences in a Sorted Array.java: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/sum-of-absolute-differences-in-a-sorted-array/ 2 | 3 | idea: Math + Prefix Sum 4 | time complexity: O(n) 5 | space complexity: O(n) 6 | 7 | class Solution { 8 | public int[] getSumAbsoluteDifferences(int[] nums) { 9 | int n = nums.length; 10 | int[] res = new int[n], sum = new int[n + 1]; 11 | for (int i = 1; i <= n; i++) { 12 | sum[i] = sum[i - 1] + nums[i - 1]; 13 | } 14 | 15 | for (int i = 0; i < n; i++) { 16 | // (nums[i] - nums[0]) + ... + (nums[i] - nums[i]) 17 | // + (nums[i + 1] - nums[i]) + ... + (nums[n - 1] - nums[i]) 18 | res[i] = nums[i] * (i + 1) - sum[i + 1] + (sum[n] - sum[i + 1]) - nums[i] * (n - (i + 1)); 19 | } 20 | 21 | 22 | return res; 23 | } 24 | } -------------------------------------------------------------------------------- /171. Excel Sheet Column Number.java: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/excel-sheet-column-number/ 2 | 3 | // 实际上考察的是【进制转换】:26进制转换成十进制。 4 | // 类似二进制转换成十进制,先从最高位开始转换,最后处理最低位 5 | 6 | class Solution { 7 | public int titleToNumber(String s) { 8 | int res = 0; 9 | for (char c: s.toCharArray()) { 10 | res = 26 * res + (c - 'A' + 1); 11 | } 12 | return res; 13 | } 14 | } -------------------------------------------------------------------------------- /172. Factorial Trailing Zeroes.java: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/factorial-trailing-zeroes/ 2 | 3 | // 要找n!的结果中有多少个0在末尾,根据数学性质,只有2*5的乘积才会有0,所以问题转化为有多少个2*5。又因为2一定是足够的,所以只要计算有多少个5即可。 4 | 5 | class Solution { 6 | public int trailingZeroes(int n) { 7 | return n == 0? 0 : n / 5 + trailingZeroes(n / 5); 8 | } 9 | } -------------------------------------------------------------------------------- /189. Rotate Array.java: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/rotate-array/ 2 | 3 | 思路1:用额外的copy数组 4 | time comp: O(n) 5 | space comp: O(n) 6 | 7 | class Solution { 8 | public void rotate(int[] nums, int k) { 9 | int n = nums.length; 10 | k = k % n; 11 | if (k == 0) { 12 | return; 13 | } 14 | 15 | int[] copy = Arrays.copyOf(nums, n); 16 | for (int newIdx = 0, currIdx = n - k; 17 | newIdx < n; 18 | newIdx++, currIdx = (currIdx + 1) % n) { 19 | nums[newIdx] = copy[currIdx]; 20 | } 21 | } 22 | } -------------------------------------------------------------------------------- /190. Reverse Bits.java: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/reverse-bits/ 2 | 3 | // 思路:把n第i位(0-based)的bit放到res第31-i位。 4 | // 注意:这里的reverse是指把二进制32位【左右镜像翻转】,不是0翻成1、1翻成0。 5 | // 犯错点:1.不是放到res的第i位,否则就变成复制n了。 6 | 7 | public class Solution { 8 | public int reverseBits(int n) { 9 | int res = 0; 10 | /* 写法一 */ 11 | for (int i = 0; i < 32; i++) { 12 | int curr = n & 1; 13 | n = n >> 1; 14 | //res = res | (curr << i); // {Mistake 1: this is copying n} 15 | res = res | (curr << 31 - i); // {Correction 1} 16 | } 17 | 18 | /* 写法二 */ 19 | /*for (int i = 0; i < 32; i++) { 20 | int curr = n & 1; 21 | n = n >> 1; 22 | res = (res << 1) + curr; 23 | }*/ 24 | 25 | return res; 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /202. Happy Number.java: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/happy-number/ 2 | 3 | // 因为不是happy number的话,会导致数的循环,所以可以维护一个Set来判断是否有重复出现的数。 4 | 5 | class Solution { 6 | public boolean isHappy(int n) { 7 | Set set = new HashSet<>(); 8 | int next = n; 9 | while (next != 1) { 10 | int temp = 0; 11 | while (next > 0) { 12 | temp += (next % 10) * (next % 10); 13 | next /= 10; 14 | } 15 | next = temp; 16 | if (set.contains(next)) return false; 17 | set.add(next); 18 | } 19 | return true; 20 | } 21 | } -------------------------------------------------------------------------------- /203. Remove Linked List Elements.java: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/remove-linked-list-elements/ 2 | 3 | // 可能会改变head,所以需要维护一个dummy。【只有当curr.next.val != val时curr才能更新】 4 | 5 | /** 6 | * Definition for singly-linked list. 7 | * public class ListNode { 8 | * int val; 9 | * ListNode next; 10 | * ListNode(int x) { val = x; } 11 | * } 12 | */ 13 | class Solution { 14 | public ListNode removeElements(ListNode head, int val) { 15 | if (head == null) return head; 16 | ListNode dummy = new ListNode(-100), curr = dummy; 17 | dummy.next = head; 18 | while (curr.next != null) { 19 | if (curr.next.val == val) curr.next = curr.next.next; 20 | else curr = curr.next; 21 | } 22 | return dummy.next; 23 | } 24 | } -------------------------------------------------------------------------------- /204. Count Primes.java: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/count-primes/ 2 | 3 | // 要利用一些数学性质。 4 | // 1)维护一个size为n的boolean数组isPrime(因为题目为小于n的所prime number个数),初始化为true。 5 | // 2)维护count表示prime number个数 6 | // 3)外层循环:从2开始,查找是否被标记为素数。如果为true,count++,然后进入内层循环 7 | // 4)内层循环:从2开始,和外层循环找到的数的乘积必然不是素数,所以将这些数全部标记为false。由于从2一直标记到n - 1,所以 8 | // 可以保证在外层循环中找到的素数一定为真素数 9 | 10 | class Solution { 11 | public int countPrimes(int n) { 12 | if (n < 2) return 0; 13 | boolean[] isPrime = new boolean[n]; 14 | Arrays.fill(isPrime, true); 15 | int count = 0; 16 | for (int i = 2; i < n; i++) { 17 | if (isPrime[i] == true) { 18 | count++; 19 | for (int j = 2; i * j < n; j++) { 20 | isPrime[i * j] = false; 21 | } 22 | } 23 | } 24 | return count; 25 | } 26 | } -------------------------------------------------------------------------------- /219. Contains Duplicate II.java: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/contains-duplicate-ii/ 2 | 3 | // 217. Contains Duplicate的follow-up,增加条件nums == nums[j]且j - i <= k。由于对index有要求,不能改变index,所以不能sort 4 | // 1)维护一个HashMap,key为nums,value为index 5 | // 2)如果HashMap存在nums且j - i <= k,返回true 6 | // 3)否则,put key and value 7 | // 4)遍历完成,跳出循环,返回false 8 | // 5)Time complexity: O(n);Space complexity: O(n) 9 | 10 | class Solution { 11 | public boolean containsNearbyDuplicate(int[] nums, int k) { 12 | if (nums == null || nums.length == 0 || k == 0) return false; 13 | Map indexMapping = new HashMap<>(); 14 | for (int i = 0; i < nums.length; i++) { 15 | if (indexMapping.containsKey(nums[i]) && i - indexMapping.get(nums[i]) <= k) return true; 16 | else indexMapping.put(nums[i], i); 17 | } 18 | return false; 19 | } 20 | } -------------------------------------------------------------------------------- /222. Count Complete Tree Nodes.java: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/count-complete-tree-nodes/ 2 | 3 | // 解法一:Recursion 4 | 5 | class Solution { 6 | public int countNodes(TreeNode root) { 7 | if (root == null) return 0; 8 | return countNodes(root.left) + countNodes(root.right) + 1; 9 | } 10 | } 11 | 12 | // 解法二:Iteration,进行preorder traversal的同时统计node数量 13 | 14 | class Solution { 15 | public int countNodes(TreeNode root) { 16 | Stack stack = new Stack(); 17 | int count = 0; 18 | while (root != null || !stack.isEmpty()) { 19 | while (root != null) { 20 | stack.push(root); 21 | root = root.left; 22 | count++; 23 | } 24 | root = stack.pop(); 25 | root = root.right; 26 | } 27 | return count; 28 | } 29 | } -------------------------------------------------------------------------------- /223. Rectangle Area.java: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/rectangle-area/ 2 | 3 | // 根据面积公式,两个矩形面积和减去重叠的面积即为所求,所以关键在于如何求重叠的面积。 4 | // 1)维护4个变量,分别表示重叠部分的左下端点坐标和右上端点坐标。 5 | // 2)关键点:确定了left和bottom的取值后,利用它们来确定right和top的取值。如果没有重叠,那么right和left取值相同,top和bottom取值相同,所以重叠面积为0。 6 | 7 | 8 | class Solution { 9 | public int computeArea(int A, int B, int C, int D, int E, int F, int G, int H) { 10 | int left = Math.max(A, E), right = Math.max(Math.min(C, G), left); 11 | int bottom = Math.max(B, F), top = Math.max(Math.min(D, H), bottom); 12 | return (C - A) * (D - B) + (G - E) * (H - F) - (right - left) * (top - bottom); 13 | } 14 | } -------------------------------------------------------------------------------- /231. Power of Two.java: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/power-of-two/ 2 | 3 | // 解法一:iteration/recursion 4 | // 时间复杂度:O(log n) 5 | // 空间复杂度:O(1) 6 | 7 | class Solution { 8 | public boolean isPowerOfTwo(int n) { 9 | /* corner case */ 10 | if (n <= 0) return false; 11 | 12 | while (n > 1) { 13 | if (n % 2 != 0) return false; 14 | n = n / 2; 15 | } 16 | return true; 17 | } 18 | } 19 | 20 | // 解法二:利用191. Number of 1 Bits启发的得到1 bit的性质,用Bit manipulation。 21 | // 时间复杂度:O(1) 22 | // 空间复杂度:O(1) 23 | 24 | class Solution { 25 | public boolean isPowerOfTwo(int n) { 26 | /* corner case */ 27 | if (n <= 0) return false; 28 | 29 | return (n & (n - 1)) == 0; 30 | } 31 | } -------------------------------------------------------------------------------- /237. Delete Node in a Linked List.java: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/delete-node-in-a-linked-list/ 2 | 3 | // 脑筋急转弯。把下一个node的值覆盖到当前node,然后删掉下一个node,即可完成当前node的“删除”。 4 | 5 | /** 6 | * Definition for singly-linked list. 7 | * public class ListNode { 8 | * int val; 9 | * ListNode next; 10 | * ListNode(int x) { val = x; } 11 | * } 12 | */ 13 | class Solution { 14 | public void deleteNode(ListNode node) { 15 | node.val = node.next.val; 16 | node.next = node.next.next; 17 | } 18 | } -------------------------------------------------------------------------------- /242. Valid Anagram.java: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/valid-anagram/ 2 | 3 | // 1)当s和t长度不相同,直接返回false 4 | // 2)利用类似sliding window的策略,数s中各个字符出现的次数,然后遍历t,如果count <= 0,说明有mismatch,返回false 5 | 6 | class Solution { 7 | public boolean isAnagram(String s, String t) { 8 | if (s.length() != t.length()) return false; 9 | int[] count = new int[128]; 10 | int total = 0; 11 | for (char c: s.toCharArray()) { 12 | count[c]++; 13 | } 14 | for (char c: t.toCharArray()) { 15 | if (count[c] <= 0) return false; 16 | count[c]--; 17 | } 18 | return true; 19 | } 20 | } -------------------------------------------------------------------------------- /246. Strobogrammatic Number.java: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/strobogrammatic-number/ 2 | 3 | // 思路:HashSet 4 | // 维护HashSet,表示合法的左右指针指向的数字的组合。如果数字组合不在HashSet中, 说明不合法,返回false。 5 | // 遍历了整个String,都合法,那么返回true。 6 | // 时间复杂度:O(n) 7 | // 空间复杂度:O(1) 8 | 9 | class Solution { 10 | Set set = new HashSet<>(Arrays.asList("00", "11", "88", "69", "96")); 11 | 12 | public boolean isStrobogrammatic(String num) { 13 | int left = 0, right = num.length() - 1; 14 | while (left <= right) { 15 | char c1 = num.charAt(left), c2 = num.charAt(right); 16 | if (!set.contains(c1 + "" + c2)) { // transform this pair of chars to a String and use HashSet to validate 17 | return false; 18 | } 19 | left++; 20 | right--; 21 | } 22 | return true; 23 | } 24 | } -------------------------------------------------------------------------------- /252. Meeting Rooms.java: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/meeting-rooms/ 2 | 3 | // 思路:Customized Sort 4 | // 时间复杂度:O(n log n) 5 | // 空间复杂度:O(n) 6 | 7 | class Solution { 8 | public boolean canAttendMeetings(int[][] intervals) { 9 | Arrays.sort(intervals, new Comparator() { 10 | @Override 11 | public int compare(int[] i1, int[] i2) { 12 | return i1[0] == i2[0] ? i1[1] - i2[1] : i1[0] - i2[0]; 13 | } 14 | }); 15 | 16 | for (int i = 1; i < intervals.length; i++) { 17 | if (intervals[i][0] < intervals[i - 1][1]) { 18 | return false; 19 | } 20 | } 21 | 22 | return true; 23 | } 24 | } -------------------------------------------------------------------------------- /258. Add Digits.java: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/add-digits/ 2 | 3 | // 解法一:recursion/iteration 4 | 5 | // 解法二:考数学性质,没啥好说,背公式背结论。 6 | 7 | class Solution { 8 | public int addDigits(int num) { 9 | if (num == 0) return 0; 10 | if (num % 9 == 0) return 9; 11 | return num % 9; 12 | } 13 | } -------------------------------------------------------------------------------- /26. Remove Duplicates from Sorted Array.java: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/remove-duplicates-from-sorted-array/ 2 | 3 | // Two pointers 4 | // 1)left指向最后一个去重后的元素,right指向第一个未被扫描的元素 5 | // 2)当nums[left] != nums[right],把nums[right]插入到left的下一位,更新left和right。否则直接更新right 6 | 7 | class Solution { 8 | public int removeDuplicates(int[] nums) { 9 | if (nums == null || nums.length == 0) return 0; 10 | int left = 0, right = 1; 11 | while (right < nums.length) { 12 | if (nums[right] != nums[left]) nums[++left] = nums[right]; 13 | right++; 14 | } 15 | return left + 1; 16 | } 17 | } -------------------------------------------------------------------------------- /263. Ugly Number.java: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/ugly-number/ 2 | 3 | // 解法一:iteration,分别整除2,3,5直到不能整除,看余数是否为1 4 | 5 | class Solution { 6 | public boolean isUgly(int num) { 7 | if(num <= 0) return false; 8 | if(num == 1) return true; 9 | while(num % 2 == 0) num = num / 2; 10 | while(num % 3 == 0) num = num / 3; 11 | while(num % 5 == 0) num = num / 5; 12 | return num == 1; 13 | } 14 | } 15 | 16 | // 解法二:recursion 17 | 18 | class Solution { 19 | public boolean isUgly(int num) { 20 | if (num <= 0) return false; 21 | if (num == 1 || num == 2 || num == 3 || num == 5) return true; 22 | return (num % 2 == 0 && isUgly(num / 2)) || (num % 3 == 0 && isUgly(num / 3)) || (num % 5 == 0 && isUgly(num / 5)); 23 | } 24 | } -------------------------------------------------------------------------------- /268. Missing Number.java: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/missing-number/ 2 | 3 | // 解法一:sort 4 | // 解法二:HashSet 5 | // 解法三:XOR,观察得知index和nums[index]都成对出现,除了缺失的数。将nums.length作为最后一个index补足后, 6 | // 利用XOR的性质,转化为136题Single Number问题。 7 | 8 | class Solution { 9 | public int missingNumber(int[] nums) { 10 | int res = nums.length; 11 | for (int i = 0; i < nums.length; i++) { 12 | res ^= (i ^ nums[i]); 13 | } 14 | return res; 15 | } 16 | } -------------------------------------------------------------------------------- /27. Remove Element.java: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/remove-element/ 2 | 3 | // Two pointers 4 | // 1)left指向第一个可插入的位置,right指向第一个未被扫描的位置 5 | // 2)只有当nums[right] != val时才将其赋值到left处 6 | 7 | class Solution { 8 | public int removeElement(int[] nums, int val) { 9 | if (nums == null || nums.length == 0) return 0; 10 | int left = 0, right = 0; 11 | while (right < nums.length) { 12 | if (nums[right] != val) nums[left++] = nums[right]; 13 | right++; 14 | } 15 | return left; 16 | } 17 | } -------------------------------------------------------------------------------- /275. H-Index II.java: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/h-index-ii/ 2 | 3 | // 274. H-Index的follow-up,给定的数组已经排好了序。属于binary search的变种。 4 | // 关键点:比较的是length - mid(表示paper数)和citations[mid](表示引用数)。 5 | // length - mid == citations[mid]的情况可以并入length - mid < citations[mid],因为要找最大的length - mid,要增加length - mid需要移动high。 6 | // 循环结束时,返回的是length - low。 7 | // 可用test case帮助记忆:[0,0,0,0,0,0]和[6,6,6,6,6] 8 | 9 | class Solution { 10 | public int hIndex(int[] citations) { 11 | int length = citations.length, low = 0, high = length - 1; 12 | while (low <= high) { 13 | int mid = low + (high - low) / 2; 14 | if (length - mid > citations[mid]) low = mid + 1; 15 | else high = mid - 1; 16 | } 17 | return length - low; 18 | } 19 | } -------------------------------------------------------------------------------- /278. First Bad Version.java: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/first-bad-version/ 2 | 3 | // 思路:尽量减少isBadVersion()的使用次数,明显要用Binary Search。套用模版即可。 4 | 5 | /* The isBadVersion API is defined in the parent class VersionControl. 6 | boolean isBadVersion(int version); */ 7 | 8 | public class Solution extends VersionControl { 9 | public int firstBadVersion(int n) { 10 | int low = 1, high = n; 11 | while (low <= high) { 12 | int mid = low + (high - low) / 2; 13 | if (isBadVersion(mid)) high = mid - 1; 14 | else low = mid + 1; 15 | } 16 | return low; 17 | } 18 | } -------------------------------------------------------------------------------- /279. Perfect Squares.java: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/perfect-squares/ 2 | 3 | // 时间复杂度为O(n^(3/2))的DP题。 4 | // 1)维护dp数组,dp[i]表示和为i的完全平方数的最小个数 5 | // 2)两层循环:外层循环遍历n个数;内层循环遍历小于i的所有完全平方数,相当于比较减掉某个完全平方数的dp加上被减掉的这个完全平方数个数(即+1),取最小值 6 | 7 | class Solution { 8 | public int numSquares(int n) { 9 | if (n <= 0) return 0; 10 | int[] dp = new int[n + 1]; 11 | for (int i = 1; i <= n; i++) { 12 | dp[i] = Integer.MAX_VALUE; 13 | for (int j = 1; j * j <= i; j++) { 14 | dp[i] = Math.min(dp[i], dp[i - j * j] + 1); 15 | } 16 | } 17 | return dp[n]; 18 | } 19 | } -------------------------------------------------------------------------------- /283. Move Zeroes.java: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/move-zeroes/ 2 | 3 | // 1)维护left和right两个pointer。其中left指向左边第一个0,right指向第一个未被扫描的数,left和right之间都是扫描过的0,left左边是所有扫描过的被交换过去的非0数。 4 | // 2)如果right是0,继续向前 5 | // 3)如果right非0,交换left和right,然后left和right都向前一步 6 | // 4)时间复杂度:O(n);空间复杂度:O(1) 7 | 8 | class Solution { 9 | public void moveZeroes(int[] nums) { 10 | if (nums == null || nums.length == 0) return; 11 | int left = 0, right = 0; 12 | while (right < nums.length) { 13 | if (nums[right] == 0) right++; 14 | else swap(nums, right++, left++); 15 | } 16 | } 17 | private void swap(int[] nums, int i, int j) { 18 | int temp = nums[i]; 19 | nums[i] = nums[j]; 20 | nums[j] = temp; 21 | } 22 | } -------------------------------------------------------------------------------- /292. Nim Game.java: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/nim-game/ 2 | 3 | // Brute Force:DP,如果拿走1个、2个或3个石头能导致输掉的,那么当前石头的数量我能赢,因为只要拿掉相应的石头数量对方就输。 4 | // 出现的问题:Memory limit exceed 5 | 6 | class Solution { 7 | public boolean canWinNim(int n) { 8 | if (n < 4) return true; 9 | boolean[] dp = new boolean[n + 1]; 10 | dp[1] = true; 11 | dp[2] = true; 12 | dp[3] = true; 13 | for (int i = 4; i <= n; i++) { 14 | dp[i] = !dp[i - 1] || !dp[i - 2] || !dp[i - 3]; 15 | } 16 | return dp[n]; 17 | } 18 | } 19 | 20 | 21 | // 优化思路:如果起手的石头数量是4的倍数,那么一定输,否则就能赢。 22 | 23 | class Solution { 24 | public boolean canWinNim(int n) { 25 | return n % 4 != 0; 26 | } 27 | } -------------------------------------------------------------------------------- /293. Flip Game.java: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/flip-game/ 2 | 3 | // 解法一:遍历 + StringBuilder.setCharAt() 4 | // 时间复杂度:O(n) 5 | // 空间复杂度:O(n^2) 6 | 7 | class Solution { 8 | public List generatePossibleNextMoves(String s) { 9 | List res = new ArrayList<>(); 10 | for (int i = 0; i < s.length() - 1; i++) { 11 | if (s.charAt(i) == '+' && s.charAt(i + 1) == '+') { 12 | res.add(set(new StringBuilder(s), i, i + 1)); 13 | } 14 | } 15 | 16 | return res; 17 | } 18 | 19 | private String set(StringBuilder sb, int i, int j) { 20 | sb.setCharAt(i, '-'); 21 | sb.setCharAt(j, '-'); 22 | return sb.toString(); 23 | } 24 | } 25 | 26 | 27 | 解法二:遍历 + String.indexOf() + String.substring() -------------------------------------------------------------------------------- /303. Range Sum Query - Immutable.java: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/range-sum-query-immutable/ 2 | 3 | // 总体思路:用一个辅助数组sums,sums[i]储存的是nums[0:i-1]的和,所以要求nums[i]+...+nums[j],只需要用(nums[0]+...+nums[j])-(nums[0]+...+nums[i-1]), 4 | // 即sums[j+1]-sums[i]。 5 | 6 | class NumArray { 7 | int[] sums; 8 | public NumArray(int[] nums) { 9 | sums = new int[nums.length + 1]; // sums[i] indicates the sum of nums[0:i-1], thus sums[0] must be 0 10 | for (int i = 1; i <= nums.length; i++) { 11 | sums[i] = nums[i - 1] + sums[i - 1]; 12 | } 13 | } 14 | 15 | public int sumRange(int i, int j) { 16 | return sums[j + 1] - sums[i]; 17 | } 18 | } 19 | 20 | /** 21 | * Your NumArray object will be instantiated and called as such: 22 | * NumArray obj = new NumArray(nums); 23 | * int param_1 = obj.sumRange(i,j); 24 | */ -------------------------------------------------------------------------------- /311. Sparse Matrix Multiplication.java: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/sparse-matrix-multiplication/ 2 | 3 | 思路:Math,根据定义计算 4 | 时间复杂度:O(m*n*p) 5 | 空间复杂度:O(m*p) 6 | 7 | class Solution { 8 | public int[][] multiply(int[][] A, int[][] B) { 9 | int m = A.length, n = m == 0 ? 0 : A[0].length, p = B.length == 0 ? 0 : B[0].length; 10 | int[][] res = new int[m][p]; 11 | for (int i = 0; i < m; i++) { 12 | for (int j = 0; j < n; j++) { 13 | if (A[i][j] == 0) continue; 14 | for (int k = 0; k < p; k++) { 15 | if (B[j][k] == 0) continue; 16 | res[i][k] += A[i][j] * B[j][k]; 17 | } 18 | } 19 | } 20 | return res; 21 | } 22 | } -------------------------------------------------------------------------------- /319. Bulb Switcher.java: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/bulb-switcher/ 2 | 3 | // 一个数的因子个数代表了它在会被turn on/off的次数,每个因子代表它在第几轮被turn on/off。因此,只有被操作了奇数次,它才能为on。 4 | // 一般一个数都有偶数个因子(如2->[1,2], 5->[1,5], 10->[1,2,5,10]),除了完全平方数,有奇数个因子(如4->[1,2,4],9->[1,3,9]),因此这个问题【转化为在小于n的数中有多少个完全平方数】。 5 | 6 | // 解法一:iteration 7 | 8 | class Solution { 9 | public int bulbSwitch(int n) { 10 | if (n <= 1) return n; 11 | int count = 1; 12 | for (int i = 2; i <= n / 2; i++) { 13 | if ((long) i * i <= n) count++; 14 | } 15 | return count; 16 | } 17 | } 18 | 19 | // 解法二:直接用内置的Math.sqrt function。 20 | 21 | class Solution { 22 | public int bulbSwitch(int n) { 23 | return (int) Math.sqrt(n); 24 | } 25 | } -------------------------------------------------------------------------------- /342. Power of Four.java: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/power-of-four/ 2 | 3 | // 思路:和231. Power of Two类似。观察可知规律:在二进制表示中只有1个1,且必须处在奇数位(从右到左的第一位、第三位、第五位……)。 4 | // 技巧在于利用这个数0x55555555,这个数的二进制表示为1010101010101010101010101010101,即只有奇数位有1. 5 | // 0xaaaaaaaa等一些其他数也和0x55555555等价。 6 | 7 | class Solution { 8 | public boolean isPowerOfFour(int num) { 9 | return num > 0 && (num & (num - 1)) == 0 && (num & 0x55555555) > 0; 10 | } 11 | } -------------------------------------------------------------------------------- /344. Reverse String.java: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/reverse-string/ 2 | 3 | // Two pointers问题。 4 | 5 | class Solution { 6 | public void reverseString(char[] s) { 7 | if (s == null || s.length == 0) return; 8 | int left = 0, right = s.length - 1; 9 | while (left < right) { 10 | swap(s, left++, right--); 11 | } 12 | } 13 | private void swap(char[] s, int i, int j) { 14 | char temp = s[i]; 15 | s[i]= s[j]; 16 | s[j] = temp; 17 | } 18 | } -------------------------------------------------------------------------------- /345. Reverse Vowels of a String.java: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/reverse-vowels-of-a-string/ 2 | 3 | // Two pointers问题。 4 | // 注意:(1)大写的AEIOU也要考虑。 5 | // (2)查找vowel可以用trick:"aeiouAEIOU".indexOf(c),或者用Set将查找降至O(1)时间。 6 | 7 | class Solution { 8 | public String reverseVowels(String s) { 9 | if (s == null || s.length() == 0) return ""; 10 | char[] sArray = s.toCharArray(); 11 | int left = 0, right = sArray.length - 1; 12 | while (left < right) { 13 | while (left < right && "aeiouAEIOU".indexOf(sArray[left]) < 0) left++; 14 | while (left < right && "aeiouAEIOU".indexOf(sArray[right]) < 0) right--; 15 | swap(sArray, left++, right--); 16 | } 17 | return new String(sArray); 18 | } 19 | private void swap(char[] s, int i, int j) { 20 | char temp = s[i]; 21 | s[i]= s[j]; 22 | s[j] = temp; 23 | } 24 | } -------------------------------------------------------------------------------- /35. Search Insert Position.java: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/search-insert-position/ 2 | 3 | // 总体思路:Binary Search模版,左闭右开 4 | // low boundary: index=0 5 | // high boundary: index=nums.length 6 | // g(m):找到最小mid index使得满足nums[mid] >= target 7 | // 返回值:low index 8 | 9 | class Solution { 10 | public int searchInsert(int[] nums, int target) { 11 | int low = 0, high = nums.length; 12 | while (low < high) { 13 | int mid = low + (high - low) / 2; 14 | if (nums[mid] >= target) high = mid; 15 | else low = mid + 1; 16 | } 17 | return low; 18 | } 19 | } -------------------------------------------------------------------------------- /357. Count Numbers with Unique Digits.java: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/count-numbers-with-unique-digits/ 2 | 3 | // 1)维护两个变量:count表示当前找到的所有unique digits的个数,temp表示在位数为i时的unique digits的个数 4 | // 2)循环的边界为n和10的较小数,因为超过10位的数不会再有新的unique digits 5 | 6 | class Solution { 7 | public int countNumbersWithUniqueDigits(int n) { 8 | if (n == 0) return 1; 9 | 10 | int count = 10, temp = 9; 11 | for (int i = 2; i <= Math.min(n, 10); i++) { 12 | temp = (9 - i + 2) * temp; 13 | count = temp + count; 14 | } 15 | return count; 16 | } 17 | } -------------------------------------------------------------------------------- /365. Water and Jug Problem.java: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/water-and-jug-problem/ 2 | 3 | // 需要利用最大公约数(greatest common divisor)的性质,具体分析见discuss:https://leetcode.com/problems/water-and-jug-problem/discuss/83715/Math-solution-Java-solution 4 | 5 | class Solution { 6 | public boolean canMeasureWater(int x, int y, int z) { 7 | if (x + y < z) return false; 8 | if (x == z || y == z || x + y == z) return true; 9 | 10 | return z % gcd(x, y) == 0; 11 | } 12 | private int gcd(int m, int n) { 13 | if (n == 0) return m; 14 | return gcd(n, m % n); 15 | } 16 | } -------------------------------------------------------------------------------- /367. Valid Perfect Square.java: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/valid-perfect-square/ 2 | 3 | // 解法一:Binary search,注意用【lon】g避免越界。 4 | 5 | class Solution { 6 | public boolean isPerfectSquare(int num) { 7 | if (num <= 0) return false; 8 | int low = 0, high = num; 9 | while (low <= high) { 10 | int mid = low + (high - low) / 2; 11 | if ((long) mid * mid == num) return true; 12 | else if ((long) mid * mid > num) high = mid - 1; 13 | else low = mid + 1; 14 | } 15 | return false; 16 | } 17 | } 18 | 19 | // 解法二:牛顿法,背公式。 20 | 21 | class Solution { 22 | public boolean isPerfectSquare(int num) { 23 | if (num < 1) return false; 24 | if (num == 1) return true; 25 | long x = num / 2; 26 | while (x * x > num) x = (x + num / x) / 2; 27 | return x * x == num; 28 | } 29 | } -------------------------------------------------------------------------------- /370. Range Addition.java: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/range-addition/ 2 | 3 | 思路:Sweep Line 4 | 5 | 时间复杂度:O(n + l), n=updates.length, l=res.length 6 | 空间复杂度:O(l), l=res.length 7 | 8 | class Solution { 9 | public int[] getModifiedArray(int length, int[][] updates) { 10 | int[] res = new int[length]; 11 | for (int[] update : updates) { 12 | int start = update[0], end = update[1], incr = update[2]; 13 | res[start] += incr; 14 | if (end + 1 < length) { 15 | res[end + 1] += -incr; 16 | } 17 | } 18 | 19 | for (int i = 1; i < length; i++) { 20 | res[i] += res[i - 1]; 21 | } 22 | 23 | return res; 24 | } 25 | } -------------------------------------------------------------------------------- /371. Sum of Two Integers.java: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/sum-of-two-integers/ 2 | 3 | // 思路:Bit Manipulation,视频详解:https://www.youtube.com/watch?v=qq64FrA2UXQ 4 | // 利用3个操作: 5 | // 1)&,找到a和b相加后出现carry的所有位置,也就是a和b都有1的bit 6 | // 2)<<,因为用&找到的carry不是下一步要加的位置,正确的位置应该是左移一位。eg.0111和0111相加,用&找到的carry为0111,但实际上是<<1后的1110 7 | // 利用&和<<找到的是下一步的carry,所以临时存在nextCarry中。 8 | // 3)^,实际执行的相加操作,会出现carry的地方(都为1)就会变成0。结果存在a中。 9 | // 然后更新b为nextCarry,当b(即nextCarry)为0时,表示下一步没有carry了,操作可以停止。最后返回a。 10 | 11 | class Solution { 12 | public int getSum(int a, int b) { 13 | int nextCarry = 0; 14 | while (b != 0) { 15 | nextCarry = (a & b) << 1; 16 | a = a ^ b; 17 | b = nextCarry; 18 | } 19 | return a; 20 | } 21 | } -------------------------------------------------------------------------------- /374. Guess Number Higher or Lower.java: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/guess-number-higher-or-lower/ 2 | 3 | // 思路:常规Binary search问题 4 | // 时间复杂度:O(log n) 5 | // 空间复杂度:O(1) 6 | 7 | /* The guess API is defined in the parent class GuessGame. 8 | @param num, your guess 9 | @return -1 if my number is lower, 1 if my number is higher, otherwise return 0 10 | int guess(int num); */ 11 | 12 | public class Solution extends GuessGame { 13 | public int guessNumber(int n) { 14 | int low = 1, high = n; 15 | while (low <= high) { 16 | int mid = low + (high - low) / 2; 17 | int guess = guess(mid); 18 | if (guess == 0) return mid; 19 | else if (guess > 0) low = mid + 1; 20 | else high = mid - 1; 21 | } 22 | return -1; 23 | } 24 | } -------------------------------------------------------------------------------- /383. Ransom Note.java: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/ransom-note/ 2 | 3 | // Character to Integer mapping的模板。 4 | // corner cases:如果ransomNote字符比magazine多,那么一定不能组成ransomNote,直接返回false。 5 | 6 | class Solution { 7 | public boolean canConstruct(String ransomNote, String magazine) { 8 | if (ransomNote.length() > magazine.length()) return false; 9 | int[] mapping = new int[128]; 10 | for (char c: magazine.toCharArray()) { 11 | mapping[c]++; 12 | } 13 | for (char c: ransomNote.toCharArray()) { 14 | if (mapping[c] <= 0) return false; 15 | mapping[c]--; 16 | } 17 | return true; 18 | } 19 | } -------------------------------------------------------------------------------- /387. First Unique Character in a String.java: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/first-unique-character-in-a-string/ 2 | 3 | // 1)把s中character出现的次数存进数组 4 | // 2)找到第一个count[c] == 1对应的index,否则返回-1 5 | 6 | class Solution { 7 | public int firstUniqChar(String s) { 8 | int[] count = new int[128]; 9 | for (char c: s.toCharArray()) { 10 | count[c]++; 11 | } 12 | for (int i = 0; i < s.length(); i++) { 13 | char c = s.charAt(i); 14 | if (count[c] == 1) return i; 15 | } 16 | return -1; 17 | } 18 | } -------------------------------------------------------------------------------- /390. Elimination Game.java: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/elimination-game/ 2 | 3 | 思路:Math,找规律,参考:https://leetcode.com/problems/elimination-game/discuss/87119/JAVA%3A-Easiest-solution-O(logN)-with-explanation 4 | 5 | 时间复杂度:O(log n) 6 | 空间复杂度:O(1) 7 | 8 | class Solution { 9 | public int lastRemaining(int n) { 10 | boolean fromLeft = true; 11 | int head = 1; // the first remaining element 12 | int step = 1; // the step to the next remaining element 13 | while (n > 1) { 14 | if (fromLeft || n % 2 == 1) { 15 | head += step; // the head should be updated because otherwise it will be eliminated 16 | } 17 | 18 | n /= 2; 19 | step *= 2; 20 | fromLeft = !fromLeft; 21 | } 22 | 23 | return head; 24 | } 25 | } -------------------------------------------------------------------------------- /396. Rotate Function.java: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/rotate-function/ 2 | 3 | idea: Math 4 | Find the mathematical observation in this question 5 | time complexity: O(n) 6 | space complexity: O(1) 7 | 8 | class Solution { 9 | public int maxRotateFunction(int[] A) { 10 | int sum = 0, funcVal = 0, len = A.length; 11 | for (int i = 0; i < len; i++) { 12 | sum += A[i]; 13 | funcVal += i * A[i]; 14 | } 15 | int max = funcVal; 16 | 17 | // observation: next function value is the previous value + sum of all values 18 | // substracted by current element (starting from the last one) - len * current element 19 | for (int i = len - 1; i >= 1; i--) { 20 | funcVal += (sum - A[i]) - (len - 1) * A[i]; 21 | max = Math.max(max, funcVal); 22 | } 23 | return max; 24 | 25 | } 26 | } -------------------------------------------------------------------------------- /398. Random Pick Index.java: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/random-pick-index/ 2 | 3 | // 思路:HashMap 4 | // 出现的问题:题目对于空间复杂度有要求,只能使用constant extra space 5 | 6 | 7 | // 思路:Reservoir Sampling 8 | // 遍历数组,如果遇到了target,记录个数count,然后“抽奖”,以如果1 / count的概率抽到0,那么也能以同样概率抽到当前index, 9 | // 那么需要更新index。 10 | // 时间复杂度:O(n) 11 | // 空间复杂度:O(1) 12 | 13 | class Solution { 14 | int[] copy; 15 | Random random; 16 | 17 | public Solution(int[] nums) { 18 | copy = nums; 19 | random = new Random(); 20 | } 21 | 22 | public int pick(int target) { 23 | int count = 0, index = -1; 24 | for (int i = 0; i < copy.length; i++) { 25 | if (copy[i] != target) continue; 26 | count++; 27 | if (random.nextInt(count) == 0) { 28 | index = i; 29 | } 30 | } 31 | return index; 32 | } 33 | } -------------------------------------------------------------------------------- /400. Nth Digit.java: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/nth-digit/ 2 | 3 | // 1)维护变量:len,表示当前搜寻的数的位数;count,表示位数为len的数的个数,注意【设为long避免越界】;startNum,表示第一个位数为len的数 4 | // 2)每次循环,n减少len * count,即位数为len的所有digit的个数,同时更新count,startNum,len 5 | // 3)根据startNum和剩下的n找到targetNum,转换为String,找到对应的digit 6 | 7 | class Solution { 8 | public int findNthDigit(int n) { 9 | int len = 1; 10 | long count = 9; 11 | int startNum = 1; 12 | while (n > len * count) { 13 | n -= len * count; 14 | count *= 10; 15 | startNum *= 10; 16 | len++; 17 | } 18 | int targetNum = startNum + (n - 1) / len; 19 | String s = Integer.toString(targetNum); 20 | return s.charAt((n - 1) % len) - '0'; 21 | } 22 | } -------------------------------------------------------------------------------- /409. Longest Palindrome.java: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/longest-palindrome/ 2 | 3 | // 1)将s中character出现的次数用ASCII码长度的数组存储 4 | // 2)不管某个character出现了奇数次还是偶数次,能作为palindrome的都只有【count / 2 * 2】次,用even变量表示 5 | // 3)如果有character出现奇数次,那么单个元素也能形成palindrome,所以odd取值为0或1,当且仅当有character出现奇数次时取1 6 | // 4)最长的palindrome长度即为even和odd的和 7 | 8 | class Solution { 9 | public int longestPalindrome(String s) { 10 | int[] sCount = new int[128]; 11 | for (char c: s.toCharArray()) { 12 | sCount[c]++; 13 | } 14 | int odd = 0, even = 0; 15 | for (int count: sCount) { 16 | even += count / 2 * 2; 17 | if (count % 2 == 1) odd = 1; 18 | } 19 | return odd + even; 20 | } 21 | } -------------------------------------------------------------------------------- /41. First Missing Positive.java: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/first-missing-positive/ 2 | 3 | // 套用模板。 4 | // 1)遍历数组,将所有元素放到该放的位置,直到放置正确、或位置被已经正确放置的元素占据、或元素为负数为止。 5 | // 2)再次遍历数组,查找第一个缺失的正整数。 6 | 7 | class Solution { 8 | public int firstMissingPositive(int[] nums) { 9 | if (nums.length == 0) return 1; 10 | for (int i = 0; i < nums.length; i++) { 11 | while (nums[i] > 0 && nums[i] <= nums.length && nums[i] != nums[nums[i] - 1]){ 12 | swap(nums, i, nums[i] - 1); 13 | } 14 | } 15 | 16 | for (int i = 0; i < nums.length; i++) { 17 | if (i != nums[i] - 1) return i + 1; 18 | } 19 | return nums.length + 1; 20 | } 21 | private void swap(int[] nums, int i, int j) { 22 | int temp = nums[i]; 23 | nums[i] = nums[j]; 24 | nums[j] = temp; 25 | } 26 | } -------------------------------------------------------------------------------- /412. Fizz Buzz.java: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/fizz-buzz/ 2 | 3 | // 思路:常规遍历,条件判断 4 | // 时间复杂度:O(n) 5 | // 空间复杂度:O(1) 6 | 7 | class Solution { 8 | public List fizzBuzz(int n) { 9 | List res = new ArrayList<>(); 10 | for (Integer i = 1; i <= n; i++) { 11 | if (i % 3 != 0 && i % 5 != 0) { 12 | res.add(i.toString()); 13 | } else { 14 | String s = ""; 15 | if (i % 3 == 0) { 16 | s += "Fizz"; 17 | } 18 | if (i % 5 == 0) { 19 | s += "Buzz"; 20 | } 21 | res.add(s); 22 | } 23 | } 24 | 25 | return res; 26 | } 27 | } -------------------------------------------------------------------------------- /413. Arithmetic Slices.java: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/arithmetic-slices/ 2 | 3 | // 思路:bottom-up DP 4 | // 状态函数:dp[i]表示数组A[0:i]范围中包含A[i]的能形成的arithmetic slices数目。 5 | // 状态转移方程:如果从当前A[i]向前连续三个数能形成arithmetic slices,那么dp[i]=dp[i-1]+1。否则,dp[i]=0. 6 | // 初始值:dp[i]=0 7 | // 时间复杂度:O(n) 8 | // 空间复杂度:O(n) 9 | 10 | // 优化:降维。因为dp[i]只和dp[i-1]有关,那么实际上只需要用到1个变量,就可以存储相关的临时结果。 11 | // 时间复杂度:O(n) 12 | // 空间复杂度:O(1) 13 | 14 | class Solution { 15 | public int numberOfArithmeticSlices(int[] A) { 16 | if (A.length < 3) return 0; 17 | 18 | int res = 0, count = 0; 19 | for (int i = 2; i < A.length; i++) { 20 | if (A[i] - A[i - 1] == A[i - 1] - A[i - 2]) { 21 | count++; 22 | } else { 23 | count = 0; 24 | } 25 | res += count; 26 | } 27 | 28 | return res; 29 | } 30 | } -------------------------------------------------------------------------------- /415. Add Strings.java: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/add-strings/ 2 | 3 | idea: StringBuilder, from right to left, add carry over, then reverse and return. 4 | 5 | class Solution { 6 | public String addStrings(String num1, String num2) { 7 | StringBuilder sb = new StringBuilder(); 8 | int idx1 = num1.length() - 1, idx2 = num2.length() - 1; 9 | int carry = 0; 10 | while (idx1 >= 0 || idx2 >= 0) { 11 | if (idx1 >= 0) { 12 | carry += num1.charAt(idx1--) - '0'; 13 | } 14 | if (idx2 >= 0) { 15 | carry += num2.charAt(idx2--) - '0'; 16 | } 17 | 18 | sb.append(carry % 10); 19 | carry = carry / 10; 20 | } 21 | 22 | if (carry > 0) { 23 | sb.append(carry); 24 | } 25 | 26 | return sb.reverse().toString(); 27 | } 28 | } -------------------------------------------------------------------------------- /45. Jump Game II.java: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/jump-game-ii/ 2 | 3 | // 属于greedy method问题。 4 | // 1)corner cases: 如果只有一个元素,那么就不用跳了,直接返回0 5 | // 2)维护3个变量:farthest,表示从当前位置能跳到的最远位置;currEnd,表示上一跳的最远位置,当超过了这个位置, 6 | // 一定会触发下一次跳跃;jump,表示跳的步数。 7 | // 3)遍历数组时,不断更新farthest。 8 | // 注意:数组遍历的范围是[0:nums.length - 2],【不需要到最后一个数】。 9 | // 4)如果当前位置到达了currEnd,表示这一跳必须结束,下一跳一定触发,所以更新jump,同时currEnd更新为farthest。 10 | 11 | class Solution { 12 | public int jump(int[] nums) { 13 | if (nums == null || nums.length < 2) return 0; 14 | int farthest = -1, currEnd = 0, jump = 0; 15 | for (int i = 0; i < nums.length - 1; i++) { // Attention 16 | farthest = Math.max(farthest, nums[i] + i); 17 | if (i == currEnd) { 18 | jump++; 19 | currEnd = farthest; 20 | } 21 | } 22 | return jump; 23 | } 24 | } -------------------------------------------------------------------------------- /453. Minimum Moves to Equal Array Elements.java: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/minimum-moves-to-equal-array-elements/ 2 | 3 | // 思路:数学问题,找规律。 4 | // 将n-1个元素同时增加1,等价于将1个元素减少1。因此,问题转化为将所有元素按每一步某个元素减少1需要多少步, 5 | // 也就是简单的将每个元素都减少到全局最小元素min,然后所有步数相加。 6 | 7 | class Solution { 8 | public int minMoves(int[] nums) { 9 | int res = 0, min = Integer.MAX_VALUE; 10 | /* find min number in nums array */ 11 | for (int n: nums) { 12 | min = Math.min(min, n); 13 | } 14 | /* get sum - n * min */ 15 | for (int n: nums) { 16 | res += n - min; 17 | } 18 | return res; 19 | } 20 | } -------------------------------------------------------------------------------- /455. Assign Cookies.java: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/assign-cookies/ 2 | 3 | // 思路:Greedy + Sort 4 | // 将小孩和饼干先排序,依次把能满足第i个小孩的饼干给小孩,直到搜索完所有饼干。 5 | // 时间复杂度:O(n log n) 6 | // 空间复杂度:O(1) 7 | 8 | class Solution { 9 | public int findContentChildren(int[] g, int[] s) { 10 | Arrays.sort(g); 11 | Arrays.sort(s); 12 | int res = 0; 13 | int i = 0, j = 0; 14 | while (i < g.length && j < s.length) { 15 | if (g[i] <= s[j]) { 16 | res++; 17 | i++; 18 | } 19 | j++; 20 | } 21 | return res; 22 | } 23 | } -------------------------------------------------------------------------------- /461. Hamming Distance.java: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/hamming-distance/submissions/ 2 | 3 | // 思路:Bit Manipulation。题目已经给出明显提示,要进行bit的操作。 4 | // 首先,利用xor得到所有差异的bit。然后,不断利用x & (x - 1)消除最后一个1bit,同时dist++。最后返回dist。 5 | 6 | class Solution { 7 | public int hammingDistance(int x, int y) { 8 | x = x ^ y; 9 | int dist = 0; 10 | while (x != 0) { 11 | dist++; 12 | x = x & (x - 1); 13 | } 14 | return dist; 15 | } 16 | } 17 | 18 | // 代码简化:利用内置函数Integer.bitCount() 19 | 20 | class Solution { 21 | public int hammingDistance(int x, int y) { 22 | return Integer.bitCount(x ^ y); 23 | } 24 | } -------------------------------------------------------------------------------- /470. Implement Rand10() Using Rand7().java: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/implement-rand10-using-rand7/ 2 | 3 | // 思路:Rejection sampling 4 | // 两次调用rand7()后,会出现49种排列结果。只需要利用前40个结果,再转化为[1:10]。因为这40个结果每一个值的概率相同, 5 | // 所以最后可以以相同的概率得到[1:10]的某一个数。如果得到的是[41:49],那么重新调用rand7()。 6 | // 犯错点:1.第一次rand7()和第二次rand7()的结果分别作为行号和列号,得到对应的一维[1:49]的值,而不是直接相乘。 7 | 8 | class Solution extends SolBase { 9 | public int rand10() { 10 | int temp = 0, first = rand7(); 11 | while (temp <= 0 || temp > 40) { 12 | int second = rand7(); 13 | //temp = first * second; // {Mistake 1} 14 | temp = (first - 1) * 7 + second; // {Correction 1} 15 | first = second; 16 | } 17 | 18 | return temp % 10 + 1; 19 | } 20 | } -------------------------------------------------------------------------------- /476. Number Complement.java: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/number-complement/ 2 | 3 | // 思路:Bit Manipulation 4 | // 先求出num二进制中最高位1的位置,对于从这个位置开始到最右边所有位置都填上1,记为sum,实际上sum就是num和题目 5 | // 要求的complement number做异或后的结果。同样,用sum和num做异或,也可以得到题目要求的complement number。 6 | // 注意:题目规定了num为正数,因此不需要对num==0特殊讨论。 7 | 8 | class Solution { 9 | public int findComplement(int num) { 10 | int sum = 0, temp = num; 11 | int i = 0; 12 | while (temp != 0) { 13 | sum |= (1 << i); 14 | i++; 15 | temp = temp >> 1; 16 | } 17 | return sum ^ num; 18 | } 19 | } 20 | 21 | 另一种写法: 22 | public int findComplement(int num) { 23 | int highestOneBit = Integer.highestOneBit(num); 24 | return num ^ (highestOneBit | highestOneBit - 1); 25 | } 26 | 27 | 代码简化:见https://leetcode.com/problems/number-complement/discuss/95992/Java-1-line-bit-manipulation-solution -------------------------------------------------------------------------------- /478. Generate Random Point in a Circle.java: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/generate-random-point-in-a-circle/ 2 | 3 | // 思路:几何题。利用极坐标系。详见https://leetcode.com/problems/generate-random-point-in-a-circle/discuss/154037/Polar-Coordinates-10-lines 4 | 5 | class Solution { 6 | double radius, xCenter, yCenter; 7 | Random rand; 8 | 9 | public Solution(double radius, double x_center, double y_center) { 10 | this.radius = radius; 11 | xCenter = x_center; 12 | yCenter = y_center; 13 | rand = new Random(); 14 | } 15 | 16 | public double[] randPoint() { 17 | double degree = rand.nextDouble() * 2 * Math.PI; 18 | double len = Math.sqrt(rand.nextDouble()) * radius; 19 | double x = xCenter + len * Math.cos(degree); 20 | double y = yCenter + len * Math.sin(degree); 21 | return new double[]{x, y}; 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /485. Max Consecutive Ones.java: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/max-consecutive-ones/ 2 | 3 | // 思路:常规遍历,取最大值 4 | // 时间复杂度:O(n) 5 | // 空间复杂度:O(1) 6 | // 犯错点:1.细节错误:要取count的最大值,记录在maxCount,而不是取最后的count 7 | 8 | class Solution { 9 | public int findMaxConsecutiveOnes(int[] nums) { 10 | int count = 0, maxCount = 0; 11 | for (int n: nums) { 12 | count = n == 1 ? count + 1 : 0; 13 | maxCount = Math.max(maxCount, count); 14 | } 15 | return maxCount; 16 | } 17 | } -------------------------------------------------------------------------------- /49. Group Anagrams.java: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/group-anagrams/ 2 | 3 | // 1)维护一个Map,key为每个string字符排序后作为anagram group representative,value为属于这个group的所有string 4 | // 2)遍历String数组,先转换成char array,排序,再转换成String,判断是否在Map中 5 | 6 | class Solution { 7 | public List> groupAnagrams(String[] strs) { 8 | List> resultList = new ArrayList<>(); 9 | Map> map = new HashMap<>(); 10 | for (String s: strs) { 11 | char[] charArray = s.toCharArray(); 12 | Arrays.sort(charArray); 13 | String sorted = new String(charArray); 14 | if (!map.containsKey(sorted)) map.put(sorted, new ArrayList()); 15 | map.get(sorted).add(s); 16 | } 17 | 18 | for(List value: map.values()) resultList.add(value); 19 | return resultList; 20 | } 21 | } -------------------------------------------------------------------------------- /492. Construct the Rectangle.java: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/construct-the-rectangle/ 2 | 3 | // 思路:Math,观察规律。 4 | // 根据题意可以发现,将area的平方根取整,这个数再求平方会小于等于area。这个数不适合做length, 5 | // 但是【可以做width】。 6 | // 接下来找到一个length,使得length * width == area且length >= width。因此只需要将width 7 | // 逐渐递减找到第一个area % width == 0即可。 8 | // 时间复杂度:O(sqrt(n)) 9 | // 空间复杂度:O(1) 10 | 11 | class Solution { 12 | public int[] constructRectangle(int area) { 13 | int width = (int) Math.sqrt(area); 14 | while (area % width != 0) { 15 | width--; 16 | } 17 | 18 | return new int[]{area / width, width}; 19 | } 20 | } -------------------------------------------------------------------------------- /504. Base 7.java: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/base-7/ 2 | 3 | // 思路:进制转换 4 | // 模版背下来! 5 | // 时间复杂度:O(log n) 6 | // 空间复杂度:O(log n) 7 | // 犯错点:1.公式错误:先得到的是位数低的数,所以最后要翻转。 8 | // 2.边界条件错误:num == 0时,循环不被执行,最后返回空字符串"",造成错误。因此num == 0单独讨论。 9 | 10 | class Solution { 11 | public String convertToBase7(int num) { 12 | if (num == 0) return "0"; 13 | 14 | int sign = num < 0 ? -1 : 1; 15 | StringBuilder sb = new StringBuilder(); 16 | num = (int) Math.abs(num); 17 | while (num > 0) { 18 | sb.append(num % 7); 19 | num /= 7; 20 | } 21 | 22 | if (sign < 0) { 23 | sb.append('-'); 24 | } 25 | return sb.reverse().toString(); 26 | } 27 | } -------------------------------------------------------------------------------- /507. Perfect Number.java: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/perfect-number/ 2 | 3 | // 暴力解法:从i=1遍历到i=num,这样会造成重复计算 4 | 5 | // 优化解法:从i=1遍历到i=sqrt(num) 6 | // 当i能被num整除,那么另一个数num / i也能被num整除。要排除掉i == num / i即i * i == num的情况。 7 | // 注意点:当i==1时,num / i结果是num本身,会被加进sum里,根据题目要求,要把num本身从sum中排除,所以最后判断的是sum - num == num 8 | 9 | class Solution { 10 | public boolean checkPerfectNumber(int num) { 11 | if (num <= 0) return false; 12 | int sum = 0; 13 | for (int i = 1; i * i <= num; i++) { 14 | if (num % i != 0) continue; 15 | sum += i; 16 | if (i * i != num) { 17 | sum += num / i; 18 | } 19 | } 20 | 21 | return sum - num == num; 22 | } 23 | } -------------------------------------------------------------------------------- /509. Fibonacci Number.java: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/fibonacci-number/ 2 | 3 | // 思路:套用递推公式即可。 4 | 5 | class Solution { 6 | public int fib(int N) { 7 | if (N == 0) return 0; 8 | 9 | int[] dp = new int[N + 1]; 10 | dp[0] = 0; 11 | dp[1] = 1; 12 | for (int i = 2; i <= N; i++) { 13 | dp[i] = dp[i - 1] + dp[i - 2]; 14 | } 15 | return dp[N]; 16 | } 17 | } -------------------------------------------------------------------------------- /510. Inorder Successor in BST II.java: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/inorder-successor-in-bst-ii/ 2 | 3 | 思路:先从子树找successor,即右子树的最左边节点; 4 | 再从parent找successor,找到某个parent使得当前节点在该parent节点的左子树。 5 | 时间复杂度:O(n) 6 | 空间复杂度:O(1) 7 | 8 | class Solution { 9 | public Node inorderSuccessor(Node node) { 10 | if (node == null) return null; 11 | 12 | if (node.right != null) { 13 | Node suc = node.right; 14 | while (suc.left != null) { 15 | suc = suc.left; 16 | } 17 | return suc; 18 | } 19 | 20 | while (node.parent != null && node == node.parent.right) { 21 | node = node.parent; 22 | } 23 | 24 | return node.parent; 25 | } 26 | } -------------------------------------------------------------------------------- /521. Longest Uncommon Subsequence I.java: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/longest-uncommon-subsequence-i/ 2 | 3 | // 关键点:要理解题目的意思。 4 | // 如果两个字符串相同,那么不存在只出现一次的子串,所以返回-1。 5 | // 否则,只要取长度较长的字符串,以整个字符串为最大子串,那么这个子串一定只出现一次。即使两个字符串长度相等, 6 | // 因为它们有不相同的字符,所以取任意一个字符串都可以。 7 | 8 | class Solution { 9 | public int findLUSlength(String a, String b) { 10 | if (a.equals(b)) return -1; 11 | 12 | return Math.max(a.length(), b.length()); 13 | } 14 | } -------------------------------------------------------------------------------- /535. Encode and Decode TinyURL.java: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/encode-and-decode-tinyurl/ 2 | 3 | // 思路:HashMap 4 | // 关键:理解题意,将input的longUrl变成任意tinyurl,还能解码成原来的input的longUrl。因此,可以直接用例子中的"http://tinyurl.com/" 5 | // 加上数字id作为唯一标识存在Map里,解码时拿出和这个标识对应的longUrl。 6 | // 因为这题是stateful的,所以可以用Map来存储。 7 | 8 | public class Codec { 9 | int id = 0; 10 | Map map = new HashMap(); 11 | 12 | // Encodes a URL to a shortened URL. 13 | public String encode(String longUrl) { 14 | String shortUrl = "http://tinyurl.com/" + id++; 15 | map.put(shortUrl, longUrl); 16 | return shortUrl; 17 | } 18 | 19 | // Decodes a shortened URL to its original URL. 20 | public String decode(String shortUrl) { 21 | return map.containsKey(shortUrl) ? map.get(shortUrl) : ""; 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /537. Complex Number Multiplication.java: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/complex-number-multiplication/ 2 | 3 | // 思路:考察数学。 4 | // 因为题目规定了input和output都要带有x+yi中的x,加号,y,和i,因此只需要把input中的实数和虚数分别取出, 5 | // 然后进行简单的相乘和相加(注意i*i=-1),最后变成字符串即可。 6 | 7 | class Solution { 8 | public String complexNumberMultiply(String a, String b) { 9 | String[] aSplit = a.split("\\+|i"), bSplit = b.split("\\+|i"); 10 | int aReal = Integer.parseInt(aSplit[0]), aImag = Integer.parseInt(aSplit[1]); 11 | int bReal = Integer.parseInt(bSplit[0]), bImag = Integer.parseInt(bSplit[1]); 12 | return (aReal * bReal - aImag * bImag) + "+" + (aReal * bImag + bReal * aImag) + "i"; 13 | } 14 | } -------------------------------------------------------------------------------- /538. Convert BST to Greater Tree.java: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/convert-bst-to-greater-tree/ 2 | 3 | // 解法一:Recursion + DFS 4 | // 【翻转的inorder traversal】,先遍历右子树,将全局变量sum更新,此时sum和所有右子树节点有关。 5 | // 利用sum更新root.val,然后再更新sum。 6 | // 然后遍历左子树。 7 | 8 | class Solution { 9 | int sum = 0; // global variable 10 | 11 | public TreeNode convertBST(TreeNode root) { 12 | convert(root); 13 | return root; 14 | } 15 | 16 | private void convert(TreeNode root) { 17 | if (root == null) return; 18 | 19 | convert(root.right); 20 | root.val += sum; 21 | sum = root.val; 22 | convert(root.left); 23 | } 24 | } 25 | 26 | 27 | 解法二:Iteration with Stack 28 | 29 | 30 | 解法三:Morris Traversal -------------------------------------------------------------------------------- /539. Minimum Time Difference.java: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/minimum-time-difference/ 2 | 3 | // 思路:Sort 4 | // 先同一转换成分钟,然后直接排序,遍历求最小间隔。最后一个数和第一个数的间隔要特殊处理。 5 | 6 | class Solution { 7 | public int findMinDifference(List timePoints) { 8 | List list = new ArrayList(); 9 | for (String str: timePoints) { 10 | String[] split = str.split(":"); 11 | int time = 60 * Integer.valueOf(split[0]) + Integer.valueOf(split[1]); 12 | list.add(time); 13 | } 14 | Collections.sort(list); 15 | int minDiff = Integer.MAX_VALUE; 16 | for (int i = 1; i < list.size(); i++) { 17 | minDiff = Math.min(minDiff, list.get(i) - list.get(i - 1)); 18 | } 19 | minDiff = Math.min(minDiff, list.get(0) + 24 * 60 - list.get(list.size() - 1)); 20 | return minDiff; 21 | } 22 | } -------------------------------------------------------------------------------- /541. Reverse String II.java: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/reverse-string-ii/ 2 | 3 | // 思路:Two pointers。 4 | // 每次处理2*k个数,但只将前k个数进行翻转,然后处理下一批数。 5 | // 犯错点:1.如果循环中直接移动left指针,那么在更新判断条件left += 2 * k的时候并不能更新成想要的结果。 6 | 7 | class Solution { 8 | public String reverseStr(String s, int k) { 9 | char[] sArray = s.toCharArray(); 10 | 11 | //for (int left = 0; left < sArray.length; left += 2 * k) { // {Mistake 1} 12 | for (int start = 0; start < sArray.length; start += 2 * k) { // {Correction 1} 13 | // {Mistake 1} 14 | int left = start; // {Correction 1} 15 | int right = Math.min(sArray.length - 1, left + k - 1); 16 | swap(sArray, left++, right--); 17 | } 18 | return new String(sArray); 19 | } 20 | private void swap(char[] s, int i, int j) { 21 | char temp = s[i]; 22 | s[i] = s[j]; 23 | s[j] = temp; 24 | } 25 | } -------------------------------------------------------------------------------- /553. Optimal Division.java: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/optimal-division/ 2 | 3 | // 思路:数学问题。详见https://leetcode.com/problems/optimal-division/solution/ 4 | // 只需要将括号把从第二个数开始到最后一个数的整个范围括起来,最后得到的结果就是最大的。 5 | 6 | class Solution { 7 | public String optimalDivision(int[] nums) { 8 | /* corner cases */ 9 | if (nums.length == 0) return ""; 10 | if (nums.length == 1) return nums[0] + ""; 11 | if (nums.length == 2) return nums[0] + "/" + nums[1]; 12 | 13 | StringBuilder sb = new StringBuilder(); 14 | for (int i = 1; i < nums.length; i++) { 15 | sb.append('/').append(nums[i]); 16 | } 17 | sb.append(')'); 18 | sb.insert(1, '('); 19 | sb.insert(0, nums[0]); 20 | return sb.toString(); 21 | } 22 | } -------------------------------------------------------------------------------- /557. Reverse Words in a String III.java: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/reverse-words-in-a-string-iii/ 2 | 3 | // 思路:考察对Java中String和StringBuilder的使用。 4 | 5 | class Solution { 6 | public String reverseWords(String s) { 7 | String[] split = s.trim().split("\\s+"); 8 | StringBuilder res = new StringBuilder(); 9 | for (String str: split) { 10 | StringBuilder sb = new StringBuilder(str); 11 | res.append(sb.reverse().toString()).append(" "); 12 | } 13 | 14 | return res.toString().trim(); 15 | } 16 | } -------------------------------------------------------------------------------- /561. Array Partition I.java: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/array-partition-i/ 2 | 3 | // 思路:找规律。 4 | // 因为需要组成pair,同时使得所有pair的较小数的加和最大,那么就需要使得每个pair的较小数都要比较大,换言之 5 | // 和它配对的大值要比较小。对于所有数中的最小值min,最合适配对的就是剩下的数当中的最小值。以此类推,可知就是 6 | // 将nums数组排序,然后相邻元素两两配对,求所有较小值的和。 7 | 8 | class Solution { 9 | public int arrayPairSum(int[] nums) { 10 | Arrays.sort(nums); 11 | int res = 0; 12 | for (int i = 0; i < nums.length; i += 2) { 13 | res += nums[i]; 14 | } 15 | return res; 16 | } 17 | } -------------------------------------------------------------------------------- /573. Squirrel Simulation.java: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/squirrel-simulation/ 2 | 3 | idea: Math 4 | time complexity: O(n) 5 | space complexity: O(1) 6 | 7 | class Solution { 8 | public int getDistance(int[] pos1, int[] pos2) { 9 | return Math.abs(pos1[0] - pos2[0]) + Math.abs(pos1[1] - pos2[1]); 10 | } 11 | 12 | public int minDistance(int height, int width, int[] tree, int[] squirrel, int[][] nuts) { 13 | int minDist = Integer.MAX_VALUE; 14 | int totalDist = 0; 15 | for (int[] nut : nuts) { 16 | totalDist += 2 * getDistance(nut, tree); 17 | } 18 | 19 | for (int[] nut : nuts) { 20 | int dist = totalDist - getDistance(nut, tree) + getDistance(nut, squirrel); 21 | minDist = Math.min(minDist, dist); 22 | } 23 | 24 | return minDist; 25 | } 26 | } -------------------------------------------------------------------------------- /575. Distribute Candies.java: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/distribute-candies/ 2 | 3 | // 关键:理解题目意思,将不同种类糖果(数字表示其种类)平均分成两份,其中一份种类最多,求种类最多的那一份中的种类数。 4 | // 思路:去重复,得到unique number的个数,并和candies.length / 2比较。因为每一份的糖果数都是candies.length / 2, 5 | // 因此如果unique number的个数大于等于candies.length / 2,也只能取candies.length / 2;如果小于,就直接 6 | // 取unique number的个数。 7 | 8 | // 解法一:Sort 9 | 10 | // 解法二:HashSet 11 | 12 | class Solution { 13 | public int distributeCandies(int[] candies) { 14 | Set set = new HashSet(); 15 | for (int n: candies) { 16 | set.add(n); 17 | } 18 | return set.size() >= candies.length / 2 ? candies.length / 2 : set.size(); 19 | } 20 | } -------------------------------------------------------------------------------- /58. Length of Last Word.java: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/length-of-last-word/ 2 | 3 | class Solution { 4 | public int lengthOfLastWord(String s) { 5 | if (s == null || s.length() == 0) return 0; 6 | 7 | int count = 0; // return value 8 | 9 | for (int i = s.length() - 1; i >= 0; i--) { 10 | if (!Character.isLetter(s.charAt(i))) continue; // skip the last couple chars if not letters 11 | 12 | while (i >= 0 && Character.isLetter(s.charAt(i))) { // enter while loop when the last letter is found 13 | count++; 14 | i--; // update i 15 | } 16 | 17 | break; // when exit the while loop, exit the for loop as well 18 | } 19 | return count; 20 | } 21 | } -------------------------------------------------------------------------------- /589. N-ary Tree Preorder Traversal.java: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/n-ary-tree-preorder-traversal/ 2 | 3 | // 解法一:Recursion 4 | // 类似Binary Tree的模版。 5 | 6 | class Solution { 7 | List res = new ArrayList(); 8 | 9 | public List preorder(Node root) { 10 | traverse(root); 11 | return res; 12 | } 13 | 14 | private void traverse(Node root) { 15 | if (root == null) return; 16 | 17 | res.add(root.val); 18 | for (Node child: root.children) { 19 | traverse(child); 20 | } 21 | } 22 | } 23 | 24 | 25 | 解法二:Iteration with Stack 26 | 详见:https://leetcode.com/problems/n-ary-tree-preorder-traversal/discuss/147955/Java-Iterative-and-Recursive-Solutions -------------------------------------------------------------------------------- /590. N-ary Tree Postorder Traversal.java: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/n-ary-tree-postorder-traversal/submissions/ 2 | 3 | // 解法一:Recursion 4 | // 类似Binary Tree的模版。 5 | 6 | class Solution { 7 | List res = new ArrayList(); 8 | 9 | public List postorder(Node root) { 10 | traverse(root); 11 | return res; 12 | } 13 | 14 | private void traverse(Node root) { 15 | if (root == null) return; 16 | 17 | for (Node child: root.children) { 18 | traverse(child); 19 | } 20 | res.add(root.val); 21 | } 22 | } 23 | 24 | 25 | 解法二:Iteration with two Stacks 26 | 详见:https://leetcode.com/problems/n-ary-tree-postorder-traversal/discuss/174665/Java-Iterative-Solution-Using-Two-Stacks. -------------------------------------------------------------------------------- /605. Can Place Flowers.java: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/can-place-flowers/solution/ 2 | 3 | 思路:Greedy 4 | 从左往右扫描,在可以种的地方都种上花。 5 | 时间复杂度:O(n) 6 | 空间复杂度:O(1) 7 | 8 | class Solution { 9 | public boolean canPlaceFlowers(int[] flowerbed, int n) { 10 | int len = flowerbed.length; 11 | for (int i = 0; i < len; i++) { 12 | if (flowerbed[i] == 1) continue; 13 | if (i > 0 && flowerbed[i - 1] == 1) continue; 14 | if (i + 1 < len && flowerbed[i + 1] == 1) continue; 15 | 16 | n--; 17 | flowerbed[i] = 1; 18 | if (n <= 0) { 19 | return true; 20 | } 21 | } 22 | 23 | return n == 0; 24 | } 25 | } -------------------------------------------------------------------------------- /617. Merge Two Binary Trees.java: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/merge-two-binary-trees/ 2 | 3 | solution: DFS 4 | time comp: O(n) 5 | space comp: O(h), h=height 6 | 7 | class Solution { 8 | public TreeNode mergeTrees(TreeNode root1, TreeNode root2) { 9 | if (root1 == null) { 10 | return root2; 11 | } 12 | if (root2 == null) { 13 | return root1; 14 | } 15 | 16 | TreeNode node = new TreeNode(root1.val + root2.val); 17 | node.left = mergeTrees(root1.left, root2.left); 18 | node.right = mergeTrees(root1.right, root2.right); 19 | 20 | return node; 21 | } 22 | } -------------------------------------------------------------------------------- /62. Unique Paths.java: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/unique-paths/ 2 | 3 | // 总体思路:求total counting number,可以用DP解决。 4 | // 状态函数:dp[i]表示到达当前行第i列(0-based)的unique path数量 5 | // 状态转移方程:在row!=0且col!=0的一般情况下,当前格子[row,col]可以从上面一格[row-1,col]或左边一格[row,col-1]走到,所以unique path数量 6 | // 为上面一格和左边一格unique path数量的总和。 7 | // 初始值:col==0时dp[0]=1,row==0时dp[col]=1 8 | // 时间复杂度:O(m*n) 9 | // 空间复杂度:O(m*n) -> O(n) 10 | 11 | class Solution { 12 | public int uniquePaths(int m, int n) { 13 | int[] dp = new int[n]; 14 | for (int row = 0; row < m; row++) { 15 | dp[0] = 1; 16 | for (int col = 1; col < n; col++) { 17 | if (row == 0) dp[col] = 1; 18 | else dp[col] += dp[col - 1]; 19 | } 20 | } 21 | return dp[n - 1]; 22 | } 23 | } -------------------------------------------------------------------------------- /628. Maximum Product of Three Numbers.java: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/maximum-product-of-three-numbers/ 2 | 3 | // 解法一:Brute Force 4 | // 时间复杂度:O(n^3) 5 | // 空间复杂度:O(1) 6 | 7 | 8 | // 解法二:Sort + Math 9 | // 直接排序(不需要转绝对值),最大乘积必然出现在最大的三个数,或最大的一个数乘以最小的 10 | // 两个数(因为可能是负数)。 11 | // 时间复杂度:O(n log n) 12 | // 空间复杂度:O(n) 13 | 14 | class Solution { 15 | public int maximumProduct(int[] nums) { 16 | Arrays.sort(nums); 17 | int n = nums.length; 18 | return Math.max(nums[0] * nums[1] * nums[n - 1], 19 | nums[n - 3] * nums[n - 2] * nums[n - 1]); 20 | } 21 | } -------------------------------------------------------------------------------- /633. Sum of Square Numbers.java: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/sum-of-square-numbers/ 2 | 3 | // 思路:先确定其中一个加数为平方数,判断另外一个数能否开平方为整数。 4 | // 时间复杂度:O(sqrt(n) * log(n)) 5 | // 空间复杂度:O(1) 6 | // 犯错点:1.条件判断i * i <= c / 2要取等,否则会漏掉c = 0和c = 1。事实上,除以2是不必要的。 7 | // 2.Math.sqrt()返回double,要强制转换为int 8 | 9 | class Solution { 10 | public boolean judgeSquareSum(int c) { 11 | //for (int i = 0; i * i < c / 2; i++) // {Mistake 1: it skips c = 0 and c = 1} 12 | for (int i = 0; i * i <= c / 2; i++) { // {Correction 1} 13 | int remain = c - i * i; 14 | //int sqrt = Math.sqrt(remain); // {Mistake 2: Math.sqrt() returns a double} 15 | int sqrt = (int) Math.sqrt(remain); // {Correction 2} 16 | if (sqrt * sqrt == remain) return true; 17 | } 18 | return false; 19 | } 20 | } -------------------------------------------------------------------------------- /643. Maximum Average Subarray I.java: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/maximum-average-subarray-i/ 2 | 3 | idea: Sliding Window 4 | time complexity: O(n) 5 | space complexity: O(1) 6 | 7 | class Solution { 8 | public double findMaxAverage(int[] nums, int k) { 9 | int sum = 0, maxSum = Integer.MIN_VALUE; 10 | for (int i = 0; i < nums.length; i++) { 11 | sum += nums[i]; 12 | if (i + 1 - k >= 0) { 13 | maxSum = Math.max(maxSum, sum); 14 | sum -= nums[i + 1 - k]; 15 | } 16 | } 17 | 18 | return ((double) maxSum) / k; 19 | } 20 | } -------------------------------------------------------------------------------- /645. Set Mismatch.java: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/set-mismatch/ 2 | 3 | // 思路:Find Missing/Duplicate Number类型题模版。 4 | // 时间复杂度:O(n)? 5 | // 空间复杂度:O(1) 6 | 7 | class Solution { 8 | public int[] findErrorNums(int[] nums) { 9 | int[] res = new int[2]; 10 | for (int i = 0; i < nums.length; i++) { 11 | while (nums[i] != nums[nums[i] - 1]) { 12 | swap(nums, i, nums[i] - 1); 13 | } 14 | 15 | if (nums[i] != i + 1) { 16 | res[0] = nums[i]; 17 | res[1] = i + 1; 18 | } 19 | } 20 | 21 | return res; 22 | } 23 | 24 | private void swap(int[] nums, int i, int j) { 25 | int temp = nums[i]; 26 | nums[i] = nums[j]; 27 | nums[j] = temp; 28 | } 29 | } -------------------------------------------------------------------------------- /646. Maximum Length of Pair Chain.java: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/maximum-length-of-pair-chain/ 2 | 3 | idea: DP. Similar to 300. Longest Increasing Subsequence 4 | time complexity: O(n^2) 5 | space complexity: O(n) 6 | 7 | class Solution { 8 | public int findLongestChain(int[][] pairs) { 9 | Arrays.sort(pairs, (a, b) -> a[0] == b[0] ? a[1] - b[1] : a[0] - b[0]); // first by [0] then by [1] 10 | int n = pairs.length; 11 | int[] dp = new int[n]; 12 | int maxLen = 0; 13 | for (int i = 0; i < n; i++) { 14 | dp[i] = 1; 15 | for (int j = i - 1; j >= 0; j--) { 16 | if (pairs[j][1] < pairs[i][0]) { 17 | dp[i] = Math.max(dp[i], dp[j] + 1); 18 | } 19 | } 20 | maxLen = Math.max(maxLen, dp[i]); 21 | } 22 | 23 | return maxLen; 24 | } 25 | } -------------------------------------------------------------------------------- /650. 2 Keys Keyboard.java: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/2-keys-keyboard/ 2 | 3 | idea: DP 4 | time complexity: O(n*sqrt(n)) 5 | space complexity: O(n) 6 | 7 | class Solution { 8 | public int minSteps(int n) { 9 | if (n == 1) { 10 | return 0; 11 | } 12 | int[] dp = new int[n+1]; 13 | for (int i = 2; i <= n; i++) { 14 | dp[i] = i; 15 | for (int step = 2; step * step <= n; step++) { 16 | int prev = i / step; 17 | if (step * prev == i) { 18 | dp[i] = Math.min(dp[i], dp[prev] + step); 19 | } 20 | } 21 | } 22 | 23 | return dp[n]; 24 | } 25 | } -------------------------------------------------------------------------------- /651. 4 Keys Keyboard.java: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/4-keys-keyboard/ 2 | 3 | idea: DP. Refer to: https://leetcode.com/problems/4-keys-keyboard/discuss/105980/Java-4-lines-recursion-with-step-by-step-explanation-to-derive-DP 4 | time complexity: O(n^2) 5 | space complexity: O(n) 6 | 7 | class Solution { 8 | public int maxA(int N) { 9 | int[] dp = new int[N+1]; 10 | for (int i = 1; i <= N; i++) { 11 | dp[i] = i; 12 | for (int j = 1; j <= i - 3; j++) { 13 | dp[i] = Math.max(dp[i], dp[j] * (i - j - 1)); 14 | } 15 | } 16 | 17 | return dp[N]; 18 | } 19 | } -------------------------------------------------------------------------------- /657. Robot Return to Origin.java: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/robot-return-to-origin/ 2 | 3 | // 思路:统计各字符出现次数。 4 | // 时间复杂度:O(n) 5 | // 空间复杂度:O(1) 6 | 7 | class Solution { 8 | public boolean judgeCircle(String moves) { 9 | int verticalCount = 0, horizontalCount = 0; 10 | for (char c : moves.toCharArray()) { 11 | switch (c) { 12 | case 'L': 13 | horizontalCount--; 14 | break; 15 | case 'R': 16 | horizontalCount++; 17 | break; 18 | case 'U': 19 | verticalCount--; 20 | break; 21 | case 'D': 22 | verticalCount++; 23 | break; 24 | } 25 | } 26 | 27 | return verticalCount == 0 && horizontalCount == 0; 28 | } 29 | } -------------------------------------------------------------------------------- /67. Add Binary.java: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/add-binary/ 2 | 3 | // 两个数(或数组)相加的模板。 4 | 5 | class Solution { 6 | public String addBinary(String a, String b) { 7 | char[] aArray = a.toCharArray(), bArray = b.toCharArray(); 8 | int i = a.length() - 1, j = b.length() - 1; 9 | StringBuilder sb = new StringBuilder(); 10 | int carry = 0; 11 | while (i >= 0 || j >= 0) { 12 | int sum = carry; 13 | if (i >= 0) sum += aArray[i--] - '0'; 14 | if (j >= 0) sum += bArray[j--] - '0'; 15 | sb.insert(0, sum % 2); 16 | carry = sum / 2; 17 | } 18 | if (carry != 0) sb.insert(0, carry); 19 | return sb.toString(); 20 | } 21 | } -------------------------------------------------------------------------------- /674. Longest Continuous Increasing Subsequence.java: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/longest-continuous-increasing-subsequence/ 2 | 3 | // 思路:常规遍历,维护变量:len,记录以nums[i]结尾的subarray长度;maxLen,全局最长长度。 4 | // 时间复杂度:O(n) 5 | // 空间复杂度:O(1) 6 | 7 | class Solution { 8 | public int findLengthOfLCIS(int[] nums) { 9 | int len = 0, maxLen = 0; 10 | for (int i = 0; i < nums.length; i++) { 11 | len = i > 0 && nums[i] > nums[i - 1] ? len + 1 : 1; 12 | maxLen = Math.max(maxLen, len); 13 | } 14 | 15 | return maxLen; 16 | } 17 | } -------------------------------------------------------------------------------- /678. Valid Parenthesis String.java: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/valid-parenthesis-string/ 2 | 3 | 解法一:Greedy。参考:https://www.youtube.com/watch?v=h9Y3i7hhCpo 4 | 5 | 时间复杂度:O(n) 6 | 空间复杂度:O(1) 7 | 8 | class Solution { 9 | public boolean checkValidString(String s) { 10 | int low = 0, high = 0; 11 | for (char c : s.toCharArray()) { 12 | low += c == '(' ? 1 : -1; 13 | high += c == ')' ? -1 : 1; 14 | if (high < 0) { 15 | return false; 16 | } 17 | 18 | low = Math.max(0, low); 19 | } 20 | 21 | return low == 0; 22 | } 23 | } 24 | 25 | 26 | 解法二:DP。参考:https://www.youtube.com/watch?v=h9Y3i7hhCpo 27 | 时间复杂度:O(n^3) 28 | 空间复杂度:O(n^2) -------------------------------------------------------------------------------- /69. Sqrt(x).java: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/sqrtx/ 2 | 3 | // 解法一:牛顿法,背公式 4 | 5 | class Solution { 6 | public int mySqrt(int x) { 7 | long sqrt = x; 8 | while (sqrt * sqrt > x) { 9 | sqrt = (sqrt + x / sqrt) / 2; 10 | } 11 | return (int) sqrt; 12 | } 13 | } 14 | 15 | 16 | // 解法二:二分法 17 | 18 | class Solution { 19 | public int mySqrt(int x) { 20 | long low = 0, high = x; 21 | while (low <= high) { 22 | long mid = (low + high) / 2; 23 | if (mid * mid <= x && ((mid + 1) * (mid + 1) > x)) return (int) mid; 24 | else if (mid * mid > x || mid * mid > Integer.MAX_VALUE) high = mid - 1; 25 | else if ((mid + 1) * (mid + 1) <= x) low = mid + 1; 26 | } 27 | return -1; 28 | } 29 | } 30 | 31 | // 解法三:用内置的Math.sqrt() -------------------------------------------------------------------------------- /693. Binary Number with Alternating Bits.java: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/binary-number-with-alternating-bits/ 2 | 3 | idea: Bit Manipulation 4 | time complexity: O(log n) 5 | space complexity: O(1) 6 | 7 | class Solution { 8 | public boolean hasAlternatingBits(int n) { 9 | int bit = n & 1; 10 | while (n > 0) { 11 | if ((n & 1) != bit) { 12 | return false; 13 | } 14 | bit = 1 - bit; 15 | n = n >> 1; 16 | } 17 | return true; 18 | } 19 | } -------------------------------------------------------------------------------- /7. Reverse Integer.java: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/reverse-integer/ 2 | 3 | // 可以作为integer reversion的模板。 4 | // 1)corner cases:判断是否为0,是就直接返回 5 | // 2)记录sign,然后把x取绝对值。注意需要【转换成long】防止过界 6 | // 3)维护reverse,每次循环时,reverse先自乘10,然后加上当前copy的%10结果,作为reverse的更新,增加一位数。同时copy /= 10来减少最后的一位数。 7 | // 4)根据是否过界、sign的情况返回相应的值 8 | 9 | class Solution { 10 | public int reverse(int x) { 11 | if (x == 0) return 0; 12 | int sign = x > 0? 1 : -1; 13 | long reverse = 0, copy = Math.abs((long) x); 14 | while (copy > 0) { 15 | reverse = reverse * 10 + copy % 10; 16 | copy /= 10; 17 | } 18 | if (reverse > Integer.MAX_VALUE) return 0; 19 | return (int) (reverse * sign); 20 | } 21 | } -------------------------------------------------------------------------------- /70. Climbing Stairs.java: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/climbing-stairs/ 2 | 3 | // 总体思路:经典的DP题,本质上是Fibonacci数列。 4 | // 状态函数:dp[i]表示到第i级台阶(1-based)的所有可能方法数 5 | // 状态转移方程:走到第i级台阶有两种方式:要么从第i-1级台阶走一步,要么从第i-2级台阶走一步。所以能走到第i级台阶的方法数就是这两种可能的总和, 6 | // 即dp[i] = dp[i - 1] + dp[i - 2]; 7 | // 初始值:dp[0]=dp[1]=1,其中dp[0]没有实际意义。 8 | // 时间复杂度:O(n) 9 | // 空间复杂度:O(n) 10 | 11 | class Solution { 12 | public int climbStairs(int n) { 13 | int[] dp = new int[n + 1]; 14 | dp[0] = dp[1] = 1; 15 | for (int i = 2; i <= n; i++) { 16 | dp[i] = dp[i - 1] + dp[i - 2]; 17 | } 18 | return dp[n]; 19 | } 20 | } -------------------------------------------------------------------------------- /700. Search in a Binary Search Tree.java: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/search-in-a-binary-search-tree/ 2 | 3 | // 思路:Recursion (DFS),类似preorder traversal 4 | // 时间复杂度:O(n) 5 | // 空间复杂度:O(depth) or O(n) 6 | 7 | class Solution { 8 | public TreeNode searchBST(TreeNode root, int val) { 9 | return dfs(root, val); 10 | } 11 | 12 | private TreeNode dfs(TreeNode node, int target) { 13 | if (node == null) { 14 | return null; 15 | } 16 | 17 | if (node.val != target) { 18 | return node.val > target ? dfs(node.left, target) : dfs(node.right, target); 19 | } 20 | 21 | return node; 22 | } 23 | } 24 | 25 | 26 | 解法二:Iteration with Stack 27 | 28 | 29 | 解法三:Morris Traversal -------------------------------------------------------------------------------- /703. Kth Largest Element in a Stream.java: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/kth-largest-element-in-a-stream/ 2 | 3 | // Intuition:Insertion Sort 4 | 5 | // 优化思路:PriorityQueue 6 | // 维护size为k的minHeap,意味着当前有k-1个元素比minHeap顶部元素大,所以顶部元素就是第k大元素。 7 | // 时间复杂度:add(): O(log k) 8 | // 空间复杂度:O(k) 9 | 10 | class KthLargest { 11 | PriorityQueue pq; 12 | int k; 13 | 14 | public KthLargest(int k, int[] nums) { 15 | this.k = k; 16 | pq = new PriorityQueue<>(); 17 | for (int n: nums) { 18 | pq.offer(n); 19 | if (pq.size() > k) { 20 | pq.poll(); 21 | } 22 | } 23 | } 24 | 25 | public int add(int val) { 26 | pq.offer(val); 27 | if (pq.size() > k) { 28 | pq.poll(); 29 | } 30 | return pq.peek(); 31 | } 32 | } -------------------------------------------------------------------------------- /704. Binary Search.java: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/binary-search/ 2 | 3 | idea: Binary Search 4 | time complexity: O(log n) 5 | space complexity: O(1) 6 | 7 | class Solution { 8 | public int search(int[] nums, int target) { 9 | int low = 0, high = nums.length - 1; 10 | while (low <= high) { 11 | int mid = low + (high - low) / 2; 12 | if (nums[mid] >= target) { 13 | high = mid - 1; 14 | } else { 15 | low = mid + 1; 16 | } 17 | } 18 | 19 | return low < nums.length && nums[low] == target ? low : -1; 20 | } 21 | } -------------------------------------------------------------------------------- /705. Design HashSet.java: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/design-hashset/ 2 | 3 | // 思路:根据数据规模和数据类型(int),利用boolean array来模拟hash。 4 | 5 | class MyHashSet { 6 | boolean[] contains; 7 | /** Initialize your data structure here. */ 8 | public MyHashSet() { 9 | contains = new boolean[1000001]; 10 | } 11 | 12 | public void add(int key) { 13 | contains[key] = true; 14 | } 15 | 16 | public void remove(int key) { 17 | contains[key] = false; 18 | } 19 | 20 | /** Returns true if this set contains the specified element */ 21 | public boolean contains(int key) { 22 | return contains[key]; 23 | } 24 | } -------------------------------------------------------------------------------- /706. Design HashMap.java: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/design-hashmap/ 2 | 3 | // 思路:根据数据规模和数据类型(int),利用int array来模拟hash。 4 | 5 | class MyHashMap { 6 | int[] map; 7 | 8 | /** Initialize your data structure here. */ 9 | public MyHashMap() { 10 | map = new int[1000001]; 11 | Arrays.fill(map, -1); 12 | } 13 | 14 | /** value will always be non-negative. */ 15 | public void put(int key, int value) { 16 | map[key] = value; 17 | } 18 | 19 | /** Returns the value to which the specified key is mapped, or -1 if this map contains no mapping for the key */ 20 | public int get(int key) { 21 | return map[key]; 22 | } 23 | 24 | /** Removes the mapping of the specified value key if this map contains a mapping for the key */ 25 | public void remove(int key) { 26 | map[key] = -1; 27 | } 28 | } -------------------------------------------------------------------------------- /717. 1-bit and 2-bit Characters.java: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/1-bit-and-2-bit-characters/ 2 | 3 | time complexity: O(n) 4 | space complexity: O(1) 5 | 6 | class Solution { 7 | public boolean isOneBitCharacter(int[] bits) { 8 | int n = bits.length, i = 0; 9 | for (; i + 1 < n; i++) { 10 | if (bits[i] == 1) { 11 | i++; 12 | } 13 | } 14 | 15 | return i == n - 1 && bits[i] == 0; 16 | } 17 | } -------------------------------------------------------------------------------- /724. Find Pivot Index.java: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/find-pivot-index/ 2 | 3 | // 思路:Prefix Sum 4 | // 两次遍历。 5 | // 第一次:求所有数的和sum。 6 | // 第二次:维护变量left,表示当前位置i的左边[0:i)的部分和,同理right表示[i+1:n)的部分和。 7 | // 如果left==right,返回i;否则,更新left+=nums[i]。 8 | // 时间复杂度:O(n) 9 | // 空间复杂度:O(1) 10 | 11 | class Solution { 12 | public int pivotIndex(int[] nums) { 13 | int sum = 0; 14 | for (int num : nums) { 15 | sum += num; 16 | } 17 | 18 | int left = 0; // left sum 19 | for (int i = 0; i < nums.length; i++) { 20 | int right = sum - nums[i] - left; // right sum 21 | if (left == right) { 22 | return i; 23 | } 24 | 25 | left += nums[i]; 26 | } 27 | 28 | return -1; 29 | } 30 | } -------------------------------------------------------------------------------- /739. Daily Temperatures.java: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/daily-temperatures/ 2 | 3 | // 思路:Stack,维护decreasing subsequence 4 | // 用Stack存放index,当遇到当前T[i]大于T[stack[top]],说明有一部分结果,为i-stack[top]。 5 | // 时间复杂度:O(n) 6 | // 空间复杂度:O(n) 7 | 8 | class Solution { 9 | public int[] dailyTemperatures(int[] T) { 10 | int[] res = new int[T.length]; 11 | int[] stack = new int[T.length + 1]; 12 | int top = -1; 13 | for (int i = 0; i < T.length; i++) { 14 | int curr = T[i]; 15 | while (top >= 0 && curr > T[stack[top]]) { 16 | res[stack[top]] = i - stack[top]; 17 | top--; 18 | } 19 | stack[++top] = i; 20 | } 21 | 22 | /*while (top >= 0) { 23 | res[stack[top--]] = 0; 24 | }*/ // unnecessary 25 | 26 | return res; 27 | } 28 | } -------------------------------------------------------------------------------- /762. Prime Number of Set Bits in Binary Representation.java: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/prime-number-of-set-bits-in-binary-representation/ 2 | 3 | // 思路:Bit Manipulation + API调用 4 | // Integer.bitCount(int num)返回num的二进制表示中的1的个数。 5 | // Integer.toBinaryString(int num)返回num的二进制表示的String。 6 | // 时间复杂度:O(R log R) 7 | // 空间复杂度:O(1) 8 | 9 | class Solution { 10 | public int countPrimeSetBits(int L, int R) { 11 | Set primeSet = new HashSet<>(Arrays.asList(2, 3, 5, 7, 11, 13, 17, 19)); 12 | int res = 0; 13 | for (int i = L; i <= R; i++) { 14 | int count = Integer.bitCount(i); 15 | if (primeSet.contains(count)) { 16 | res++; 17 | } 18 | } 19 | 20 | return res; 21 | } 22 | } -------------------------------------------------------------------------------- /766. Toeplitz Matrix.java: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/toeplitz-matrix/ 2 | 3 | // 思路:Brute Force,比较每个数matrix[row][col]是否和对角线的前一个数matrix[row - 1][col - 1]相同。 4 | // 时间复杂度:O(rowLen * colLen) 5 | // 空间复杂度:O(1) 6 | 7 | class Solution { 8 | public boolean isToeplitzMatrix(int[][] matrix) { 9 | int rowLen = matrix.length, colLen = rowLen == 0 ? 0 : matrix[0].length; 10 | for (int row = 0; row < rowLen; row++) { 11 | for (int col = 0; col < colLen; col++) { 12 | if (row - 1 >= 0 && col - 1 >= 0 && matrix[row][col] != matrix[row - 1][col - 1]) { 13 | return false; 14 | } 15 | } 16 | } 17 | 18 | return true; 19 | } 20 | } -------------------------------------------------------------------------------- /771. Jewels and Stones.java: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/jewels-and-stones/ 2 | 3 | // 思路:遍历,考察内置函数的使用 4 | // 想判断某字符串是否含有某字符,可以用HashSet,【也可以用内置的indexOf()】 5 | // 时间复杂度:O(j*s), j=J.length() by indexOf(), s=S.length() 6 | // 空间复杂度:O(1) 7 | 8 | class Solution { 9 | public int numJewelsInStones(String J, String S) { 10 | int res = 0; 11 | for (char c: S.toCharArray()) { 12 | if (J.indexOf(c) != -1) { 13 | res++; 14 | } 15 | } 16 | 17 | return res; 18 | } 19 | } -------------------------------------------------------------------------------- /780. Reaching Points.java: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/reaching-points/ 2 | 3 | 思路:Math。参考:https://leetcode.com/problems/reaching-points/discuss/375429/Detailed-explanation.-or-full-through-process-or-Java-100-beat 4 | 5 | 时间复杂度:O(log n), n=max(tx, ty) 6 | 空间复杂度:O(1) 7 | 8 | class Solution { 9 | public boolean reachingPoints(int sx, int sy, int tx, int ty) { 10 | while (tx > sx && ty > sy) { 11 | if (tx > ty) { 12 | tx %= ty; 13 | } else { 14 | ty %= tx; 15 | } 16 | } 17 | 18 | return (sx == tx && ty >= sy && (ty - sy) % sx == 0) 19 | || (sy == ty && tx >= sx && (tx - sx) % sy == 0); 20 | } 21 | } -------------------------------------------------------------------------------- /796. Rotate String.java: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/rotate-string/ 2 | 3 | // 思路:常规比较 4 | // 时间复杂度:O(n^2) 5 | // 空间复杂度:O(n) 6 | 7 | class Solution { 8 | public boolean rotateString(String A, String B) { 9 | // edge cases 10 | if (A.isEmpty() && B.isEmpty()) { 11 | return true; 12 | } 13 | if (A.length() != B.length()) { 14 | return false; 15 | } 16 | 17 | int index = B.indexOf(A.charAt(0)); 18 | while (index >= 0) { 19 | String newStr = B.substring(index) + B.substring(0, index); 20 | if (A.equals(newStr)) { 21 | return true; 22 | } 23 | index = B.indexOf(A.charAt(0), index + 1); 24 | } 25 | 26 | return false; 27 | } 28 | } -------------------------------------------------------------------------------- /814. Binary Tree Pruning.java: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/binary-tree-pruning/ 2 | 3 | 思路:DFS 4 | 时间复杂度:O(n) 5 | 空间复杂度:O(h), h=height of tree 6 | 7 | class Solution { 8 | /* return true if this whole tree rooted at TreeNode node can be pruned */ 9 | private boolean dfs(TreeNode node) { 10 | if (node == null) { 11 | return true; 12 | } 13 | 14 | boolean isLeftPruned = dfs(node.left), isRightPruned = dfs(node.right); 15 | if (isLeftPruned) { 16 | node.left = null; 17 | } 18 | if (isRightPruned) { 19 | node.right = null; 20 | } 21 | 22 | return node.val == 0 && isLeftPruned && isRightPruned; 23 | } 24 | 25 | public TreeNode pruneTree(TreeNode root) { 26 | return dfs(root) ? null : root; 27 | } 28 | } -------------------------------------------------------------------------------- /824. Goat Latin.java: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/goat-latin/ 2 | 3 | 思路:String API 4 | 5 | class Solution { 6 | public String toGoatLatin(String S) { 7 | String[] split = S.split("\\s+"); 8 | for (int i = 0; i < split.length; i++) { 9 | StringBuilder sb = new StringBuilder(split[i]); 10 | char c = sb.charAt(0); 11 | if (!"aeiouAEIOU".contains(c + "")) { 12 | sb.deleteCharAt(0); 13 | sb.append(c); 14 | } 15 | 16 | sb.append("ma"); 17 | for (int j = 0; j < i + 1; j++) { 18 | sb.append("a"); 19 | } 20 | split[i] = sb.toString(); 21 | } 22 | 23 | return String.join(" ", split); 24 | } 25 | } -------------------------------------------------------------------------------- /832. Flipping an Image.java: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/flipping-an-image/ 2 | 3 | // 思路:Bit Manipulation 4 | // 时间复杂度:O(m*n) 5 | // 空间复杂度:O(1) 6 | // 犯错点:1.细节错误:如果一维数组个数为奇数,那么最中间的那个元素只需要翻转一次。因此,需要判断left是否等于right。 7 | 8 | class Solution { 9 | public int[][] flipAndInvertImage(int[][] A) { 10 | for (int[] arr: A) { 11 | int left = 0, right = arr.length - 1; 12 | while (left <= right) { 13 | int temp = arr[left]; 14 | arr[left] = arr[right]; 15 | arr[right] = temp; 16 | 17 | arr[left] ^= 1; 18 | if (left != right) arr[right] ^= 1; 19 | 20 | left++; 21 | right--; 22 | } 23 | } 24 | 25 | return A; 26 | } 27 | } -------------------------------------------------------------------------------- /836. Rectangle Overlap.java: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/rectangle-overlap/ 2 | 3 | 思路:Math 4 | 排除所有rec1在rec2的左、右、上、下的情况即可。 5 | 时间复杂度:O(1) 6 | 空间复杂度:O(1) 7 | 8 | class Solution { 9 | public boolean isRectangleOverlap(int[] rec1, int[] rec2) { 10 | return !(rec1[2] <= rec2[0] || rec1[1] >= rec2[3] || rec1[0] >= rec2[2] || rec1[3] <= rec2[1]); 11 | } 12 | } -------------------------------------------------------------------------------- /852. Peak Index in a Mountain Array.java: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/peak-index-in-a-mountain-array/ 2 | 3 | // 思路:Binary Search模版 4 | // g(m): 由于确定有peak,且0 A[mid + 1]使得大于mid的所有数都成立。 5 | 6 | class Solution { 7 | public int peakIndexInMountainArray(int[] A) { 8 | int low = 0, high = A.length - 1; 9 | while (low <= high) { 10 | int mid = low + (high - low) / 2; 11 | if (A[mid] > A[mid + 1]) high = mid - 1; 12 | else low = mid + 1; 13 | } 14 | return low; 15 | } 16 | } -------------------------------------------------------------------------------- /867. Transpose Matrix.java: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/transpose-matrix/ 2 | 3 | // 思路:Math,矩阵transpose定义 4 | // 时间复杂度:O(rowLen * colLen) 5 | // 空间复杂度:O(rowLen * colLen) 6 | 7 | class Solution { 8 | public int[][] transpose(int[][] A) { 9 | int rowLen = A.length, colLen = rowLen == 0 ? 0 : A[0].length; 10 | int[][] res = new int[colLen][rowLen]; 11 | for (int row = 0; row < rowLen; row++) { 12 | for (int col = 0; col < colLen; col++) { 13 | res[col][row] = A[row][col]; 14 | } 15 | } 16 | 17 | return res; 18 | } 19 | } -------------------------------------------------------------------------------- /872. Leaf-Similar Trees.java: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/leaf-similar-trees/ 2 | 3 | // 思路:Recursion (DFS),类似preorder traversal 4 | // 时间复杂度:O(n1 + n2) 5 | // 空间复杂度:O(n1 + n2) 6 | 7 | class Solution { 8 | public boolean leafSimilar(TreeNode root1, TreeNode root2) { 9 | List list1 = new ArrayList<>(); 10 | List list2 = new ArrayList<>(); 11 | dfs(root1, list1); 12 | dfs(root2, list2); 13 | return list1.equals(list2); 14 | } 15 | 16 | private void dfs(TreeNode node, List res) { 17 | if (node == null) { 18 | return; 19 | } 20 | if (node.left == null && node.right == null) { 21 | res.add(node.val); 22 | return; 23 | } 24 | 25 | dfs(node.left, res); 26 | dfs(node.right, res); 27 | } 28 | } -------------------------------------------------------------------------------- /876. Middle of the Linked List.java: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/middle-of-the-linked-list/ 2 | 3 | // 思路:Two Pointers (fast & slow) 4 | // 注意,题目要求如果LinkedList有偶数个ListNode,那么要返回中间靠右的一个。 5 | // 时间复杂度:O(n) 6 | // 空间复杂度:O(1) 7 | // 犯错点:1.题意理解错误:input的head指向的就是第一个ListNode,而不是第一个前的dummy node。 8 | 9 | class Solution { 10 | public ListNode middleNode(ListNode head) { 11 | if (head == null) { 12 | return null; 13 | } 14 | 15 | //ListNode slow = head.next, fast = head.next; // {Mistake 1} 16 | ListNode slow = head, fast = head; // {Correction 1} 17 | while (fast.next != null && fast.next.next != null) { 18 | slow = slow.next; 19 | fast = fast.next.next; 20 | } 21 | 22 | return fast.next == null ? slow : slow.next; 23 | } 24 | } -------------------------------------------------------------------------------- /88. Merge Sorted Array.java: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/merge-sorted-array/ 2 | 3 | idea: Two (Three?) Pointers 4 | time comp: O(m+n) 5 | space comp: O(1) 6 | 7 | class Solution { 8 | public void merge(int[] nums1, int m, int[] nums2, int n) { 9 | int right = m + n - 1; 10 | m--; 11 | n--; 12 | while (n >= 0 && right >= 0) { 13 | if (m >= 0 && nums1[m] >= nums2[n]) { 14 | nums1[right] = nums1[m]; 15 | right--; 16 | m--; 17 | } else { 18 | nums1[right] = nums2[n]; 19 | right--; 20 | n--; 21 | } 22 | } 23 | } 24 | } -------------------------------------------------------------------------------- /881. Boats to Save People.java: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/boats-to-save-people/ 2 | 3 | idea: Sort + Two Pointers + Greedy 4 | time complexity: O(n log n) 5 | space complexity: O(n) for sorting 6 | 7 | class Solution { 8 | public int numRescueBoats(int[] people, int limit) { 9 | int res = 0; 10 | Arrays.sort(people); 11 | int left = 0, right = people.length - 1; 12 | while (left <= right) { 13 | res++; 14 | 15 | if (people[left] + people[right] <= limit) { 16 | left++; 17 | } 18 | 19 | right--; 20 | } 21 | 22 | return res; 23 | } 24 | } -------------------------------------------------------------------------------- /888. Fair Candy Swap.java: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/fair-candy-swap/ 2 | 3 | idea: Math 4 | time complexity: O(a + b) 5 | space complexity: O(b) 6 | 7 | class Solution { 8 | public int[] fairCandySwap(int[] A, int[] B) { 9 | int sum1 = 0, sum2 = 0; 10 | Set set = new HashSet<>(); 11 | for (int num : A) { 12 | sum1 += num; 13 | } 14 | for (int num : B) { 15 | set.add(num); 16 | sum2 += num; 17 | } 18 | 19 | int delta = (sum2 - sum1) / 2; 20 | 21 | for (int num : A) { 22 | if (set.contains(num + delta)) { 23 | return new int[]{num, num + delta}; 24 | } 25 | } 26 | 27 | return null; 28 | } 29 | } -------------------------------------------------------------------------------- /896. Monotonic Array.java: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/monotonic-array/ 2 | 3 | idea: Use 2 variables 4 | time complexity: O(n) 5 | space complexity: O(1) 6 | 7 | class Solution { 8 | public boolean isMonotonic(int[] A) { 9 | boolean isIncr = true, isDecr = true; 10 | for (int i = 1; i < A.length; i++) { 11 | isIncr &= A[i - 1] <= A[i]; 12 | isDecr &= A[i - 1] >= A[i]; 13 | } 14 | 15 | return isIncr || isDecr; 16 | } 17 | } -------------------------------------------------------------------------------- /9. Palindrome Number.java: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/palindrome-number/ 2 | 3 | // 1)考虑corner cases:0一定为true,负数或者非0的10的倍数一定为false。这一步的判断是为了避免影响接下来用integer reversion。 4 | // 2)用integer reversion模板得到reverse的数。这里有一个trick:不需要将x完全reverse,【只需要reverse一半即可】 5 | // 3)由于只reverse了一半,当原来的x是奇数的时候,最后reverse会多一位数,所以还需判断x == reverse / 10 6 | 7 | class Solution { 8 | public boolean isPalindrome(int x) { 9 | if (x == 0) return true; 10 | if (x < 0 || x % 10 == 0) return false; 11 | int reverse = 0; 12 | while (x > reverse) { 13 | reverse = reverse * 10 + x % 10; 14 | x = x /10; 15 | } 16 | return x == reverse || x == reverse / 10; 17 | } 18 | } -------------------------------------------------------------------------------- /905. Sort Array By Parity.java: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/sort-array-by-parity/ 2 | 3 | // 思路:Two Pointers (left & right) 4 | // 维护A[0:left)为偶数,A[right+1:length)为奇数。 5 | // 时间复杂度:O(1) 6 | // 空间复杂度:O(1) 7 | 8 | class Solution { 9 | public int[] sortArrayByParity(int[] A) { 10 | int left = 0, right = A.length - 1; 11 | while (left <= right) { 12 | if (A[left] % 2 == 1) { 13 | swap(A, left, right--); 14 | } else { 15 | left++; 16 | } 17 | } 18 | 19 | return A; 20 | } 21 | 22 | private void swap(int[] arr, int i, int j) { 23 | int temp = arr[i]; 24 | arr[i] = arr[j]; 25 | arr[j] = temp; 26 | } 27 | } -------------------------------------------------------------------------------- /921. Minimum Add to Make Parentheses Valid.java: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/minimum-add-to-make-parentheses-valid/ 2 | 3 | idea: Greedy 4 | time complexity: O(n) 5 | space complexity: O(1) 6 | 7 | class Solution { 8 | public int minAddToMakeValid(String S) { 9 | int left = 0, res = 0; 10 | for (char c : S.toCharArray()) { 11 | if (c == '(') { 12 | left++; 13 | } else if (left == 0) { 14 | res++; 15 | } else { 16 | left--; 17 | } 18 | } 19 | 20 | return res + left; 21 | } 22 | } -------------------------------------------------------------------------------- /933. Number of Recent Calls.java: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/number-of-recent-calls/ 2 | 3 | solution: Queue 4 | Simply compare the time of the head in Queue with the query time t, remove those 5 | greater than 3000ms window size. 6 | time complexity: O(Q), where Q is the number of queries made 7 | space complexity: O(n), n=max number of pings 8 | 9 | class RecentCounter { 10 | Queue queue; 11 | 12 | public RecentCounter() { 13 | queue = new LinkedList<>(); 14 | } 15 | 16 | public int ping(int t) { 17 | queue.offer(t); 18 | while (!queue.isEmpty() && t - queue.peek() > 3000) { 19 | queue.poll(); 20 | } 21 | 22 | return queue.size(); 23 | } 24 | } 25 | 26 | /** 27 | * Your RecentCounter object will be instantiated and called as such: 28 | * RecentCounter obj = new RecentCounter(); 29 | * int param_1 = obj.ping(t); 30 | */ -------------------------------------------------------------------------------- /944. Delete Columns to Make Sorted.java: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/delete-columns-to-make-sorted/ 2 | 3 | idea: Brute force 4 | time complexity: O(m * n) 5 | space complexity: O(1) 6 | 7 | class Solution { 8 | public int minDeletionSize(String[] A) { 9 | int n = A.length, m = A[0].length(); 10 | int ret = 0; 11 | for (int i = 0; i < m; i++) { 12 | for (int j = 1; j < n; j++) { 13 | if (A[j].charAt(i) < A[j - 1].charAt(i)) { 14 | ret++; 15 | break; 16 | } 17 | } 18 | } 19 | 20 | return ret; 21 | } 22 | } -------------------------------------------------------------------------------- /945. Minimum Increment to Make Array Unique.java: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/minimum-increment-to-make-array-unique/ 2 | 3 | 思路:Math (Greedy?) + Sort 4 | 观察到,对于[1,1,2,2,3],不管是变成[1,2,3,4,5],还是[1,4,5,2,3],增量都是一样的,因此可以采用 5 | “贪心”的做法。 6 | 首先对数组排序,维护变量min表示当前需要增加到的最小值。如果当前值num < min,那么需要的增量为min-num。 7 | 如果num >= min,后面的数都会比min大,因此不需要增量,而要把min更新为num。 8 | 时间复杂度:O(n log n) 9 | 空间复杂度:O(1) 10 | 优化:见:https://leetcode.com/problems/minimum-increment-to-make-array-unique/discuss/197687/JavaC%2B%2BPython-Straight-Forward 11 | 12 | class Solution { 13 | public int minIncrementForUnique(int[] A) { 14 | Arrays.sort(A); 15 | int min = 0, res = 0; 16 | for (int num : A) { 17 | if (num > min) { 18 | min = num; 19 | } else { 20 | res += (min - num); 21 | } 22 | min++; 23 | } 24 | return res; 25 | } 26 | } -------------------------------------------------------------------------------- /950. Reveal Cards In Increasing Order.java: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/reveal-cards-in-increasing-order/ 2 | 3 | idea: Simulation. Referring to: https://leetcode.com/problems/reveal-cards-in-increasing-order/discuss/201574/C%2B%2B-with-picture-skip-over-empty-spaces 4 | 5 | class Solution { 6 | public int[] deckRevealedIncreasing(int[] deck) { 7 | int n = deck.length; 8 | int[] res = new int[n]; 9 | Arrays.sort(deck); 10 | boolean skip = false; 11 | int i = 0, j = 0; 12 | while (i < n) { 13 | while (res[j] > 0) { 14 | j = (j + 1) %n; 15 | } 16 | 17 | if (!skip) { 18 | res[j] = deck[i++]; 19 | } else { 20 | j = (j + 1) %n; 21 | } 22 | 23 | skip = !skip; 24 | } 25 | 26 | return res; 27 | } 28 | } -------------------------------------------------------------------------------- /951. Flip Equivalent Binary Trees.java: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/flip-equivalent-binary-trees/ 2 | 3 | idea: DFS 4 | time complexity: O(n) 5 | space complexity: O(h) 6 | 7 | class Solution { 8 | private boolean dfs(TreeNode node1, TreeNode node2) { 9 | if (node1 == null && node2 == null) { 10 | return true; 11 | } 12 | if (node1 == null || node2 == null) { 13 | return false; 14 | } 15 | 16 | return node1.val == node2.val && 17 | ((dfs(node1.left, node2.left) && dfs(node1.right, node2.right)) 18 | || (dfs(node1.left, node2.right) && dfs(node1.right, node2.left)) 19 | ); 20 | } 21 | 22 | public boolean flipEquiv(TreeNode root1, TreeNode root2) { 23 | return dfs(root1, root2); 24 | } 25 | } -------------------------------------------------------------------------------- /961. N-Repeated Element in Size 2N Array.java: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/n-repeated-element-in-size-2n-array/ 2 | 3 | // 思路:Hash Table 4 | // 由于题目限制了只有1种元素会出现2次以上,且要找的就是这个元素,因此可以直接用HashSet来找重复元素。 5 | // 时间复杂度:O(n) 6 | // 空间复杂度:O(n) 7 | 8 | class Solution { 9 | public int repeatedNTimes(int[] A) { 10 | int len = A.length, res = 0; 11 | Set set = new HashSet<>(); 12 | for (int num : A) { 13 | if (set.contains(num)) { 14 | return num; 15 | } 16 | set.add(num); 17 | } 18 | 19 | return -1; 20 | } 21 | } -------------------------------------------------------------------------------- /977. Squares of a Sorted Array.java: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/squares-of-a-sorted-array/ 2 | 3 | 思路:Two Pointers (left & right) 4 | 在整数数轴(从负数到正数)取平方,结果是先递减再递增。 5 | time comp: O(n) 6 | space comp: O(n) 7 | 8 | class Solution { 9 | public int[] sortedSquares(int[] nums) { 10 | int left = 0, right = nums.length - 1; 11 | int[] ret = new int[nums.length]; 12 | for (int i = nums.length - 1; i >= 0; i--) { 13 | int squaredLeft = nums[left] * nums[left], squaredRight = nums[right] * nums[right]; 14 | if (squaredLeft >= squaredRight) { 15 | ret[i] = squaredLeft; 16 | left++; 17 | } else { 18 | ret[i] = squaredRight; 19 | right--; 20 | } 21 | } 22 | 23 | return ret; 24 | } 25 | } -------------------------------------------------------------------------------- /978. Longest Turbulent Subarray.java: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/longest-turbulent-subarray/ 2 | 3 | idea: DP (cache info) 4 | time complexity: O(n) 5 | space complexity: O(1) 6 | 7 | class Solution { 8 | public int maxTurbulenceSize(int[] A) { 9 | int n = A.length, currLen = 1, maxLen = 1; 10 | long preDiff = 0; 11 | for (int i = 1; i < n; i++) { 12 | long currDiff = A[i] - A[i - 1]; 13 | if (preDiff * currDiff >= 0) { 14 | currLen = currDiff == 0 ? 1 : 2; 15 | } else { 16 | currLen++; 17 | } 18 | maxLen = Math.max(maxLen, currLen); 19 | preDiff = currDiff; 20 | } 21 | 22 | return maxLen; 23 | } 24 | } -------------------------------------------------------------------------------- /989. Add to Array-Form of Integer.java: -------------------------------------------------------------------------------- 1 | 2 | 3 | 时间复杂度:O(max(A.length, log K)) 4 | 空间复杂度:O(max(A.length, log K)) 5 | 6 | class Solution { 7 | public List addToArrayForm(int[] A, int K) { 8 | List res = new ArrayList<>(); 9 | int carry = 0; 10 | for (int i = A.length - 1; i >= 0 || K > 0; i--, K /= 10) { 11 | int digit = i >= 0 ? A[i] : 0; 12 | digit += K % 10 + carry; 13 | res.add(0, digit % 10); 14 | carry = digit / 10; 15 | } 16 | 17 | if (carry > 0) { 18 | res.add(0, carry); 19 | } 20 | return res; 21 | } 22 | } -------------------------------------------------------------------------------- /991. Broken Calculator.java: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/broken-calculator/ 2 | 3 | 思路:Math + Greedy。参考:https://leetcode.com/problems/broken-calculator/discuss/234484/JavaC%2B%2BPython-Change-Y-to-X-in-1-Line 4 | 将从X经过减和乘得到Y转换成从Y经过除和加得到X。 5 | 时间复杂度:O(log Y) 6 | 空间复杂度:O(1) 7 | 8 | class Solution { 9 | public int brokenCalc(int X, int Y) { 10 | int step = 0; 11 | while (Y > X) { 12 | Y = Y % 2 == 0 ? Y / 2 : Y + 1; 13 | step++; 14 | } 15 | 16 | return step + X - Y; 17 | } 18 | } --------------------------------------------------------------------------------