├── LICENSE ├── README.md ├── pom.xml └── src └── leetcode ├── ListNode.java ├── Node.java ├── Solution.java ├── TreeNode.java ├── backtrack ├── Interview0812.java ├── Solution10.java ├── Solution131.java ├── Solution139.java ├── Solution17.java ├── Solution216.java ├── Solution22.java ├── Solution257.java ├── Solution39.java ├── Solution40.java ├── Solution46.java ├── Solution47.java ├── Solution77.java ├── Solution78.java ├── Solution784.java └── SolutionLCR157.java ├── binaryindexedtree ├── BinaryIndexedTree.java ├── NumArray.java ├── Solution1395.java ├── Solution1893.java ├── Solution2179.java ├── Solution327.java └── Solution775.java ├── binarysearch ├── Solution1005.java ├── Solution153.java ├── Solution154.java ├── Solution1608.java ├── Solution162.java ├── Solution1818.java ├── Solution240.java ├── Solution268.java ├── Solution33.java ├── Solution34.java ├── Solution35.java ├── Solution367.java ├── Solution436.java ├── Solution532.java ├── Solution704.java ├── Solution74.java ├── Solution744.java ├── Solution81.java ├── Solution852.java ├── SolutionOffer532.java ├── TopVotedCandidate.java └── greedyalgorithm │ ├── Solution1011.java │ ├── Solution1552.java │ ├── Solution1760.java │ ├── Solution1802.java │ ├── Solution2226.java │ ├── Solution410.java │ ├── Solution475.java │ ├── Solution668.java │ ├── Solution719.java │ └── Solution875.java ├── bit ├── Solution1073.java ├── Solution136.java ├── Solution137.java ├── Solution191.java ├── Solution231.java ├── Solution260.java ├── Solution318.java ├── Solution371.java ├── Solution50.java └── SolutionLCR133.java ├── datastructure ├── AllOne.java ├── LFUCache.java ├── LRUCache.java ├── LRUCacheLinkedHashMap.java ├── MyCircularDeque.java ├── MyLinkedList.java ├── Skiplist.java └── Trie.java ├── doublepointer ├── Interview0105.java ├── Interview1001.java ├── Interview1711.java ├── Solution11.java ├── Solution125.java ├── Solution134.java ├── Solution15.java ├── Solution16.java ├── Solution167.java ├── Solution18.java ├── Solution26.java ├── Solution27.java ├── Solution392.java ├── Solution413.java ├── Solution443.java ├── Solution481.java ├── Solution524.java ├── Solution56.java ├── Solution581.java ├── Solution611.java ├── Solution658.java ├── Solution777.java ├── Solution80.java ├── Solution809.java ├── Solution825.java ├── Solution838.java ├── Solution870.java ├── Solution88.java ├── Solution881.java └── SolutionLCR139.java ├── dp ├── Interview1709.java ├── Solution1035.java ├── Solution1143.java ├── Solution1218.java ├── Solution1312.java ├── Solution264.java ├── Solution300.java ├── Solution322.java ├── Solution343.java ├── Solution467.java ├── Solution509.java ├── Solution516.java ├── Solution637.java ├── Solution64.java ├── Solution72.java ├── SolutionLCR166.java ├── SolutionLCR185.java ├── SolutionOffer14.java ├── SolutionOffer46.java ├── fibonacci │ ├── Solution1749.java │ ├── Solution198.java │ ├── Solution213.java │ ├── Solution2266.java │ ├── Solution2320.java │ ├── Solution2466.java │ ├── Solution2606.java │ ├── Solution53.java │ ├── Solution70.java │ ├── Solution740.java │ ├── Solution746.java │ └── SolutionLCR165.java ├── memory │ └── Solution377.java └── 动态规划二维数组字符串关系图.png ├── graph ├── Solution1519.java ├── Solution207.java ├── Solution210.java ├── Solution802.java ├── Solution851.java └── algorithms │ ├── BreadthFirstPaths.java │ ├── CC.java │ ├── DepthFirstOrder.java │ ├── DepthFirstPaths.java │ ├── Dijkstra.java │ ├── DirectedCycle.java │ ├── DirectedDFS.java │ ├── LazyPrimMST.java │ ├── PrimMST.java │ ├── Test.java │ ├── Topological.java │ ├── TreMaux.java │ ├── basic │ ├── Digraph.java │ ├── DirectedEdge.java │ ├── Edge.java │ ├── EdgeWeightedDigraph.java │ ├── EdgeWeightedGraph.java │ ├── Graph.java │ └── VToTreeWeight.java │ └── tinyG.txt ├── greedyalgorithm ├── Solution121.java ├── Solution122.java ├── Solution123.java ├── Solution135.java ├── Solution179.java ├── Solution1953.java ├── Solution334.java ├── Solution55.java └── Solution768.java ├── hashmap ├── DetectSquares.java ├── FreqStack.java ├── RandomizedSet.java ├── Solution1.java ├── Solution1282.java ├── Solution169.java ├── Solution205.java ├── Solution229.java ├── Solution242.java ├── Solution2962.java ├── Solution299.java ├── Solution387.java ├── Solution388.java ├── Solution409.java ├── Solution41.java ├── Solution447.java ├── Solution49.java └── Solution811.java ├── linkedlist ├── Solution0205.java ├── Solution138.java ├── Solution141.java ├── Solution142.java ├── Solution148.java ├── Solution160.java ├── Solution1823.java ├── Solution19.java ├── Solution206.java ├── Solution23.java ├── Solution234.java ├── Solution237.java ├── Solution24.java ├── Solution25.java ├── Solution287.java ├── Solution328.java ├── Solution382.java ├── Solution430.java ├── Solution445.java ├── Solution725.java ├── Solution817.java ├── Solution82.java ├── Solution83.java ├── Solution86.java ├── Solution876.java ├── Solution92.java ├── SolutionOffer06.java ├── SolutionOffer18.java ├── SolutionOffer22.java ├── SolutionOffer25.java ├── SolutionOffer35.java └── SolutionOfferTwo29.java ├── prefixsum ├── NumArray.java ├── Solution1310.java ├── Solution1588.java ├── Solution1652.java ├── Solution1744.java ├── Solution1894.java ├── Solution2055.java ├── Solution238.java ├── Solution274.java ├── Solution396.java ├── Solution497.java ├── Solution523.java ├── Solution525.java ├── Solution528.java ├── Solution560.java ├── Solution724.java ├── Solution926.java ├── matrix │ ├── NumMatrix.java │ └── Solution661.java ├── 二维数组前缀和计算方法.png └── 前缀和.drawio.png ├── priorityqueue ├── DeapSort.java ├── Interview1714.java ├── KthLargest.java ├── MedianFinder.java ├── Multiway.java ├── MyPriorityQueue.java ├── Solution1405.java ├── Solution1705.java ├── Solution1834.java ├── Solution215.java ├── Solution373.java ├── Solution4.java ├── Solution45.java ├── Solution692.java ├── Solution871.java ├── Solution954.java └── SolutionLCR159.java ├── queue ├── MovingAverage.java ├── MyCircularQueue.java ├── RecentCounter.java ├── Solution1047.java ├── Solution649.java └── monotonic │ ├── MaxQueue.java │ ├── Solution1438.java │ ├── Solution2100.java │ ├── Solution239.java │ └── Solution654.java ├── recursion ├── Solution200.java ├── Solution79.java ├── SolutionLCR129.java ├── SolutionLCR130.java └── SolutionOffer13.java ├── segmenttree ├── MyCalendar.java ├── MyCalendarThree.java ├── MyCalendarTwo.java ├── NumArray.java ├── RangeModule.java ├── SegmentTree.java ├── SegmentTree2.java ├── SegmentTree3.java ├── Solution1109.java ├── Solution1893.java ├── Solution239.java ├── Solution327.java └── Solution654.java ├── simulate ├── MyCalendar.java ├── NumMatrix.java ├── Solution1109.java ├── Solution12.java ├── Solution189.java ├── Solution1893.java ├── Solution219.java ├── Solution2257.java ├── Solution2672.java ├── Solution2934.java ├── Solution3025.java ├── Solution354.java ├── Solution400.java ├── Solution406.java ├── Solution415.java ├── Solution48.java ├── Solution496.java ├── Solution54.java ├── Solution556.java ├── Solution560.java ├── Solution59.java ├── Solution796.java └── Solution89.java ├── slidingwindow ├── Solution1004.java ├── Solution1052.java ├── Solution1208.java ├── Solution1423.java ├── Solution1446.java ├── Solution1695.java ├── Solution1759.java ├── Solution1984.java ├── Solution2024.java ├── Solution2302.java ├── Solution3.java ├── Solution424.java ├── Solution438.java ├── Solution567.java ├── Solution643.java ├── Solution713.java ├── Solution76.java ├── Solution904.java ├── Solution992.java ├── SolutionLCR008.java ├── SolutionOffer48.java ├── SolutionOffer57.java └── SolutionOffer572.java ├── sort ├── Solution1051.java ├── Solution1403.java ├── Solution1833.java ├── Solution324.java ├── Solution373.java ├── Solution451.java ├── Solution75.java ├── Solution937.java ├── Solution969.java ├── SolutionLCR164.java ├── SolutionLCR170.java ├── SolutionLCR186.java └── algorithms │ ├── BubbleSort.java │ ├── BucketSort.java │ ├── CountingSort.java │ ├── InsertSort.java │ ├── MergeSort.java │ ├── MergeSort2.java │ ├── MergeSort3.java │ ├── MergeSort4.java │ ├── QuickSort.java │ ├── QuickSort2.java │ ├── QuickSort3.java │ ├── QuickSort4.java │ ├── RadixSort.java │ ├── RadixSortMSD.java │ ├── SelectionSort.java │ └── ShellSort.java ├── stack ├── MinStack.java ├── MyQueue.java ├── Solution1106.java ├── Solution1190.java ├── Solution20.java ├── Solution32.java ├── Solution636.java ├── Solution71.java ├── Solution726.java ├── Solution735.java ├── Solution856.java ├── Solution946.java └── monotonic │ ├── Solution1475.java │ ├── Solution1673.java │ ├── Solution42.java │ ├── Solution496.java │ ├── Solution503.java │ ├── Solution654.java │ ├── Solution739.java │ ├── Solution795.java │ ├── Solution84.java │ ├── Solution85.java │ ├── Solution907.java │ └── StockSpanner.java ├── str ├── Interview1002.java ├── Solution14.java ├── Solution1455.java ├── Solution151.java ├── Solution165.java ├── Solution187.java ├── Solution394.java ├── Solution43.java ├── Solution6.java └── Solution8.java ├── tree ├── bst │ ├── BinarySearchTree.java │ ├── Interview0406.java │ ├── Solution1305.java │ ├── Solution230.java │ ├── Solution235.java │ ├── Solution450.java │ ├── Solution669.java │ ├── Solution94.java │ ├── Solution98.java │ ├── Solution99.java │ ├── SolutionLCR155.java │ └── SolutionLCR174.java ├── dfs │ ├── Solution114.java │ ├── Solution2096.java │ ├── Solution437.java │ ├── Solution652.java │ └── Solution863.java ├── levelorder │ ├── Codec.java │ ├── Solution102.java │ ├── Solution103.java │ ├── Solution111.java │ ├── Solution199.java │ ├── Solution623.java │ ├── Solution655.java │ ├── Solution987.java │ └── SolutionLCR151.java ├── postorder │ ├── Solution104.java │ ├── Solution1080.java │ ├── Solution110.java │ ├── Solution124.java │ ├── Solution145.java │ ├── Solution236.java │ ├── Solution337.java │ ├── Solution687.java │ ├── Solution814.java │ └── Solution979.java ├── preorder │ ├── Codec.java │ ├── Solution101.java │ ├── Solution105.java │ ├── Solution106.java │ ├── Solution108.java │ ├── Solution109.java │ ├── Solution113.java │ ├── Solution129.java │ ├── Solution144.java │ ├── Solution144Iteration.java │ ├── Solution226.java │ ├── Solution617.java │ ├── Solution654.java │ ├── Solution662.java │ ├── SolutionLCR143.java │ └── SolutionLCR152.java └── redblacktree │ ├── LeftLeaningRedBlackTree.java │ ├── Solution220.java │ └── StockPrice.java └── utils └── Matrix.java /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2023 方圆 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 4.0.0 6 | 7 | src.leetcode 8 | LeetCode 9 | 1.0-SNAPSHOT 10 | 11 | 12 | 21 13 | 21 14 | UTF-8 15 | 16 | 17 | -------------------------------------------------------------------------------- /src/leetcode/ListNode.java: -------------------------------------------------------------------------------- 1 | package leetcode; 2 | 3 | public class ListNode { 4 | public int val; 5 | public ListNode next; 6 | 7 | public ListNode(int val) { 8 | this.val = val; 9 | } 10 | 11 | ListNode(int val, ListNode next) { 12 | this.val = val; 13 | this.next = next; 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /src/leetcode/Node.java: -------------------------------------------------------------------------------- 1 | package leetcode; 2 | 3 | public class Node { 4 | public int val; 5 | public Node left; 6 | public Node right; 7 | public Node next; 8 | public Node random; 9 | 10 | public Node() {} 11 | 12 | public Node(int _val) { 13 | val = _val; 14 | } 15 | 16 | public Node(int _val,Node _left,Node _right) { 17 | val = _val; 18 | left = _left; 19 | right = _right; 20 | } 21 | } -------------------------------------------------------------------------------- /src/leetcode/Solution.java: -------------------------------------------------------------------------------- 1 | package leetcode; 2 | 3 | /** 4 | * 供本地题解使用 5 | * 6 | * @author FangYuan 7 | * @since 2023-11-14 09:26:23 8 | */ 9 | public class Solution { 10 | 11 | 12 | } 13 | -------------------------------------------------------------------------------- /src/leetcode/TreeNode.java: -------------------------------------------------------------------------------- 1 | package leetcode; 2 | 3 | import java.util.LinkedList; 4 | import java.util.Queue; 5 | 6 | public class TreeNode { 7 | public int val; 8 | public TreeNode left; 9 | public TreeNode right; 10 | 11 | public TreeNode(int x) { 12 | val = x; 13 | } 14 | 15 | public void print() { 16 | Queue queue = new LinkedList<>(); 17 | queue.offer(this); 18 | 19 | while (!queue.isEmpty()) { 20 | int size = queue.size(); 21 | 22 | while (size != 0) { 23 | size--; 24 | TreeNode node = queue.poll(); 25 | if (node != null) { 26 | queue.offer(node.left); 27 | queue.offer((node.right)); 28 | System.out.print(node.val); 29 | } else { 30 | System.out.print("null"); 31 | } 32 | if (size != 0) { 33 | System.out.print(", "); 34 | } 35 | } 36 | System.out.println(); 37 | } 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /src/leetcode/backtrack/Solution78.java: -------------------------------------------------------------------------------- 1 | package leetcode.backtrack; 2 | 3 | import java.util.LinkedList; 4 | import java.util.List; 5 | 6 | public class Solution78 { 7 | 8 | // 定义全局变量 9 | List> res; 10 | 11 | public List> subsets(int[] nums) { 12 | res = new LinkedList<>(); 13 | backtrack(nums, 0, new LinkedList<>()); 14 | return res; 15 | } 16 | 17 | /** 18 | * 回溯 19 | * 20 | * @param nums 选择列表 21 | * @param begin 构造子集开始的子数组索引 22 | * @param path 走过的路径 23 | */ 24 | private void backtrack(int[] nums, int begin, LinkedList path) { 25 | // 走过的所有路径均为答案之一 26 | res.add((List) path.clone()); 27 | for (int i = begin; i < nums.length; i++) { 28 | // 每一步的操作:将下边大于等于 begin 的元素加入到路径中 29 | path.add(nums[i]); 30 | // 子问题: 31 | backtrack(nums, i + 1, path); 32 | // 恢复现场:即将递归前加入路径的元素移除 33 | path.removeLast(); 34 | } 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /src/leetcode/binarysearch/Solution153.java: -------------------------------------------------------------------------------- 1 | package leetcode.binarysearch; 2 | 3 | public class Solution153 { 4 | public int findMin(int[] nums) { 5 | int left = 0, right = nums.length - 1; 6 | while (left <= right) { 7 | int mid = left + right >> 1; 8 | if (nums[mid] > nums[right]) { 9 | left = mid + 1; 10 | continue; 11 | } 12 | 13 | if (mid - 1 >= 0 && nums[mid - 1] < nums[mid]) { 14 | right = mid - 1; 15 | } else { 16 | left = mid + 1; 17 | } 18 | } 19 | 20 | return nums[right]; 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /src/leetcode/binarysearch/Solution1608.java: -------------------------------------------------------------------------------- 1 | package leetcode.binarysearch; 2 | 3 | import java.util.Arrays; 4 | 5 | public class Solution1608 { 6 | 7 | public int specialArray(int[] nums) { 8 | Arrays.sort(nums); 9 | 10 | for (int i = 0; i <= nums.length; i++) { 11 | int left = 0, right = nums.length; 12 | while (left < right) { 13 | int mid = left + right >> 1; 14 | 15 | if (nums[mid] >= i) { 16 | right = mid; 17 | } else { 18 | left = mid + 1; 19 | } 20 | } 21 | 22 | if (nums.length - left == i) { 23 | return i; 24 | } 25 | } 26 | 27 | return -1; 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /src/leetcode/binarysearch/Solution162.java: -------------------------------------------------------------------------------- 1 | package leetcode.binarysearch; 2 | 3 | public class Solution162 { 4 | 5 | public static void main(String[] args) { 6 | System.out.println(new Solution162().findPeakElement(new int[]{1, 2, 3, 4})); 7 | } 8 | 9 | public int findPeakElement(int[] nums) { 10 | int left = 0, right = nums.length; 11 | while (left < right) { 12 | int mid = left + right >> 1; 13 | if (mid + 1 == nums.length || nums[mid] > nums[mid + 1]) { 14 | right = mid; 15 | } else { 16 | left = mid + 1; 17 | } 18 | } 19 | 20 | return left; 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /src/leetcode/binarysearch/Solution240.java: -------------------------------------------------------------------------------- 1 | package leetcode.binarysearch; 2 | 3 | public class Solution240 { 4 | public boolean searchMatrix(int[][] matrix, int target) { 5 | for (int[] row : matrix) { 6 | if (row[0] > target) { 7 | continue; 8 | } 9 | 10 | int left = 0, right = row.length; 11 | while (left < right) { 12 | int mid = left + right >> 1; 13 | 14 | if (row[mid] > target) { 15 | right = mid; 16 | } else if (row[mid] < target) { 17 | left = mid + 1; 18 | } else { 19 | return true; 20 | } 21 | } 22 | } 23 | 24 | return false; 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /src/leetcode/binarysearch/Solution268.java: -------------------------------------------------------------------------------- 1 | package leetcode.binarysearch; 2 | 3 | import java.util.Arrays; 4 | 5 | public class Solution268 { 6 | public int missingNumber(int[] nums) { 7 | Arrays.sort(nums); 8 | 9 | int left = 0, right = nums.length; 10 | while (left < right) { 11 | int mid = left + right >> 1; 12 | 13 | if (nums[mid] == mid) { 14 | left = mid + 1; 15 | } else { 16 | right = mid; 17 | } 18 | } 19 | 20 | return left; 21 | } 22 | 23 | } 24 | -------------------------------------------------------------------------------- /src/leetcode/binarysearch/Solution33.java: -------------------------------------------------------------------------------- 1 | package leetcode.binarysearch; 2 | 3 | public class Solution33 { 4 | 5 | public static void main(String[] args) { 6 | System.out.println(new Solution33().search(new int[]{1, 3, 5}, 3)); 7 | } 8 | 9 | public int search(int[] nums, int target) { 10 | int left = 0, right = nums.length - 1; 11 | while (left <= right) { 12 | int mid = left + right >> 1; 13 | 14 | if (nums[mid] > nums[right] && target < nums[left]) { 15 | left = mid + 1; 16 | continue; 17 | } 18 | if (nums[mid] < nums[right] && target > nums[right]) { 19 | right = mid - 1; 20 | continue; 21 | } 22 | 23 | if (nums[mid] > target) { 24 | right = mid - 1; 25 | } else if (nums[mid] < target) { 26 | left = mid + 1; 27 | } else { 28 | return mid; 29 | } 30 | } 31 | 32 | return -1; 33 | } 34 | 35 | } 36 | -------------------------------------------------------------------------------- /src/leetcode/binarysearch/Solution34.java: -------------------------------------------------------------------------------- 1 | package leetcode.binarysearch; 2 | 3 | public class Solution34 { 4 | public int[] searchRange(int[] nums, int target) { 5 | int left = 0, right = nums.length; 6 | while (left < right) { 7 | int mid = left + right >> 1; 8 | 9 | if (nums[mid] > target) { 10 | right = mid; 11 | } else if (nums[mid] < target) { 12 | left = mid + 1; 13 | } else { 14 | left = mid; 15 | right = mid; 16 | 17 | while (left - 1 >= 0 && nums[left - 1] == target) { 18 | left--; 19 | } 20 | while (right + 1 < nums.length && nums[right + 1] == target) { 21 | right++; 22 | } 23 | return new int[]{left, right}; 24 | } 25 | } 26 | 27 | return new int[]{left, right}; 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /src/leetcode/binarysearch/Solution35.java: -------------------------------------------------------------------------------- 1 | package leetcode.binarysearch; 2 | 3 | public class Solution35 { 4 | 5 | public static void main(String[] args) { 6 | System.out.println(new Solution35().searchInsert(new int[]{1, 3, 5, 6}, 4)); 7 | } 8 | 9 | public int searchInsert(int[] nums, int target) { 10 | int left = 0, right = nums.length; 11 | 12 | while (left < right) { 13 | int mid = left + right >> 1; 14 | 15 | if (nums[mid] > target) { 16 | right = mid; 17 | } else if (nums[mid] < target) { 18 | left = mid + 1; 19 | } else { 20 | return mid; 21 | } 22 | } 23 | 24 | return left; 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /src/leetcode/binarysearch/Solution367.java: -------------------------------------------------------------------------------- 1 | package leetcode.binarysearch; 2 | 3 | public class Solution367 { 4 | 5 | public static void main(String[] args) { 6 | System.out.println(new Solution367().isPerfectSquare(1)); 7 | } 8 | 9 | public boolean isPerfectSquare(int num) { 10 | long left = 1, right = num; 11 | while (left <= right) { 12 | long mid = left + right >> 1; 13 | 14 | if (mid * mid > num) { 15 | right = mid - 1; 16 | } else if (mid * mid < num) { 17 | left = mid + 1; 18 | } else { 19 | return true; 20 | } 21 | } 22 | 23 | return false; 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /src/leetcode/binarysearch/Solution532.java: -------------------------------------------------------------------------------- 1 | package leetcode.binarysearch; 2 | 3 | import java.util.Arrays; 4 | 5 | public class Solution532 { 6 | public int findPairs(int[] nums, int k) { 7 | Arrays.sort(nums); 8 | int res = 0; 9 | for (int i = 0; i < nums.length; i++) { 10 | if (i > 0 && nums[i - 1] == nums[i]) { 11 | continue; 12 | } 13 | int left = i + 1, right = nums.length; 14 | while (left < right) { 15 | int mid = left + right >> 1; 16 | 17 | if (nums[mid] - nums[i] == k) { 18 | res++; 19 | break; 20 | } else if (nums[mid] - nums[i] > k) { 21 | right = mid; 22 | } else { 23 | left = mid + 1; 24 | } 25 | } 26 | } 27 | 28 | return res; 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /src/leetcode/binarysearch/Solution704.java: -------------------------------------------------------------------------------- 1 | package leetcode.binarysearch; 2 | 3 | public class Solution704 { 4 | 5 | public static void main(String[] args) { 6 | System.out.println(new Solution704().search(new int[]{1, 2, 4, 5}, 3)); 7 | } 8 | 9 | public int search(int[] nums, int target) { 10 | int left = 0, right = nums.length; 11 | 12 | while (left < right) { 13 | int mid = left + right >> 1; 14 | 15 | if (nums[mid] > target) { 16 | right = mid; 17 | } else if (nums[mid] < target) { 18 | left = mid + 1; 19 | } else { 20 | return mid; 21 | } 22 | } 23 | 24 | return -1; 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /src/leetcode/binarysearch/Solution74.java: -------------------------------------------------------------------------------- 1 | package leetcode.binarysearch; 2 | 3 | public class Solution74 { 4 | public boolean searchMatrix(int[][] matrix, int target) { 5 | for (int i = 0; i < matrix.length; i++) { 6 | for (int j = 0; j < matrix[0].length; j++) { 7 | if (matrix[i][j] <= target && target <= matrix[i][matrix[i].length - 1]) { 8 | int left = 0, right = matrix[i].length; 9 | while (left < right) { 10 | int mid = left + right >> 1; 11 | 12 | if (matrix[i][mid] == target) { 13 | return true; 14 | } else if (matrix[i][mid] < target) { 15 | left = mid + 1; 16 | } else { 17 | right = mid; 18 | } 19 | } 20 | 21 | return false; 22 | } 23 | } 24 | } 25 | 26 | return false; 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /src/leetcode/binarysearch/Solution744.java: -------------------------------------------------------------------------------- 1 | package leetcode.binarysearch; 2 | 3 | public class Solution744 { 4 | public char nextGreatestLetter(char[] letters, char target) { 5 | int left = 0, right = letters.length; 6 | while (left < right) { 7 | int mid = left + right >> 1; 8 | 9 | if (letters[mid] > target) { 10 | right = mid; 11 | } else { 12 | left = mid + 1; 13 | } 14 | } 15 | 16 | return left == letters.length ? letters[0] : letters[left]; 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /src/leetcode/binarysearch/Solution81.java: -------------------------------------------------------------------------------- 1 | package leetcode.binarysearch; 2 | 3 | public class Solution81 { 4 | 5 | public static void main(String[] args) { 6 | System.out.println(new Solution81().search(new int[]{1}, 1)); 7 | } 8 | 9 | public boolean search(int[] nums, int target) { 10 | int left = 0, right = nums.length - 1; 11 | while (left <= right) { 12 | int mid = left + right >> 1; 13 | 14 | if (nums[mid] > nums[right] && target < nums[left]) { 15 | left = mid + 1; 16 | continue; 17 | } 18 | if (nums[mid] < nums[right] && target > nums[right]) { 19 | right = mid - 1; 20 | continue; 21 | } 22 | 23 | for (int i = left; i <= right; i++) { 24 | if (target == nums[i]) { 25 | return true; 26 | } 27 | } 28 | break; 29 | } 30 | 31 | return false; 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /src/leetcode/binarysearch/Solution852.java: -------------------------------------------------------------------------------- 1 | package leetcode.binarysearch; 2 | 3 | public class Solution852 { 4 | 5 | public int peakIndexInMountainArray(int[] arr) { 6 | int left = 0, right = arr.length; 7 | while (left < right) { 8 | int mid = left + right >> 1; 9 | 10 | if (mid + 1 == arr.length || arr[mid] > arr[mid + 1]) { 11 | right = mid; 12 | } else { 13 | left = mid + 1; 14 | } 15 | } 16 | 17 | return left; 18 | } 19 | 20 | } 21 | -------------------------------------------------------------------------------- /src/leetcode/binarysearch/SolutionOffer532.java: -------------------------------------------------------------------------------- 1 | package leetcode.binarysearch; 2 | 3 | public class SolutionOffer532 { 4 | 5 | public static void main(String[] args) { 6 | System.out.println(new SolutionOffer532().missingNumber(new int[]{0, 2, 3})); 7 | } 8 | 9 | public int missingNumber(int[] nums) { 10 | int left = 0, right = nums.length; 11 | while (left < right) { 12 | int mid = left + right >> 1; 13 | if (nums[mid] != mid) { 14 | right = mid; 15 | } else { 16 | left = mid + 1; 17 | } 18 | } 19 | 20 | return left; 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /src/leetcode/binarysearch/greedyalgorithm/Solution1760.java: -------------------------------------------------------------------------------- 1 | package leetcode.binarysearch.greedyalgorithm; 2 | 3 | import java.util.Arrays; 4 | 5 | public class Solution1760 { 6 | 7 | public static void main(String[] args) { 8 | System.out.println(new Solution1760().minimumSize(new int[]{9}, 2)); 9 | } 10 | 11 | public int minimumSize(int[] nums, int maxOperations) { 12 | int left = 1, right = Arrays.stream(nums).max().getAsInt(); 13 | while (left < right) { 14 | int mid = left + right >> 1; 15 | 16 | int op = 0; 17 | for (int num : nums) { 18 | op += (num - 1) / mid; 19 | } 20 | if (op > maxOperations) { 21 | left = mid + 1; 22 | } else { 23 | right = mid; 24 | } 25 | } 26 | 27 | return right; 28 | } 29 | 30 | } 31 | -------------------------------------------------------------------------------- /src/leetcode/binarysearch/greedyalgorithm/Solution2226.java: -------------------------------------------------------------------------------- 1 | package leetcode.binarysearch.greedyalgorithm; 2 | 3 | import java.util.Arrays; 4 | 5 | public class Solution2226 { 6 | 7 | public static void main(String[] args) { 8 | // 5 9 | System.out.println(new Solution2226().maximumCandies(new int[]{5, 8, 6}, 3)); 10 | } 11 | 12 | public int maximumCandies(int[] candies, long k) { 13 | int left = 1, right = Arrays.stream(candies).max().getAsInt() + 1; 14 | 15 | while (left < right) { 16 | int mid = left + right >> 1; 17 | 18 | long children = 0; 19 | for (int candy : candies) { 20 | children += candy / mid; 21 | } 22 | 23 | if (children >= k) { 24 | left = mid + 1; 25 | } else { 26 | right = mid; 27 | } 28 | } 29 | 30 | return left - 1; 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /src/leetcode/binarysearch/greedyalgorithm/Solution668.java: -------------------------------------------------------------------------------- 1 | package leetcode.binarysearch.greedyalgorithm; 2 | 3 | public class Solution668 { 4 | 5 | public static void main(String[] args) { 6 | System.out.println(new Solution668().findKthNumber(3, 3, 5)); 7 | } 8 | public int findKthNumber(int m, int n, int k) { 9 | int left = 1, right = m * n; 10 | while (left < right) { 11 | int mid = left + right >> 1; 12 | 13 | int count = 0; 14 | for (int i = 1; i <= m; i++) { 15 | count += Math.min(n, mid / i); 16 | } 17 | 18 | if (count >= k) { 19 | right = mid; 20 | } else { 21 | left = mid + 1; 22 | } 23 | } 24 | 25 | return left; 26 | } 27 | 28 | } 29 | -------------------------------------------------------------------------------- /src/leetcode/binarysearch/greedyalgorithm/Solution719.java: -------------------------------------------------------------------------------- 1 | package leetcode.binarysearch.greedyalgorithm; 2 | 3 | import java.util.Arrays; 4 | 5 | public class Solution719 { 6 | public int smallestDistancePair(int[] nums, int k) { 7 | Arrays.sort(nums); 8 | 9 | int left = 0, right = (int) 1e6 + 1; 10 | while (left < right) { 11 | int mid = left + right >> 1; 12 | 13 | int count = 0; 14 | for (int i = 0, j = 1; i < nums.length; i++) { 15 | while (j < nums.length && nums[j] - nums[i] <= mid) { 16 | j++; 17 | } 18 | count += j - i - 1; 19 | } 20 | 21 | if (count >= k) { 22 | right = mid; 23 | } else { 24 | left = mid + 1; 25 | } 26 | } 27 | 28 | return left; 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /src/leetcode/binarysearch/greedyalgorithm/Solution875.java: -------------------------------------------------------------------------------- 1 | package leetcode.binarysearch.greedyalgorithm; 2 | 3 | import java.util.Arrays; 4 | 5 | public class Solution875 { 6 | 7 | public static void main(String[] args) { 8 | System.out.println(new Solution875().minEatingSpeed(new int[]{3, 6, 7, 11}, 8)); 9 | } 10 | 11 | public int minEatingSpeed(int[] piles, int h) { 12 | int left = 1, right = Arrays.stream(piles).max().getAsInt() + 1; 13 | while (left < right) { 14 | int mid = left + right >> 1; 15 | 16 | int curHour = 0; 17 | for (int pile : piles) { 18 | curHour += pile / mid; 19 | if (pile % mid > 0) { 20 | curHour++; 21 | } 22 | } 23 | 24 | if (curHour > h) { 25 | left = mid + 1; 26 | } else { 27 | right = mid; 28 | } 29 | } 30 | 31 | return right; 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /src/leetcode/bit/Solution136.java: -------------------------------------------------------------------------------- 1 | package leetcode.bit; 2 | 3 | public class Solution136 { 4 | public int singleNumber(int[] nums) { 5 | int res = nums[0]; 6 | for (int i = 1; i < nums.length; i++) { 7 | res ^= nums[i]; 8 | } 9 | 10 | return res; 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /src/leetcode/bit/Solution137.java: -------------------------------------------------------------------------------- 1 | package leetcode.bit; 2 | 3 | public class Solution137 { 4 | public int singleNumber(int[] nums) { 5 | int[] bits = new int[32]; 6 | for (int i = 0; i < nums.length; i++) { 7 | for (int j = bits.length - 1; j >= 0; j--) { 8 | bits[j] += nums[i] & 1; 9 | nums[i] >>>= 1; 10 | } 11 | } 12 | 13 | int res = 0; 14 | for (int bit : bits) { 15 | res <<= 1; 16 | res |= bit % 3; 17 | } 18 | 19 | return res; 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /src/leetcode/bit/Solution191.java: -------------------------------------------------------------------------------- 1 | package leetcode.bit; 2 | 3 | public class Solution191 { 4 | // you need to treat n as an unsigned value 5 | public int hammingWeight(int n) { 6 | int res = 0; 7 | while (n != 0) { 8 | res += n & 1; 9 | n >>>= 1; 10 | } 11 | 12 | return res; 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /src/leetcode/bit/Solution231.java: -------------------------------------------------------------------------------- 1 | package leetcode.bit; 2 | 3 | public class Solution231 { 4 | public boolean isPowerOfTwo(int n) { 5 | return n > 0 && ((n & (n - 1)) == 0); 6 | } 7 | } 8 | -------------------------------------------------------------------------------- /src/leetcode/bit/Solution260.java: -------------------------------------------------------------------------------- 1 | package leetcode.bit; 2 | 3 | public class Solution260 { 4 | public int[] singleNumber(int[] nums) { 5 | int xor = 0; 6 | for (int num : nums) { 7 | xor ^= num; 8 | } 9 | int lowbit = xor & -xor; 10 | int[] res = new int[2]; 11 | for (int num : nums) { 12 | res[(num & lowbit) == 0 ? 0 : 1] ^= num; 13 | } 14 | 15 | return res; 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /src/leetcode/bit/Solution318.java: -------------------------------------------------------------------------------- 1 | package leetcode.bit; 2 | 3 | public class Solution318 { 4 | public int maxProduct(String[] words) { 5 | int[] masks = new int[words.length]; 6 | for (int i = 0; i < words.length; i++) { 7 | int temp = 0; 8 | for (int j = 0; j < words[i].length(); j++) { 9 | int num = words[i].charAt(j) - 'a'; 10 | temp |= (1 << num); 11 | } 12 | masks[i] = temp; 13 | } 14 | 15 | int res = 0; 16 | for (int i = 0; i < words.length; i++) { 17 | for (int j = 0; j < i; j++) { 18 | if ((masks[i] & masks[j]) == 0) { 19 | res = Math.max(res, words[i].length() * words[j].length()); 20 | } 21 | } 22 | } 23 | 24 | return res; 25 | } 26 | 27 | 28 | } 29 | -------------------------------------------------------------------------------- /src/leetcode/bit/Solution371.java: -------------------------------------------------------------------------------- 1 | package leetcode.bit; 2 | 3 | public class Solution371 { 4 | public int getSum(int a, int b) { 5 | // 无进位相加 + 进位,进位为0时结束 6 | while (b != 0) { 7 | // 无进位相加 8 | int temp = a ^ b; 9 | // 进位 10 | b = (a & b) << 1; 11 | a = temp; 12 | } 13 | return a; 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /src/leetcode/bit/Solution50.java: -------------------------------------------------------------------------------- 1 | package leetcode.bit; 2 | 3 | public class Solution50 { 4 | public double myPow(double x, int n) { 5 | if (x == 0) { 6 | return 0; 7 | } 8 | 9 | if (n < 0) { 10 | n = -n; 11 | x = 1 / x; 12 | } 13 | double res = 1.0; 14 | while (n != 0) { 15 | if ((n & 1) == 1) { 16 | res *= x; 17 | } 18 | x *= x; 19 | n >>>= 1; 20 | } 21 | 22 | return res; 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /src/leetcode/bit/SolutionLCR133.java: -------------------------------------------------------------------------------- 1 | package leetcode.bit; 2 | 3 | public class SolutionLCR133 { 4 | // you need to treat n as an unsigned value 5 | public int hammingWeight(int n) { 6 | int res = 0; 7 | while (n != 0) { 8 | if ((n & 1) == 1) { 9 | res++; 10 | } 11 | n >>>= 1; 12 | } 13 | return res; 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /src/leetcode/datastructure/LRUCacheLinkedHashMap.java: -------------------------------------------------------------------------------- 1 | package leetcode.datastructure; 2 | 3 | import java.util.LinkedHashMap; 4 | import java.util.Map; 5 | 6 | /** 7 | * LinkedHashMap 实现方法 8 | * 9 | * @author FangYuan 10 | * @since 2023-07-18 20:35:51 11 | */ 12 | public class LRUCacheLinkedHashMap extends LinkedHashMap { 13 | 14 | int capacity; 15 | 16 | public LRUCacheLinkedHashMap(int capacity) { 17 | super(capacity, 0.75F, true); 18 | this.capacity = capacity; 19 | } 20 | 21 | public int get(int key) { 22 | return super.getOrDefault(key, -1); 23 | } 24 | 25 | public void put(int key, int value) { 26 | super.put(key, value); 27 | } 28 | 29 | @Override 30 | protected boolean removeEldestEntry(Map.Entry eldest) { 31 | return super.size() > this.capacity; 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /src/leetcode/doublepointer/Interview1001.java: -------------------------------------------------------------------------------- 1 | package leetcode.doublepointer; 2 | 3 | import java.util.Arrays; 4 | 5 | public class Interview1001 { 6 | public void merge(int[] A, int m, int[] B, int n) { 7 | int[] temp = Arrays.copyOfRange(A, 0, m); 8 | int a = 0, b = 0; 9 | int index = 0; 10 | int length = m + n; 11 | while (index < length) { 12 | if (a >= m) { 13 | A[index++] = B[b++]; 14 | continue; 15 | } 16 | if (b >= n) { 17 | A[index++] = temp[a++]; 18 | continue; 19 | } 20 | 21 | if (temp[a] <= B[b]) { 22 | A[index++] = temp[a++]; 23 | } else { 24 | A[index++] = B[b++]; 25 | } 26 | } 27 | } 28 | 29 | } 30 | -------------------------------------------------------------------------------- /src/leetcode/doublepointer/Interview1711.java: -------------------------------------------------------------------------------- 1 | package leetcode.doublepointer; 2 | 3 | public class Interview1711 { 4 | public int findClosest(String[] words, String word1, String word2) { 5 | int res = words.length; 6 | int word1Index = -1, word2Index = -1; 7 | for (int i = 0; i < words.length; i++) { 8 | if (words[i].equals(word1)) { 9 | word1Index = i; 10 | } 11 | if (words[i].equals(word2)) { 12 | word2Index = i; 13 | } 14 | if (word1Index != -1 && word2Index != -1) { 15 | res = Math.min(res, Math.abs(word1Index - word2Index)); 16 | } 17 | } 18 | return res; 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /src/leetcode/doublepointer/Solution11.java: -------------------------------------------------------------------------------- 1 | package leetcode.doublepointer; 2 | 3 | public class Solution11 { 4 | 5 | public static void main(String[] args) { 6 | System.out.println(new Solution11().maxArea(new int[]{1, 1})); 7 | } 8 | 9 | public int maxArea(int[] height) { 10 | int res = 0; 11 | int left = 0, right = height.length - 1; 12 | while (left < right) { 13 | if (height[left] <= height[right]) { 14 | res = Math.max((right - left) * height[left++], res); 15 | } else { 16 | res = Math.max((right - left) * height[right--], res); 17 | } 18 | } 19 | 20 | return res; 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /src/leetcode/doublepointer/Solution125.java: -------------------------------------------------------------------------------- 1 | package leetcode.doublepointer; 2 | 3 | public class Solution125 { 4 | 5 | public static void main(String[] args) { 6 | System.out.println(new Solution125().isPalindrome("A man, a plan, a canal: Panama")); 7 | } 8 | 9 | public boolean isPalindrome(String s) { 10 | String lowerCase = s.toLowerCase(); 11 | 12 | int left = 0, right = lowerCase.length() - 1; 13 | while (left < right) { 14 | while (left < right && !Character.isLetterOrDigit(lowerCase.charAt(left))) { 15 | left++; 16 | } 17 | while (left < right && !Character.isLetterOrDigit(lowerCase.charAt(right))) { 18 | right--; 19 | } 20 | if (lowerCase.charAt(left) != lowerCase.charAt(right)) { 21 | return false; 22 | } 23 | left++; 24 | right--; 25 | } 26 | 27 | return true; 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /src/leetcode/doublepointer/Solution167.java: -------------------------------------------------------------------------------- 1 | package leetcode.doublepointer; 2 | 3 | public class Solution167 { 4 | public int[] twoSum(int[] numbers, int target) { 5 | int left = 0, right = numbers.length - 1; 6 | while (left < right) { 7 | int sum = numbers[left] + numbers[right]; 8 | 9 | if (sum == target) { 10 | return new int[]{left + 1, right + 1}; 11 | } else if (sum > target) { 12 | right--; 13 | } else { 14 | left++; 15 | } 16 | } 17 | 18 | return null; 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /src/leetcode/doublepointer/Solution26.java: -------------------------------------------------------------------------------- 1 | package leetcode.doublepointer; 2 | 3 | public class Solution26 { 4 | public int removeDuplicates(int[] nums) { 5 | int left = 0, right = 0; 6 | while (right < nums.length) { 7 | while (right + 1 < nums.length && nums[right] == nums[right + 1]) { 8 | right++; 9 | } 10 | if (right < nums.length) { 11 | nums[left++] = nums[right++]; 12 | } 13 | } 14 | 15 | return left + 1; 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /src/leetcode/doublepointer/Solution27.java: -------------------------------------------------------------------------------- 1 | package leetcode.doublepointer; 2 | 3 | public class Solution27 { 4 | 5 | public static void main(String[] args) { 6 | // 5 7 | System.out.println(new Solution27().removeElement(new int[]{0, 1, 2, 2, 3, 0, 4, 2}, 2)); 8 | } 9 | 10 | public int removeElement(int[] nums, int val) { 11 | int left = 0, right = 0; 12 | while (right < nums.length) { 13 | while (right < nums.length && nums[right] == val) { 14 | right++; 15 | } 16 | if (right < nums.length) { 17 | nums[left++] = nums[right++]; 18 | } 19 | } 20 | 21 | return left; 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /src/leetcode/doublepointer/Solution392.java: -------------------------------------------------------------------------------- 1 | package leetcode.doublepointer; 2 | 3 | public class Solution392 { 4 | 5 | public boolean isSubsequence(String s, String t) { 6 | int l = 0, r = 0; 7 | while (l < s.length() && r < t.length()) { 8 | if (s.charAt(l) == t.charAt(r)) { 9 | l++; 10 | } 11 | r++; 12 | } 13 | 14 | return l == s.length(); 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /src/leetcode/doublepointer/Solution413.java: -------------------------------------------------------------------------------- 1 | package leetcode.doublepointer; 2 | 3 | public class Solution413 { 4 | 5 | public static void main(String[] args) { 6 | // 2 7 | System.out.println(new Solution413().numberOfArithmeticSlices(new int[]{1, 2, 3, 999, 3, 4, 5, 7})); 8 | } 9 | 10 | public int numberOfArithmeticSlices(int[] nums) { 11 | int res = 0; 12 | if (nums.length < 3) { 13 | return res; 14 | } 15 | 16 | int left = 0, right = left + 1; 17 | while (right < nums.length) { 18 | int b = nums[right] - nums[left]; 19 | while (right + 1 < nums.length && (nums[right + 1] - nums[right]) == b) { 20 | right++; 21 | if (right - left + 1 >= 3) { 22 | res += right - left - 1; 23 | } 24 | } 25 | 26 | left = right++; 27 | } 28 | 29 | return res; 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /src/leetcode/doublepointer/Solution443.java: -------------------------------------------------------------------------------- 1 | package leetcode.doublepointer; 2 | 3 | public class Solution443 { 4 | 5 | public static void main(String[] args) { 6 | System.out.println(new Solution443().compress(new char[]{'a', 'a', 'b', 'b', 'b', 'c', 'c', 'c'})); 7 | } 8 | 9 | public int compress(char[] chars) { 10 | int index = 0; 11 | int left = 0, right = 0; 12 | while (right < chars.length) { 13 | while (right + 1 < chars.length && chars[right + 1] == chars[right]) { 14 | right++; 15 | } 16 | chars[index++] = chars[right]; 17 | if (right - left > 0) { 18 | char[] num = String.valueOf(right - left + 1).toCharArray(); 19 | for (char c : num) { 20 | chars[index++] = c; 21 | } 22 | } 23 | left = ++right; 24 | } 25 | return index; 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /src/leetcode/doublepointer/Solution481.java: -------------------------------------------------------------------------------- 1 | package leetcode.doublepointer; 2 | 3 | public class Solution481 { 4 | 5 | public static void main(String[] args) { 6 | System.out.println(new Solution481().magicalString(7)); 7 | } 8 | 9 | public int magicalString(int n) { 10 | // 122 112 1 221221121122... 11 | if (n <= 3) { 12 | return 1; 13 | } 14 | 15 | int index = 2; 16 | int[] nums = new int[n + 2]; 17 | nums[0] = 1; 18 | nums[1] = 2; 19 | nums[2] = 2; 20 | int num = 1; 21 | for (int i = 3; i < n;) { 22 | nums[i++] = num; 23 | if (nums[index] == 2) { 24 | nums[i++] = num; 25 | } 26 | if (num == 1) { 27 | num = 2; 28 | } else { 29 | num = 1; 30 | } 31 | index++; 32 | } 33 | 34 | int res = 0; 35 | for (int i = 0; i < n; i++) { 36 | res += nums[i] == 1 ? 1 : 0; 37 | } 38 | 39 | return res; 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /src/leetcode/doublepointer/Solution581.java: -------------------------------------------------------------------------------- 1 | package leetcode.doublepointer; 2 | 3 | import java.util.Arrays; 4 | 5 | public class Solution581 { 6 | 7 | public static void main(String[] args) { 8 | System.out.println(new Solution581().findUnsortedSubarray(new int[]{1, 3, 2, 3, 3})); 9 | } 10 | 11 | public int findUnsortedSubarray(int[] nums) { 12 | int[] temp = new int[nums.length]; 13 | System.arraycopy(nums, 0, temp, 0, temp.length); 14 | Arrays.sort(nums); 15 | int left = 0, right = nums.length - 1; 16 | while (left <= right && nums[left] == temp[left]) { 17 | left++; 18 | } 19 | while (left <= right && nums[right] == temp[right]) { 20 | right--; 21 | } 22 | 23 | return right - left + 1; 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /src/leetcode/doublepointer/Solution611.java: -------------------------------------------------------------------------------- 1 | package leetcode.doublepointer; 2 | 3 | import java.util.Arrays; 4 | 5 | public class Solution611 { 6 | public int triangleNumber(int[] nums) { 7 | if (nums.length <= 2) { 8 | return 0; 9 | } 10 | Arrays.sort(nums); 11 | 12 | int res = 0; 13 | for (int one = 0; one < nums.length; one++) { 14 | int two = one + 1; 15 | while (two <= nums.length - 2) { 16 | int three = two + 1; 17 | int sum = nums[one] + nums[two]; 18 | 19 | while (three < nums.length && sum > nums[three]) { 20 | res++; 21 | three++; 22 | } 23 | two++; 24 | } 25 | } 26 | 27 | return res; 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /src/leetcode/doublepointer/Solution80.java: -------------------------------------------------------------------------------- 1 | package leetcode.doublepointer; 2 | 3 | public class Solution80 { 4 | public int removeDuplicates(int[] nums) { 5 | int length = nums.length; 6 | int left = 0, right = left + 1; 7 | while (right < length) { 8 | while (right < length && nums[right] == nums[right - 1]) { 9 | right++; 10 | } 11 | // 重复的超过2 将后续的元素移动过来 12 | if (right - left > 2) { 13 | length -= (right - left - 2); 14 | System.arraycopy(nums, right, nums, left + 2, nums.length - right); 15 | left += 2; 16 | right = left + 1; 17 | } else { 18 | left = right; 19 | right++; 20 | } 21 | } 22 | 23 | return length; 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /src/leetcode/doublepointer/Solution88.java: -------------------------------------------------------------------------------- 1 | package leetcode.doublepointer; 2 | 3 | import leetcode.Solution; 4 | 5 | public class Solution88 { 6 | 7 | public static void main(String[] args) { 8 | new Solution88().merge(new int[]{4, 5, 6, 0, 0, 0}, 3, new int[]{1, 2, 3}, 3); 9 | } 10 | 11 | public void merge(int[] nums1, int m, int[] nums2, int n) { 12 | int index = 0; 13 | int i = 0, j = 0; 14 | int[] res = new int[m + n]; 15 | while (i < m || j < n) { 16 | if (i >= m) { 17 | res[index++] = nums2[j++]; 18 | } else if (j >= n) { 19 | res[index++] = nums1[i++]; 20 | } else { 21 | if (nums1[i] <= nums2[j]) { 22 | res[index++] = nums1[i++]; 23 | } else { 24 | res[index++] = nums2[j++]; 25 | } 26 | } 27 | } 28 | System.arraycopy(res, 0, nums1, 0, res.length); 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /src/leetcode/doublepointer/Solution881.java: -------------------------------------------------------------------------------- 1 | package leetcode.doublepointer; 2 | 3 | import java.util.Arrays; 4 | 5 | public class Solution881 { 6 | 7 | public static void main(String[] args) { 8 | // 3 9 | System.out.println(new Solution881().numRescueBoats(new int[]{3, 2, 3, 2, 2}, 6)); 10 | } 11 | 12 | public int numRescueBoats(int[] people, int limit) { 13 | int res = 0; 14 | int left = 0, right = people.length - 1; 15 | Arrays.sort(people); 16 | 17 | while (left <= right) { 18 | int curPeople = 0; 19 | int curWeight = 0; 20 | while (curPeople < 2 && left <= right && curWeight + people[right] <= limit) { 21 | curWeight += people[right--]; 22 | curPeople++; 23 | } 24 | while (curPeople < 2 && left <= right && curWeight + people[left] <= limit) { 25 | curWeight += people[left++]; 26 | curPeople++; 27 | } 28 | res++; 29 | } 30 | 31 | return res; 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /src/leetcode/doublepointer/SolutionLCR139.java: -------------------------------------------------------------------------------- 1 | package leetcode.doublepointer; 2 | 3 | public class SolutionLCR139 { 4 | public int[] trainingPlan(int[] actions) { 5 | int left = 0, right = actions.length - 1; 6 | 7 | while (left < right) { 8 | while (left < right && actions[left] % 2 == 1) { 9 | left++; 10 | } 11 | while (left < right && actions[right] % 2 == 0) { 12 | right--; 13 | } 14 | 15 | swap(actions, left, right); 16 | } 17 | 18 | return actions; 19 | } 20 | 21 | private void swap(int[] nums, int left, int right) { 22 | int temp = nums[left]; 23 | nums[left] = nums[right]; 24 | nums[right] = temp; 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /src/leetcode/dp/Interview1709.java: -------------------------------------------------------------------------------- 1 | package leetcode.dp; 2 | 3 | public class Interview1709 { 4 | public int getKthMagicNumber(int k) { 5 | int[] res = new int[k]; 6 | res[0] = 1; 7 | int a3 = 0, b5 = 0, c7 = 0; 8 | for (int i = 1; i < res.length; i++) { 9 | int a = res[a3] * 3, b = res[b5] * 5, c = res[c7] * 7; 10 | int num = Math.min(a, Math.min(b, c)); 11 | res[i] = num; 12 | if (num == a) { 13 | a3++; 14 | } 15 | if (num == b) { 16 | b5++; 17 | } 18 | if (num == c) { 19 | c7++; 20 | } 21 | } 22 | 23 | return res[k - 1]; 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /src/leetcode/dp/Solution1035.java: -------------------------------------------------------------------------------- 1 | package leetcode.dp; 2 | 3 | public class Solution1035 { 4 | 5 | /** 6 | * 转换成最长公共子序列问题是比较难想到的 7 | * 连线不相交,则数组中各个元素的相对顺序相同 8 | * dp[i][j] 表示 text1[0..i] 和 text2[0..j] 的最长公共子序列 9 | *

10 | * 如果 text1[i] == text2[j],那么 dp[i][j] 就是 dp[i-1][j-1] 的值加一 11 | * 如果 text1[i] != text2[j],那么 dp[i][j] 就是 dp[i-1][j] 和 dp[i][j-1] 的最大值 12 | */ 13 | public int maxUncrossedLines(int[] nums1, int[] nums2) { 14 | int[][] dp = new int[nums1.length + 1][nums2.length + 1]; 15 | for (int i = 1; i <= nums1.length; i++) { 16 | for (int j = 1; j <= nums2.length; j++) { 17 | if (nums1[i - 1] == nums2[j - 1]) { 18 | dp[i][j] = dp[i - 1][j - 1] + 1; 19 | } else { 20 | dp[i][j] = Math.max(dp[i - 1][j], dp[i][j - 1]); 21 | } 22 | } 23 | } 24 | 25 | return dp[nums1.length][nums2.length]; 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /src/leetcode/dp/Solution1143.java: -------------------------------------------------------------------------------- 1 | package leetcode.dp; 2 | 3 | public class Solution1143 { 4 | 5 | /** 6 | * 最长子序列问题: 7 | * 如果两个字符串的最后一个字符相等,那么最长子序列就是去掉最后一个字符的两个字符串的最长子序列加一 8 | * 如果两个字符串的最后一个字符不相等,那么最长子序列就是去掉 text1 的最后一个字符和 text2 的最长子序列, 9 | * 去掉 text2 的最后一个字符和 text1 的最长子序列的最大值 10 | */ 11 | public int longestCommonSubsequence(String text1, String text2) { 12 | // base case 值为 0,表示字符串无子序列 13 | int[][] dp = new int[text1.length() + 1][text2.length() + 1]; 14 | 15 | // 相等取对角线值(相等字符串长度)加一 16 | // 不等则取上、左最大值 17 | for (int i = 1; i <= text1.length(); i++) { 18 | for (int j = 1; j <= text2.length(); j++) { 19 | if (text1.charAt(i - 1) == text2.charAt(j - 1)) { 20 | dp[i][j] = dp[i - 1][j - 1] + 1; 21 | } else { 22 | dp[i][j] = Math.max(dp[i - 1][j], dp[i][j - 1]); 23 | } 24 | } 25 | } 26 | 27 | return dp[text1.length()][text2.length()]; 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /src/leetcode/dp/Solution1218.java: -------------------------------------------------------------------------------- 1 | package leetcode.dp; 2 | 3 | import java.util.HashMap; 4 | 5 | public class Solution1218 { 6 | 7 | public static void main(String[] args) { 8 | // 2 9 | System.out.println(new Solution1218() 10 | .longestSubsequence(new int[]{10, -11, 8, -1, -14, -5, 7, 15, 7, -2, 14, 5, -3, -9, 12, -9}, -2)); 11 | } 12 | 13 | public int longestSubsequence(int[] arr, int difference) { 14 | int res = 0; 15 | HashMap numCount = new HashMap<>(); 16 | for (int i : arr) { 17 | int cur = numCount.getOrDefault(i - difference, 0) + 1; 18 | numCount.put(i, cur); 19 | res = Math.max(res, cur); 20 | } 21 | 22 | return res; 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /src/leetcode/dp/Solution1312.java: -------------------------------------------------------------------------------- 1 | package leetcode.dp; 2 | 3 | public class Solution1312 { 4 | public int minInsertions(String s) { 5 | int[][] dp = new int[s.length()][s.length()]; 6 | 7 | // 不断的从子串计算转换成回文串的开销 8 | for (int subLength = 2; subLength <= s.length(); subLength++) { 9 | for (int i = 0, j = subLength - 1; j < s.length(); i++, j++) { 10 | if (s.charAt(i) == s.charAt(j)) { 11 | // i和j分别为子串最两边的两个元素,dp[i + 1][j - 1] 表示它们的子回文串 12 | dp[i][j] = dp[i + 1][j - 1]; 13 | } else { 14 | // dp[i][j - 1] 和 dp[i + 1][j] 分别表示两个子串转换成回文串的开销 15 | dp[i][j] = Math.min(dp[i][j - 1], dp[i + 1][j]) + 1; 16 | } 17 | } 18 | } 19 | 20 | return dp[0][s.length() - 1]; 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /src/leetcode/dp/Solution264.java: -------------------------------------------------------------------------------- 1 | package leetcode.dp; 2 | 3 | public class Solution264 { 4 | public int nthUglyNumber(int n) { 5 | int[] dp = new int[n + 1]; 6 | dp[1] = 1; 7 | 8 | int a = 1; 9 | int b = 1; 10 | int c = 1; 11 | for (int i = 2; i <= n; i++) { 12 | int a1 = dp[a] * 2; 13 | int b1 = dp[b] * 3; 14 | int c1 = dp[c] * 5; 15 | dp[i] = Math.min(a1, Math.min(b1, c1)); 16 | if (a1 == dp[i]) { 17 | a++; 18 | } 19 | if (b1 == dp[i]) { 20 | b++; 21 | } 22 | if (c1 == dp[i]) { 23 | c++; 24 | } 25 | } 26 | 27 | return dp[n]; 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /src/leetcode/dp/Solution300.java: -------------------------------------------------------------------------------- 1 | package leetcode.dp; 2 | 3 | import java.util.Arrays; 4 | 5 | public class Solution300 { 6 | public int lengthOfLIS(int[] nums) { 7 | // base case 1 8 | int[] dp = new int[nums.length]; 9 | Arrays.fill(dp, 1); 10 | int res = 1; 11 | 12 | for (int i = 1; i < nums.length; i++) { 13 | for (int j = 0; j < i; j++) { 14 | if (nums[i] > nums[j]) { 15 | dp[i] = Math.max(dp[j] + 1, dp[i]); 16 | } 17 | } 18 | res = Math.max(dp[i], res); 19 | } 20 | 21 | return res; 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /src/leetcode/dp/Solution322.java: -------------------------------------------------------------------------------- 1 | package leetcode.dp; 2 | 3 | import java.util.Arrays; 4 | 5 | public class Solution322 { 6 | public int coinChange(int[] coins, int amount) { 7 | // base case 每个索引对应金额,初始情况大于对应金额即可 8 | int[] dp = new int[amount + 1]; 9 | Arrays.fill(dp, amount + 1); 10 | // 初始0为0 表示正好凑齐的都到这个位置,而正好凑齐不需要累加 11 | dp[0] = 0; 12 | 13 | // 初始化每个金额所需的因硬币数量 14 | for (int i = 1; i <= amount; i++) { 15 | for (int coin : coins) { 16 | if (i >= coin) { 17 | dp[i] = Math.min(dp[i], dp[i - coin] + 1); 18 | } 19 | } 20 | } 21 | 22 | return dp[amount] == amount + 1 ? -1 : dp[amount]; 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /src/leetcode/dp/Solution343.java: -------------------------------------------------------------------------------- 1 | package leetcode.dp; 2 | 3 | public class Solution343 { 4 | public int integerBreak(int n) { 5 | if (n <= 3) { 6 | return n - 1; 7 | } 8 | int[] dp = new int[n + 1]; 9 | dp[1] = 1; 10 | dp[2] = 2; 11 | dp[3] = 3; 12 | 13 | for (int i = 4; i <= n; i++) { 14 | for (int j = 1; j <= n - 1; j++) { 15 | dp[i] = Math.max(dp[i], dp[j] * (i - j)); 16 | } 17 | } 18 | 19 | return dp[n]; 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /src/leetcode/dp/Solution509.java: -------------------------------------------------------------------------------- 1 | package leetcode.dp; 2 | 3 | public class Solution509 { 4 | public int fib(int n) { 5 | if (n == 0) { 6 | return 0; 7 | } 8 | if (n == 1) { 9 | return 1; 10 | } 11 | 12 | int[] dp = new int[n + 1]; 13 | dp[0] = 0; 14 | dp[1] = 1; 15 | for (int i = 2; i <= n; i++) { 16 | dp[i] = dp[i - 1] + dp[i - 2]; 17 | } 18 | 19 | return dp[n]; 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /src/leetcode/dp/Solution516.java: -------------------------------------------------------------------------------- 1 | package leetcode.dp; 2 | 3 | public class Solution516 { 4 | public int longestPalindromeSubseq(String s) { 5 | int[][] dp = new int[s.length()][s.length()]; 6 | for (int i = 0; i < dp.length; i++) { 7 | dp[i][i] = 1; 8 | } 9 | 10 | for (int sublength = 2; sublength <= s.length(); sublength++) { 11 | for (int i = 0, j = sublength - 1; j < s.length(); i++, j++) { 12 | if (s.charAt(i) == s.charAt(j)) { 13 | dp[i][j] = dp[i + 1][j - 1] + 2; 14 | } else { 15 | dp[i][j] = Math.max(dp[i + 1][j], dp[i][j - 1]); 16 | } 17 | } 18 | } 19 | 20 | return dp[0][s.length() - 1]; 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /src/leetcode/dp/Solution64.java: -------------------------------------------------------------------------------- 1 | package leetcode.dp; 2 | 3 | public class Solution64 { 4 | public int minPathSum(int[][] grid) { 5 | // base case 初始化第一行和第一列 6 | for (int i = 1; i < grid.length; i++) { 7 | grid[i][0] += grid[i - 1][0]; 8 | } 9 | for (int i = 1; i < grid[0].length; i++) { 10 | grid[0][i] += grid[0][i - 1]; 11 | } 12 | 13 | // 取小累加 14 | for (int i = 1; i < grid.length; i++) { 15 | for (int j = 1; j < grid[0].length; j++) { 16 | grid[i][j] += Math.min(grid[i - 1][j], grid[i][j - 1]); 17 | } 18 | } 19 | 20 | return grid[grid.length - 1][grid[0].length - 1]; 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /src/leetcode/dp/SolutionLCR166.java: -------------------------------------------------------------------------------- 1 | package leetcode.dp; 2 | 3 | public class SolutionLCR166 { 4 | 5 | public static void main(String[] args) { 6 | System.out.println(new SolutionLCR166().jewelleryValue(new int[][]{new int[]{1, 2, 5}, new int[]{3, 2, 1}})); 7 | } 8 | 9 | public int jewelleryValue(int[][] frame) { 10 | for (int i = 1; i < frame.length; i++) { 11 | frame[i][0] += frame[i - 1][0]; 12 | } 13 | for (int i = 1; i < frame[0].length; i++) { 14 | frame[0][i] += frame[0][i - 1]; 15 | } 16 | 17 | for (int i = 1; i < frame.length; i++) { 18 | for (int j = 1; j < frame[0].length; j++) { 19 | frame[i][j] += Math.max(frame[i - 1][j], frame[i][j - 1]); 20 | } 21 | } 22 | 23 | return frame[frame.length - 1][frame[0].length - 1]; 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /src/leetcode/dp/SolutionLCR185.java: -------------------------------------------------------------------------------- 1 | package leetcode.dp; 2 | 3 | public class SolutionLCR185 { 4 | public double[] dicesProbability(int n) { 5 | // base case 6 | double[] dp = new double[]{1 / 6d, 1 / 6d, 1 / 6d, 1 / 6d, 1 / 6d, 1 / 6d}; 7 | 8 | for (int i = 2; i <= n; i++) { 9 | // 推导公式 10 | double[] temp = new double[i * 5 + 1]; 11 | // 在前一组的基础上加 12 | for (int j = 0; j < dp.length; j++) { 13 | // 6个骰子6种组合 14 | for (int k = 0; k < 6; k++) { 15 | temp[j + k] += dp[j] / 6d; 16 | } 17 | } 18 | dp = temp; 19 | } 20 | 21 | return dp; 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /src/leetcode/dp/SolutionOffer14.java: -------------------------------------------------------------------------------- 1 | package leetcode.dp; 2 | 3 | public class SolutionOffer14 { 4 | public int cuttingRope(int n) { 5 | if (n <= 3) { 6 | return n - 1; 7 | } 8 | 9 | // base case 10 | int[] dp = new int[n + 1]; 11 | dp[1] = 1; 12 | dp[2] = 2; 13 | dp[3] = 3; 14 | for (int i = 3; i <= n; i++) { 15 | for (int j = 1; j <= i - 1; j++) { 16 | dp[i] = Math.max(dp[i], dp[j] * (i - j)); 17 | } 18 | } 19 | 20 | return dp[n]; 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /src/leetcode/dp/SolutionOffer46.java: -------------------------------------------------------------------------------- 1 | package leetcode.dp; 2 | 3 | public class SolutionOffer46 { 4 | public int translateNum(int num) { 5 | // 很像斐波那契数列 6 | String numStr = String.valueOf(num); 7 | // base case 8 | int[] dp = new int[numStr.length() + 1]; 9 | dp[0] = 1; 10 | dp[1] = 1; 11 | 12 | for (int i = 2; i <= numStr.length(); i++) { 13 | int curNum = Integer.parseInt(numStr.substring(i - 2, i)); 14 | if (curNum >= 10 && curNum <= 25) { 15 | dp[i] = dp[i - 1] + dp[i - 2]; 16 | } else { 17 | dp[i] = dp[i - 1]; 18 | } 19 | } 20 | 21 | return dp[numStr.length()]; 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /src/leetcode/dp/fibonacci/Solution1749.java: -------------------------------------------------------------------------------- 1 | package leetcode.dp.fibonacci; 2 | 3 | public class Solution1749 { 4 | 5 | public static void main(String[] args) { 6 | System.out.println(new Solution1749().maxAbsoluteSum(new int[]{-7, -1, 0, -2, 1, 3, 8, -2, -6, -1, -10, -6, -6, 8, -4, -9, -4, 1, 4, -9})); 7 | } 8 | 9 | public int maxAbsoluteSum(int[] nums) { 10 | int max = nums[0], min = nums[0]; 11 | int[] nums2 = new int[nums.length]; 12 | System.arraycopy(nums, 0, nums2, 0, nums.length); 13 | for (int i = 1; i < nums.length; i++) { 14 | // 取最大和取最小 15 | if (nums[i - 1] > 0) { 16 | nums[i] += nums[i - 1]; 17 | } 18 | max = Math.max(max, nums[i]); 19 | if (nums2[i - 1] < 0) { 20 | nums2[i] += nums2[i - 1]; 21 | } 22 | min = Math.min(min, nums2[i]); 23 | } 24 | 25 | return Math.max(max, Math.abs(min)); 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /src/leetcode/dp/fibonacci/Solution198.java: -------------------------------------------------------------------------------- 1 | package leetcode.dp.fibonacci; 2 | 3 | public class Solution198 { 4 | public int rob(int[] nums) { 5 | if (nums.length == 1) { 6 | return nums[0]; 7 | } 8 | 9 | int[] dp = new int[nums.length + 2]; 10 | for (int i = 0; i < nums.length; i++) { 11 | // 偷 / 不偷 12 | dp[i + 2] = Math.max(nums[i] + dp[i], dp[i + 1]); 13 | } 14 | 15 | return Math.max(dp[dp.length - 1], dp[dp.length - 2]); 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /src/leetcode/dp/fibonacci/Solution213.java: -------------------------------------------------------------------------------- 1 | package leetcode.dp.fibonacci; 2 | 3 | 4 | public class Solution213 { 5 | 6 | public static void main(String[] args) { 7 | System.out.println(new Solution213().rob(new int[]{1})); 8 | } 9 | 10 | public int rob(int[] nums) { 11 | if (nums.length == 1) { 12 | return nums[0]; 13 | } 14 | return Math.max(doRob(nums, 0, nums.length - 2), doRob(nums, 1, nums.length - 1)); 15 | } 16 | 17 | // 第一家抢或第一家不抢 18 | private int doRob(int[] nums, int left, int right) { 19 | int[] dp = new int[right - left + 3]; 20 | 21 | for (int i = left; i <= right; i++) { 22 | // 抢还是不抢 23 | dp[i - left + 2] = Math.max(nums[i] + dp[i - left], dp[i - left + 1]); 24 | } 25 | 26 | return dp[dp.length - 1]; 27 | } 28 | 29 | } 30 | -------------------------------------------------------------------------------- /src/leetcode/dp/fibonacci/Solution2320.java: -------------------------------------------------------------------------------- 1 | package leetcode.dp.fibonacci; 2 | 3 | public class Solution2320 { 4 | 5 | public static void main(String[] args) { 6 | System.out.println(new Solution2320().countHousePlacements(1)); 7 | } 8 | 9 | int MOD = (int) (1e9 + 7); 10 | 11 | public int countHousePlacements(int n) { 12 | long[] dp = new long[n + 2]; 13 | dp[0] = 1; 14 | dp[1] = 1; 15 | 16 | for (int i = 0; i < n; i++) { 17 | // dp[i] = dp[i - 1] + dp[i - 2] 18 | dp[i + 2] = (dp[i] + dp[i + 1]) % MOD; 19 | } 20 | 21 | return (int) ((dp[dp.length - 1] * dp[dp.length - 1]) % MOD); 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /src/leetcode/dp/fibonacci/Solution2466.java: -------------------------------------------------------------------------------- 1 | package leetcode.dp.fibonacci; 2 | 3 | public class Solution2466 { 4 | 5 | public static void main(String[] args) { 6 | System.out.println(new Solution2466().countGoodStrings(500, 500, 5, 2)); 7 | } 8 | 9 | public int countGoodStrings(int low, int high, int zero, int one) { 10 | // dp[i] = dp[i - zero] + dp[i - one]; 11 | long[] dp = new long[high + 1]; 12 | dp[0] = 1; 13 | 14 | for (int i = 1; i <= high; i++) { 15 | if (i - zero >= 0) { 16 | dp[i] += dp[i - zero]; 17 | dp[i] %= (long) (1e9 + 7); 18 | } 19 | if (i - one >= 0) { 20 | dp[i] += dp[i - one]; 21 | dp[i] %= (long) (1e9 + 7); 22 | } 23 | } 24 | 25 | long res = 0; 26 | for (int i = low; i <= high; i++) { 27 | res = (long) ((res + dp[i]) % (1e9 + 7)); 28 | } 29 | 30 | return (int) res; 31 | } 32 | 33 | } 34 | -------------------------------------------------------------------------------- /src/leetcode/dp/fibonacci/Solution53.java: -------------------------------------------------------------------------------- 1 | package leetcode.dp.fibonacci; 2 | 3 | public class Solution53 { 4 | public int maxSubArray(int[] nums) { 5 | int max = nums[0]; 6 | 7 | for (int i = 1; i < nums.length; i++) { 8 | if (nums[i - 1] > 0) { 9 | nums[i] += nums[i - 1]; 10 | } 11 | max = Math.max(max, nums[i]); 12 | } 13 | 14 | return max; 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /src/leetcode/dp/fibonacci/Solution70.java: -------------------------------------------------------------------------------- 1 | package leetcode.dp.fibonacci; 2 | 3 | public class Solution70 { 4 | public int climbStairs(int n) { 5 | int[] dp = new int[n + 1]; 6 | dp[0] = 1; 7 | dp[1] = 1; 8 | 9 | for (int i = 2; i <= n; i++) { 10 | dp[i] = dp[i - 1] + dp[i - 2]; 11 | } 12 | 13 | return dp[n]; 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /src/leetcode/dp/fibonacci/Solution746.java: -------------------------------------------------------------------------------- 1 | package leetcode.dp.fibonacci; 2 | 3 | public class Solution746 { 4 | 5 | public static void main(String[] args) { 6 | System.out.println(new Solution746().minCostClimbingStairs(new int[]{10, 15, 20})); 7 | } 8 | 9 | public int minCostClimbingStairs(int[] cost) { 10 | int[] dp = new int[cost.length + 1]; 11 | for (int i = 2; i < dp.length; i++) { 12 | dp[i] = Math.min(dp[i - 1] + cost[i - 1], dp[i - 2] + cost[i - 2]); 13 | } 14 | 15 | return dp[dp.length - 1]; 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /src/leetcode/dp/fibonacci/SolutionLCR165.java: -------------------------------------------------------------------------------- 1 | package leetcode.dp.fibonacci; 2 | 3 | public class SolutionLCR165 { 4 | public int crackNumber(int ciphertext) { 5 | String s = String.valueOf(ciphertext); 6 | int[] dp = new int[s.length() + 1]; 7 | dp[0] = 1; 8 | dp[1] = 1; 9 | 10 | for (int i = 2; i < s.length(); i++) { 11 | int num = Integer.parseInt(s.substring(i - 2, i)); 12 | if (10 <= num && num <= 25) { 13 | dp[i] = dp[i - 1] + dp[i - 2]; 14 | } else { 15 | dp[i] = dp[i - 1]; 16 | } 17 | } 18 | 19 | return dp[s.length()]; 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /src/leetcode/dp/memory/Solution377.java: -------------------------------------------------------------------------------- 1 | package leetcode.dp.memory; 2 | 3 | import java.util.Arrays; 4 | 5 | public class Solution377 { 6 | 7 | public static void main(String[] args) { 8 | System.out.println(new Solution377().combinationSum4(new int[]{1, 2, 3}, 4)); 9 | } 10 | 11 | private int[] memo; 12 | 13 | public int combinationSum4(int[] nums, int target) { 14 | // 记录和为 i 的组合数目 15 | this.memo = new int[target + 1]; 16 | Arrays.fill(memo, -1); 17 | dfs(nums, target); 18 | 19 | return memo[target]; 20 | } 21 | 22 | private int dfs(int[] nums, int sum) { 23 | if (memo[sum] != -1) { 24 | return memo[sum]; 25 | } 26 | if (sum == 0) { 27 | return 1; 28 | } 29 | 30 | int res = 0; 31 | for (int num : nums) { 32 | if (num <= sum) { 33 | res += dfs(nums, sum - num); 34 | } 35 | } 36 | memo[sum] = res; 37 | 38 | return res; 39 | } 40 | 41 | } 42 | -------------------------------------------------------------------------------- /src/leetcode/dp/动态规划二维数组字符串关系图.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/FangYuan33/LeetCode/4beffc725e4b6782c01c6707bdf8c49bab3d0afa/src/leetcode/dp/动态规划二维数组字符串关系图.png -------------------------------------------------------------------------------- /src/leetcode/graph/algorithms/DirectedDFS.java: -------------------------------------------------------------------------------- 1 | package leetcode.graph.algorithms; 2 | 3 | import leetcode.graph.algorithms.basic.Digraph; 4 | 5 | import java.util.List; 6 | 7 | /** 8 | * 有向图的深度优先搜索算法 9 | * 10 | * @author FangYuan 11 | * @since 2024-01-29 20:45:36 12 | */ 13 | public class DirectedDFS { 14 | 15 | private boolean[] marked; 16 | 17 | public DirectedDFS(Digraph digraph, int s) { 18 | marked = new boolean[digraph.V()]; 19 | dfs(digraph, s); 20 | } 21 | 22 | public DirectedDFS(Digraph digraph, List sources) { 23 | marked = new boolean[digraph.V()]; 24 | for (Integer s : sources) { 25 | if (!marked[s]) { 26 | dfs(digraph, s); 27 | } 28 | } 29 | } 30 | 31 | private void dfs(Digraph digraph, int s) { 32 | if (marked[s]) { 33 | return; 34 | } 35 | 36 | marked[s] = true; 37 | for (Integer v : digraph.adj(s)) { 38 | dfs(digraph, v); 39 | } 40 | } 41 | 42 | public boolean marked(int v) { 43 | return marked[v]; 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /src/leetcode/graph/algorithms/Test.java: -------------------------------------------------------------------------------- 1 | package leetcode.graph.algorithms; 2 | 3 | import leetcode.graph.algorithms.basic.Graph; 4 | 5 | public class Test { 6 | public static void main(String[] args) { 7 | Graph graph = new Graph(""); 8 | 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /src/leetcode/graph/algorithms/Topological.java: -------------------------------------------------------------------------------- 1 | package leetcode.graph.algorithms; 2 | 3 | import leetcode.graph.algorithms.basic.Digraph; 4 | 5 | import java.util.Stack; 6 | 7 | /** 8 | * 有向无环图-拓扑排序 9 | * 拓扑排序的目标是将所有节点排序,使得排在前面的节点不能依赖于排在后面的节点 10 | * 拓扑排序的顺序即为一个有向无环图的逆后序排序 11 | * 12 | * @author FangYuan 13 | * @since 2024-01-30 12:55:11 14 | */ 15 | public class Topological { 16 | 17 | private Stack topologicalOrder; 18 | 19 | public Topological(Digraph digraph) { 20 | DirectedCycle directedCycle = new DirectedCycle(digraph); 21 | if (!directedCycle.hasCycle()) { 22 | DepthFirstOrder order = new DepthFirstOrder(digraph); 23 | topologicalOrder = order.reversePost(); 24 | } 25 | } 26 | 27 | /** 28 | * 有向无环图? 29 | */ 30 | public boolean isDAG() { 31 | // 这个判断好有意思哈哈 32 | return topologicalOrder != null; 33 | } 34 | 35 | public Stack order() { 36 | return topologicalOrder; 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /src/leetcode/graph/algorithms/TreMaux.java: -------------------------------------------------------------------------------- 1 | package leetcode.graph.algorithms; 2 | 3 | import leetcode.graph.algorithms.basic.Graph; 4 | 5 | import java.util.LinkedList; 6 | 7 | /** 8 | * TreMaux 算法记录图中某起点所能经过的点和数量 9 | * 10 | * @author FangYuan 11 | * @since 2024-01-24 21:06:04 12 | */ 13 | public class TreMaux { 14 | private boolean[] marked; 15 | 16 | private int count; 17 | 18 | public TreMaux(Graph graph, int begin) { 19 | marked = new boolean[graph.V()]; 20 | dfs(graph, begin); 21 | } 22 | 23 | private void dfs(Graph graph, int s) { 24 | marked[s] = true; 25 | count++; 26 | LinkedList adj = graph.adj(s); 27 | for (Integer v : adj) { 28 | if (!marked[v]) { 29 | dfs(graph, v); 30 | } 31 | } 32 | } 33 | 34 | public int getCount() { 35 | return count; 36 | } 37 | 38 | public boolean marked(int w) { 39 | return marked[w]; 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /src/leetcode/graph/algorithms/basic/Edge.java: -------------------------------------------------------------------------------- 1 | package leetcode.graph.algorithms.basic; 2 | 3 | public class Edge implements Comparable { 4 | 5 | private final int v; 6 | 7 | private final int w; 8 | 9 | private final double weight; 10 | 11 | public Edge(int v, int w, double weight) { 12 | this.v = v; 13 | this.w = w; 14 | this.weight = weight; 15 | } 16 | 17 | public double weight() { 18 | return weight; 19 | } 20 | 21 | public int either() { 22 | return v; 23 | } 24 | 25 | public int other(int v) { 26 | if (v == this.v) { 27 | return w; 28 | } 29 | if (v == this.w) { 30 | return v; 31 | } 32 | return -1; 33 | } 34 | 35 | @Override 36 | public int compareTo(Edge that) { 37 | return Double.compare(this.weight(), that.weight()); 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /src/leetcode/graph/algorithms/basic/EdgeWeightedGraph.java: -------------------------------------------------------------------------------- 1 | package leetcode.graph.algorithms.basic; 2 | 3 | import java.util.LinkedList; 4 | 5 | /** 6 | * 加权无向图 7 | * 8 | * @author FangYuan 9 | * @since 2024-01-31 13:15:45 10 | */ 11 | public class EdgeWeightedGraph { 12 | 13 | private final int V; 14 | 15 | private int E; 16 | 17 | private final LinkedList[] adj; 18 | 19 | public EdgeWeightedGraph(int v) { 20 | this.V = v; 21 | this.E = 0; 22 | adj = new LinkedList[v]; 23 | for (int i = 0; i < adj.length; i++) { 24 | adj[i] = new LinkedList<>(); 25 | } 26 | } 27 | 28 | public void addEdge(Edge e) { 29 | int v = e.either(), w = e.other(v); 30 | adj[v].add(e); 31 | adj[w].add(e); 32 | E++; 33 | } 34 | 35 | public LinkedList adj(int v) { 36 | return adj[v]; 37 | } 38 | 39 | public int getV() { 40 | return V; 41 | } 42 | 43 | public int getE() { 44 | return E; 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /src/leetcode/graph/algorithms/tinyG.txt: -------------------------------------------------------------------------------- 1 | 13 2 | 13 3 | 0 5 4 | 4 3 5 | 0 1 6 | 9 12 7 | 6 4 8 | 5 4 9 | 0 2 10 | 11 12 11 | 9 10 12 | 0 6 13 | 7 8 14 | 9 11 15 | 5 3 -------------------------------------------------------------------------------- /src/leetcode/greedyalgorithm/Solution121.java: -------------------------------------------------------------------------------- 1 | package leetcode.greedyalgorithm; 2 | 3 | public class Solution121 { 4 | public int maxProfit(int[] prices) { 5 | int res = 0; 6 | // 持有价格 7 | int carry = prices[0]; 8 | for (int i = 1; i < prices.length; i++) { 9 | if (prices[i] < carry) { 10 | // 价格小则直接变更持有价格 11 | carry = prices[i]; 12 | } else { 13 | // 当前价格比持有价格大计算利润 14 | res = Math.max(res, prices[i] - carry); 15 | } 16 | } 17 | 18 | return res; 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /src/leetcode/greedyalgorithm/Solution122.java: -------------------------------------------------------------------------------- 1 | package leetcode.greedyalgorithm; 2 | 3 | public class Solution122 { 4 | public int maxProfit(int[] prices) { 5 | int res = 0; 6 | // 持有价格 7 | int carry = prices[0]; 8 | 9 | for (int i = 1; i < prices.length; i++) { 10 | if (carry <= prices[i]) { 11 | // 持有价格低来获取利润 12 | res += (prices[i] - carry); 13 | } 14 | // 持有价格高或者每次计算完利润后都要变更持有价格 15 | carry = prices[i]; 16 | } 17 | 18 | return res; 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /src/leetcode/greedyalgorithm/Solution135.java: -------------------------------------------------------------------------------- 1 | package leetcode.greedyalgorithm; 2 | 3 | import java.util.Arrays; 4 | 5 | public class Solution135 { 6 | public int candy(int[] ratings) { 7 | // 左右两边分别比一次,去两者最大值 8 | int[] left = new int[ratings.length]; 9 | int[] right = new int[ratings.length]; 10 | Arrays.fill(left, 1); 11 | Arrays.fill(right, 1); 12 | 13 | // 从第二个同学开始,不断地比较左边 14 | for (int i = 1; i < left.length; i++) { 15 | if (ratings[i] > ratings[i - 1]) { 16 | left[i] = left[i - 1] + 1; 17 | } 18 | } 19 | // 注意这里,比较完左边后,最后一个同学的糖果数量就确定了,直接赋值即可 20 | int candyCount = left[left.length - 1]; 21 | // 从倒数第二个同学开始比,不断地比较右边 22 | for (int i = right.length - 2; i >= 0; i--) { 23 | if (ratings[i] > ratings[i + 1]) { 24 | right[i] = right[i + 1] + 1; 25 | } 26 | // 已经赋值了最右侧的同学,不断的从倒数第二个同学累加即可 27 | candyCount += Math.max(left[i], right[i]); 28 | } 29 | 30 | return candyCount; 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /src/leetcode/greedyalgorithm/Solution179.java: -------------------------------------------------------------------------------- 1 | package leetcode.greedyalgorithm; 2 | 3 | import java.util.Arrays; 4 | 5 | public class Solution179 { 6 | public String largestNumber(int[] nums) { 7 | String[] ss = new String[nums.length]; 8 | for (int i = 0; i < nums.length; i++) { 9 | ss[i] = String.valueOf(nums[i]); 10 | } 11 | Arrays.sort(ss, (x, y) -> { 12 | String a = x + y, b = y + x; 13 | return b.compareTo(a); 14 | }); 15 | 16 | StringBuilder res = new StringBuilder(); 17 | for (String s : ss) { 18 | res.append(s); 19 | } 20 | int index = 0; 21 | while (index < res.length() - 1 && res.charAt(index) == '0') { 22 | index++; 23 | } 24 | return res.substring(index); 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /src/leetcode/greedyalgorithm/Solution1953.java: -------------------------------------------------------------------------------- 1 | package leetcode.greedyalgorithm; 2 | 3 | import java.util.Arrays; 4 | import java.util.PriorityQueue; 5 | 6 | public class Solution1953 { 7 | 8 | public static void main(String[] args) { 9 | System.out.println(new Solution1953().numberOfWeeks(new int[]{5, 7, 5, 7, 9, 7})); 10 | } 11 | 12 | public long numberOfWeeks(int[] milestones) { 13 | long sum = 0, max = 0; 14 | for (int milestone : milestones) { 15 | sum += milestone; 16 | max = Math.max(max, milestone); 17 | } 18 | 19 | if (max > (sum - max)) { 20 | return (sum - max) * 2 + 1; 21 | } else { 22 | return sum; 23 | } 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /src/leetcode/greedyalgorithm/Solution334.java: -------------------------------------------------------------------------------- 1 | package leetcode.greedyalgorithm; 2 | 3 | import java.util.HashMap; 4 | 5 | public class Solution334 { 6 | 7 | public static void main(String[] args) { 8 | System.out.println(new Solution334().increasingTriplet(new int[]{1, 5, 0, 4, 1, 3})); 9 | } 10 | 11 | public boolean increasingTriplet(int[] nums) { 12 | boolean exist = true; 13 | int min = nums[0], mid = Integer.MAX_VALUE; 14 | for (int i = 1; i < nums.length; i++) { 15 | if (nums[i] > mid) { 16 | return exist; 17 | } 18 | if (nums[i] > min) { 19 | mid = Math.min(mid, nums[i]); 20 | } else { 21 | min = nums[i]; 22 | } 23 | } 24 | return !exist; 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /src/leetcode/greedyalgorithm/Solution55.java: -------------------------------------------------------------------------------- 1 | package leetcode.greedyalgorithm; 2 | 3 | public class Solution55 { 4 | public boolean canJump(int[] nums) { 5 | int distance = nums[0]; 6 | for (int i = 1; i < nums.length; i++) { 7 | if (distance >= i) { 8 | distance = Math.max(distance, i + nums[i]); 9 | } else { 10 | break; 11 | } 12 | } 13 | 14 | return distance >= nums.length - 1; 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /src/leetcode/greedyalgorithm/Solution768.java: -------------------------------------------------------------------------------- 1 | package leetcode.greedyalgorithm; 2 | 3 | import java.util.ArrayDeque; 4 | 5 | public class Solution768 { 6 | public int maxChunksToSorted(int[] arr) { 7 | // 保留块中最大值作为块的代表 8 | ArrayDeque stack = new ArrayDeque<>(); 9 | for(int num : arr) { 10 | // 如果存在比当前最大值块小的元素,那么该元素需要将其余较大的元素挤走,因为这些待被挤走的元素已经不能够成为块的代表了 11 | if(!stack.isEmpty() && num < stack.getLast()) { 12 | int max = stack.removeLast(); 13 | while(!stack.isEmpty() && num < stack.getLast()) stack.removeLast(); 14 | // 最终入栈的是最大值而不是 num 因为 num 会作为该最大值块中的一个元素 15 | stack.addLast(max); 16 | } else { 17 | // 比最大值 >= 的直接入栈 18 | stack.addLast(num); 19 | } 20 | } 21 | return stack.size(); 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /src/leetcode/hashmap/FreqStack.java: -------------------------------------------------------------------------------- 1 | package leetcode.hashmap; 2 | 3 | import java.util.ArrayList; 4 | import java.util.HashMap; 5 | import java.util.List; 6 | 7 | public class FreqStack { 8 | 9 | HashMap numFreq; 10 | 11 | HashMap> freqNum; 12 | 13 | int maxFreq; 14 | 15 | public FreqStack() { 16 | numFreq = new HashMap<>(); 17 | freqNum = new HashMap<>(); 18 | maxFreq = 0; 19 | } 20 | 21 | public void push(int val) { 22 | int freq = numFreq.getOrDefault(val, 0) + 1; 23 | numFreq.put(val, freq); 24 | 25 | maxFreq = Math.max(maxFreq, freq); 26 | 27 | List list = freqNum.getOrDefault(freq, new ArrayList<>()); 28 | list.add(val); 29 | freqNum.put(freq, list); 30 | } 31 | 32 | public int pop() { 33 | List list = freqNum.get(maxFreq); 34 | Integer res = list.remove(list.size() - 1); 35 | numFreq.put(res, maxFreq - 1); 36 | if (list.size() == 0) { 37 | maxFreq--; 38 | } 39 | return res; 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /src/leetcode/hashmap/Solution1.java: -------------------------------------------------------------------------------- 1 | package leetcode.hashmap; 2 | 3 | import java.util.HashMap; 4 | 5 | public class Solution1 { 6 | public int[] twoSum(int[] nums, int target) { 7 | HashMap hashMap = new HashMap<>(nums.length); 8 | 9 | for (int i = 0; i < nums.length; i++) { 10 | int num = target - nums[i]; 11 | if (hashMap.containsKey(num)) { 12 | return new int[]{hashMap.get(num), i}; 13 | } 14 | hashMap.put(nums[i], i); 15 | } 16 | 17 | return new int[]{-1, -1}; 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /src/leetcode/hashmap/Solution169.java: -------------------------------------------------------------------------------- 1 | package leetcode.hashmap; 2 | 3 | import java.util.HashMap; 4 | 5 | public class Solution169 { 6 | public int majorityElement(int[] nums) { 7 | int halfLength = nums.length / 2; 8 | HashMap numCount = new HashMap<>(); 9 | for (int num : nums) { 10 | numCount.put(num, numCount.getOrDefault(num, 0) + 1); 11 | if (numCount.get(num) > halfLength) { 12 | return num; 13 | } 14 | } 15 | 16 | return -1; 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /src/leetcode/hashmap/Solution205.java: -------------------------------------------------------------------------------- 1 | package leetcode.hashmap; 2 | 3 | import java.util.HashMap; 4 | 5 | public class Solution205 { 6 | public boolean isIsomorphic(String s, String t) { 7 | HashMap mapping1 = new HashMap<>(); 8 | HashMap mapping2 = new HashMap<>(); 9 | char[] sCharArray = s.toCharArray(); 10 | char[] tCharArray = t.toCharArray(); 11 | for (int i = 0; i < sCharArray.length; i++) { 12 | if (mapping1.containsKey(sCharArray[i])) { 13 | if (mapping1.get(sCharArray[i]) != tCharArray[i]) { 14 | return false; 15 | } 16 | } else if (mapping2.containsKey(tCharArray[i])) { 17 | if (mapping2.get(tCharArray[i]) != sCharArray[i]) { 18 | return false; 19 | } 20 | } else { 21 | mapping1.put(sCharArray[i], tCharArray[i]); 22 | mapping2.put(tCharArray[i], sCharArray[i]); 23 | } 24 | } 25 | 26 | return true; 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /src/leetcode/hashmap/Solution229.java: -------------------------------------------------------------------------------- 1 | package leetcode.hashmap; 2 | 3 | import java.util.*; 4 | 5 | public class Solution229 { 6 | public List majorityElement(int[] nums) { 7 | HashMap numCount = new HashMap<>(); 8 | for (int num : nums) { 9 | numCount.put(num, numCount.getOrDefault(num, 0) + 1); 10 | } 11 | 12 | int n = nums.length / 3; 13 | LinkedList res = new LinkedList<>(); 14 | for (Map.Entry entry : numCount.entrySet()) { 15 | if (entry.getValue() > n) { 16 | res.add(entry.getKey()); 17 | } 18 | } 19 | 20 | return res; 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /src/leetcode/hashmap/Solution242.java: -------------------------------------------------------------------------------- 1 | package leetcode.hashmap; 2 | 3 | import java.util.HashMap; 4 | 5 | public class Solution242 { 6 | public boolean isAnagram(String s, String t) { 7 | if (s.length() != t.length()) { 8 | return false; 9 | } 10 | 11 | HashMap mapS = getCharNumMap(s); 12 | HashMap mapT = getCharNumMap(t); 13 | 14 | for (char c : t.toCharArray()) { 15 | if (!mapS.containsKey(c) || !mapS.get(c).equals(mapT.get(c))) { 16 | return false; 17 | } 18 | } 19 | 20 | return true; 21 | } 22 | 23 | private HashMap getCharNumMap(String s) { 24 | HashMap mapS = new HashMap<>(); 25 | for (char c : s.toCharArray()) { 26 | mapS.put(c, mapS.getOrDefault(c, 0) + 1); 27 | } 28 | return mapS; 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /src/leetcode/hashmap/Solution2962.java: -------------------------------------------------------------------------------- 1 | package leetcode.hashmap; 2 | 3 | import java.util.Arrays; 4 | import java.util.HashMap; 5 | 6 | public class Solution2962 { 7 | public long countSubarrays(int[] nums, int k) { 8 | long res = 0; 9 | int max = Arrays.stream(nums).max().getAsInt(); 10 | int num = 0; 11 | 12 | // map 将对应的数量和索引记录下来 13 | HashMap numIndex = new HashMap<>(); 14 | numIndex.put(0, 0); 15 | for (int i = 0; i < nums.length; i++) { 16 | if (nums[i] == max) { 17 | num++; 18 | numIndex.put(num, i); 19 | } 20 | if (num >= k) { 21 | int maxIndex = numIndex.get(num - k + 1); 22 | res += (maxIndex + 1); 23 | } 24 | } 25 | 26 | return res; 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /src/leetcode/hashmap/Solution387.java: -------------------------------------------------------------------------------- 1 | package leetcode.hashmap; 2 | 3 | import java.util.LinkedHashMap; 4 | import java.util.Map; 5 | 6 | public class Solution387 { 7 | 8 | public static void main(String[] args) { 9 | System.out.println(new Solution387().firstUniqChar("loveleetcode")); 10 | } 11 | 12 | public int firstUniqChar(String s) { 13 | LinkedHashMap linkedHashMap = new LinkedHashMap<>(); 14 | char[] charArray = s.toCharArray(); 15 | 16 | for (int i = 0; i < charArray.length; i++) { 17 | if (linkedHashMap.containsKey(charArray[i])) { 18 | linkedHashMap.put(charArray[i], -1); 19 | } else { 20 | linkedHashMap.put(charArray[i], i); 21 | } 22 | } 23 | 24 | for (Map.Entry entry : linkedHashMap.entrySet()) { 25 | if (entry.getValue() != -1) { 26 | return entry.getValue(); 27 | } 28 | } 29 | 30 | return -1; 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /src/leetcode/hashmap/Solution409.java: -------------------------------------------------------------------------------- 1 | package leetcode.hashmap; 2 | 3 | import java.util.HashMap; 4 | import java.util.Map; 5 | 6 | public class Solution409 { 7 | public int longestPalindrome(String s) { 8 | HashMap characterCount = new HashMap<>(); 9 | for (char c : s.toCharArray()) { 10 | characterCount.put(c, characterCount.getOrDefault(c, 0) + 1); 11 | } 12 | 13 | int res = 0; 14 | for (Map.Entry entry : characterCount.entrySet()) { 15 | res += entry.getValue() / 2 * 2; 16 | if (res % 2 == 0 && entry.getValue() % 2 == 1) { 17 | res++; 18 | } 19 | } 20 | return res; 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /src/leetcode/hashmap/Solution41.java: -------------------------------------------------------------------------------- 1 | package leetcode.hashmap; 2 | 3 | public class Solution41 { 4 | 5 | public static void main(String[] args) { 6 | System.out.println(new Solution41().firstMissingPositive(new int[]{-1, 4, 2, 1, 9, 10})); 7 | } 8 | 9 | public int firstMissingPositive(int[] nums) { 10 | for (int i = 0; i < nums.length;) { 11 | if (nums[i] - 1 != i && (nums[i] - 1) < nums.length && (nums[i] - 1) >= 0 && nums[nums[i] - 1] != nums[i]) { 12 | int temp = nums[nums[i] - 1]; 13 | nums[nums[i] - 1] = nums[i]; 14 | nums[i] = temp; 15 | } else { 16 | i++; 17 | } 18 | } 19 | 20 | int res = 1; 21 | for (int num : nums) { 22 | if (num == res) { 23 | res++; 24 | } 25 | } 26 | 27 | return res; 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /src/leetcode/linkedlist/Solution0205.java: -------------------------------------------------------------------------------- 1 | package leetcode.linkedlist; 2 | 3 | import leetcode.ListNode; 4 | 5 | public class Solution0205 { 6 | public ListNode addTwoNumbers(ListNode l1, ListNode l2) { 7 | ListNode pre = new ListNode(-1); 8 | ListNode res = pre; 9 | 10 | int carry = 0; 11 | while (l1 != null || l2 != null) { 12 | int x = l1 != null ? l1.val : 0; 13 | int y = l2 != null ? l2.val : 0; 14 | 15 | // 求和 16 | int sum = x + y + carry; 17 | int val = sum % 10; 18 | carry = sum / 10; 19 | pre.next = new ListNode(val); 20 | pre = pre.next; 21 | 22 | if (l1 != null) { 23 | l1 = l1.next; 24 | } 25 | if (l2 != null) { 26 | l2 = l2.next; 27 | } 28 | } 29 | if (carry == 1) { 30 | pre.next = new ListNode(1); 31 | } 32 | 33 | return res.next; 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /src/leetcode/linkedlist/Solution138.java: -------------------------------------------------------------------------------- 1 | package leetcode.linkedlist; 2 | 3 | import leetcode.Node; 4 | 5 | import java.util.HashMap; 6 | 7 | public class Solution138 { 8 | 9 | HashMap map; 10 | 11 | public Node copyRandomList(Node head) { 12 | map = new HashMap<>(); 13 | return doCopyRandomList(head); 14 | } 15 | 16 | private Node doCopyRandomList(Node node) { 17 | if (node == null) { 18 | return null; 19 | } 20 | if (map.containsKey(node)) { 21 | return map.get(node); 22 | } 23 | 24 | Node newNode = new Node(node.val); 25 | map.put(node, newNode); 26 | newNode.next = doCopyRandomList(node.next); 27 | newNode.random = doCopyRandomList(node.random); 28 | 29 | return newNode; 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /src/leetcode/linkedlist/Solution141.java: -------------------------------------------------------------------------------- 1 | package leetcode.linkedlist; 2 | 3 | import leetcode.ListNode; 4 | 5 | public class Solution141 { 6 | public boolean hasCycle(ListNode head) { 7 | ListNode slow = head, fast = head; 8 | 9 | while (fast != null && fast.next != null) { 10 | slow = slow.next; 11 | fast = fast.next.next; 12 | 13 | if (slow == fast) { 14 | return true; 15 | } 16 | } 17 | 18 | return false; 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /src/leetcode/linkedlist/Solution142.java: -------------------------------------------------------------------------------- 1 | package leetcode.linkedlist; 2 | 3 | import leetcode.ListNode; 4 | 5 | public class Solution142 { 6 | public ListNode detectCycle(ListNode head) { 7 | // 空节点和单节点不能成环 8 | if (head == null || head.next == null) { 9 | return null; 10 | } 11 | 12 | ListNode fast = head; 13 | ListNode slow = head; 14 | while (fast != null && fast.next != null) { 15 | fast = fast.next.next; 16 | slow = slow.next; 17 | // 相遇说明有环 18 | if (slow == fast) { 19 | // f 表示 fast 指针走的距离;s 表示 slow 指针走的距离;记圈中节点数为 n; 20 | // 头节点到入环节点的距离为 x,那么走 n * k + x 距离始终在头节点处,其中 k 为任意正整数 21 | // f = 2s, f = n * y + s 其中 y 为 fast 多走的圈数 -> s = n * y 22 | // 我们可知相遇后,如果 slow 再走 x 那么即可达到入口处,如果此时 slow 和头节点一起走,相遇时则为入口节点 23 | while (slow != head) { 24 | slow = slow.next; 25 | head = head.next; 26 | } 27 | return head; 28 | } 29 | } 30 | 31 | return null; 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /src/leetcode/linkedlist/Solution160.java: -------------------------------------------------------------------------------- 1 | package leetcode.linkedlist; 2 | 3 | import leetcode.ListNode; 4 | 5 | public class Solution160 { 6 | public ListNode getIntersectionNode(ListNode headA, ListNode headB) { 7 | // 如果有公共节点,两个链表分别从头节点开始走,走完各个链表的节点后,再走对方的节点 8 | // 而在走对方的节点时,它们两个一起走下去会一起遇到交点 9 | ListNode aNode = headA, bNode = headB; 10 | while (aNode != null && bNode != null) { 11 | // 先判断 因为交点可能是第一个节点 12 | if (aNode == bNode) { 13 | return aNode; 14 | } else if (aNode.next == null && bNode.next == null) { 15 | // 这种情况是两链表没有相交的情况 16 | break; 17 | } 18 | aNode = aNode.next == null ? headB : aNode.next; 19 | bNode = bNode.next == null ? headA : bNode.next; 20 | } 21 | 22 | return null; 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /src/leetcode/linkedlist/Solution1823.java: -------------------------------------------------------------------------------- 1 | package leetcode.linkedlist; 2 | 3 | import java.util.LinkedList; 4 | 5 | public class Solution1823 { 6 | 7 | public static void main(String[] args) { 8 | System.out.println(new Solution1823().findTheWinner(5, 2)); 9 | } 10 | 11 | public int findTheWinner(int n, int k) { 12 | LinkedList children = new LinkedList<>(); 13 | for (int i = 1; i <= n; i++) { 14 | children.add(i); 15 | } 16 | 17 | int cur = 0; 18 | while (children.size() > 1) { 19 | int index = cur + k - 1 < children.size() ? cur + k - 1 : (cur + k - 1) % children.size(); 20 | children.remove(index); 21 | cur = index; 22 | } 23 | 24 | return children.peek(); 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /src/leetcode/linkedlist/Solution19.java: -------------------------------------------------------------------------------- 1 | package leetcode.linkedlist; 2 | 3 | import leetcode.ListNode; 4 | 5 | public class Solution19 { 6 | public ListNode removeNthFromEnd(ListNode head, int n) { 7 | ListNode pre = new ListNode(-1); 8 | pre.next = head; 9 | 10 | // 先把倒数的位数走完 11 | ListNode cur = head; 12 | while (n != 0) { 13 | cur = cur.next; 14 | n--; 15 | } 16 | 17 | ListNode node = pre; 18 | // 然后以该位置为准,走到 NULL,这是 node 就走到了要删除的前一个节点 19 | while (cur != null) { 20 | cur = cur.next; 21 | node = node.next; 22 | } 23 | // 执行删除 24 | node.next = node.next.next; 25 | 26 | return pre.next; 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /src/leetcode/linkedlist/Solution206.java: -------------------------------------------------------------------------------- 1 | package leetcode.linkedlist; 2 | 3 | import leetcode.ListNode; 4 | 5 | public class Solution206 { 6 | public ListNode reverseList(ListNode head) { 7 | ListNode pre = null; 8 | 9 | while (head != null) { 10 | ListNode temp = head.next; 11 | head.next = pre; 12 | pre = head; 13 | head = temp; 14 | } 15 | return pre; 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /src/leetcode/linkedlist/Solution234.java: -------------------------------------------------------------------------------- 1 | package leetcode.linkedlist; 2 | 3 | import leetcode.ListNode; 4 | 5 | public class Solution234 { 6 | public boolean isPalindrome(ListNode head) { 7 | // 快慢指针分开 8 | ListNode slow = head, fast = head; 9 | while (fast != null && fast.next != null) { 10 | slow = slow.next; 11 | fast = fast.next.next; 12 | } 13 | 14 | ListNode halfHead = reverse(slow); 15 | while (halfHead != null && head != null) { 16 | if (halfHead.val != head.val) { 17 | return false; 18 | } 19 | halfHead = halfHead.next; 20 | head = head.next; 21 | } 22 | 23 | return true; 24 | } 25 | 26 | private ListNode reverse(ListNode node) { 27 | ListNode pre = null; 28 | 29 | while (node != null) { 30 | ListNode temp = node.next; 31 | 32 | node.next = pre; 33 | pre = node; 34 | node = temp; 35 | } 36 | 37 | return pre; 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /src/leetcode/linkedlist/Solution237.java: -------------------------------------------------------------------------------- 1 | package leetcode.linkedlist; 2 | 3 | import leetcode.ListNode; 4 | 5 | public class Solution237 { 6 | public void deleteNode(ListNode node) { 7 | // 将后续的值前移,删除尾巴节点 8 | ListNode pre = node; 9 | node.val = node.next.val; 10 | node = node.next; 11 | 12 | while (node != null) { 13 | if (node.next != null) { 14 | node.val = node.next.val; 15 | pre = pre.next; 16 | node = node.next; 17 | } else { 18 | pre.next = null; 19 | break; 20 | } 21 | } 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /src/leetcode/linkedlist/Solution24.java: -------------------------------------------------------------------------------- 1 | package leetcode.linkedlist; 2 | 3 | import leetcode.ListNode; 4 | 5 | public class Solution24 { 6 | public ListNode swapPairs(ListNode head) { 7 | if (head != null && head.next != null) { 8 | ListNode next = head.next; 9 | ListNode temp = next.next; 10 | 11 | // 反转 12 | next.next = head; 13 | head.next = temp; 14 | // 递归 15 | head.next = swapPairs(temp); 16 | 17 | return next; 18 | } else { 19 | return head; 20 | } 21 | } 22 | 23 | } 24 | -------------------------------------------------------------------------------- /src/leetcode/linkedlist/Solution287.java: -------------------------------------------------------------------------------- 1 | package leetcode.linkedlist; 2 | 3 | public class Solution287 { 4 | 5 | public static void main(String[] args) { 6 | System.out.println(new Solution287().findDuplicate(new int[]{1, 3, 4, 2, 2})); 7 | } 8 | 9 | public int findDuplicate(int[] nums) { 10 | int slow = 0, fast = 0; 11 | 12 | // 第一次相遇,已经在环形链表中 13 | do { 14 | slow = next(nums, slow); 15 | fast = next(nums, next(nums, fast)); 16 | } while (slow != fast); 17 | // 头节点从 0 开始走,与 slow 相遇即是环的入口,该入口被多个节点指向 18 | int head = 0; 19 | while (slow != head) { 20 | slow = next(nums, slow); 21 | head = next(nums, head); 22 | } 23 | 24 | // 那么slow即为指向该入口的重复元素之一 25 | return slow; 26 | } 27 | 28 | private int next(int[] nums, int i) { 29 | return nums[i]; 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /src/leetcode/linkedlist/Solution328.java: -------------------------------------------------------------------------------- 1 | package leetcode.linkedlist; 2 | 3 | import leetcode.ListNode; 4 | 5 | public class Solution328 { 6 | public ListNode oddEvenList(ListNode head) { 7 | if (head == null || head.next == null || head.next.next == null) { 8 | return head; 9 | } 10 | 11 | ListNode pre = new ListNode(1); 12 | pre.next = head; 13 | 14 | ListNode one = head; 15 | ListNode twoHead = head.next; 16 | ListNode two = twoHead; 17 | 18 | while (one.next != null && two.next != null) { 19 | one.next = one.next.next; 20 | two.next = one.next.next; 21 | 22 | one = one.next; 23 | two = two.next; 24 | } 25 | // 拼接奇偶链表 26 | one.next = twoHead; 27 | 28 | return pre.next; 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /src/leetcode/linkedlist/Solution382.java: -------------------------------------------------------------------------------- 1 | package leetcode.linkedlist; 2 | 3 | import leetcode.ListNode; 4 | 5 | import java.util.ArrayList; 6 | import java.util.List; 7 | import java.util.Random; 8 | 9 | public class Solution382 { 10 | // 蓄水池抽样的方法:放在 list 里之后随机取数 11 | private List list; 12 | 13 | private Random random; 14 | 15 | public Solution382(ListNode head) { 16 | random = new Random(); 17 | list = new ArrayList<>(); 18 | 19 | while (head != null) { 20 | list.add(head.val); 21 | head = head.next; 22 | } 23 | } 24 | 25 | public int getRandom() { 26 | int index = random.nextInt(list.size()); 27 | return list.get(index); 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /src/leetcode/linkedlist/Solution817.java: -------------------------------------------------------------------------------- 1 | package leetcode.linkedlist; 2 | 3 | import leetcode.ListNode; 4 | 5 | import java.util.ArrayList; 6 | 7 | public class Solution817 { 8 | public int numComponents(ListNode head, int[] nums) { 9 | ArrayList list = new ArrayList<>(nums.length); 10 | for (int num : nums) { 11 | list.add(num); 12 | } 13 | 14 | int res = 0; 15 | while (head != null) { 16 | if (list.contains(head.val)) { 17 | res++; 18 | while (head != null && list.contains(head.val)) { 19 | head = head.next; 20 | } 21 | } else { 22 | head = head.next; 23 | } 24 | } 25 | 26 | return res; 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /src/leetcode/linkedlist/Solution82.java: -------------------------------------------------------------------------------- 1 | package leetcode.linkedlist; 2 | 3 | import leetcode.ListNode; 4 | 5 | public class Solution82 { 6 | public ListNode deleteDuplicates(ListNode head) { 7 | ListNode pre = new ListNode(-1); 8 | pre.next = head; 9 | // 把重复的前驱节点也记录下来,删除节点的时候使用 10 | ListNode preHead = pre; 11 | 12 | while (head != null) { 13 | if (head.next != null && head.val == head.next.val) { 14 | // 碰见重复的一直删除 15 | while (head.next != null && head.val == head.next.val) { 16 | head.next = head.next.next; 17 | } 18 | 19 | // 删除完毕后把这个节点也删除 20 | preHead.next = head.next; 21 | head = preHead.next; 22 | } else { 23 | // 不重复的变换指针即可 24 | head = head.next; 25 | preHead = preHead.next; 26 | } 27 | } 28 | 29 | return pre.next; 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /src/leetcode/linkedlist/Solution83.java: -------------------------------------------------------------------------------- 1 | package leetcode.linkedlist; 2 | 3 | import leetcode.ListNode; 4 | 5 | public class Solution83 { 6 | public ListNode deleteDuplicates(ListNode head) { 7 | ListNode pre = new ListNode(-1); 8 | pre.next = head; 9 | 10 | while (head != null) { 11 | // 存在值相等的话一直删除,否则换到下一个节点 12 | if (head.next != null && head.val == head.next.val) { 13 | head.next = head.next.next; 14 | } else { 15 | head = head.next; 16 | } 17 | } 18 | 19 | return pre.next; 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /src/leetcode/linkedlist/Solution86.java: -------------------------------------------------------------------------------- 1 | package leetcode.linkedlist; 2 | 3 | import leetcode.ListNode; 4 | 5 | public class Solution86 { 6 | 7 | public ListNode partition(ListNode head, int x) { 8 | ListNode smallPre = new ListNode(0), bigPre = new ListNode(0); 9 | ListNode small = smallPre, big = bigPre; 10 | 11 | while (head != null) { 12 | // 在原来的位置删除 13 | ListNode temp = head.next; 14 | head.next = null; 15 | 16 | if (head.val < x) { 17 | // 插入小链表中 18 | small.next = head; 19 | small = small.next; 20 | } else { 21 | big.next = head; 22 | big = big.next; 23 | } 24 | 25 | head = temp; 26 | } 27 | small.next = bigPre.next; 28 | 29 | return smallPre.next; 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /src/leetcode/linkedlist/Solution876.java: -------------------------------------------------------------------------------- 1 | package leetcode.linkedlist; 2 | 3 | import leetcode.ListNode; 4 | 5 | public class Solution876 { 6 | public ListNode middleNode(ListNode head) { 7 | ListNode slow = head, fast = head; 8 | 9 | while (fast != null && fast.next != null) { 10 | slow = slow.next; 11 | fast = fast.next.next; 12 | } 13 | 14 | return slow; 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /src/leetcode/linkedlist/SolutionOffer06.java: -------------------------------------------------------------------------------- 1 | package leetcode.linkedlist; 2 | 3 | import leetcode.ListNode; 4 | 5 | import java.util.ArrayList; 6 | import java.util.List; 7 | 8 | public class SolutionOffer06 { 9 | 10 | private List res; 11 | 12 | public int[] reversePrint(ListNode head) { 13 | res = new ArrayList<>(); 14 | recursion(head); 15 | 16 | int[] resArray = new int[res.size()]; 17 | for (int i = 0; i < resArray.length; i++) { 18 | resArray[i] = res.get(i); 19 | } 20 | 21 | return resArray; 22 | } 23 | 24 | private void recursion(ListNode node) { 25 | // 递归结束条件 26 | if (node == null) { 27 | return; 28 | } 29 | 30 | recursion(node.next); 31 | res.add(node.val); 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /src/leetcode/linkedlist/SolutionOffer18.java: -------------------------------------------------------------------------------- 1 | package leetcode.linkedlist; 2 | 3 | import leetcode.ListNode; 4 | 5 | public class SolutionOffer18 { 6 | public ListNode deleteNode(ListNode head, int val) { 7 | if (head == null) { 8 | return null; 9 | } 10 | 11 | ListNode pre = new ListNode(-1); 12 | pre.next = head; 13 | 14 | ListNode preDelete = pre; 15 | while (head != null) { 16 | if (head.val == val) { 17 | preDelete.next = head.next; 18 | break; 19 | } 20 | head = head.next; 21 | preDelete = preDelete.next; 22 | } 23 | 24 | return pre.next; 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /src/leetcode/linkedlist/SolutionOffer22.java: -------------------------------------------------------------------------------- 1 | package leetcode.linkedlist; 2 | 3 | import leetcode.ListNode; 4 | 5 | public class SolutionOffer22 { 6 | public ListNode getKthFromEnd(ListNode head, int k) { 7 | ListNode slow = head, fast = head; 8 | 9 | while (k != 0) { 10 | k--; 11 | fast = fast.next; 12 | } 13 | 14 | while (fast != null) { 15 | slow = slow.next; 16 | fast = fast.next; 17 | } 18 | 19 | return slow; 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /src/leetcode/linkedlist/SolutionOffer25.java: -------------------------------------------------------------------------------- 1 | package leetcode.linkedlist; 2 | 3 | import leetcode.ListNode; 4 | 5 | public class SolutionOffer25 { 6 | public ListNode mergeTwoLists(ListNode l1, ListNode l2) { 7 | if (l1 == null && l2 == null) { 8 | return null; 9 | } 10 | if (l1 == null) { 11 | return l2; 12 | } 13 | if (l2 == null) { 14 | return l1; 15 | } 16 | 17 | if (l1.val <= l2.val) { 18 | l1.next = mergeTwoLists(l1.next, l2); 19 | return l1; 20 | } else { 21 | l2.next = mergeTwoLists(l1, l2.next); 22 | return l2; 23 | } 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /src/leetcode/linkedlist/SolutionOffer35.java: -------------------------------------------------------------------------------- 1 | package leetcode.linkedlist; 2 | 3 | import java.util.HashMap; 4 | 5 | public class SolutionOffer35 { 6 | static class Node { 7 | int val; 8 | Node next; 9 | Node random; 10 | 11 | public Node(int val) { 12 | this.val = val; 13 | this.next = null; 14 | this.random = null; 15 | } 16 | } 17 | 18 | private HashMap nodeNodeMap = new HashMap<>(); 19 | 20 | public Node copyRandomList(Node head) { 21 | if (head == null) { 22 | return null; 23 | } 24 | 25 | // 看看新节点有没有创建过 26 | Node node; 27 | if (nodeNodeMap.containsKey(head)) { 28 | node = nodeNodeMap.get(head); 29 | } else { 30 | node = new Node(head.val); 31 | nodeNodeMap.put(head, node); 32 | node.next = copyRandomList(head.next); 33 | node.random = copyRandomList(head.random); 34 | } 35 | 36 | return node; 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /src/leetcode/prefixsum/NumArray.java: -------------------------------------------------------------------------------- 1 | package leetcode.prefixsum; 2 | 3 | public class NumArray { 4 | 5 | int[] sum; 6 | 7 | public NumArray(int[] nums) { 8 | sum = new int[nums.length + 1]; 9 | for (int i = 1; i < sum.length; i++) { 10 | sum[i] = sum[i - 1] + nums[i - 1]; 11 | } 12 | } 13 | 14 | public int sumRange(int left, int right) { 15 | return sum[right + 1] - sum[left]; 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /src/leetcode/prefixsum/Solution1310.java: -------------------------------------------------------------------------------- 1 | package leetcode.prefixsum; 2 | 3 | import java.util.Arrays; 4 | 5 | public class Solution1310 { 6 | 7 | public static void main(String[] args) { 8 | System.out.println(Arrays.toString( 9 | new Solution1310().xorQueries(new int[]{1, 3, 4, 8}, 10 | new int[][]{ 11 | new int[]{0, 1}, 12 | new int[]{1, 2}, 13 | new int[]{0, 3}, 14 | new int[]{3, 3} 15 | }))); 16 | } 17 | 18 | public int[] xorQueries(int[] arr, int[][] queries) { 19 | int[] preSum = new int[arr.length + 1]; 20 | for (int i = 1; i < preSum.length; i++) { 21 | preSum[i] = preSum[i - 1] ^ arr[i - 1]; 22 | } 23 | 24 | int[] res = new int[queries.length]; 25 | for (int i = 0; i < queries.length; i++) { 26 | res[i] = preSum[queries[i][1] + 1] ^ preSum[queries[i][0]]; 27 | } 28 | 29 | return res; 30 | } 31 | 32 | } 33 | -------------------------------------------------------------------------------- /src/leetcode/prefixsum/Solution1588.java: -------------------------------------------------------------------------------- 1 | package leetcode.prefixsum; 2 | 3 | public class Solution1588 { 4 | 5 | public static void main(String[] args) { 6 | System.out.println(new Solution1588().sumOddLengthSubarrays(new int[]{1, 4, 2, 5, 3})); 7 | } 8 | 9 | public int sumOddLengthSubarrays(int[] arr) { 10 | int[] preSum = new int[arr.length + 1]; 11 | for (int i = 1; i < preSum.length; i++) { 12 | preSum[i] = preSum[i - 1] + arr[i - 1]; 13 | } 14 | 15 | int res = 0; 16 | // preSum[left, right] = preSum[0, right] - preSum[0, left] 17 | for (int i = 1; i < preSum.length; i += 2) { 18 | for (int left = 0, right = left + i; right <= arr.length; left++, right++) { 19 | res += preSum[right] - preSum[left]; 20 | } 21 | } 22 | 23 | return res; 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /src/leetcode/prefixsum/Solution1894.java: -------------------------------------------------------------------------------- 1 | package leetcode.prefixsum; 2 | 3 | public class Solution1894 { 4 | public int chalkReplacer(int[] chalk, int k) { 5 | long[] preSum = new long[chalk.length + 1]; 6 | for (int i = 1; i < preSum.length; i++) { 7 | preSum[i] = preSum[i - 1] + chalk[i - 1]; 8 | } 9 | 10 | long all = k % preSum[preSum.length - 1]; 11 | for (int i = 1; i < preSum.length; i++) { 12 | if (all < preSum[i]) { 13 | return i - 1; 14 | } 15 | } 16 | 17 | return -1; 18 | } 19 | 20 | } 21 | -------------------------------------------------------------------------------- /src/leetcode/prefixsum/Solution238.java: -------------------------------------------------------------------------------- 1 | package leetcode.prefixsum; 2 | 3 | import java.util.Arrays; 4 | 5 | public class Solution238 { 6 | 7 | public static void main(String[] args) { 8 | System.out.println(Arrays.toString(new Solution238().productExceptSelf(new int[]{1, 2, 3, 4}))); 9 | } 10 | 11 | public int[] productExceptSelf(int[] nums) { 12 | int[] left = new int[nums.length + 1]; 13 | Arrays.fill(left, 1); 14 | for (int i = 1; i < left.length; i++) { 15 | left[i] = left[i - 1] * nums[i - 1]; 16 | } 17 | int[] right = new int[nums.length + 1]; 18 | Arrays.fill(right, 1); 19 | for (int i = right.length - 2; i >= 0; i--) { 20 | right[i] = right[i + 1] * nums[i]; 21 | } 22 | 23 | int[] res = new int[nums.length]; 24 | for (int i = 0; i < nums.length; i++) { 25 | res[i] = left[i] * right[i + 1]; 26 | } 27 | return res; 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /src/leetcode/prefixsum/Solution274.java: -------------------------------------------------------------------------------- 1 | package leetcode.prefixsum; 2 | 3 | public class Solution274 { 4 | public int hIndex(int[] citations) { 5 | int[] counting = new int[1001]; 6 | for (int citation : citations) { 7 | counting[citation]++; 8 | } 9 | for (int i = counting.length - 1; i > 0; i--) { 10 | counting[i - 1] += counting[i]; 11 | } 12 | int res = 0; 13 | for (int i = 0; i < counting.length; i++) { 14 | if (counting[i] >= i) { 15 | res = Math.max(res, i); 16 | } 17 | } 18 | 19 | return res; 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /src/leetcode/prefixsum/Solution396.java: -------------------------------------------------------------------------------- 1 | package leetcode.prefixsum; 2 | 3 | public class Solution396 { 4 | 5 | public static void main(String[] args) { 6 | System.out.println(new Solution396().maxRotateFunction(new int[]{4, 3, 2, 6})); 7 | } 8 | 9 | public int maxRotateFunction(int[] nums) { 10 | int[] preSum = new int[nums.length * 2 + 1]; 11 | for (int i = 1; i < preSum.length; i++) { 12 | preSum[i] = preSum[i - 1] + nums[(i - 1) % nums.length]; 13 | } 14 | 15 | int first = 0; 16 | for (int i = 1; i < nums.length; i++) { 17 | first += nums[i] * i; 18 | } 19 | int res = first; 20 | for (int i = 1; i < nums.length; i++) { 21 | first -= preSum[nums.length + i - 1] - preSum[i]; 22 | first += (nums.length - 1) * nums[i - 1]; 23 | 24 | res = Math.max(res, first); 25 | } 26 | 27 | return res; 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /src/leetcode/prefixsum/Solution525.java: -------------------------------------------------------------------------------- 1 | package leetcode.prefixsum; 2 | 3 | import java.util.HashMap; 4 | 5 | public class Solution525 { 6 | 7 | public static void main(String[] args) { 8 | System.out.println(new Solution525().findMaxLength(new int[]{0, 1, 0})); 9 | } 10 | 11 | public int findMaxLength(int[] nums) { 12 | int preSum = 0; 13 | HashMap preSumIndex = new HashMap<>(); 14 | preSumIndex.put(preSum, -1); 15 | int res = 0; 16 | for (int i = 0; i < nums.length; i++) { 17 | preSum += nums[i] == 0 ? -1 : 1; 18 | if (preSumIndex.containsKey(preSum)) { 19 | res = Math.max(res, i - preSumIndex.get(preSum)); 20 | } else { 21 | preSumIndex.put(preSum, i); 22 | } 23 | } 24 | 25 | return res; 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /src/leetcode/prefixsum/Solution528.java: -------------------------------------------------------------------------------- 1 | package leetcode.prefixsum; 2 | 3 | import java.util.Random; 4 | 5 | public class Solution528 { 6 | 7 | Random random; 8 | 9 | int[] preSum; 10 | 11 | public Solution528(int[] w) { 12 | random = new Random(); 13 | this.preSum = new int[w.length + 1]; 14 | for (int i = 1; i < preSum.length; i++) { 15 | preSum[i] = preSum[i - 1] + w[i - 1]; 16 | } 17 | } 18 | 19 | public int pickIndex() { 20 | int num = random.nextInt(preSum[preSum.length - 1]) + 1; 21 | int left = 1, right = preSum.length; 22 | while (left < right) { 23 | int mid = left + right >> 1; 24 | 25 | if (preSum[mid] >= num) { 26 | right = mid; 27 | } else { 28 | left = mid + 1; 29 | } 30 | } 31 | 32 | return left - 1; 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /src/leetcode/prefixsum/Solution560.java: -------------------------------------------------------------------------------- 1 | package leetcode.prefixsum; 2 | 3 | import java.util.HashMap; 4 | 5 | public class Solution560 { 6 | public static void main(String[] args) { 7 | // 3 8 | System.out.println(new Solution560().subarraySum(new int[]{1, -1, 0}, 0)); 9 | // 2 10 | System.out.println(new Solution560().subarraySum(new int[]{1, 2, 3}, 3)); 11 | } 12 | 13 | public int subarraySum(int[] nums, int k) { 14 | HashMap preSumNum = new HashMap<>(); 15 | int preSum = 0; 16 | preSumNum.put(preSum, 1); 17 | int res = 0; 18 | for (int num : nums) { 19 | preSum += num; 20 | if (preSumNum.containsKey(preSum - k)) { 21 | res += preSumNum.get(preSum - k); 22 | } 23 | preSumNum.put(preSum, preSumNum.getOrDefault(preSum, 0) + 1); 24 | } 25 | 26 | return res; 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /src/leetcode/prefixsum/Solution724.java: -------------------------------------------------------------------------------- 1 | package leetcode.prefixsum; 2 | 3 | public class Solution724 { 4 | 5 | public static void main(String[] args) { 6 | System.out.println(new Solution724().pivotIndex(new int[]{1, 7, 3, 6, 5, 6})); 7 | } 8 | 9 | public int pivotIndex(int[] nums) { 10 | // preSum[i - 1] == preSum[i + 1, n] == preSum[0, n] - preSum[0, i] 11 | int[] preSum = new int[nums.length + 1]; 12 | for (int i = 1; i < preSum.length; i++) { 13 | preSum[i] = preSum[i - 1] + nums[i - 1]; 14 | } 15 | 16 | for (int i = 0; i < nums.length; i++) { 17 | if (preSum[i] == preSum[preSum.length - 1] - preSum[i + 1]) { 18 | return i; 19 | } 20 | } 21 | 22 | return -1; 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /src/leetcode/prefixsum/Solution926.java: -------------------------------------------------------------------------------- 1 | package leetcode.prefixsum; 2 | 3 | public class Solution926 { 4 | 5 | public static void main(String[] args) { 6 | // 1 7 | System.out.println(new Solution926().minFlipsMonoIncr("11011")); 8 | } 9 | 10 | public int minFlipsMonoIncr(String s) { 11 | char[] charArray = s.toCharArray(); 12 | int[] preSum = new int[s.length() + 1]; 13 | for (int i = 1; i < preSum.length; i++) { 14 | preSum[i] = preSum[i - 1] + (charArray[i - 1] - '0'); 15 | } 16 | 17 | int res = Integer.MAX_VALUE; 18 | for (int i = 0; i < charArray.length; i++) { 19 | int left = preSum[i], right = (charArray.length - i - 1) - (preSum[preSum.length - 1] - preSum[i + 1]); 20 | res = Math.min(res, left + right); 21 | } 22 | 23 | return res; 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /src/leetcode/prefixsum/matrix/NumMatrix.java: -------------------------------------------------------------------------------- 1 | package leetcode.prefixsum.matrix; 2 | 3 | public class NumMatrix { 4 | 5 | public static void main(String[] args) { 6 | NumMatrix numMatrix = new NumMatrix(new int[][]{new int[]{-4, -5}}); 7 | 8 | System.out.println(numMatrix.sumRegion(0, 0, 0, 1)); 9 | } 10 | 11 | int[][] preSum; 12 | 13 | public NumMatrix(int[][] matrix) { 14 | preSum = new int[matrix.length + 1][matrix[0].length + 1]; 15 | 16 | for (int i = 1; i < preSum.length; i++) { 17 | for (int j = 1; j < preSum[0].length; j++) { 18 | preSum[i][j] = preSum[i - 1][j] + preSum[i][j - 1] - preSum[i - 1][j - 1] + matrix[i - 1][j - 1]; 19 | } 20 | } 21 | } 22 | 23 | public int sumRegion(int row1, int col1, int row2, int col2) { 24 | row1++; col1++; row2++; col2++; 25 | return preSum[row2][col2] - preSum[row1 - 1][col2] - preSum[row2][col1 - 1] + preSum[row1 - 1][col1 - 1]; 26 | } 27 | 28 | } 29 | -------------------------------------------------------------------------------- /src/leetcode/prefixsum/二维数组前缀和计算方法.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/FangYuan33/LeetCode/4beffc725e4b6782c01c6707bdf8c49bab3d0afa/src/leetcode/prefixsum/二维数组前缀和计算方法.png -------------------------------------------------------------------------------- /src/leetcode/prefixsum/前缀和.drawio.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/FangYuan33/LeetCode/4beffc725e4b6782c01c6707bdf8c49bab3d0afa/src/leetcode/prefixsum/前缀和.drawio.png -------------------------------------------------------------------------------- /src/leetcode/priorityqueue/Interview1714.java: -------------------------------------------------------------------------------- 1 | package leetcode.priorityqueue; 2 | 3 | import java.util.PriorityQueue; 4 | 5 | public class Interview1714 { 6 | public int[] smallestK(int[] arr, int k) { 7 | int[] res = new int[k]; 8 | if (k == 0) { 9 | return res; 10 | } 11 | 12 | PriorityQueue priorityQueue = new PriorityQueue<>((x, y) -> y - x); 13 | for (int i = 0; i < arr.length; i++) { 14 | if (priorityQueue.size() < k) { 15 | priorityQueue.offer(arr[i]); 16 | } else { 17 | if (arr[i] < priorityQueue.peek()) { 18 | priorityQueue.poll(); 19 | priorityQueue.offer(arr[i]); 20 | } 21 | } 22 | } 23 | 24 | for (int i = 0; i < res.length; i++) { 25 | res[i] = priorityQueue.poll(); 26 | } 27 | 28 | return res; 29 | } 30 | 31 | } 32 | -------------------------------------------------------------------------------- /src/leetcode/priorityqueue/MedianFinder.java: -------------------------------------------------------------------------------- 1 | package leetcode.priorityqueue; 2 | 3 | import java.util.PriorityQueue; 4 | 5 | public class MedianFinder { 6 | 7 | PriorityQueue left; 8 | 9 | PriorityQueue right; 10 | 11 | public MedianFinder() { 12 | left = new PriorityQueue<>((x, y) -> y - x); 13 | right = new PriorityQueue<>(); 14 | } 15 | 16 | public void addNum(int num) { 17 | if (left.size() == right.size()) { 18 | right.offer(num); 19 | left.offer(right.poll()); 20 | } else { 21 | left.offer(num); 22 | right.offer(left.poll()); 23 | } 24 | } 25 | 26 | public double findMedian() { 27 | return left.size() == right.size() ? (left.peek() + right.peek()) / 2.0 : left.peek(); 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /src/leetcode/priorityqueue/Solution215.java: -------------------------------------------------------------------------------- 1 | package leetcode.priorityqueue; 2 | 3 | import java.util.PriorityQueue; 4 | 5 | public class Solution215 { 6 | 7 | public static void main(String[] args) { 8 | System.out.println(new Solution215().findKthLargest(new int[]{3, 2, 3, 1, 2, 4, 5, 5, 6}, 4)); 9 | } 10 | 11 | public int findKthLargest(int[] nums, int k) { 12 | PriorityQueue priorityQueue = new PriorityQueue<>(); 13 | 14 | for (int num : nums) { 15 | if (priorityQueue.size() < k) { 16 | priorityQueue.offer(num); 17 | } else { 18 | if (num > priorityQueue.peek()) { 19 | priorityQueue.poll(); 20 | priorityQueue.offer(num); 21 | } 22 | } 23 | } 24 | 25 | return priorityQueue.peek(); 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /src/leetcode/priorityqueue/Solution373.java: -------------------------------------------------------------------------------- 1 | package leetcode.priorityqueue; 2 | 3 | import java.util.*; 4 | 5 | public class Solution373 { 6 | 7 | public static void main(String[] args) { 8 | System.out.println(new Solution373().kSmallestPairs(new int[]{1, 7, 11}, new int[]{2, 4, 6}, 3)); 9 | } 10 | 11 | public List> kSmallestPairs(int[] nums1, int[] nums2, int k) { 12 | PriorityQueue priorityQueue = new PriorityQueue<>(Comparator.comparingInt(x -> (nums1[x[0]] + nums2[x[1]]))); 13 | for (int i = 0; i < nums1.length; i++) { 14 | priorityQueue.offer(new int[]{i, 0}); 15 | } 16 | 17 | List> res = new LinkedList<>(); 18 | for (int i = 0; i < k && !priorityQueue.isEmpty(); i++) { 19 | int[] e = priorityQueue.poll(); 20 | res.add(Arrays.asList(nums1[e[0]], nums2[e[1]])); 21 | if (e[1] + 1 < nums2.length) { 22 | priorityQueue.offer(new int[]{e[0], e[1] + 1}); 23 | } 24 | } 25 | 26 | return res; 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /src/leetcode/priorityqueue/Solution4.java: -------------------------------------------------------------------------------- 1 | package leetcode.priorityqueue; 2 | 3 | import java.util.PriorityQueue; 4 | 5 | public class Solution4 { 6 | public double findMedianSortedArrays(int[] nums1, int[] nums2) { 7 | PriorityQueue left = new PriorityQueue<>((x, y) -> y - x); 8 | PriorityQueue right = new PriorityQueue<>(); 9 | 10 | into(left, right, nums1); 11 | into(left, right, nums2); 12 | 13 | if (left.size() == right.size()) { 14 | return (left.peek() + right.peek()) / 2.0; 15 | } else { 16 | return left.peek(); 17 | } 18 | } 19 | 20 | private void into(PriorityQueue left, PriorityQueue right, int[] nums) { 21 | for (int num : nums) { 22 | if (left.size() == right.size()) { 23 | right.offer(num); 24 | left.offer(right.poll()); 25 | } else { 26 | left.offer(num); 27 | right.offer(left.poll()); 28 | } 29 | } 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /src/leetcode/priorityqueue/Solution45.java: -------------------------------------------------------------------------------- 1 | package leetcode.priorityqueue; 2 | 3 | import leetcode.Solution; 4 | 5 | import java.util.PriorityQueue; 6 | 7 | public class Solution45 { 8 | public static void main(String[] args) { 9 | System.out.println(new Solution45().jump(new int[]{0})); 10 | } 11 | 12 | public int jump(int[] nums) { 13 | int res = 0; 14 | PriorityQueue priorityQueue = new PriorityQueue<>((x, y) -> y - x); 15 | int index = 0; 16 | int cur = 0; 17 | 18 | while (cur < nums.length - 1) { 19 | while (index < nums.length && index <= cur) { 20 | priorityQueue.offer(index + nums[index]); 21 | index++; 22 | } 23 | if (priorityQueue.isEmpty()) { 24 | break; 25 | } else { 26 | Integer feature = priorityQueue.poll(); 27 | cur = feature; 28 | res++; 29 | } 30 | } 31 | 32 | return res; 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /src/leetcode/priorityqueue/SolutionLCR159.java: -------------------------------------------------------------------------------- 1 | package leetcode.priorityqueue; 2 | 3 | import java.util.PriorityQueue; 4 | 5 | public class SolutionLCR159 { 6 | public int[] inventoryManagement(int[] stock, int cnt) { 7 | int[] res = new int[cnt]; 8 | if (cnt == 0) { 9 | return res; 10 | } 11 | 12 | PriorityQueue priorityQueue = new PriorityQueue<>((x, y) -> y - x); 13 | for (int s : stock) { 14 | if (priorityQueue.size() < cnt) { 15 | priorityQueue.offer(s); 16 | } else { 17 | if (s < priorityQueue.peek()) { 18 | priorityQueue.poll(); 19 | priorityQueue.offer(s); 20 | } 21 | } 22 | } 23 | 24 | for (int i = 0; i < res.length; i++) { 25 | res[i] = priorityQueue.poll(); 26 | } 27 | 28 | return res; 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /src/leetcode/queue/MovingAverage.java: -------------------------------------------------------------------------------- 1 | package leetcode.queue; 2 | 3 | import java.util.ArrayDeque; 4 | import java.util.Deque; 5 | 6 | public class MovingAverage { 7 | 8 | private Deque deque; 9 | 10 | private int size; 11 | 12 | private int sum; 13 | 14 | /** Initialize your data structure here. */ 15 | public MovingAverage(int size) { 16 | this.size = size; 17 | deque = new ArrayDeque<>(); 18 | sum = 0; 19 | } 20 | 21 | public double next(int val) { 22 | sum += val; 23 | deque.offer(val); 24 | 25 | if (deque.size() > size) { 26 | sum -= deque.poll(); 27 | } 28 | 29 | return (double) sum / deque.size(); 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /src/leetcode/queue/RecentCounter.java: -------------------------------------------------------------------------------- 1 | package leetcode.queue; 2 | 3 | import java.util.ArrayDeque; 4 | import java.util.Deque; 5 | 6 | public class RecentCounter { 7 | 8 | Deque deque; 9 | 10 | public RecentCounter() { 11 | deque = new ArrayDeque<>(); 12 | } 13 | 14 | public int ping(int t) { 15 | deque.offer(t); 16 | 17 | int left = t - 3000; 18 | while (!deque.isEmpty() && deque.peek() < left) { 19 | deque.poll(); 20 | } 21 | 22 | return deque.size(); 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /src/leetcode/queue/Solution1047.java: -------------------------------------------------------------------------------- 1 | package leetcode.queue; 2 | 3 | import java.util.ArrayDeque; 4 | import java.util.Deque; 5 | 6 | public class Solution1047 { 7 | public String removeDuplicates(String s) { 8 | Deque queue = new ArrayDeque<>(); 9 | char[] charArray = s.toCharArray(); 10 | 11 | for (char c : charArray) { 12 | if (!queue.isEmpty() && queue.peekLast() == c) { 13 | queue.pollLast(); 14 | } else { 15 | queue.offer(c); 16 | } 17 | } 18 | 19 | StringBuilder res = new StringBuilder(); 20 | while (!queue.isEmpty()) { 21 | res.append(queue.poll()); 22 | } 23 | 24 | return res.toString(); 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /src/leetcode/queue/monotonic/MaxQueue.java: -------------------------------------------------------------------------------- 1 | package leetcode.queue.monotonic; 2 | 3 | import java.util.ArrayDeque; 4 | import java.util.Deque; 5 | 6 | public class MaxQueue { 7 | 8 | Deque max; 9 | 10 | Deque queue; 11 | 12 | public MaxQueue() { 13 | max = new ArrayDeque<>(); 14 | queue = new ArrayDeque<>(); 15 | } 16 | 17 | public int max_value() { 18 | if (queue.isEmpty()) { 19 | return -1; 20 | } 21 | 22 | return max.peekFirst(); 23 | } 24 | 25 | public void push_back(int value) { 26 | queue.addLast(value); 27 | 28 | while (!max.isEmpty() && value > max.peekLast()) { 29 | max.pollLast(); 30 | } 31 | max.addLast(value); 32 | } 33 | 34 | public int pop_front() { 35 | if (queue.isEmpty()) { 36 | return -1; 37 | } 38 | 39 | Integer res = queue.pollFirst(); 40 | if (res.equals(max.peekFirst())) { 41 | max.pollFirst(); 42 | } 43 | 44 | return res; 45 | } 46 | 47 | } 48 | -------------------------------------------------------------------------------- /src/leetcode/recursion/SolutionLCR130.java: -------------------------------------------------------------------------------- 1 | package leetcode.recursion; 2 | 3 | public class SolutionLCR130 { 4 | 5 | int res; 6 | 7 | int cnt; 8 | 9 | int m; 10 | 11 | int n; 12 | 13 | public int wardrobeFinishing(int m, int n, int cnt) { 14 | this.res = 0; 15 | this.cnt = cnt; 16 | this.m = m; 17 | this.n = n; 18 | 19 | recursion(0, 0, new boolean[m][n]); 20 | 21 | return res; 22 | } 23 | 24 | private void recursion(int m, int n, boolean[][] visited) { 25 | if (m >= this.m || n >= this.n || visited[m][n] 26 | || m % 10 + m / 10 % 10 + n % 10 + n / 10 % 10 > this.cnt) { 27 | return; 28 | } 29 | res++; 30 | visited[m][n] = true; 31 | recursion(m + 1, n, visited); 32 | recursion(m, n + 1, visited); 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /src/leetcode/simulate/MyCalendar.java: -------------------------------------------------------------------------------- 1 | package leetcode.simulate; 2 | 3 | import java.util.ArrayList; 4 | import java.util.List; 5 | 6 | public class MyCalendar { 7 | 8 | public static void main(String[] args) { 9 | MyCalendar myCalendar = new MyCalendar(); 10 | 11 | myCalendar.book(10, 20); 12 | myCalendar.book(15, 25); 13 | } 14 | 15 | List calendarDate; 16 | 17 | public MyCalendar() { 18 | calendarDate = new ArrayList<>(); 19 | } 20 | 21 | public boolean book(int start, int end) { 22 | for (int[] date : calendarDate) { 23 | int left = date[0], right = date[1]; 24 | 25 | if (start >= right || end <= left) { 26 | continue; 27 | } 28 | return false; 29 | } 30 | calendarDate.add(new int[]{start, end}); 31 | 32 | return true; 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /src/leetcode/simulate/NumMatrix.java: -------------------------------------------------------------------------------- 1 | package leetcode.simulate; 2 | 3 | public class NumMatrix { 4 | 5 | int[][] matrix; 6 | 7 | public NumMatrix(int[][] matrix) { 8 | this.matrix = matrix; 9 | } 10 | 11 | public int sumRegion(int row1, int col1, int row2, int col2) { 12 | int res = 0; 13 | 14 | for (int i = row1; i <= row2; i++) { 15 | for (int j = col1; j <= col2; j++) { 16 | res += matrix[i][j]; 17 | } 18 | } 19 | 20 | return res; 21 | } 22 | 23 | } 24 | -------------------------------------------------------------------------------- /src/leetcode/simulate/Solution1109.java: -------------------------------------------------------------------------------- 1 | package leetcode.simulate; 2 | 3 | public class Solution1109 { 4 | 5 | public static void main(String[] args) { 6 | new Solution1109().corpFlightBookings(new int[][]{new int[]{1, 2, 10}, new int[]{2, 3, 20}, new int[]{2, 5, 25}}, 5); 7 | } 8 | 9 | public int[] corpFlightBookings(int[][] bookings, int n) { 10 | int[] res = new int[n]; 11 | for (int[] booking : bookings) { 12 | int left = booking[0], right = booking[1]; 13 | int val = booking[2]; 14 | 15 | for (int i = left; i <= right; i++) { 16 | res[i - 1] += val; 17 | } 18 | } 19 | 20 | return res; 21 | } 22 | 23 | } 24 | -------------------------------------------------------------------------------- /src/leetcode/simulate/Solution189.java: -------------------------------------------------------------------------------- 1 | package leetcode.simulate; 2 | 3 | public class Solution189 { 4 | public void rotate(int[] nums, int k) { 5 | k = k % nums.length; 6 | if (k == 0) { 7 | return; 8 | } 9 | 10 | int[] temp = new int[k]; 11 | System.arraycopy(nums, nums.length - k, temp, 0, temp.length); 12 | System.arraycopy(nums, 0, nums, k, nums.length - k); 13 | System.arraycopy(temp, 0, nums, 0, temp.length); 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /src/leetcode/simulate/Solution1893.java: -------------------------------------------------------------------------------- 1 | package leetcode.simulate; 2 | 3 | public class Solution1893 { 4 | public boolean isCovered(int[][] ranges, int left, int right) { 5 | for (int i = left; i <= right; i++) { 6 | boolean exist = false; 7 | for (int[] range : ranges) { 8 | int l = range[0], r = range[1]; 9 | 10 | if (l <= i && i <= r) { 11 | exist = true; 12 | break; 13 | } 14 | } 15 | 16 | if (!exist) { 17 | return false; 18 | } 19 | } 20 | 21 | return true; 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /src/leetcode/simulate/Solution219.java: -------------------------------------------------------------------------------- 1 | package leetcode.simulate; 2 | 3 | import java.util.HashMap; 4 | 5 | public class Solution219 { 6 | 7 | public static void main(String[] args) { 8 | System.out.println(new Solution219().containsNearbyDuplicate(new int[]{1, 2, 3, 1, 2, 3}, 2)); 9 | } 10 | 11 | 12 | public boolean containsNearbyDuplicate(int[] nums, int k) { 13 | HashMap numIndex = new HashMap<>(); 14 | for (int i = 0; i < nums.length; i++) { 15 | if (numIndex.containsKey(nums[i])) { 16 | if (i - numIndex.get(nums[i]) <= k) { 17 | return true; 18 | } 19 | } 20 | numIndex.put(nums[i], i); 21 | } 22 | 23 | return false; 24 | } 25 | 26 | } 27 | -------------------------------------------------------------------------------- /src/leetcode/simulate/Solution2934.java: -------------------------------------------------------------------------------- 1 | package leetcode.simulate; 2 | 3 | public class Solution2934 { 4 | 5 | public static void main(String[] args) { 6 | System.out.println(new Solution2934().minOperations(new int[]{1, 5, 15}, new int[]{1, 1, 1})); 7 | } 8 | 9 | public int minOperations(int[] nums1, int[] nums2) { 10 | int n = nums1.length; 11 | int res = Math.min(operate(nums1[n - 1], nums2[n - 1], nums1, nums2), 12 | 1 + operate(nums2[n - 1], nums1[n - 1], nums1, nums2)); 13 | return res > n ? -1 : res; 14 | } 15 | 16 | private int operate(int max1, int max2, int[] nums1, int[] nums2) { 17 | int res = 0; 18 | for (int i = 0; i < nums1.length - 1; i++) { 19 | if (nums1[i] > max1 || nums2[i] > max2) { 20 | if (nums1[i] > max2 || nums2[i] > max1) { 21 | return nums1.length + 1; 22 | } 23 | res++; 24 | } 25 | } 26 | 27 | return res; 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /src/leetcode/simulate/Solution400.java: -------------------------------------------------------------------------------- 1 | package leetcode.simulate; 2 | 3 | public class Solution400 { 4 | 5 | public static void main(String[] args) { 6 | System.out.println(new Solution400().findNthDigit(11)); 7 | } 8 | 9 | public int findNthDigit(int n) { 10 | // 计算出它在哪个组 11 | int row = 1; 12 | while (n > Math.pow(10, row - 1) * 9 * row) { 13 | n -= Math.pow(10, row - 1) * 9 * row; 14 | row++; 15 | } 16 | // 计算它是第几个数字 17 | int count = n % row == 0 ? n / row : n / row + 1; 18 | // 是多少 19 | String num = String.valueOf((long) (Math.pow(10, row - 1) + count - 1)); 20 | // 从头向后偏 21 | long step = n % row; 22 | return step == 0 ? num.charAt(num.length() - 1) - '0' : num.charAt((int) (step - 1)) - '0'; 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /src/leetcode/simulate/Solution415.java: -------------------------------------------------------------------------------- 1 | package leetcode.simulate; 2 | 3 | public class Solution415 { 4 | 5 | public String addStrings(String num1, String num2) { 6 | StringBuilder res = new StringBuilder(); 7 | int carry = 0; 8 | int index1 = num1.length() - 1, index2 = num2.length() - 1; 9 | while (index1 >= 0 || index2 >= 0) { 10 | int x = index1 >= 0 ? num1.charAt(index1) - '0' : 0; 11 | int y = index2 >= 0 ? num2.charAt(index2) - '0' : 0; 12 | 13 | int sum = x + y + carry; 14 | int cur = sum % 10; 15 | carry = sum / 10; 16 | res.append(cur); 17 | index1--; 18 | index2--; 19 | } 20 | if (carry == 1) { 21 | res.append(carry); 22 | } 23 | 24 | return res.reverse().toString(); 25 | } 26 | 27 | } 28 | -------------------------------------------------------------------------------- /src/leetcode/simulate/Solution48.java: -------------------------------------------------------------------------------- 1 | package leetcode.simulate; 2 | 3 | public class Solution48 { 4 | 5 | public static void main(String[] args) { 6 | new Solution48().rotate(new int[][]{new int[]{5, 1, 9, 11}, new int[]{2, 4, 8, 10}, new int[]{13, 3, 6, 7}, new int[]{15, 14, 12, 16}}); 7 | } 8 | 9 | public void rotate(int[][] matrix) { 10 | int n = matrix.length; 11 | 12 | for (int i = 0; i < n / 2; i++) { 13 | // j 表示每行旋转的索引范围 14 | for (int j = i; j < n - 1 - i; j++) { 15 | // 一圈一圈的交换 16 | int temp = matrix[j][n - 1 - i]; 17 | matrix[j][n - 1 - i] = matrix[i][j]; 18 | int temp2 = matrix[n - 1 - i][n - 1 - j]; 19 | matrix[n - 1 - i][n - 1 - j] = temp; 20 | matrix[i][j] = matrix[n - 1 - j][i]; 21 | matrix[n - 1 - j][i] = temp2; 22 | } 23 | } 24 | } 25 | 26 | } 27 | -------------------------------------------------------------------------------- /src/leetcode/simulate/Solution496.java: -------------------------------------------------------------------------------- 1 | package leetcode.simulate; 2 | 3 | import java.util.Arrays; 4 | 5 | public class Solution496 { 6 | 7 | public static void main(String[] args) { 8 | System.out.println(Arrays.toString(new Solution496().nextGreaterElement(new int[]{4, 1, 2}, new int[]{1, 3, 4, 2})));; 9 | } 10 | 11 | public int[] nextGreaterElement(int[] nums1, int[] nums2) { 12 | int[] res = new int[nums1.length]; 13 | Arrays.fill(res, -1); 14 | 15 | for (int i = 0; i < nums1.length; i++) { 16 | for (int j = 0; j < nums2.length; j++) { 17 | if (nums1[i] == nums2[j]) { 18 | j++; 19 | while (j < nums2.length) { 20 | if (nums2[j] > nums1[i]) { 21 | res[i] = nums2[j]; 22 | break; 23 | } 24 | j++; 25 | } 26 | } 27 | } 28 | } 29 | 30 | return res; 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /src/leetcode/simulate/Solution560.java: -------------------------------------------------------------------------------- 1 | package leetcode.simulate; 2 | 3 | public class Solution560 { 4 | public int subarraySum(int[] nums, int k) { 5 | int res = 0; 6 | // 暴力穷举法 7 | for (int i = 0; i < nums.length; i++) { 8 | int preSum = 0; 9 | for (int j = i; j < nums.length; j++) { 10 | preSum += nums[j]; 11 | 12 | if (preSum == k) { 13 | res++; 14 | } 15 | } 16 | } 17 | 18 | return res; 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /src/leetcode/simulate/Solution796.java: -------------------------------------------------------------------------------- 1 | package leetcode.simulate; 2 | 3 | public class Solution796 { 4 | 5 | public boolean rotateString(String s, String goal) { 6 | StringBuilder origin = new StringBuilder(s); 7 | int index = 0; 8 | while (index < origin.length()) { 9 | if (origin.toString().equals(goal)) { 10 | return true; 11 | } else { 12 | char c = origin.charAt(0); 13 | origin.deleteCharAt(0); 14 | origin.append(c); 15 | } 16 | index++; 17 | } 18 | 19 | return false; 20 | } 21 | 22 | } 23 | -------------------------------------------------------------------------------- /src/leetcode/simulate/Solution89.java: -------------------------------------------------------------------------------- 1 | package leetcode.simulate; 2 | 3 | import java.util.ArrayList; 4 | import java.util.List; 5 | 6 | public class Solution89 { 7 | public List grayCode(int n) { 8 | List res = new ArrayList<>(); 9 | res.add(0); 10 | 11 | while (n-- > 0) { 12 | int m = res.size(); 13 | for (int i = m - 1; i >= 0; i--) { 14 | res.set(i, res.get(i) << 1); 15 | res.add(res.get(i) + 1); 16 | } 17 | } 18 | 19 | return res; 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /src/leetcode/slidingwindow/Solution1004.java: -------------------------------------------------------------------------------- 1 | package leetcode.slidingwindow; 2 | 3 | public class Solution1004 { 4 | 5 | public static void main(String[] args) { 6 | System.out.println(new Solution1004().longestOnes(new int[]{1, 1, 1, 0, 0, 0, 1, 1, 1, 1, 0}, 2)); 7 | } 8 | 9 | public int longestOnes(int[] nums, int k) { 10 | int res = 0; 11 | int left = 0, right = 0; 12 | while (right < nums.length) { 13 | if (nums[right] == 0) { 14 | k--; 15 | } 16 | 17 | while (k < 0 && left <= right) { 18 | if (nums[left] == 0) { 19 | k++; 20 | } 21 | left++; 22 | } 23 | res = Math.max(res, right - left + 1); 24 | 25 | right++; 26 | } 27 | 28 | return res; 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /src/leetcode/slidingwindow/Solution1052.java: -------------------------------------------------------------------------------- 1 | package leetcode.slidingwindow; 2 | 3 | public class Solution1052 { 4 | 5 | public static void main(String[] args) { 6 | System.out.println(new Solution1052().maxSatisfied( 7 | new int[]{1, 0, 1, 2, 1, 1, 7, 5}, 8 | new int[]{0, 1, 0, 1, 0, 1, 0, 1}, 3)); 9 | } 10 | 11 | public int maxSatisfied(int[] customers, int[] grumpy, int minutes) { 12 | int already = 0; 13 | for (int i = 0; i < customers.length; i++) { 14 | if (grumpy[i] == 0) { 15 | already += customers[i]; 16 | customers[i] = 0; 17 | } 18 | } 19 | 20 | int max = 0; 21 | int sum = 0; 22 | int left = 0, right = 0; 23 | while (right < customers.length) { 24 | sum += customers[right]; 25 | 26 | if (right - left + 1 == minutes) { 27 | max = Math.max(max, sum); 28 | sum -= customers[left++]; 29 | } 30 | 31 | right++; 32 | } 33 | 34 | return already + max; 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /src/leetcode/slidingwindow/Solution1208.java: -------------------------------------------------------------------------------- 1 | package leetcode.slidingwindow; 2 | 3 | public class Solution1208 { 4 | public int equalSubstring(String s, String t, int maxCost) { 5 | int res = 0; 6 | int left = 0, right = 0; 7 | while (right < s.length()) { 8 | maxCost -= Math.abs(s.charAt(right) - t.charAt(right)); 9 | 10 | while (maxCost < 0 && left <= right) { 11 | maxCost += Math.abs(s.charAt(left) - t.charAt(left)); 12 | left++; 13 | } 14 | res = Math.max(res, right - left + 1); 15 | 16 | right++; 17 | } 18 | 19 | return res; 20 | } 21 | 22 | } 23 | -------------------------------------------------------------------------------- /src/leetcode/slidingwindow/Solution1423.java: -------------------------------------------------------------------------------- 1 | package leetcode.slidingwindow; 2 | 3 | public class Solution1423 { 4 | public int maxScore(int[] cardPoints, int k) { 5 | int sum = 0; 6 | for (int cardPoint : cardPoints) { 7 | sum += cardPoint; 8 | } 9 | if (k == cardPoints.length) { 10 | return sum; 11 | } 12 | 13 | int temp = 0; 14 | int min = sum; 15 | int left = 0, right = 0; 16 | while (right < cardPoints.length) { 17 | temp += cardPoints[right]; 18 | 19 | if (right - left + 1 == cardPoints.length - k) { 20 | min = Math.min(min, temp); 21 | temp -= cardPoints[left++]; 22 | } 23 | 24 | right++; 25 | } 26 | 27 | return sum - min; 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /src/leetcode/slidingwindow/Solution1446.java: -------------------------------------------------------------------------------- 1 | package leetcode.slidingwindow; 2 | 3 | public class Solution1446 { 4 | 5 | public static void main(String[] args) { 6 | System.out.println(new Solution1446().maxPower("cc")); 7 | } 8 | 9 | public int maxPower(String s) { 10 | int res = 1; 11 | char cur = s.charAt(0); 12 | int left = 0, right = 1; 13 | while (right < s.length()) { 14 | if (s.charAt(right) != cur) { 15 | cur = s.charAt(right); 16 | left = right; 17 | } 18 | res = Math.max(right - left + 1, res); 19 | 20 | right++; 21 | } 22 | 23 | return res; 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /src/leetcode/slidingwindow/Solution1695.java: -------------------------------------------------------------------------------- 1 | package leetcode.slidingwindow; 2 | 3 | import java.util.HashSet; 4 | 5 | public class Solution1695 { 6 | 7 | public static void main(String[] args) { 8 | // 17 9 | System.out.println(new Solution1695().maximumUniqueSubarray(new int[]{4, 2, 4, 5, 6})); 10 | } 11 | 12 | public int maximumUniqueSubarray(int[] nums) { 13 | HashSet mark = new HashSet<>(); 14 | int res = 0; 15 | int sum = 0; 16 | int left = 0, right = 0; 17 | while (right < nums.length) { 18 | sum += nums[right]; 19 | while (mark.contains(nums[right]) && left < right) { 20 | sum -= nums[left]; 21 | mark.remove(nums[left++]); 22 | } 23 | mark.add(nums[right]); 24 | res = Math.max(res, sum); 25 | 26 | right++; 27 | } 28 | 29 | return res; 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /src/leetcode/slidingwindow/Solution1759.java: -------------------------------------------------------------------------------- 1 | package leetcode.slidingwindow; 2 | 3 | public class Solution1759 { 4 | public int countHomogenous(String s) { 5 | long res = 0; 6 | int left = 0, right = 0; 7 | while (right < s.length()) { 8 | while (s.charAt(left) != s.charAt(right) && left < right) { 9 | left++; 10 | } 11 | res += right - left + 1; 12 | right++; 13 | } 14 | 15 | return (int) (res % (1e9 + 7)); 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /src/leetcode/slidingwindow/Solution1984.java: -------------------------------------------------------------------------------- 1 | package leetcode.slidingwindow; 2 | 3 | import java.util.Arrays; 4 | 5 | public class Solution1984 { 6 | 7 | public static void main(String[] args) { 8 | System.out.println(new Solution1984().minimumDifference(new int[]{87063, 61094, 44530, 21297, 95857, 93551, 9918}, 6)); 9 | } 10 | 11 | public int minimumDifference(int[] nums, int k) { 12 | if (k == 0) { 13 | return 0; 14 | } 15 | Arrays.sort(nums); 16 | 17 | int res = Integer.MAX_VALUE; 18 | int right = k - 1; 19 | while (right < nums.length) { 20 | res = Math.min(nums[right] - nums[right - k + 1], res); 21 | right++; 22 | } 23 | 24 | return res; 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /src/leetcode/slidingwindow/Solution2024.java: -------------------------------------------------------------------------------- 1 | package leetcode.slidingwindow; 2 | 3 | public class Solution2024 { 4 | public int maxConsecutiveAnswers(String answerKey, int k) { 5 | int res = 0; 6 | int tCount = 0, fCount = 0; 7 | int left = 0, right = 0; 8 | while (right < answerKey.length()) { 9 | if (answerKey.charAt(right) == 'T') { 10 | tCount++; 11 | } else { 12 | fCount++; 13 | } 14 | int maxCount = Math.max(tCount, fCount); 15 | 16 | while (right - left + 1 - maxCount > k) { 17 | if (answerKey.charAt(left) == 'T') { 18 | tCount--; 19 | } else { 20 | fCount--; 21 | } 22 | left++; 23 | } 24 | res = Math.max(res, right - left + 1); 25 | 26 | right++; 27 | } 28 | 29 | return res; 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /src/leetcode/slidingwindow/Solution2302.java: -------------------------------------------------------------------------------- 1 | package leetcode.slidingwindow; 2 | 3 | import leetcode.Solution; 4 | 5 | public class Solution2302 { 6 | public static void main(String[] args) { 7 | System.out.println(new Solution2302().countSubarrays(new int[]{9, 5, 3, 8, 4, 7, 2, 7, 4, 5, 4, 9, 1, 4, 8, 10, 8, 10, 4, 7}, 4)); 8 | } 9 | 10 | public long countSubarrays(int[] nums, long k) { 11 | long res = 0; 12 | int left = 0, right = 0; 13 | long sum = 0; 14 | while (right < nums.length) { 15 | sum += nums[right]; 16 | // 不符合条件则不断缩小窗口 17 | while (sum * (right - left + 1) >= k && left <= right) { 18 | sum -= nums[left++]; 19 | } 20 | 21 | if (left <= right && sum * (right - left + 1) < k) { 22 | // 符合条件累加 23 | res += (right - left + 1); 24 | } 25 | right++; 26 | } 27 | 28 | return res; 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /src/leetcode/slidingwindow/Solution3.java: -------------------------------------------------------------------------------- 1 | package leetcode.slidingwindow; 2 | 3 | import java.util.HashSet; 4 | 5 | public class Solution3 { 6 | 7 | public static void main(String[] args) { 8 | System.out.println(new Solution3().lengthOfLongestSubstring("abba")); 9 | } 10 | 11 | public int lengthOfLongestSubstring(String s) { 12 | int res = 0; 13 | HashSet mark = new HashSet<>(); 14 | int left = 0, right = 0; 15 | while (right < s.length()) { 16 | while (mark.contains(s.charAt(right)) && left < right) { 17 | mark.remove(s.charAt(left++)); 18 | } 19 | mark.add(s.charAt(right)); 20 | res = Math.max(res, right - left + 1); 21 | 22 | right++; 23 | } 24 | 25 | return res; 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /src/leetcode/slidingwindow/Solution424.java: -------------------------------------------------------------------------------- 1 | package leetcode.slidingwindow; 2 | 3 | public class Solution424 { 4 | 5 | public static void main(String[] args) { 6 | // 4 7 | System.out.println(new Solution424().characterReplacement("ABBB", 2)); 8 | } 9 | 10 | public int characterReplacement(String s, int k) { 11 | int res = 0; 12 | int[] mark = new int[26]; 13 | int maxCount = 0; 14 | char[] charArray = s.toCharArray(); 15 | 16 | int left = 0, right = 0; 17 | while (right < charArray.length) { 18 | mark[charArray[right] - 'A']++; 19 | maxCount = Math.max(maxCount, mark[charArray[right] - 'A']); 20 | 21 | while (right - left + 1 - maxCount > k) { 22 | mark[charArray[left++] - 'A']--; 23 | } 24 | res = Math.max(res, right - left + 1); 25 | right++; 26 | } 27 | 28 | return res; 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /src/leetcode/slidingwindow/Solution643.java: -------------------------------------------------------------------------------- 1 | package leetcode.slidingwindow; 2 | 3 | public class Solution643 { 4 | public double findMaxAverage(int[] nums, int k) { 5 | double res = Integer.MIN_VALUE; 6 | 7 | int sum = 0; 8 | int left = 0, right = 0; 9 | while (right < nums.length) { 10 | sum += nums[right]; 11 | if (right - left + 1 == k) { 12 | res = Math.max(res, (double) sum / k); 13 | } 14 | 15 | if (right >= k - 1) { 16 | sum -= nums[left]; 17 | left++; 18 | } 19 | right++; 20 | } 21 | 22 | return res; 23 | } 24 | 25 | } 26 | -------------------------------------------------------------------------------- /src/leetcode/slidingwindow/Solution713.java: -------------------------------------------------------------------------------- 1 | package leetcode.slidingwindow; 2 | 3 | public class Solution713 { 4 | 5 | public static void main(String[] args) { 6 | // 2 7 | System.out.println(new Solution713().numSubarrayProductLessThanK(new int[]{1, 3, 1}, 2)); 8 | } 9 | 10 | public int numSubarrayProductLessThanK(int[] nums, int k) { 11 | if (k == 0 || k == 1) { 12 | return 0; 13 | } 14 | 15 | int res = 0; 16 | int sum = 1; 17 | int left = 0, right = 0; 18 | while (right < nums.length) { 19 | sum *= nums[right]; 20 | 21 | while (sum >= k && left <= right) { 22 | sum /= nums[left++]; 23 | } 24 | res += right - left + 1; 25 | 26 | right++; 27 | } 28 | 29 | return res; 30 | } 31 | 32 | } 33 | -------------------------------------------------------------------------------- /src/leetcode/slidingwindow/Solution904.java: -------------------------------------------------------------------------------- 1 | package leetcode.slidingwindow; 2 | 3 | import java.util.HashMap; 4 | 5 | public class Solution904 { 6 | 7 | public static void main(String[] args) { 8 | // 5 9 | System.out.println(new Solution904().totalFruit(new int[]{3, 3, 3, 1, 2, 1, 1, 2, 3, 3, 4})); 10 | } 11 | 12 | public int totalFruit(int[] fruits) { 13 | int res = 0; 14 | HashMap mark = new HashMap<>(); 15 | int left = 0, right = 0; 16 | while (right < fruits.length) { 17 | mark.put(fruits[right], mark.getOrDefault(fruits[right], 0) + 1); 18 | 19 | while (mark.size() > 2 && left < right) { 20 | Integer num = mark.get(fruits[left]); 21 | if (num == 1) { 22 | mark.remove(fruits[left]); 23 | } else { 24 | mark.put(fruits[left], num - 1); 25 | } 26 | left++; 27 | } 28 | res = Math.max(res, right - left + 1); 29 | 30 | right++; 31 | } 32 | 33 | return res; 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /src/leetcode/slidingwindow/SolutionLCR008.java: -------------------------------------------------------------------------------- 1 | package leetcode.slidingwindow; 2 | 3 | public class SolutionLCR008 { 4 | 5 | public static void main(String[] args) { 6 | // 1 7 | System.out.println(new SolutionLCR008().minSubArrayLen(4, new int[]{1, 4, 4})); 8 | } 9 | 10 | public int minSubArrayLen(int target, int[] nums) { 11 | int res = Integer.MAX_VALUE; 12 | int sum = 0; 13 | int left = 0, right = 0; 14 | while (right < nums.length) { 15 | sum += nums[right]; 16 | 17 | while (sum >= target && left <= right) { 18 | if (right - left + 1 < res) { 19 | res = right - left + 1; 20 | } 21 | sum -= nums[left++]; 22 | } 23 | right++; 24 | } 25 | 26 | return res == Integer.MAX_VALUE ? 0 : res; 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /src/leetcode/slidingwindow/SolutionOffer48.java: -------------------------------------------------------------------------------- 1 | package leetcode.slidingwindow; 2 | 3 | import java.util.HashMap; 4 | 5 | public class SolutionOffer48 { 6 | public static void main(String[] args) { 7 | System.out.println(new SolutionOffer48().lengthOfLongestSubstring("abba")); 8 | } 9 | 10 | public int lengthOfLongestSubstring(String s) { 11 | // 滑动窗口 结合hashmap 12 | HashMap map = new HashMap<>(); 13 | // 滑动窗口 14 | int left = 0, right = 0; 15 | int res = 0; 16 | 17 | while (right < s.length()) { 18 | // 有重复 19 | if (map.containsKey(s.charAt(right))) { 20 | // 窗口缩小 21 | left = Math.max(map.get(s.charAt(right)) + 1, left); 22 | } 23 | // 没重复 24 | map.put(s.charAt(right), right); 25 | 26 | res = Math.max(res, right - left + 1); 27 | 28 | // 窗口扩大 29 | right++; 30 | } 31 | 32 | return res; 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /src/leetcode/slidingwindow/SolutionOffer572.java: -------------------------------------------------------------------------------- 1 | package leetcode.slidingwindow; 2 | 3 | import java.util.ArrayList; 4 | import java.util.Arrays; 5 | import java.util.List; 6 | 7 | public class SolutionOffer572 { 8 | public static void main(String[] args) { 9 | System.out.println(Arrays.deepToString(new SolutionOffer572().findContinuousSequence(9))); 10 | } 11 | 12 | public int[][] findContinuousSequence(int target) { 13 | List res = new ArrayList<>(); 14 | 15 | int sum = 0; 16 | int left = 1, right = 1; 17 | while (right < target) { 18 | while (sum > target) { 19 | sum -= left++; 20 | } 21 | if (sum == target) { 22 | int[] element = new int[right - left]; 23 | for (int i = left; i < right; i++) { 24 | element[i - left] = i; 25 | } 26 | res.add(element); 27 | } 28 | 29 | sum += right++; 30 | } 31 | 32 | return res.toArray(new int[res.size()][]); 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /src/leetcode/sort/Solution1051.java: -------------------------------------------------------------------------------- 1 | package leetcode.sort; 2 | 3 | import java.util.Arrays; 4 | 5 | public class Solution1051 { 6 | public int heightChecker(int[] heights) { 7 | int[] temp = Arrays.copyOfRange(heights, 0, heights.length); 8 | Arrays.sort(temp); 9 | 10 | int res = 0; 11 | for (int i = 0; i < heights.length; i++) { 12 | if (heights[i] != temp[i]) { 13 | res++; 14 | } 15 | } 16 | 17 | return res; 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /src/leetcode/sort/Solution1403.java: -------------------------------------------------------------------------------- 1 | package leetcode.sort; 2 | 3 | import java.util.ArrayList; 4 | import java.util.Arrays; 5 | import java.util.List; 6 | 7 | public class Solution1403 { 8 | public List minSubsequence(int[] nums) { 9 | Arrays.sort(nums); 10 | List res = new ArrayList<>(); 11 | int sum = 0; 12 | for (int num : nums) { 13 | sum += num; 14 | } 15 | 16 | int cur = 0, index = nums.length - 1; 17 | while (cur <= sum) { 18 | cur += nums[index]; 19 | sum -= nums[index]; 20 | res.add(nums[index--]); 21 | } 22 | 23 | return res; 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /src/leetcode/sort/Solution324.java: -------------------------------------------------------------------------------- 1 | package leetcode.sort; 2 | 3 | import java.util.Arrays; 4 | 5 | public class Solution324 { 6 | 7 | public static void main(String[] args) { 8 | new Solution324().wiggleSort(new int[]{1, 1, 2, 1, 2, 2, 1}); 9 | } 10 | 11 | public void wiggleSort(int[] nums) { 12 | int[] temp = Arrays.copyOfRange(nums, 0, nums.length); 13 | Arrays.sort(temp); 14 | 15 | int small = nums.length - 1 >> 1, big = nums.length - 1; 16 | for (int i = 0; i < nums.length; i++) { 17 | if (i % 2 == 0) { 18 | nums[i] = temp[small--]; 19 | } else { 20 | nums[i] = temp[big--]; 21 | } 22 | } 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /src/leetcode/sort/Solution75.java: -------------------------------------------------------------------------------- 1 | package leetcode.sort; 2 | 3 | public class Solution75 { 4 | 5 | public static void main(String[] args) { 6 | new Solution75().sortColors(new int[]{2, 0, 2, 1, 1, 0}); 7 | } 8 | 9 | public void sortColors(int[] nums) { 10 | sort(nums, 0, nums.length - 1); 11 | } 12 | 13 | private void sort(int[] nums, int left, int right) { 14 | if (left >= right) { 15 | return; 16 | } 17 | 18 | int base = nums[left]; 19 | int l = left, mid = left + 1, r = right; 20 | while (mid <= r) { 21 | if (nums[mid] < base) { 22 | swap(nums, l++, mid++); 23 | } else if (nums[mid] > base) { 24 | swap(nums, mid, r--); 25 | } else { 26 | mid++; 27 | } 28 | } 29 | 30 | sort(nums, left, l - 1); 31 | sort(nums, mid, right); 32 | } 33 | 34 | private void swap(int[] nums, int left, int right) { 35 | int temp = nums[left]; 36 | nums[left] = nums[right]; 37 | nums[right] = temp; 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /src/leetcode/sort/SolutionLCR164.java: -------------------------------------------------------------------------------- 1 | package leetcode.sort; 2 | 3 | import java.util.Arrays; 4 | 5 | public class SolutionLCR164 { 6 | public String crackPassword(int[] password) { 7 | String[] s = new String[password.length]; 8 | for (int i = 0; i < password.length; i++) { 9 | s[i] = String.valueOf(password[i]); 10 | } 11 | Arrays.sort(s, (x, y) -> (x + y).compareTo(y + x)); 12 | 13 | StringBuilder res = new StringBuilder(); 14 | for (String e : s) { 15 | res.append(e); 16 | } 17 | 18 | return res.toString(); 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /src/leetcode/sort/SolutionLCR186.java: -------------------------------------------------------------------------------- 1 | package leetcode.sort; 2 | 3 | import java.util.Arrays; 4 | 5 | public class SolutionLCR186 { 6 | 7 | public static void main(String[] args) { 8 | System.out.println(new SolutionLCR186().checkDynasty(new int[]{0, 6, 9, 0, 7})); 9 | } 10 | 11 | public boolean checkDynasty(int[] places) { 12 | Arrays.sort(places); 13 | 14 | int zeroNum = 0; 15 | for (int i = 0; i < places.length; i++) { 16 | if (places[i] == 0) { 17 | zeroNum++; 18 | continue; 19 | } 20 | if (i > 0 && places[i] == places[i - 1]) { 21 | return false; 22 | } 23 | } 24 | 25 | int num = places[places.length - 1] - places[zeroNum] + 1 - places.length + zeroNum; 26 | return zeroNum >= num; 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /src/leetcode/sort/algorithms/BubbleSort.java: -------------------------------------------------------------------------------- 1 | package leetcode.sort.algorithms; 2 | 3 | import java.util.Arrays; 4 | 5 | public class BubbleSort { 6 | 7 | public static void main(String[] args) { 8 | int[] origin = {4, 3, 5, 2, 6, 1, 1, 0}; 9 | new BubbleSort().sort(origin); 10 | System.out.println(Arrays.toString(origin)); 11 | } 12 | 13 | public void sort(int[] nums) { 14 | for (int i = nums.length - 1; i > 0; i--) { 15 | boolean flag = true; 16 | for (int j = 0; j < i; j++) { 17 | if (nums[j] > nums[j + 1]) { 18 | swap(nums, j, j + 1); 19 | flag = false; 20 | } 21 | } 22 | if (flag) { 23 | break; 24 | } 25 | } 26 | } 27 | 28 | private void swap(int[] nums, int i, int j) { 29 | int temp = nums[i]; 30 | nums[i] = nums[j]; 31 | nums[j] = temp; 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /src/leetcode/sort/algorithms/InsertSort.java: -------------------------------------------------------------------------------- 1 | package leetcode.sort.algorithms; 2 | 3 | import java.util.Arrays; 4 | 5 | public class InsertSort { 6 | 7 | public static void main(String[] args) { 8 | int[] origin = {4, 3, 5, 2, 6, 1, 1, 0}; 9 | new InsertSort().sort(origin); 10 | System.out.println(Arrays.toString(origin)); 11 | } 12 | 13 | public void sort(int[] nums) { 14 | for (int i = 1; i < nums.length; i++) { 15 | int base = nums[i]; 16 | 17 | int j = i - 1; 18 | while (j >= 0 && nums[j] > base) { 19 | nums[j + 1] = nums[j--]; 20 | } 21 | nums[j + 1] = base; 22 | } 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /src/leetcode/sort/algorithms/SelectionSort.java: -------------------------------------------------------------------------------- 1 | package leetcode.sort.algorithms; 2 | 3 | import java.util.Arrays; 4 | 5 | /** 6 | * 选择排序:每次选择未排序数组中的最小值,将其放到已排序区间的末尾 7 | * 空间复杂度:O(1) 8 | * 原地排序 9 | * 非稳定排序:会改变等值元素之间的相对位置 10 | * 非自适应排序:最好/平均/最坏时间复杂度均为 O(n^2) 11 | */ 12 | public class SelectionSort { 13 | 14 | public static void main(String[] args) { 15 | int[] origin = {4, 3, 5, 2, 6, 1, 1, 0}; 16 | new SelectionSort().sort(origin); 17 | System.out.println(Arrays.toString(origin)); 18 | } 19 | 20 | private void sort(int[] nums) { 21 | for (int i = 0; i < nums.length; i++) { 22 | int min = i; 23 | for (int j = i + 1; j < nums.length; j++) { 24 | if (nums[j] < nums[min]) { 25 | min = j; 26 | } 27 | } 28 | swap(nums, i, min); 29 | } 30 | } 31 | 32 | private void swap(int[] nums, int i, int j) { 33 | int temp = nums[i]; 34 | nums[i] = nums[j]; 35 | nums[j] = temp; 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /src/leetcode/sort/algorithms/ShellSort.java: -------------------------------------------------------------------------------- 1 | package leetcode.sort.algorithms; 2 | 3 | import java.util.Arrays; 4 | 5 | public class ShellSort { 6 | 7 | public static void main(String[] args) { 8 | int[] origin = {4, 3, 5, 2, 6, 1, 1, 0}; 9 | new ShellSort().sort(origin); 10 | System.out.println(Arrays.toString(origin)); 11 | } 12 | 13 | private void sort(int[] nums) { 14 | int h = 1; 15 | int N = nums.length; 16 | while (h < N / 3) { 17 | h = 3 * h + 1; 18 | } 19 | 20 | while (h >= 1) { 21 | for (int i = h; i < nums.length; i++) { 22 | int base = nums[i]; 23 | 24 | int j = i - h; 25 | while (j >= 0 && base < nums[j]) { 26 | nums[j + h] = nums[j]; 27 | j -= h; 28 | } 29 | nums[j + h] = base; 30 | } 31 | h /= 3; 32 | } 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /src/leetcode/stack/MinStack.java: -------------------------------------------------------------------------------- 1 | package leetcode.stack; 2 | 3 | import java.util.Stack; 4 | 5 | public class MinStack { 6 | 7 | private Stack stack; 8 | 9 | private Stack minStack; 10 | 11 | public MinStack() { 12 | stack = new Stack<>(); 13 | minStack = new Stack<>(); 14 | } 15 | 16 | public void push(int val) { 17 | stack.push(val); 18 | if (minStack.isEmpty() || minStack.peek() >= val) { 19 | minStack.push(val); 20 | } 21 | } 22 | 23 | public void pop() { 24 | if (stack.isEmpty()) { 25 | return; 26 | } 27 | 28 | Integer val = stack.pop(); 29 | if (minStack.peek().equals(val)) { 30 | minStack.pop(); 31 | } 32 | } 33 | 34 | public int top() { 35 | return stack.peek(); 36 | } 37 | 38 | public int getMin() { 39 | return minStack.peek(); 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /src/leetcode/stack/MyQueue.java: -------------------------------------------------------------------------------- 1 | package leetcode.stack; 2 | 3 | import java.util.Stack; 4 | 5 | public class MyQueue { 6 | 7 | private final Stack left; 8 | 9 | public final Stack right; 10 | 11 | public MyQueue() { 12 | left = new Stack<>(); 13 | right = new Stack<>(); 14 | } 15 | 16 | public void push(int x) { 17 | right.push(x); 18 | } 19 | 20 | public int pop() { 21 | transfer(); 22 | return left.pop(); 23 | } 24 | 25 | public int peek() { 26 | transfer(); 27 | return left.peek(); 28 | } 29 | 30 | private void transfer() { 31 | if (left.isEmpty()) { 32 | while (!right.isEmpty()) { 33 | left.push(right.pop()); 34 | } 35 | } 36 | } 37 | 38 | public boolean empty() { 39 | return left.isEmpty() && right.isEmpty(); 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /src/leetcode/stack/Solution20.java: -------------------------------------------------------------------------------- 1 | package leetcode.stack; 2 | 3 | import java.util.Stack; 4 | 5 | public class Solution20 { 6 | 7 | public static void main(String[] args) { 8 | new Solution20().isValid("(){}}{"); 9 | } 10 | public boolean isValid(String s) { 11 | // 左括号进栈,右括号出栈比对是不是对应的左括号 12 | Stack stack = new Stack<>(); 13 | char[] charArray = s.toCharArray(); 14 | 15 | for (char c : charArray) { 16 | if (c == '(' || c == '[' || c == '{') { 17 | stack.push(c); 18 | } else if (c == ')') { 19 | if (stack.isEmpty() || stack.pop() != '(') { 20 | return false; 21 | } 22 | } else if (c == ']') { 23 | if (stack.isEmpty() || stack.pop() != '[') { 24 | return false; 25 | } 26 | } else if (c == '}') { 27 | if (stack.isEmpty() || stack.pop() != '{') { 28 | return false; 29 | } 30 | } 31 | } 32 | 33 | return stack.isEmpty(); 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /src/leetcode/stack/Solution856.java: -------------------------------------------------------------------------------- 1 | package leetcode.stack; 2 | 3 | import java.util.Stack; 4 | 5 | public class Solution856 { 6 | public int scoreOfParentheses(String s) { 7 | Stack stack = new Stack<>(); 8 | char[] charArray = s.toCharArray(); 9 | 10 | for (char c : charArray) { 11 | if (c == ')') { 12 | // 右括号的话,如果 peek 为 0 那么则是 () 情况 如果不为 0 我们需要把它乘 2 13 | stack.push(Math.max(1, 2 * stack.pop())); 14 | // 以上算完之后是单个的元素,如果其中还有其他单个元素的话,则加一起,是 )( 的情况 15 | if (stack.size() > 1) { 16 | stack.push(stack.pop() + stack.pop()); 17 | } 18 | } else { 19 | // 左括号的话,需要加入一个 0 来达成 () 的计算 20 | stack.push(0); 21 | } 22 | } 23 | 24 | return stack.peek(); 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /src/leetcode/stack/Solution946.java: -------------------------------------------------------------------------------- 1 | package leetcode.stack; 2 | 3 | import java.util.Stack; 4 | 5 | public class Solution946 { 6 | public boolean validateStackSequences(int[] pushed, int[] popped) { 7 | // pushed 不断的入栈,入栈完成后和 popped 比较,符合的话出栈,最终栈为空即可行 8 | Stack stack = new Stack<>(); 9 | 10 | int popIndex = 0; 11 | for (int i : pushed) { 12 | stack.push(i); 13 | 14 | while (popIndex < popped.length && !stack.isEmpty() && popped[popIndex] == stack.peek()) { 15 | stack.pop(); 16 | popIndex++; 17 | } 18 | } 19 | 20 | return stack.isEmpty(); 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /src/leetcode/stack/monotonic/Solution1475.java: -------------------------------------------------------------------------------- 1 | package leetcode.stack.monotonic; 2 | 3 | import java.util.Arrays; 4 | import java.util.Stack; 5 | 6 | public class Solution1475 { 7 | public static void main(String[] args) { 8 | System.out.println(Arrays.toString(new Solution1475().finalPrices(new int[]{8, 4, 6, 2, 3}))); 9 | ; 10 | } 11 | 12 | public int[] finalPrices(int[] prices) { 13 | Stack stack = new Stack<>(); 14 | 15 | for (int i = 0; i < prices.length; i++) { 16 | while (!stack.isEmpty() && prices[i] <= prices[stack.peek()]) { 17 | prices[stack.pop()] -= prices[i]; 18 | } 19 | stack.push(i); 20 | } 21 | 22 | return prices; 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /src/leetcode/stack/monotonic/Solution42.java: -------------------------------------------------------------------------------- 1 | package leetcode.stack.monotonic; 2 | 3 | import java.util.Stack; 4 | 5 | public class Solution42 { 6 | 7 | public static void main(String[] args) { 8 | System.out.println(new Solution42().trap(new int[]{4, 2, 0, 3, 2, 5})); 9 | } 10 | 11 | public int trap(int[] height) { 12 | int res = 0; 13 | Stack stack = new Stack<>(); 14 | for (int i = 0; i < height.length; i++) { 15 | while (!stack.isEmpty() && height[i] > height[stack.peek()]) { 16 | int floor = height[stack.pop()]; 17 | if (!stack.isEmpty()) { 18 | Integer w = i - stack.peek() - 1; 19 | Integer h = Math.min(height[stack.peek()], height[i]) - floor; 20 | res += w * h; 21 | } 22 | } 23 | stack.push(i); 24 | } 25 | 26 | return res; 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /src/leetcode/stack/monotonic/Solution503.java: -------------------------------------------------------------------------------- 1 | package leetcode.stack.monotonic; 2 | 3 | import java.util.Arrays; 4 | import java.util.Stack; 5 | 6 | public class Solution503 { 7 | public int[] nextGreaterElements(int[] nums) { 8 | Stack stack = new Stack<>(); 9 | int n = nums.length; 10 | int[] res = new int[n]; 11 | Arrays.fill(res, -1); 12 | 13 | for (int i = 0; i < n * 2; i++) { 14 | while (!stack.isEmpty() && nums[i % n] > nums[stack.peek()]) { 15 | res[stack.pop()] = nums[i % n]; 16 | } 17 | stack.push(i % n); 18 | } 19 | 20 | return res; 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /src/leetcode/stack/monotonic/Solution739.java: -------------------------------------------------------------------------------- 1 | package leetcode.stack.monotonic; 2 | 3 | import java.util.Arrays; 4 | import java.util.Stack; 5 | 6 | public class Solution739 { 7 | 8 | public static void main(String[] args) { 9 | System.out.println(Arrays.toString(new Solution739().dailyTemperatures(new int[]{73, 74, 75, 71, 69, 72, 76, 73}))); 10 | } 11 | 12 | public int[] dailyTemperatures(int[] temperatures) { 13 | int[] answer = new int[temperatures.length]; 14 | 15 | Stack stack = new Stack<>(); 16 | for (int i = 0; i < temperatures.length; i++) { 17 | while (!stack.isEmpty() && temperatures[i] > temperatures[stack.peek()]) { 18 | Integer index = stack.pop(); 19 | answer[index] = i - index; 20 | } 21 | stack.push(i); 22 | } 23 | 24 | return answer; 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /src/leetcode/str/Interview1002.java: -------------------------------------------------------------------------------- 1 | package leetcode.str; 2 | 3 | import java.util.ArrayList; 4 | import java.util.Arrays; 5 | import java.util.HashMap; 6 | import java.util.List; 7 | 8 | public class Interview1002 { 9 | public List> groupAnagrams(String[] strs) { 10 | HashMap> hashMap = new HashMap<>(); 11 | for (String str : strs) { 12 | char[] charArray = str.toCharArray(); 13 | Arrays.sort(charArray); 14 | String key = new String(charArray); 15 | List element = hashMap.getOrDefault(key, new ArrayList<>()); 16 | element.add(str); 17 | hashMap.put(key, element); 18 | } 19 | 20 | return new ArrayList<>(hashMap.values()); 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /src/leetcode/str/Solution14.java: -------------------------------------------------------------------------------- 1 | package leetcode.str; 2 | 3 | public class Solution14 { 4 | public String longestCommonPrefix(String[] strs) { 5 | String res = strs[0]; 6 | 7 | for (int i = 1; i < strs.length; i++) { 8 | char[] charArray = strs[i].toCharArray(); 9 | int index = 0; 10 | while (index < charArray.length && index < res.length()) { 11 | if (res.charAt(index) == charArray[index]) { 12 | index++; 13 | } else { 14 | break; 15 | } 16 | } 17 | res = strs[i].substring(0, index); 18 | } 19 | 20 | return res; 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /src/leetcode/str/Solution1455.java: -------------------------------------------------------------------------------- 1 | package leetcode.str; 2 | 3 | public class Solution1455 { 4 | public int isPrefixOfWord(String sentence, String searchWord) { 5 | String[] s = sentence.split(" "); 6 | 7 | for (int i = 0; i < s.length; i++) { 8 | if (s[i].startsWith(searchWord)) { 9 | return i; 10 | } 11 | } 12 | 13 | return -1; 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /src/leetcode/str/Solution151.java: -------------------------------------------------------------------------------- 1 | package leetcode.str; 2 | 3 | import java.util.Stack; 4 | 5 | public class Solution151 { 6 | 7 | public static void main(String[] args) { 8 | System.out.println(new Solution151().reverseWords("a good example")); 9 | } 10 | 11 | public String reverseWords(String s) { 12 | Stack stack = new Stack<>(); 13 | String[] strings = s.split(" "); 14 | for (String string : strings) { 15 | if (!"".equals(string)) { 16 | stack.push(string); 17 | } 18 | } 19 | 20 | StringBuilder builder = new StringBuilder(); 21 | while (!stack.isEmpty()) { 22 | builder.append(stack.pop()).append(" "); 23 | } 24 | return builder.substring(0, builder.length() - 1); 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /src/leetcode/str/Solution165.java: -------------------------------------------------------------------------------- 1 | package leetcode.str; 2 | 3 | public class Solution165 { 4 | 5 | public int compareVersion(String version1, String version2) { 6 | String[] number1 = version1.split("\\."); 7 | String[] number2 = version2.split("\\."); 8 | 9 | for (int i = 0; i < number1.length || i < number2.length; i++) { 10 | int value1 = 0, value2 = 0; 11 | 12 | if (i < number1.length) { 13 | value1 = Integer.parseInt(number1[i]); 14 | } 15 | if (i < number2.length) { 16 | value2 = Integer.parseInt(number2[i]); 17 | } 18 | 19 | if (value1 > value2) { 20 | return 1; 21 | } 22 | if (value1 < value2) { 23 | return -1; 24 | } 25 | } 26 | 27 | return 0; 28 | } 29 | } 30 | 31 | -------------------------------------------------------------------------------- /src/leetcode/str/Solution187.java: -------------------------------------------------------------------------------- 1 | package leetcode.str; 2 | 3 | import java.util.*; 4 | 5 | public class Solution187 { 6 | 7 | public static void main(String[] args) { 8 | new Solution187().findRepeatedDnaSequences("AAAAAAAAAAA"); 9 | } 10 | 11 | public List findRepeatedDnaSequences(String s) { 12 | HashMap map = new HashMap<>(); 13 | 14 | for (int i = 0; i + 10 <= s.length(); i++) { 15 | String dna = s.substring(i, i + 10); 16 | map.put(dna, map.getOrDefault(dna, 0) + 1); 17 | } 18 | 19 | List res = new ArrayList<>(); 20 | for (Map.Entry entry : map.entrySet()) { 21 | if (entry.getValue() > 1) { 22 | res.add(entry.getKey()); 23 | } 24 | } 25 | 26 | return res; 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /src/leetcode/tree/bst/Interview0406.java: -------------------------------------------------------------------------------- 1 | package leetcode.tree.bst; 2 | 3 | import leetcode.TreeNode; 4 | import leetcode.tree.levelorder.Codec; 5 | 6 | public class Interview0406 { 7 | 8 | public static void main(String[] args) { 9 | new Interview0406().inorderSuccessor(new Codec().deserialize("5,3,6,2,4,null,null,1"), new TreeNode(1)); 10 | } 11 | 12 | TreeNode pre = null; 13 | 14 | public TreeNode inorderSuccessor(TreeNode root, TreeNode p) { 15 | if (root == null || p == null) { 16 | return null; 17 | } 18 | 19 | TreeNode left = inorderSuccessor(root.left, p); 20 | if (pre != null && pre.val == p.val) { 21 | return root; 22 | } 23 | pre = root; 24 | TreeNode right = inorderSuccessor(root.right, p); 25 | 26 | return left == null ? right : left; 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /src/leetcode/tree/bst/Solution230.java: -------------------------------------------------------------------------------- 1 | package leetcode.tree.bst; 2 | 3 | import leetcode.TreeNode; 4 | 5 | public class Solution230 { 6 | 7 | int k; 8 | 9 | int res; 10 | 11 | public int kthSmallest(TreeNode root, int k) { 12 | this.k = k; 13 | midOrder(root); 14 | return res; 15 | } 16 | 17 | private void midOrder(TreeNode node) { 18 | if (node == null || k == 0) { 19 | return; 20 | } 21 | 22 | midOrder(node.left); 23 | k--; 24 | if (k == 0) { 25 | res = node.val; 26 | return; 27 | } 28 | midOrder(node.right); 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /src/leetcode/tree/bst/Solution235.java: -------------------------------------------------------------------------------- 1 | package leetcode.tree.bst; 2 | 3 | import leetcode.TreeNode; 4 | 5 | public class Solution235 { 6 | public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) { 7 | if (p.val < root.val && q.val < root.val) { 8 | return lowestCommonAncestor(root.left, p, q); 9 | } 10 | if (p.val > root.val && q.val > root.val) { 11 | return lowestCommonAncestor(root.right, p, q); 12 | } 13 | 14 | return root; 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /src/leetcode/tree/bst/Solution450.java: -------------------------------------------------------------------------------- 1 | package leetcode.tree.bst; 2 | 3 | import leetcode.TreeNode; 4 | 5 | public class Solution450 { 6 | 7 | public TreeNode deleteNode(TreeNode root, int key) { 8 | if (root == null) { 9 | return null; 10 | } 11 | 12 | if (key > root.val) { 13 | root.right = deleteNode(root.right, key); 14 | return root; 15 | } 16 | if (key < root.val) { 17 | root.left = deleteNode(root.left, key); 18 | return root; 19 | } 20 | if (root.left == null) { 21 | return root.right; 22 | } 23 | if (root.right == null) { 24 | return root.left; 25 | } 26 | TreeNode right = root.right; 27 | while (right.left != null) { 28 | right = right.left; 29 | } 30 | right.left = root.left; 31 | 32 | return root.right; 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /src/leetcode/tree/bst/Solution669.java: -------------------------------------------------------------------------------- 1 | package leetcode.tree.bst; 2 | 3 | import leetcode.TreeNode; 4 | 5 | public class Solution669 { 6 | public TreeNode trimBST(TreeNode root, int low, int high) { 7 | if (root == null) { 8 | return null; 9 | } 10 | if (root.val < low) { 11 | return trimBST(root.right, low, high); 12 | } 13 | if (root.val > high) { 14 | return trimBST(root.left, low, high); 15 | } 16 | root.left = trimBST(root.left, low, high); 17 | root.right = trimBST(root.right, low, high); 18 | 19 | return root; 20 | } 21 | 22 | } 23 | -------------------------------------------------------------------------------- /src/leetcode/tree/bst/Solution94.java: -------------------------------------------------------------------------------- 1 | package leetcode.tree.bst; 2 | 3 | import leetcode.TreeNode; 4 | 5 | import java.util.ArrayList; 6 | import java.util.List; 7 | 8 | public class Solution94 { 9 | 10 | List res; 11 | public List inorderTraversal(TreeNode root) { 12 | res = new ArrayList<>(); 13 | midOrder(root); 14 | return res; 15 | } 16 | 17 | private void midOrder(TreeNode root) { 18 | if (root == null) { 19 | return; 20 | } 21 | 22 | midOrder(root.left); 23 | res.add(root.val); 24 | midOrder(root.right); 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /src/leetcode/tree/bst/Solution98.java: -------------------------------------------------------------------------------- 1 | package leetcode.tree.bst; 2 | 3 | import leetcode.TreeNode; 4 | 5 | public class Solution98 { 6 | long pre = Long.MIN_VALUE; 7 | 8 | public boolean isValidBST(TreeNode root) { 9 | if (root == null) { 10 | return true; 11 | } 12 | 13 | boolean left = isValidBST(root.left); 14 | if (pre >= root.val) { 15 | return false; 16 | } 17 | pre = root.val; 18 | boolean right = isValidBST(root.right); 19 | 20 | return left && right; 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /src/leetcode/tree/bst/Solution99.java: -------------------------------------------------------------------------------- 1 | package leetcode.tree.bst; 2 | 3 | import leetcode.TreeNode; 4 | 5 | public class Solution99 { 6 | 7 | TreeNode one = null, two = null; 8 | 9 | TreeNode pre = null; 10 | 11 | public void recoverTree(TreeNode root) { 12 | if (root == null) { 13 | return; 14 | } 15 | 16 | markNode(root); 17 | int temp = one.val; 18 | one.val = two.val; 19 | two.val = temp; 20 | } 21 | 22 | private void markNode(TreeNode node) { 23 | if (node == null) { 24 | return; 25 | } 26 | 27 | markNode(node.left); 28 | if (pre != null && pre.val >= node.val) { 29 | if (one == null) { 30 | one = pre; 31 | } 32 | two = node; 33 | } 34 | pre = node; 35 | markNode(node.right); 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /src/leetcode/tree/bst/SolutionLCR155.java: -------------------------------------------------------------------------------- 1 | package leetcode.tree.bst; 2 | 3 | import leetcode.Node; 4 | 5 | public class SolutionLCR155 { 6 | 7 | Node pre = null; 8 | 9 | public Node treeToDoublyList(Node root) { 10 | if (root == null) { 11 | return null; 12 | } 13 | 14 | Node head = new Node(); 15 | pre = head; 16 | doTreeToDoublyList(root); 17 | head.right.left = pre; 18 | pre.right = head.right; 19 | return head.right; 20 | } 21 | 22 | private void doTreeToDoublyList(Node node) { 23 | if (node == null) { 24 | return; 25 | } 26 | 27 | doTreeToDoublyList(node.left); 28 | pre.right = node; 29 | node.left = pre; 30 | pre = node; 31 | doTreeToDoublyList(node.right); 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /src/leetcode/tree/bst/SolutionLCR174.java: -------------------------------------------------------------------------------- 1 | package leetcode.tree.bst; 2 | 3 | import leetcode.TreeNode; 4 | 5 | import java.util.ArrayList; 6 | import java.util.List; 7 | 8 | public class SolutionLCR174 { 9 | 10 | List nodes; 11 | 12 | public int findTargetNode(TreeNode root, int cnt) { 13 | nodes = new ArrayList<>(); 14 | midOrder(root); 15 | return nodes.get(nodes.size() - cnt); 16 | } 17 | 18 | private void midOrder(TreeNode node) { 19 | if (node == null) { 20 | return; 21 | } 22 | 23 | midOrder(node.left); 24 | nodes.add(node.val); 25 | midOrder(node.right); 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /src/leetcode/tree/dfs/Solution114.java: -------------------------------------------------------------------------------- 1 | package leetcode.tree.dfs; 2 | 3 | import leetcode.TreeNode; 4 | 5 | public class Solution114 { 6 | public void flatten(TreeNode root) { 7 | if (root == null) { 8 | return; 9 | } 10 | 11 | if (root.left != null) { 12 | TreeNode left = root.left; 13 | TreeNode right = root.right; 14 | TreeNode rightPre = left; 15 | while (rightPre.right != null) { 16 | rightPre = rightPre.right; 17 | } 18 | rightPre.right = right; 19 | root.right = left; 20 | root.left = null; 21 | } 22 | 23 | flatten(root.right); 24 | } 25 | 26 | 27 | } 28 | -------------------------------------------------------------------------------- /src/leetcode/tree/dfs/Solution437.java: -------------------------------------------------------------------------------- 1 | package leetcode.tree.dfs; 2 | 3 | import leetcode.TreeNode; 4 | 5 | public class Solution437 { 6 | 7 | int res; 8 | 9 | int targetSum; 10 | 11 | public int pathSum(TreeNode root, int targetSum) { 12 | this.res = 0; 13 | this.targetSum = targetSum; 14 | doPathSum(root); 15 | 16 | return res; 17 | } 18 | 19 | private void doPathSum(TreeNode root) { 20 | if (root == null) { 21 | return; 22 | } 23 | 24 | doPathSum2(root, root.val); 25 | doPathSum(root.left); 26 | doPathSum(root.right); 27 | } 28 | 29 | private void doPathSum2(TreeNode root, long val) { 30 | if (root == null) { 31 | return; 32 | } 33 | 34 | if (val == targetSum) { 35 | res++; 36 | } 37 | if (root.left != null) { 38 | doPathSum2(root.left, val + root.left.val); 39 | } 40 | if (root.right != null) { 41 | doPathSum2(root.right, val + root.right.val); 42 | } 43 | } 44 | 45 | } 46 | -------------------------------------------------------------------------------- /src/leetcode/tree/dfs/Solution652.java: -------------------------------------------------------------------------------- 1 | package leetcode.tree.dfs; 2 | 3 | import leetcode.TreeNode; 4 | 5 | import java.util.ArrayList; 6 | import java.util.HashMap; 7 | import java.util.List; 8 | 9 | public class Solution652 { 10 | 11 | List res; 12 | 13 | HashMap map; 14 | 15 | public List findDuplicateSubtrees(TreeNode root) { 16 | res = new ArrayList<>(); 17 | map = new HashMap<>(); 18 | recursion(root); 19 | 20 | return res; 21 | } 22 | 23 | private String recursion(TreeNode root) { 24 | if (root == null) { 25 | return " "; 26 | } 27 | 28 | StringBuilder nodes = new StringBuilder(); 29 | nodes.append(root.val).append("_"); 30 | nodes.append(recursion(root.left)).append(recursion(root.right)); 31 | 32 | String key = nodes.toString(); 33 | map.put(key, map.getOrDefault(key, 0) + 1); 34 | if (map.get(key) == 2) { 35 | res.add(root); 36 | } 37 | 38 | return key; 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /src/leetcode/tree/levelorder/Solution111.java: -------------------------------------------------------------------------------- 1 | package leetcode.tree.levelorder; 2 | 3 | import leetcode.TreeNode; 4 | 5 | import java.util.LinkedList; 6 | import java.util.Queue; 7 | 8 | public class Solution111 { 9 | public int minDepth(TreeNode root) { 10 | int res = 0; 11 | if (root == null) { 12 | return res; 13 | } 14 | 15 | Queue queue = new LinkedList<>(); 16 | queue.offer(root); 17 | while (!queue.isEmpty()) { 18 | res++; 19 | int size = queue.size(); 20 | for (int i = 0; i < size; i++) { 21 | TreeNode node = queue.poll(); 22 | if (node.left == null && node.right == null) { 23 | return res; 24 | } 25 | if (node.left != null) { 26 | queue.offer(node.left); 27 | } 28 | if (node.right != null) { 29 | queue.offer(node.right); 30 | } 31 | } 32 | } 33 | 34 | return res; 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /src/leetcode/tree/levelorder/Solution199.java: -------------------------------------------------------------------------------- 1 | package leetcode.tree.levelorder; 2 | 3 | import leetcode.TreeNode; 4 | 5 | import java.util.ArrayList; 6 | import java.util.LinkedList; 7 | import java.util.List; 8 | import java.util.Queue; 9 | 10 | public class Solution199 { 11 | public List rightSideView(TreeNode root) { 12 | List res = new LinkedList<>(); 13 | if (root == null) { 14 | return res; 15 | } 16 | 17 | LinkedList queue = new LinkedList<>(); 18 | queue.offer(root); 19 | while (!queue.isEmpty()) { 20 | res.add(queue.peekLast().val); 21 | int size = queue.size(); 22 | for (int i = 0; i < size; i++) { 23 | TreeNode node = queue.poll(); 24 | if (node.left != null) { 25 | queue.offer(node.left); 26 | } 27 | if (node.right != null) { 28 | queue.offer(node.right); 29 | } 30 | } 31 | } 32 | 33 | return res; 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /src/leetcode/tree/postorder/Solution104.java: -------------------------------------------------------------------------------- 1 | package leetcode.tree.postorder; 2 | 3 | import leetcode.TreeNode; 4 | 5 | public class Solution104 { 6 | public int maxDepth(TreeNode root) { 7 | if (root == null) { 8 | return 0; 9 | } 10 | 11 | int left = maxDepth(root.left); 12 | int right = maxDepth(root.right); 13 | 14 | return Math.max(left, right) + 1; 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /src/leetcode/tree/postorder/Solution1080.java: -------------------------------------------------------------------------------- 1 | package leetcode.tree.postorder; 2 | 3 | import leetcode.TreeNode; 4 | 5 | public class Solution1080 { 6 | public TreeNode sufficientSubset(TreeNode root, int limit) { 7 | boolean delete = postOrder(root, 0, limit); 8 | if (delete) { 9 | return null; 10 | } 11 | 12 | return root; 13 | } 14 | 15 | private boolean postOrder(TreeNode node, int s, int limit) { 16 | if (node == null) { 17 | return true; 18 | } 19 | if (node.left == null && node.right == null) { 20 | return node.val + s < limit; 21 | } 22 | 23 | boolean left = postOrder(node.left, s + node.val, limit); 24 | boolean right = postOrder(node.right, s + node.val, limit); 25 | 26 | if (left) { 27 | node.left = null; 28 | } 29 | if (right) { 30 | node.right = null; 31 | } 32 | 33 | return left && right; 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /src/leetcode/tree/postorder/Solution110.java: -------------------------------------------------------------------------------- 1 | package leetcode.tree.postorder; 2 | 3 | import leetcode.TreeNode; 4 | 5 | public class Solution110 { 6 | 7 | public boolean isBalanced(TreeNode root) { 8 | if (root == null) { 9 | return true; 10 | } 11 | 12 | return depth(root) != -1; 13 | } 14 | 15 | private int depth(TreeNode node) { 16 | if (node == null) { 17 | return 0; 18 | } 19 | 20 | int left = depth(node.left); 21 | int right = depth(node.right); 22 | if (left == -1 || right == -1 || Math.abs(left - right) > 1) { 23 | return -1; 24 | } 25 | 26 | return Math.max(left, right) + 1; 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /src/leetcode/tree/postorder/Solution145.java: -------------------------------------------------------------------------------- 1 | package leetcode.tree.postorder; 2 | 3 | import leetcode.TreeNode; 4 | 5 | import java.util.ArrayList; 6 | import java.util.List; 7 | 8 | public class Solution145 { 9 | 10 | List res; 11 | 12 | public List postorderTraversal(TreeNode root) { 13 | res = new ArrayList<>(); 14 | postOrder(root); 15 | return res; 16 | } 17 | 18 | private void postOrder(TreeNode node) { 19 | if (node == null) { 20 | return; 21 | } 22 | 23 | postOrder(node.left); 24 | postOrder(node.right); 25 | res.add(node.val); 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /src/leetcode/tree/postorder/Solution236.java: -------------------------------------------------------------------------------- 1 | package leetcode.tree.postorder; 2 | 3 | import leetcode.TreeNode; 4 | 5 | public class Solution236 { 6 | public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) { 7 | if (root == null || p.val == root.val || q.val == root.val) { 8 | return root; 9 | } 10 | 11 | TreeNode left = lowestCommonAncestor(root.left, p, q); 12 | TreeNode right = lowestCommonAncestor(root.right, p, q); 13 | if (left != null && right != null) { 14 | return root; 15 | } 16 | return left == null ? right : left; 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /src/leetcode/tree/postorder/Solution337.java: -------------------------------------------------------------------------------- 1 | package leetcode.tree.postorder; 2 | 3 | import leetcode.TreeNode; 4 | 5 | import java.util.HashMap; 6 | 7 | public class Solution337 { 8 | 9 | HashMap memo = new HashMap<>(); 10 | 11 | public int rob(TreeNode root) { 12 | if (root == null) { 13 | return 0; 14 | } 15 | if (memo.containsKey(root)) { 16 | return memo.get(root); 17 | } 18 | 19 | // 抢当前节点 20 | int val1 = root.val; 21 | if (root.left != null) { 22 | val1 += rob(root.left.left); 23 | val1 += rob(root.left.right); 24 | } 25 | if (root.right != null) { 26 | val1 += rob(root.right.left); 27 | val1 += rob(root.right.right); 28 | } 29 | // 不抢当前节点 30 | int val2 = rob(root.left) + rob(root.right); 31 | int max = Math.max(val1, val2); 32 | memo.put(root, max); 33 | 34 | return max; 35 | } 36 | 37 | 38 | } 39 | -------------------------------------------------------------------------------- /src/leetcode/tree/postorder/Solution687.java: -------------------------------------------------------------------------------- 1 | package leetcode.tree.postorder; 2 | 3 | import leetcode.TreeNode; 4 | 5 | public class Solution687 { 6 | 7 | int res; 8 | 9 | public int longestUnivaluePath(TreeNode root) { 10 | this.res = 0; 11 | doLongestUnivaluePath(root); 12 | return res; 13 | } 14 | 15 | private int doLongestUnivaluePath(TreeNode node) { 16 | if (node == null) { 17 | return 0; 18 | } 19 | 20 | int left = doLongestUnivaluePath(node.left); 21 | int right = doLongestUnivaluePath(node.right); 22 | int cur = 0, max = 0; 23 | if (node.left != null && node.left.val == node.val) { 24 | max = left + 1; 25 | cur = left + 1; 26 | } 27 | if (node.right != null && node.right.val == node.val) { 28 | cur += right + 1; 29 | max = Math.max(max, right + 1); 30 | } 31 | res = Math.max(res, cur); 32 | 33 | return max; 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /src/leetcode/tree/postorder/Solution814.java: -------------------------------------------------------------------------------- 1 | package leetcode.tree.postorder; 2 | 3 | import leetcode.TreeNode; 4 | import leetcode.tree.levelorder.Codec; 5 | 6 | public class Solution814 { 7 | 8 | public static void main(String[] args) { 9 | TreeNode treeNode = new Codec().deserialize("1,null,0,0,1"); 10 | 11 | new Solution814().pruneTree(treeNode); 12 | } 13 | 14 | public TreeNode pruneTree(TreeNode root) { 15 | if (root == null) { 16 | return null; 17 | } 18 | 19 | int res = doPruneTree(root); 20 | if (res == 0) { 21 | return null; 22 | } 23 | 24 | return root; 25 | } 26 | 27 | private int doPruneTree(TreeNode node) { 28 | if (node == null) { 29 | return 0; 30 | } 31 | 32 | int left = doPruneTree(node.left); 33 | int right = doPruneTree(node.right); 34 | 35 | if (left == 0) { 36 | node.left = null; 37 | } 38 | if (right == 0) { 39 | node.right = null; 40 | } 41 | 42 | return node.val + left + right; 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /src/leetcode/tree/postorder/Solution979.java: -------------------------------------------------------------------------------- 1 | package leetcode.tree.postorder; 2 | 3 | import leetcode.TreeNode; 4 | 5 | public class Solution979 { 6 | 7 | int res = 0; 8 | 9 | public int distributeCoins(TreeNode root) { 10 | postOrder(root); 11 | return res; 12 | } 13 | 14 | 15 | private int postOrder(TreeNode node) { 16 | if (node == null) { 17 | return 1; 18 | } 19 | 20 | int left = postOrder(node.left) - 1; 21 | int right = postOrder(node.right) - 1; 22 | 23 | // 计算当前的金币数 24 | node.val += (left + right); 25 | 26 | // 少了去要,多了上交 27 | if (node.val > 1) { 28 | // 上交的数量 29 | res += (node.val - 1); 30 | } else { 31 | // 要的数量 32 | res += -node.val + 1; 33 | } 34 | 35 | return node.val; 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /src/leetcode/tree/preorder/Solution108.java: -------------------------------------------------------------------------------- 1 | package leetcode.tree.preorder; 2 | 3 | import leetcode.TreeNode; 4 | 5 | public class Solution108 { 6 | public TreeNode sortedArrayToBST(int[] nums) { 7 | return build(nums, 0, nums.length - 1); 8 | } 9 | 10 | private TreeNode build(int[] nums, int left, int right) { 11 | if (left > right) { 12 | return null; 13 | } 14 | 15 | int mid = left + right >> 1; 16 | TreeNode node = new TreeNode(nums[mid]); 17 | node.left = build(nums, left, mid - 1); 18 | node.right = build(nums, mid + 1, right); 19 | 20 | return node; 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /src/leetcode/tree/preorder/Solution109.java: -------------------------------------------------------------------------------- 1 | package leetcode.tree.preorder; 2 | 3 | import leetcode.ListNode; 4 | import leetcode.TreeNode; 5 | 6 | import java.util.ArrayList; 7 | import java.util.List; 8 | 9 | public class Solution109 { 10 | public TreeNode sortedListToBST(ListNode head) { 11 | List nodes = new ArrayList<>(); 12 | while (head != null) { 13 | nodes.add(head); 14 | head = head.next; 15 | } 16 | 17 | return build(nodes, 0, nodes.size() - 1); 18 | } 19 | 20 | private TreeNode build(List nodes, int left, int right) { 21 | if (left > right) { 22 | return null; 23 | } 24 | 25 | int mid = left + right >> 1; 26 | TreeNode node = new TreeNode(nodes.get(mid).val); 27 | node.left = build(nodes, left, mid - 1); 28 | node.right = build(nodes, mid + 1, right); 29 | 30 | return node; 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /src/leetcode/tree/preorder/Solution113.java: -------------------------------------------------------------------------------- 1 | package leetcode.tree.preorder; 2 | 3 | import leetcode.TreeNode; 4 | 5 | import java.util.ArrayList; 6 | import java.util.LinkedList; 7 | import java.util.List; 8 | 9 | public class Solution113 { 10 | 11 | List> res = new ArrayList<>(); 12 | 13 | public List> pathSum(TreeNode root, int targetSum) { 14 | preOrder(root, new LinkedList<>(), targetSum); 15 | return res; 16 | } 17 | 18 | private void preOrder(TreeNode node, LinkedList element, int sum) { 19 | if (node == null) { 20 | return; 21 | } 22 | 23 | sum -= node.val; 24 | element.addLast(node.val); 25 | if (sum == 0 && node.left == null && node.right == null) { 26 | res.add((List) element.clone()); 27 | } 28 | preOrder(node.left, element, sum); 29 | preOrder(node.right, element, sum); 30 | 31 | element.removeLast(); 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /src/leetcode/tree/preorder/Solution144.java: -------------------------------------------------------------------------------- 1 | package leetcode.tree.preorder; 2 | 3 | import leetcode.TreeNode; 4 | 5 | import java.util.ArrayList; 6 | import java.util.List; 7 | 8 | public class Solution144 { 9 | 10 | List res; 11 | 12 | public List preorderTraversal(TreeNode root) { 13 | res = new ArrayList<>(); 14 | preorder(root); 15 | 16 | return res; 17 | } 18 | 19 | private void preorder(TreeNode root) { 20 | if (root == null) { 21 | return; 22 | } 23 | 24 | res.add(root.val); 25 | preorder(root.left); 26 | preorder(root.right); 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /src/leetcode/tree/preorder/Solution144Iteration.java: -------------------------------------------------------------------------------- 1 | package leetcode.tree.preorder; 2 | 3 | import leetcode.TreeNode; 4 | 5 | import java.util.ArrayList; 6 | import java.util.List; 7 | import java.util.Stack; 8 | 9 | public class Solution144Iteration { 10 | 11 | public List preorderTraversal(TreeNode root) { 12 | List res = new ArrayList<>(); 13 | 14 | Stack stack = new Stack<>(); 15 | if (root != null) { 16 | stack.push(root); 17 | } 18 | while (!stack.isEmpty()) { 19 | TreeNode node = stack.pop(); 20 | res.add(node.val); 21 | if (node.right != null) { 22 | stack.push(node.right); 23 | } 24 | if (node.left != null) { 25 | stack.push(node.left); 26 | } 27 | } 28 | 29 | return res; 30 | } 31 | 32 | } 33 | -------------------------------------------------------------------------------- /src/leetcode/tree/preorder/Solution226.java: -------------------------------------------------------------------------------- 1 | package leetcode.tree.preorder; 2 | 3 | import leetcode.TreeNode; 4 | 5 | public class Solution226 { 6 | public TreeNode invertTree(TreeNode root) { 7 | if (root == null) { 8 | return null; 9 | } 10 | 11 | TreeNode temp = root.left; 12 | root.left = root.right; 13 | root.right = temp; 14 | invertTree(root.left); 15 | invertTree(root.right); 16 | 17 | return root; 18 | } 19 | 20 | } 21 | -------------------------------------------------------------------------------- /src/leetcode/tree/preorder/Solution617.java: -------------------------------------------------------------------------------- 1 | package leetcode.tree.preorder; 2 | 3 | import leetcode.TreeNode; 4 | 5 | public class Solution617 { 6 | public TreeNode mergeTrees(TreeNode root1, TreeNode root2) { 7 | if (root1 == null) { 8 | return root2; 9 | } 10 | if (root2 == null) { 11 | return root1; 12 | } 13 | 14 | TreeNode root = new TreeNode(root1.val + root2.val); 15 | root.left = mergeTrees(root1.left, root2.left); 16 | root.right = mergeTrees(root1.right, root2.right); 17 | 18 | return root; 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /src/leetcode/tree/preorder/Solution654.java: -------------------------------------------------------------------------------- 1 | package leetcode.tree.preorder; 2 | 3 | import leetcode.TreeNode; 4 | 5 | public class Solution654 { 6 | public TreeNode constructMaximumBinaryTree(int[] nums) { 7 | return doConstructMaximumBinaryTree(nums, 0, nums.length - 1); 8 | } 9 | 10 | private TreeNode doConstructMaximumBinaryTree(int[] nums, int left, int right) { 11 | if (left > right) { 12 | return null; 13 | } 14 | 15 | int max = left; 16 | for (int i = left; i <= right; i++) { 17 | if (nums[i] > nums[max]) { 18 | max = i; 19 | } 20 | } 21 | TreeNode node = new TreeNode(nums[max]); 22 | node.left = doConstructMaximumBinaryTree(nums, left, max - 1); 23 | node.right = doConstructMaximumBinaryTree(nums, max + 1, right); 24 | 25 | return node; 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /src/leetcode/tree/preorder/SolutionLCR143.java: -------------------------------------------------------------------------------- 1 | package leetcode.tree.preorder; 2 | 3 | import leetcode.TreeNode; 4 | 5 | public class SolutionLCR143 { 6 | public boolean isSubStructure(TreeNode A, TreeNode B) { 7 | if (A == null || B == null) { 8 | return false; 9 | } 10 | 11 | return doIsSubStructure(A, B) || isSubStructure(A.left, B) || isSubStructure(A.right, B); 12 | } 13 | 14 | private boolean doIsSubStructure(TreeNode A, TreeNode B) { 15 | if (B == null) { 16 | return true; 17 | } 18 | if (A == null || A.val != B.val) { 19 | return false; 20 | } 21 | 22 | return doIsSubStructure(A.left, B.left) && doIsSubStructure(A.right, B.right); 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /src/leetcode/tree/preorder/SolutionLCR152.java: -------------------------------------------------------------------------------- 1 | package leetcode.tree.preorder; 2 | 3 | public class SolutionLCR152 { 4 | public boolean verifyTreeOrder(int[] postorder) { 5 | return doVerifyTreeOrder(postorder, 0, postorder.length - 1); 6 | } 7 | 8 | private boolean doVerifyTreeOrder(int[] postOrder, int left, int root) { 9 | if (left >= root) { 10 | return true; 11 | } 12 | 13 | int right = left; 14 | while (right < postOrder.length && postOrder[right] < postOrder[root]) { 15 | right++; 16 | } 17 | int tempRight = right; 18 | while (tempRight < postOrder.length && postOrder[tempRight] > postOrder[root]) { 19 | tempRight++; 20 | } 21 | 22 | return tempRight == root && doVerifyTreeOrder(postOrder, left, right - 1) && doVerifyTreeOrder(postOrder, right, root - 1); 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /src/leetcode/utils/Matrix.java: -------------------------------------------------------------------------------- 1 | package leetcode.utils; 2 | 3 | import java.util.Arrays; 4 | 5 | public class Matrix { 6 | 7 | public static void main(String[] args) { 8 | System.out.println(Arrays.deepToString(Matrix.convert("[[1,2,2],[1,1,0],[0,1,0]]"))); 9 | } 10 | 11 | /** 12 | * 将字符串转换为 2 维数组 13 | * eg: [[1,2,2],[1,1,0],[0,1,0]] 14 | */ 15 | public static int[][] convert(String s) { 16 | String[] elements = s.substring(1, s.length() - 1).split("],"); 17 | int n = elements.length; 18 | int m = elements[0].split(",").length; 19 | int[][] twoDimensionalArray = new int[n][m]; 20 | for (int i = 0; i < n; i++) { 21 | // 去除方括号 22 | String row = elements[i].replace("[", "").replace("]", ""); 23 | // 按 "," 分割字符串 24 | String[] nums = row.split(","); 25 | for (int j = 0; j < m; j++) { 26 | twoDimensionalArray[i][j] = Integer.parseInt(nums[j]); 27 | } 28 | } 29 | return twoDimensionalArray; 30 | } 31 | } 32 | --------------------------------------------------------------------------------