{"problem_id": "algo_00001", "original_id": "two-sum", "title": "两数之和", "category": "array", "difficulty": "easy", "companies": ["Amazon", "Google"], "description": "给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那两个整数,并返回他们的数组下标。", "solution_python": "def twoSum(nums, target):\n hashmap = {}\n for i, num in enumerate(nums):\n complement = target - num\n if complement in hashmap:\n return [hashmap[complement], i]\n hashmap[num] = i\n return []", "solution_java": "public int[] twoSum(int[] nums, int target) {\n Map map = new HashMap<>();\n for (int i = 0; i < nums.length; i++) {\n int complement = target - nums[i];\n if (map.containsKey(complement)) return new int[]{map.get(complement), i};\n map.put(nums[i], i);\n }\n return new int[]{};\n}", "solution_cpp": "vector twoSum(vector& nums, int target) {\n unordered_map m;\n for (int i = 0; i < nums.size(); i++) {\n if (m.count(target - nums[i])) return {m[target - nums[i]], i};\n m[nums[i]] = i;\n }\n return {};\n}", "test_cases": ["nums=[2,7,11,15], target=9 -> [0,1]", "nums=[3,2,4], target=6 -> [1,2]"], "key_points": ["哈希表一次遍历", "空间换时间"], "tags": ["array", "easy", "Amazon", "Google"]} {"problem_id": "algo_00002", "original_id": "merge-sorted", "title": "合并两个有序数组", "category": "array", "difficulty": "easy", "companies": ["Microsoft", "Uber"], "description": "给你两个按非递减顺序排列的整数数组 nums1 和 nums2,另有两个整数 m 和 n,分别表示 nums1 和 nums2 中的元素数目。请你合并 nums2 到 nums1 中。", "solution_python": "def merge(nums1, m, nums2, n):\n p1, p2, p = m-1, n-1, m+n-1\n while p1 >= 0 and p2 >= 0:\n if nums1[p1] > nums2[p2]: nums1[p] = nums1[p1]; p1 -= 1\n else: nums1[p] = nums2[p2]; p2 -= 1\n p -= 1\n while p2 >= 0: nums1[p] = nums2[p2]; p2 -= 1; p -= 1", "solution_java": "public void merge(int[] nums1, int m, int[] nums2, int n) {\n int p1 = m-1, p2 = n-1, p = m+n-1;\n while (p1 >= 0 && p2 >= 0) {\n nums1[p--] = nums1[p1] > nums2[p2] ? nums1[p1--] : nums2[p2--];\n }\n while (p2 >= 0) nums1[p--] = nums2[p2--];\n}", "solution_cpp": "void merge(vector& nums1, int m, vector& nums2, int n) {\n int p1 = m-1, p2 = n-1, p = m+n-1;\n while (p1 >= 0 && p2 >= 0) nums1[p--] = nums1[p1] > nums2[p2] ? nums1[p1--] : nums2[p2--];\n while (p2 >= 0) nums1[p--] = nums2[p2--];\n}", "test_cases": ["nums1=[1,2,3], m=3, nums2=[2,5,6], n=3 -> [1,2,2,3,5,6]", "nums1=[], m=0, nums2=[1], n=1 -> [1]"], "key_points": ["从后往前合并", "三指针技巧"], "tags": ["array", "easy", "Microsoft", "Uber"]} {"problem_id": "algo_00003", "original_id": "max-subarray", "title": "最大子数组和", "category": "array", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "给你一个整数数组 nums ,请你找出一个具有最大和的连续子数组,返回其最大和。", "solution_python": "def maxSubArray(nums):\n max_sum = current = nums[0]\n for num in nums[1:]:\n current = max(num, current + num)\n max_sum = max(max_sum, current)\n return max_sum", "solution_java": "public int maxSubArray(int[] nums) {\n int maxSum = nums[0], curr = nums[0];\n for (int i = 1; i < nums.length; i++) {\n curr = Math.max(nums[i], curr + nums[i]);\n maxSum = Math.max(maxSum, curr);\n }\n return maxSum;\n}", "solution_cpp": "int maxSubArray(vector& nums) {\n int maxSum = nums[0], curr = nums[0];\n for (int i = 1; i < nums.size(); i++) {\n curr = max(nums[i], curr + nums[i]);\n maxSum = max(maxSum, curr);\n }\n return maxSum;\n}", "test_cases": ["nums=[-2,1,-3,4,-1,2,1,-5,4] -> 6", "nums=[1] -> 1"], "key_points": ["Kadane算法", "动态规划基础题"], "tags": ["array", "medium", "Google", "Microsoft"]} {"problem_id": "algo_00004", "original_id": "valid-parentheses", "title": "有效的括号", "category": "string", "difficulty": "easy", "companies": ["Google", "Uber"], "description": "给定一个只包括 '(',')','{','}','[',']' 的字符串 s,判断字符串是否有效。", "solution_python": "def isValid(s):\n stack = []\n mapping = {')': '(', ']': '[', '}': '{'}\n for c in s:\n if c in mapping:\n if not stack or stack[-1] != mapping[c]: return False\n stack.pop()\n else: stack.append(c)\n return not stack", "solution_java": "public boolean isValid(String s) {\n Stack stack = new Stack<>();\n Map map = Map.of(')', '(', ']', '[', '}', '{');\n for (char c : s.toCharArray()) {\n if (map.containsValue(c)) stack.push(c);\n else if (!stack.isEmpty() && stack.pop() != map.get(c)) return false;\n }\n return stack.isEmpty();\n}", "solution_cpp": "bool isValid(string s) {\n stack st;\n unordered_map m = {{')','('},{']','['},{'}','{'}};\n for (char c : s) {\n if (m.find(c) == m.end()) st.push(c);\n else if (st.empty() || st.top() != m[c]) return false;\n else st.pop();\n }\n return st.empty();\n}", "test_cases": ["s=\"()\" -> true", "s=\"()[]{}\" -> true", "s=\"(]\" -> false"], "key_points": ["栈匹配法", "注意空栈边界"], "tags": ["string", "easy", "Google", "Uber"]} {"problem_id": "algo_00005", "original_id": "longest-palindrome", "title": "最长回文子串", "category": "string", "difficulty": "medium", "companies": ["Google", "Amazon"], "description": "给你一个字符串 s,找到 s 中最长的回文子串。", "solution_python": "def longestPalindrome(s):\n def expand(l, r):\n while l >= 0 and r < len(s) and s[l] == s[r]: l -= 1; r += 1\n return l + 1, r - 1\n start = end = 0\n for i in range(len(s)):\n l1, r1 = expand(i, i)\n l2, r2 = expand(i, i + 1)\n if r1 - l1 > end - start: start, end = l1, r1\n if r2 - l2 > end - start: start, end = l2, r2\n return s[start:end+1]", "solution_java": "public String longestPalindrome(String s) {\n int start = 0, end = 0;\n for (int i = 0; i < s.length(); i++) {\n int len1 = expand(s, i, i), len2 = expand(s, i, i+1);\n int len = Math.max(len1, len2);\n if (len > end - start) { start = i - (len-1)/2; end = i + len/2; }\n }\n return s.substring(start, end + 1);\n}\nprivate int expand(String s, int l, int r) {\n while (l >= 0 && r < s.length() && s.charAt(l) == s.charAt(r)) { l--; r++; }\n return r - l - 1;\n}", "solution_cpp": "string longestPalindrome(string s) {\n int start = 0, end = 0;\n for (int i = 0; i < s.size(); i++) {\n int len1 = expand(s, i, i), len2 = expand(s, i, i+1);\n if (max(len1, len2) > end - start) { start = i - (max(len1,len2)-1)/2; end = i + max(len1,len2)/2; }\n }\n return s.substr(start, end - start + 1);\n}", "test_cases": ["s=\"babad\" -> bab或aba", "s=\"cbbd\" -> bb"], "key_points": ["中心扩展法", "处理奇偶长度"], "tags": ["string", "medium", "Google", "Amazon"]} {"problem_id": "algo_00006", "original_id": "reverse-list", "title": "反转链表", "category": "linkedlist", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "给你单链表的头节点 head,请你反转链表,并返回反转后的链表。", "solution_python": "def reverseList(head):\n prev = None\n curr = head\n while curr:\n nxt = curr.next\n curr.next = prev\n prev = curr\n curr = nxt\n return prev", "solution_java": "public ListNode reverseList(ListNode head) {\n ListNode prev = null, curr = head;\n while (curr != null) {\n ListNode next = curr.next;\n curr.next = prev;\n prev = curr;\n curr = next;\n }\n return prev;\n}", "solution_cpp": "ListNode* reverseList(ListNode* head) {\n ListNode* prev = nullptr, *curr = head;\n while (curr) {\n ListNode* next = curr->next;\n curr->next = prev;\n prev = curr;\n curr = next;\n }\n return prev;\n}", "test_cases": ["head=[1,2,3,4,5] -> [5,4,3,2,1]", "head=[1,2] -> [2,1]"], "key_points": ["迭代法 O(1)空间", "递归法 O(n)空间"], "tags": ["linkedlist", "medium", "Google", "Microsoft"]} {"problem_id": "algo_00007", "original_id": "middle-node", "title": "链表的中间结点", "category": "linkedlist", "difficulty": "easy", "companies": ["Amazon", "Facebook"], "description": "给你单链表的头节点 head,请你找出并返回链表的中间结点。如果有两个中间结点,则返回第二个中间结点。", "solution_python": "def middleNode(head):\n slow = fast = head\n while fast and fast.next:\n slow = slow.next\n fast = fast.next.next\n return slow", "solution_java": "public ListNode middleNode(ListNode head) {\n ListNode slow = head, fast = head;\n while (fast != null && fast.next != null) {\n slow = slow.next;\n fast = fast.next.next;\n }\n return slow;\n}", "solution_cpp": "ListNode* middleNode(ListNode* head) {\n ListNode* slow = head, *fast = head;\n while (fast && fast->next) { slow = slow->next; fast = fast->next->next; }\n return slow;\n}", "test_cases": ["head=[1,2,3,4,5] -> 3", "head=[1,2,3,4,5,6] -> 4"], "key_points": ["快慢指针", "O(n)时间O(1)空间"], "tags": ["linkedlist", "easy", "Amazon", "Facebook"]} {"problem_id": "algo_00008", "original_id": "max-depth", "title": "二叉树的最大深度", "category": "tree", "difficulty": "easy", "companies": ["Microsoft", "Apple"], "description": "给定一个二叉树 root,返回其最大深度。", "solution_python": "def maxDepth(root):\n if not root: return 0\n return max(maxDepth(root.left), maxDepth(root.right)) + 1", "solution_java": "public int maxDepth(TreeNode root) {\n if (root == null) return 0;\n return Math.max(maxDepth(root.left), maxDepth(root.right)) + 1;\n}", "solution_cpp": "int maxDepth(TreeNode* root) {\n if (!root) return 0;\n return max(maxDepth(root->left), maxDepth(root->right)) + 1;\n}", "test_cases": ["root=[3,9,20,null,null,15,7] -> 3", "root=[1,null,2] -> 2"], "key_points": ["DFS递归", "层序遍历也可"], "tags": ["tree", "easy", "Microsoft", "Apple"]} {"problem_id": "algo_00009", "original_id": "inorder-traversal", "title": "二叉树的中序遍历", "category": "tree", "difficulty": "easy", "companies": ["Google", "Microsoft"], "description": "给定一个二叉树的根节点 root,返回它的中序遍历结果。", "solution_python": "def inorderTraversal(root):\n result = []\n def dfs(node):\n if node:\n dfs(node.left)\n result.append(node.val)\n dfs(node.right)\n dfs(root)\n return result", "solution_java": "public List inorderTraversal(TreeNode root) {\n List res = new ArrayList<>();\n dfs(root, res);\n return res;\n}\nprivate void dfs(TreeNode node, List res) {\n if (node == null) return;\n dfs(node.left, res); res.add(node.val); dfs(node.right, res);\n}", "solution_cpp": "vector inorderTraversal(TreeNode* root) {\n vector res;\n dfs(root, res);\n return res;\n}\nvoid dfs(TreeNode* node, vector& res) {\n if (!node) return;\n dfs(node->left, res); res.push_back(node->val); dfs(node->right, res);\n}", "test_cases": ["root=[1,null,2,3] -> [1,3,2]", "root=[] -> []"], "key_points": ["左-根-右顺序", "递归最简洁"], "tags": ["tree", "easy", "Google", "Microsoft"]} {"problem_id": "algo_00010", "original_id": "binary-search", "title": "二分查找", "category": "binarysearch", "difficulty": "easy", "companies": ["Google", "Amazon"], "description": "给定一个 n 个元素有序的(升序)整型数组 nums 和一个目标值 target,写一个函数搜索 nums 中的 target,如果目标值存在返回下标,否则返回 -1。", "solution_python": "def search(nums, target):\n left, right = 0, len(nums) - 1\n while left <= right:\n mid = (left + right) // 2\n if nums[mid] == target: return mid\n elif nums[mid] < target: left = mid + 1\n else: right = mid - 1\n return -1", "solution_java": "public int search(int[] nums, int target) {\n int left = 0, right = nums.length - 1;\n while (left <= right) {\n int mid = left + (right - left) / 2;\n if (nums[mid] == target) return mid;\n else if (nums[mid] < target) left = mid + 1;\n else right = mid - 1;\n }\n return -1;\n}", "solution_cpp": "int search(vector& nums, int target) {\n int left = 0, right = nums.size() - 1;\n while (left <= right) {\n int mid = left + (right - left) / 2;\n if (nums[mid] == target) return mid;\n else if (nums[mid] < target) left = mid + 1;\n else right = mid - 1;\n }\n return -1;\n}", "test_cases": ["nums=[-1,0,3,5,9,12], target=9 -> 4", "nums=[-1,0,3,5,9,12], target=2 -> -1"], "key_points": ["标准模板", "注意防溢出写法"], "tags": ["binarysearch", "easy", "Google", "Amazon"]} {"problem_id": "algo_00011", "original_id": "climbing-stairs", "title": "爬楼梯", "category": "dp", "difficulty": "easy", "companies": ["Amazon", "Google"], "description": "假设你正在爬楼梯。需要 n 阶你才能到达楼顶。每次你可以爬 1 或 2 个台阶。你有多少种不同的方法可以爬到楼顶?", "solution_python": "def climbStairs(n):\n if n <= 2: return n\n a, b = 1, 2\n for _ in range(3, n+1):\n a, b = b, a + b\n return b", "solution_java": "public int climbStairs(int n) {\n if (n <= 2) return n;\n int a = 1, b = 2;\n for (int i = 3; i <= n; i++) { int temp = a + b; a = b; b = temp; }\n return b;\n}", "solution_cpp": "int climbStairs(int n) {\n if (n <= 2) return n;\n int a = 1, b = 2;\n for (int i = 3; i <= n; i++) { int temp = a + b; a = b; b = temp; }\n return b;\n}", "test_cases": ["n=2 -> 2", "n=3 -> 3", "n=5 -> 8"], "key_points": ["斐波那契数列", "滚动数组优化空间"], "tags": ["dp", "easy", "Amazon", "Google"]} {"problem_id": "algo_00012", "original_id": "coin-change", "title": "零钱兑换", "category": "dp", "difficulty": "medium", "companies": ["Google", "Amazon"], "description": "给你一个整数数组 coins 表示不同面额的硬币,以及一个整数 amount 表示总金额。计算并返回可以凑成总金额所需的最少的硬币个数。如果没有任何一种硬币组合能组成总金额,返回 -1。", "solution_python": "def coinChange(coins, amount):\n dp = [float('inf')] * (amount + 1)\n dp[0] = 0\n for coin in coins:\n for x in range(coin, amount + 1):\n dp[x] = min(dp[x], dp[x - coin] + 1)\n return dp[amount] if dp[amount] != float('inf') else -1", "solution_java": "public int coinChange(int[] coins, int amount) {\n int[] dp = new int[amount + 1];\n Arrays.fill(dp, amount + 1);\n dp[0] = 0;\n for (int coin : coins) {\n for (int x = coin; x <= amount; x++) {\n dp[x] = Math.min(dp[x], dp[x - coin] + 1);\n }\n }\n return dp[amount] > amount ? -1 : dp[amount];\n}", "solution_cpp": "int coinChange(vector& coins, int amount) {\n vector dp(amount + 1, amount + 1);\n dp[0] = 0;\n for (int coin : coins) {\n for (int x = coin; x <= amount; x++) {\n dp[x] = min(dp[x], dp[x - coin] + 1);\n }\n }\n return dp[amount] > amount ? -1 : dp[amount];\n}", "test_cases": ["coins=[1,2,5], amount=11 -> 3", "coins=[2], amount=3 -> -1"], "key_points": ["完全背包问题", "dp[x] = min(dp[x-coin]+1)"], "tags": ["dp", "medium", "Google", "Amazon"]} {"problem_id": "algo_00013", "original_id": "subsets", "title": "子集", "category": "backtracking", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "给你一个整数数组 nums ,数组中的元素 互不相同 。返回该数组所有可能的子集(幂集)。", "solution_python": "def subsets(nums):\n result = []\n def backtrack(start, path):\n result.append(path[:])\n for i in range(start, len(nums)):\n path.append(nums[i])\n backtrack(i + 1, path)\n path.pop()\n backtrack(0, [])\n return result", "solution_java": "public List> subsets(int[] nums) {\n List> result = new ArrayList<>();\n backtrack(nums, 0, new ArrayList<>(), result);\n return result;\n}\nprivate void backtrack(int[] nums, int start, List path, List> result) {\n result.add(new ArrayList<>(path));\n for (int i = start; i < nums.length; i++) {\n path.add(nums[i]);\n backtrack(nums, i + 1, path, result);\n path.remove(path.size() - 1);\n }\n}", "solution_cpp": "vector> subsets(vector& nums) {\n vector> result;\n vector path;\n backtrack(nums, 0, path, result);\n return result;\n}\nvoid backtrack(vector& nums, int start, vector& path, vector>& result) {\n result.push_back(path);\n for (int i = start; i < nums.size(); i++) {\n path.push_back(nums[i]);\n backtrack(nums, i + 1, path, result);\n path.pop_back();\n }\n}", "test_cases": ["nums=[1,2,3] -> [[],[1],[2],[1,2],[3],[1,3],[2,3],[1,2,3]]"], "key_points": ["选或不选", "DFS遍历子集树"], "tags": ["backtracking", "medium", "Google", "Microsoft"]} {"problem_id": "algo_00014", "original_id": "permutations", "title": "全排列", "category": "backtracking", "difficulty": "medium", "companies": ["Google", "Facebook"], "description": "给定一个不含重复数字的数组 nums,返回其所有可能的全排列。", "solution_python": "def permute(nums):\n result = []\n def backtrack(path, used):\n if len(path) == len(nums):\n result.append(path[:])\n return\n for i in range(len(nums)):\n if used[i]: continue\n used[i] = True\n path.append(nums[i])\n backtrack(path, used)\n path.pop()\n used[i] = False\n backtrack([], [False]*len(nums))\n return result", "solution_java": "public List> permute(int[] nums) {\n List> result = new ArrayList<>();\n boolean[] used = new boolean[nums.length];\n backtrack(nums, used, new ArrayList<>(), result);\n return result;\n}\nprivate void backtrack(int[] nums, boolean[] used, List path, List> result) {\n if (path.size() == nums.length) { result.add(new ArrayList<>(path)); return; }\n for (int i = 0; i < nums.length; i++) {\n if (used[i]) continue;\n used[i] = true;\n path.add(nums[i]);\n backtrack(nums, used, path, result);\n path.remove(path.size() - 1);\n used[i] = false;\n }\n}", "solution_cpp": "vector> permute(vector& nums) {\n vector> result;\n vector used(nums.size(), false);\n vector path;\n backtrack(nums, used, path, result);\n return result;\n}\nvoid backtrack(vector& nums, vector& used, vector& path, vector>& result) {\n if (path.size() == nums.size()) { result.push_back(path); return; }\n for (int i = 0; i < nums.size(); i++) {\n if (used[i]) continue;\n used[i] = true;\n path.push_back(nums[i]);\n backtrack(nums, used, path, result);\n path.pop_back();\n used[i] = false;\n }\n}", "test_cases": ["nums=[1,2,3] -> [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]"], "key_points": ["标记已使用元素", "回溯经典模板"], "tags": ["backtracking", "medium", "Google", "Facebook"]} {"problem_id": "algo_00015", "original_id": "top-k-frequent", "title": "前K个高频元素", "category": "heap", "difficulty": "medium", "companies": ["Amazon", "Facebook"], "description": "给你一个整数数组 nums 和一个整数 k,请你返回其中出现频率前 k 高的元素。", "solution_python": "import heapq\nfrom collections import Counter\ndef topKFrequent(nums, k):\n count = Counter(nums)\n heap = []\n for num, freq in count.items():\n heapq.heappush(heap, (freq, num))\n if len(heap) > k: heapq.heappop(heap)\n return [num for freq, num in heap]", "solution_java": "public int[] topKFrequent(int[] nums, int k) {\n Map count = new HashMap<>();\n for (int n : nums) count.put(n, count.getOrDefault(n, 0) + 1);\n PriorityQueue> heap = \n new PriorityQueue<>((a, b) -> a.getValue() - b.getValue());\n for (Map.Entry e : count.entrySet()) {\n heap.offer(e);\n if (heap.size() > k) heap.poll();\n }\n int[] res = new int[k];\n for (int i = k - 1; i >= 0; i--) res[i] = heap.poll().getKey();\n return res;\n}", "solution_cpp": "vector topKFrequent(vector& nums, int k) {\n unordered_map count;\n for (int n : nums) count[n]++;\n priority_queue, vector>, greater>> heap;\n for (auto& [num, freq] : count) {\n heap.push({freq, num});\n if (heap.size() > k) heap.pop();\n }\n vector res;\n while (!heap.empty()) { res.push_back(heap.top().second); heap.pop(); }\n reverse(res.begin(), res.end());\n return res;\n}", "test_cases": ["nums=[1,1,1,2,2,3], k=2 -> [1,2]", "nums=[1], k=1 -> [1]"], "key_points": ["小顶堆保持大小k", "时间复杂度O(nlogk)"], "tags": ["heap", "medium", "Amazon", "Facebook"]} {"problem_id": "algo_00016", "original_id": "3sum", "title": "三数之和", "category": "two-pointers", "difficulty": "medium", "companies": ["Google", "Amazon"], "description": "给你一个整数数组 nums,判断是否存在三元组满足和为0,返回所有不重复的三元组。", "solution_python": "def threeSum(nums):\n nums.sort()\n result = []\n for i in range(len(nums) - 2):\n if i > 0 and nums[i] == nums[i-1]: continue\n left, right = i + 1, len(nums) - 1\n while left < right:\n total = nums[i] + nums[left] + nums[right]\n if total < 0: left += 1\n elif total > 0: right -= 1\n else:\n result.append([nums[i], nums[left], nums[right]])\n while left < right and nums[left] == nums[left+1]: left += 1\n while left < right and nums[right] == nums[right-1]: right -= 1\n left += 1; right -= 1\n return result", "solution_java": "public List> threeSum(int[] nums) {\n Arrays.sort(nums);\n List> result = new ArrayList<>();\n for (int i = 0; i < nums.length - 2; i++) {\n if (i > 0 && nums[i] == nums[i-1]) continue;\n int left = i + 1, right = nums.length - 1;\n while (left < right) {\n int total = nums[i] + nums[left] + nums[right];\n if (total < 0) left++;\n else if (total > 0) right--;\n else {\n result.add(Arrays.asList(nums[i], nums[left], nums[right]));\n while (left < right && nums[left] == nums[left+1]) left++;\n while (left < right && nums[right] == nums[right-1]) right--;\n left++; right--;\n }\n }\n }\n return result;\n}", "solution_cpp": "vector> threeSum(vector& nums) {\n sort(nums.begin(), nums.end());\n vector> result;\n for (int i = 0; i < nums.size() - 2; i++) {\n if (i > 0 && nums[i] == nums[i-1]) continue;\n int left = i + 1, right = nums.size() - 1;\n while (left < right) {\n int total = nums[i] + nums[left] + nums[right];\n if (total < 0) left++;\n else if (total > 0) right--;\n else {\n result.push_back({nums[i], nums[left], nums[right]});\n while (left < right && nums[left] == nums[left+1]) left++;\n while (left < right && nums[right] == nums[right-1]) right--;\n left++; right--;\n }\n }\n }\n return result;\n}", "test_cases": ["nums=[-1,0,1,2,-1,-4] -> [[-1,-1,2],[-1,0,1]]"], "key_points": ["排序+双指针", "去重是关键"], "tags": ["two-pointers", "medium", "Google", "Amazon"]} {"problem_id": "algo_00017", "original_id": "container-water", "title": "盛最多水的容器", "category": "two-pointers", "difficulty": "medium", "companies": ["Google", "Uber"], "description": "给定一个长度为 n 的整数数组 height,找出其中的两条线,使得它们与 x 轴共同构成的容器可以容纳最多的水。", "solution_python": "def maxArea(height):\n left, right = 0, len(height) - 1\n max_area = 0\n while left < right:\n h = min(height[left], height[right])\n max_area = max(max_area, h * (right - left))\n if height[left] < height[right]: left += 1\n else: right -= 1\n return max_area", "solution_java": "public int maxArea(int[] height) {\n int left = 0, right = height.length - 1, maxArea = 0;\n while (left < right) {\n int h = Math.min(height[left], height[right]);\n maxArea = Math.max(maxArea, h * (right - left));\n if (height[left] < height[right]) left++;\n else right--;\n }\n return maxArea;\n}", "solution_cpp": "int maxArea(vector& height) {\n int left = 0, right = height.size() - 1, maxArea = 0;\n while (left < right) {\n int h = min(height[left], height[right]);\n maxArea = max(maxArea, h * (right - left));\n if (height[left] < height[right]) left++;\n else right--;\n }\n return maxArea;\n}", "test_cases": ["height=[1,8,6,2,5,4,8,3,7] -> 49"], "key_points": ["移动短边指针", "面积=min(h1,h2)*width"], "tags": ["two-pointers", "medium", "Google", "Uber"]} {"problem_id": "algo_00018", "original_id": "min-stack", "title": "最小栈", "category": "stack", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "设计一个支持 push,pop,top 操作,并能在常数时间内检索到最小元素的栈。", "solution_python": "class MinStack:\n def __init__(self):\n self.stack = []\n self.min_stack = []\n def push(self, val):\n self.stack.append(val)\n self.min_stack.append(min(val, self.min_stack[-1] if self.min_stack else val))\n def pop(self):\n self.stack.pop(); self.min_stack.pop()\n def top(self): return self.stack[-1]\n def getMin(self): return self.min_stack[-1]", "solution_java": "class MinStack {\n Stack stack = new Stack<>();\n Stack minStack = new Stack<>();\n public void push(int val) { stack.push(val); minStack.push(Math.min(val, minStack.isEmpty() ? val : minStack.peek())); }\n public void pop() { stack.pop(); minStack.pop(); }\n public int top() { return stack.peek(); }\n public int getMin() { return minStack.peek(); }\n}", "solution_cpp": "class MinStack {\n stack st, minSt;\npublic:\n void push(int val) { st.push(val); minSt.push(min(val, minSt.empty() ? val : minSt.top())); }\n void pop() { st.pop(); minSt.pop(); }\n int top() { return st.top(); }\n int getMin() { return minSt.top(); }\n};", "test_cases": ["push(-2), push(0), push(-3) -> getMin() returns -3"], "key_points": ["辅助栈记录最小值", "O(1)时间获取最小值"], "tags": ["stack", "medium", "Google", "Microsoft"]} {"problem_id": "algo_00019", "original_id": "lru-cache", "title": "LRU缓存", "category": "design", "difficulty": "hard", "companies": ["Google", "Amazon"], "description": "设计和实现一个 LRU(最近最少使用)缓存机制。", "solution_python": "class LRUCache:\n def __init__(self, capacity):\n self.capacity = capacity\n self.cache = {}\n self.order = []\n def get(self, key):\n if key not in self.cache: return -1\n self.order.remove(key); self.order.append(key)\n return self.cache[key]\n def put(self, key, value):\n if key in self.cache:\n self.order.remove(key)\n elif len(self.cache) >= self.capacity:\n del self.cache[self.order.pop(0)]\n self.cache[key] = value; self.order.append(key)", "solution_java": "class LRUCache {\n int capacity;\n LinkedHashMap cache = new LinkedHashMap<>();\n public LRUCache(int cap) { capacity = cap; }\n public int get(int key) { return cache.containsKey(key) ? cache.remove(key) : -1; }\n public void put(int key, int val) {\n if (cache.containsKey(key)) cache.remove(key);\n else if (cache.size() >= capacity) cache.remove(cache.keySet().iterator().next());\n cache.put(key, val);\n }\n}", "solution_cpp": "class LRUCache {\n int cap;\n list> dll;\n unordered_map>::iterator> cache;\npublic:\n LRUCache(int capacity) : cap(capacity) {}\n int get(int key) {\n auto it = cache.find(key);\n if (it == cache.end()) return -1;\n dll.splice(dll.end(), dll, it->second);\n return it->second->second;\n }\n void put(int key, int value) {\n auto it = cache.find(key);\n if (it != cache.end()) dll.erase(it->second);\n else if (cache.size() >= cap) { cache.erase(dll.front().first); dll.pop_front(); }\n dll.push_back({key, value});\n cache[key] = --dll.end();\n }\n};", "test_cases": ["put(1,1), put(2,2), get(1) -> 1"], "key_points": ["HashMap + 双向链表", "O(1)时间操作"], "tags": ["design", "hard", "Google", "Amazon"]} {"problem_id": "algo_00020", "original_id": "num-islands", "title": "岛屿数量", "category": "graph", "difficulty": "medium", "companies": ["Google", "Facebook"], "description": "给你一个由 '1'(陆地)和 '0'(水)组成的二维网格,请你计算网格中岛屿的数量。岛屿总是被水包围,且只能由水平或垂直方向相邻的陆地连接形成。", "solution_python": "def numIslands(grid):\n if not grid: return 0\n rows, cols = len(grid), len(grid[0])\n count = 0\n def dfs(r, c):\n if r < 0 or r >= rows or c < 0 or c >= cols or grid[r][c] != '1': return\n grid[r][c] = '0'\n dfs(r+1, c); dfs(r-1, c); dfs(r, c+1); dfs(r, c-1)\n for r in range(rows):\n for c in range(cols):\n if grid[r][c] == '1': count += 1; dfs(r, c)\n return count", "solution_java": "public int numIslands(char[][] grid) {\n if (grid.length == 0) return 0;\n int count = 0;\n for (int i = 0; i < grid.length; i++)\n for (int j = 0; j < grid[0].length; j++)\n if (grid[i][j] == '1') { count++; dfs(grid, i, j); }\n return count;\n}\nprivate void dfs(char[][] grid, int r, int c) {\n if (r < 0 || r >= grid.length || c < 0 || c >= grid[0].length || grid[r][c] != '1') return;\n grid[r][c] = '0';\n dfs(grid, r+1, c); dfs(grid, r-1, c); dfs(grid, r, c+1); dfs(grid, r, c-1);\n}", "solution_cpp": "int numIslands(vector>& grid) {\n if (grid.empty()) return 0;\n int count = 0;\n for (int i = 0; i < grid.size(); i++)\n for (int j = 0; j < grid[0].size(); j++)\n if (grid[i][j] == '1') { count++; dfs(grid, i, j); }\n return count;\n}\nvoid dfs(vector>& grid, int r, int c) {\n if (r < 0 || r >= grid.size() || c < 0 || c >= grid[0].size() || grid[r][c] != '1') return;\n grid[r][c] = '0';\n dfs(grid, r+1, c); dfs(grid, r-1, c); dfs(grid, r, c+1); dfs(grid, r, c-1);\n}", "test_cases": ["grid=[[1,1,1,1,0],[1,1,0,1,0],[1,1,0,0,0],[0,0,0,0,0]] -> 1"], "key_points": ["DFS/BFS遍历", "访问后标记为0避免重复"], "tags": ["graph", "medium", "Google", "Facebook"]} {"problem_id": "algo_00021", "original_id": "two-sum", "title": "两数之和", "category": "array", "difficulty": "easy", "companies": ["Amazon", "Google"], "description": "给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那两个整数,并返回他们的数组下标。", "solution_python": "def twoSum(nums, target):\n hashmap = {}\n for i, num in enumerate(nums):\n complement = target - num\n if complement in hashmap:\n return [hashmap[complement], i]\n hashmap[num] = i\n return []", "solution_java": "public int[] twoSum(int[] nums, int target) {\n Map map = new HashMap<>();\n for (int i = 0; i < nums.length; i++) {\n int complement = target - nums[i];\n if (map.containsKey(complement)) return new int[]{map.get(complement), i};\n map.put(nums[i], i);\n }\n return new int[]{};\n}", "solution_cpp": "vector twoSum(vector& nums, int target) {\n unordered_map m;\n for (int i = 0; i < nums.size(); i++) {\n if (m.count(target - nums[i])) return {m[target - nums[i]], i};\n m[nums[i]] = i;\n }\n return {};\n}", "test_cases": ["nums=[2,7,11,15], target=9 -> [0,1]", "nums=[3,2,4], target=6 -> [1,2]"], "key_points": ["哈希表一次遍历", "空间换时间"], "tags": ["array", "easy", "Amazon", "Google"]} {"problem_id": "algo_00022", "original_id": "merge-sorted", "title": "合并两个有序数组", "category": "array", "difficulty": "easy", "companies": ["Microsoft", "Uber"], "description": "给你两个按非递减顺序排列的整数数组 nums1 和 nums2,另有两个整数 m 和 n,分别表示 nums1 和 nums2 中的元素数目。请你合并 nums2 到 nums1 中。", "solution_python": "def merge(nums1, m, nums2, n):\n p1, p2, p = m-1, n-1, m+n-1\n while p1 >= 0 and p2 >= 0:\n if nums1[p1] > nums2[p2]: nums1[p] = nums1[p1]; p1 -= 1\n else: nums1[p] = nums2[p2]; p2 -= 1\n p -= 1\n while p2 >= 0: nums1[p] = nums2[p2]; p2 -= 1; p -= 1", "solution_java": "public void merge(int[] nums1, int m, int[] nums2, int n) {\n int p1 = m-1, p2 = n-1, p = m+n-1;\n while (p1 >= 0 && p2 >= 0) {\n nums1[p--] = nums1[p1] > nums2[p2] ? nums1[p1--] : nums2[p2--];\n }\n while (p2 >= 0) nums1[p--] = nums2[p2--];\n}", "solution_cpp": "void merge(vector& nums1, int m, vector& nums2, int n) {\n int p1 = m-1, p2 = n-1, p = m+n-1;\n while (p1 >= 0 && p2 >= 0) nums1[p--] = nums1[p1] > nums2[p2] ? nums1[p1--] : nums2[p2--];\n while (p2 >= 0) nums1[p--] = nums2[p2--];\n}", "test_cases": ["nums1=[1,2,3], m=3, nums2=[2,5,6], n=3 -> [1,2,2,3,5,6]", "nums1=[], m=0, nums2=[1], n=1 -> [1]"], "key_points": ["从后往前合并", "三指针技巧"], "tags": ["array", "easy", "Microsoft", "Uber"]} {"problem_id": "algo_00023", "original_id": "max-subarray", "title": "最大子数组和", "category": "array", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "给你一个整数数组 nums ,请你找出一个具有最大和的连续子数组,返回其最大和。", "solution_python": "def maxSubArray(nums):\n max_sum = current = nums[0]\n for num in nums[1:]:\n current = max(num, current + num)\n max_sum = max(max_sum, current)\n return max_sum", "solution_java": "public int maxSubArray(int[] nums) {\n int maxSum = nums[0], curr = nums[0];\n for (int i = 1; i < nums.length; i++) {\n curr = Math.max(nums[i], curr + nums[i]);\n maxSum = Math.max(maxSum, curr);\n }\n return maxSum;\n}", "solution_cpp": "int maxSubArray(vector& nums) {\n int maxSum = nums[0], curr = nums[0];\n for (int i = 1; i < nums.size(); i++) {\n curr = max(nums[i], curr + nums[i]);\n maxSum = max(maxSum, curr);\n }\n return maxSum;\n}", "test_cases": ["nums=[-2,1,-3,4,-1,2,1,-5,4] -> 6", "nums=[1] -> 1"], "key_points": ["Kadane算法", "动态规划基础题"], "tags": ["array", "medium", "Google", "Microsoft"]} {"problem_id": "algo_00024", "original_id": "valid-parentheses", "title": "有效的括号", "category": "string", "difficulty": "easy", "companies": ["Google", "Uber"], "description": "给定一个只包括 '(',')','{','}','[',']' 的字符串 s,判断字符串是否有效。", "solution_python": "def isValid(s):\n stack = []\n mapping = {')': '(', ']': '[', '}': '{'}\n for c in s:\n if c in mapping:\n if not stack or stack[-1] != mapping[c]: return False\n stack.pop()\n else: stack.append(c)\n return not stack", "solution_java": "public boolean isValid(String s) {\n Stack stack = new Stack<>();\n Map map = Map.of(')', '(', ']', '[', '}', '{');\n for (char c : s.toCharArray()) {\n if (map.containsValue(c)) stack.push(c);\n else if (!stack.isEmpty() && stack.pop() != map.get(c)) return false;\n }\n return stack.isEmpty();\n}", "solution_cpp": "bool isValid(string s) {\n stack st;\n unordered_map m = {{')','('},{']','['},{'}','{'}};\n for (char c : s) {\n if (m.find(c) == m.end()) st.push(c);\n else if (st.empty() || st.top() != m[c]) return false;\n else st.pop();\n }\n return st.empty();\n}", "test_cases": ["s=\"()\" -> true", "s=\"()[]{}\" -> true", "s=\"(]\" -> false"], "key_points": ["栈匹配法", "注意空栈边界"], "tags": ["string", "easy", "Google", "Uber"]} {"problem_id": "algo_00025", "original_id": "longest-palindrome", "title": "最长回文子串", "category": "string", "difficulty": "medium", "companies": ["Google", "Amazon"], "description": "给你一个字符串 s,找到 s 中最长的回文子串。", "solution_python": "def longestPalindrome(s):\n def expand(l, r):\n while l >= 0 and r < len(s) and s[l] == s[r]: l -= 1; r += 1\n return l + 1, r - 1\n start = end = 0\n for i in range(len(s)):\n l1, r1 = expand(i, i)\n l2, r2 = expand(i, i + 1)\n if r1 - l1 > end - start: start, end = l1, r1\n if r2 - l2 > end - start: start, end = l2, r2\n return s[start:end+1]", "solution_java": "public String longestPalindrome(String s) {\n int start = 0, end = 0;\n for (int i = 0; i < s.length(); i++) {\n int len1 = expand(s, i, i), len2 = expand(s, i, i+1);\n int len = Math.max(len1, len2);\n if (len > end - start) { start = i - (len-1)/2; end = i + len/2; }\n }\n return s.substring(start, end + 1);\n}\nprivate int expand(String s, int l, int r) {\n while (l >= 0 && r < s.length() && s.charAt(l) == s.charAt(r)) { l--; r++; }\n return r - l - 1;\n}", "solution_cpp": "string longestPalindrome(string s) {\n int start = 0, end = 0;\n for (int i = 0; i < s.size(); i++) {\n int len1 = expand(s, i, i), len2 = expand(s, i, i+1);\n if (max(len1, len2) > end - start) { start = i - (max(len1,len2)-1)/2; end = i + max(len1,len2)/2; }\n }\n return s.substr(start, end - start + 1);\n}", "test_cases": ["s=\"babad\" -> bab或aba", "s=\"cbbd\" -> bb"], "key_points": ["中心扩展法", "处理奇偶长度"], "tags": ["string", "medium", "Google", "Amazon"]} {"problem_id": "algo_00026", "original_id": "reverse-list", "title": "反转链表", "category": "linkedlist", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "给你单链表的头节点 head,请你反转链表,并返回反转后的链表。", "solution_python": "def reverseList(head):\n prev = None\n curr = head\n while curr:\n nxt = curr.next\n curr.next = prev\n prev = curr\n curr = nxt\n return prev", "solution_java": "public ListNode reverseList(ListNode head) {\n ListNode prev = null, curr = head;\n while (curr != null) {\n ListNode next = curr.next;\n curr.next = prev;\n prev = curr;\n curr = next;\n }\n return prev;\n}", "solution_cpp": "ListNode* reverseList(ListNode* head) {\n ListNode* prev = nullptr, *curr = head;\n while (curr) {\n ListNode* next = curr->next;\n curr->next = prev;\n prev = curr;\n curr = next;\n }\n return prev;\n}", "test_cases": ["head=[1,2,3,4,5] -> [5,4,3,2,1]", "head=[1,2] -> [2,1]"], "key_points": ["迭代法 O(1)空间", "递归法 O(n)空间"], "tags": ["linkedlist", "medium", "Google", "Microsoft"]} {"problem_id": "algo_00027", "original_id": "middle-node", "title": "链表的中间结点", "category": "linkedlist", "difficulty": "easy", "companies": ["Amazon", "Facebook"], "description": "给你单链表的头节点 head,请你找出并返回链表的中间结点。如果有两个中间结点,则返回第二个中间结点。", "solution_python": "def middleNode(head):\n slow = fast = head\n while fast and fast.next:\n slow = slow.next\n fast = fast.next.next\n return slow", "solution_java": "public ListNode middleNode(ListNode head) {\n ListNode slow = head, fast = head;\n while (fast != null && fast.next != null) {\n slow = slow.next;\n fast = fast.next.next;\n }\n return slow;\n}", "solution_cpp": "ListNode* middleNode(ListNode* head) {\n ListNode* slow = head, *fast = head;\n while (fast && fast->next) { slow = slow->next; fast = fast->next->next; }\n return slow;\n}", "test_cases": ["head=[1,2,3,4,5] -> 3", "head=[1,2,3,4,5,6] -> 4"], "key_points": ["快慢指针", "O(n)时间O(1)空间"], "tags": ["linkedlist", "easy", "Amazon", "Facebook"]} {"problem_id": "algo_00028", "original_id": "max-depth", "title": "二叉树的最大深度", "category": "tree", "difficulty": "easy", "companies": ["Microsoft", "Apple"], "description": "给定一个二叉树 root,返回其最大深度。", "solution_python": "def maxDepth(root):\n if not root: return 0\n return max(maxDepth(root.left), maxDepth(root.right)) + 1", "solution_java": "public int maxDepth(TreeNode root) {\n if (root == null) return 0;\n return Math.max(maxDepth(root.left), maxDepth(root.right)) + 1;\n}", "solution_cpp": "int maxDepth(TreeNode* root) {\n if (!root) return 0;\n return max(maxDepth(root->left), maxDepth(root->right)) + 1;\n}", "test_cases": ["root=[3,9,20,null,null,15,7] -> 3", "root=[1,null,2] -> 2"], "key_points": ["DFS递归", "层序遍历也可"], "tags": ["tree", "easy", "Microsoft", "Apple"]} {"problem_id": "algo_00029", "original_id": "inorder-traversal", "title": "二叉树的中序遍历", "category": "tree", "difficulty": "easy", "companies": ["Google", "Microsoft"], "description": "给定一个二叉树的根节点 root,返回它的中序遍历结果。", "solution_python": "def inorderTraversal(root):\n result = []\n def dfs(node):\n if node:\n dfs(node.left)\n result.append(node.val)\n dfs(node.right)\n dfs(root)\n return result", "solution_java": "public List inorderTraversal(TreeNode root) {\n List res = new ArrayList<>();\n dfs(root, res);\n return res;\n}\nprivate void dfs(TreeNode node, List res) {\n if (node == null) return;\n dfs(node.left, res); res.add(node.val); dfs(node.right, res);\n}", "solution_cpp": "vector inorderTraversal(TreeNode* root) {\n vector res;\n dfs(root, res);\n return res;\n}\nvoid dfs(TreeNode* node, vector& res) {\n if (!node) return;\n dfs(node->left, res); res.push_back(node->val); dfs(node->right, res);\n}", "test_cases": ["root=[1,null,2,3] -> [1,3,2]", "root=[] -> []"], "key_points": ["左-根-右顺序", "递归最简洁"], "tags": ["tree", "easy", "Google", "Microsoft"]} {"problem_id": "algo_00030", "original_id": "binary-search", "title": "二分查找", "category": "binarysearch", "difficulty": "easy", "companies": ["Google", "Amazon"], "description": "给定一个 n 个元素有序的(升序)整型数组 nums 和一个目标值 target,写一个函数搜索 nums 中的 target,如果目标值存在返回下标,否则返回 -1。", "solution_python": "def search(nums, target):\n left, right = 0, len(nums) - 1\n while left <= right:\n mid = (left + right) // 2\n if nums[mid] == target: return mid\n elif nums[mid] < target: left = mid + 1\n else: right = mid - 1\n return -1", "solution_java": "public int search(int[] nums, int target) {\n int left = 0, right = nums.length - 1;\n while (left <= right) {\n int mid = left + (right - left) / 2;\n if (nums[mid] == target) return mid;\n else if (nums[mid] < target) left = mid + 1;\n else right = mid - 1;\n }\n return -1;\n}", "solution_cpp": "int search(vector& nums, int target) {\n int left = 0, right = nums.size() - 1;\n while (left <= right) {\n int mid = left + (right - left) / 2;\n if (nums[mid] == target) return mid;\n else if (nums[mid] < target) left = mid + 1;\n else right = mid - 1;\n }\n return -1;\n}", "test_cases": ["nums=[-1,0,3,5,9,12], target=9 -> 4", "nums=[-1,0,3,5,9,12], target=2 -> -1"], "key_points": ["标准模板", "注意防溢出写法"], "tags": ["binarysearch", "easy", "Google", "Amazon"]} {"problem_id": "algo_00031", "original_id": "climbing-stairs", "title": "爬楼梯", "category": "dp", "difficulty": "easy", "companies": ["Amazon", "Google"], "description": "假设你正在爬楼梯。需要 n 阶你才能到达楼顶。每次你可以爬 1 或 2 个台阶。你有多少种不同的方法可以爬到楼顶?", "solution_python": "def climbStairs(n):\n if n <= 2: return n\n a, b = 1, 2\n for _ in range(3, n+1):\n a, b = b, a + b\n return b", "solution_java": "public int climbStairs(int n) {\n if (n <= 2) return n;\n int a = 1, b = 2;\n for (int i = 3; i <= n; i++) { int temp = a + b; a = b; b = temp; }\n return b;\n}", "solution_cpp": "int climbStairs(int n) {\n if (n <= 2) return n;\n int a = 1, b = 2;\n for (int i = 3; i <= n; i++) { int temp = a + b; a = b; b = temp; }\n return b;\n}", "test_cases": ["n=2 -> 2", "n=3 -> 3", "n=5 -> 8"], "key_points": ["斐波那契数列", "滚动数组优化空间"], "tags": ["dp", "easy", "Amazon", "Google"]} {"problem_id": "algo_00032", "original_id": "coin-change", "title": "零钱兑换", "category": "dp", "difficulty": "medium", "companies": ["Google", "Amazon"], "description": "给你一个整数数组 coins 表示不同面额的硬币,以及一个整数 amount 表示总金额。计算并返回可以凑成总金额所需的最少的硬币个数。如果没有任何一种硬币组合能组成总金额,返回 -1。", "solution_python": "def coinChange(coins, amount):\n dp = [float('inf')] * (amount + 1)\n dp[0] = 0\n for coin in coins:\n for x in range(coin, amount + 1):\n dp[x] = min(dp[x], dp[x - coin] + 1)\n return dp[amount] if dp[amount] != float('inf') else -1", "solution_java": "public int coinChange(int[] coins, int amount) {\n int[] dp = new int[amount + 1];\n Arrays.fill(dp, amount + 1);\n dp[0] = 0;\n for (int coin : coins) {\n for (int x = coin; x <= amount; x++) {\n dp[x] = Math.min(dp[x], dp[x - coin] + 1);\n }\n }\n return dp[amount] > amount ? -1 : dp[amount];\n}", "solution_cpp": "int coinChange(vector& coins, int amount) {\n vector dp(amount + 1, amount + 1);\n dp[0] = 0;\n for (int coin : coins) {\n for (int x = coin; x <= amount; x++) {\n dp[x] = min(dp[x], dp[x - coin] + 1);\n }\n }\n return dp[amount] > amount ? -1 : dp[amount];\n}", "test_cases": ["coins=[1,2,5], amount=11 -> 3", "coins=[2], amount=3 -> -1"], "key_points": ["完全背包问题", "dp[x] = min(dp[x-coin]+1)"], "tags": ["dp", "medium", "Google", "Amazon"]} {"problem_id": "algo_00033", "original_id": "subsets", "title": "子集", "category": "backtracking", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "给你一个整数数组 nums ,数组中的元素 互不相同 。返回该数组所有可能的子集(幂集)。", "solution_python": "def subsets(nums):\n result = []\n def backtrack(start, path):\n result.append(path[:])\n for i in range(start, len(nums)):\n path.append(nums[i])\n backtrack(i + 1, path)\n path.pop()\n backtrack(0, [])\n return result", "solution_java": "public List> subsets(int[] nums) {\n List> result = new ArrayList<>();\n backtrack(nums, 0, new ArrayList<>(), result);\n return result;\n}\nprivate void backtrack(int[] nums, int start, List path, List> result) {\n result.add(new ArrayList<>(path));\n for (int i = start; i < nums.length; i++) {\n path.add(nums[i]);\n backtrack(nums, i + 1, path, result);\n path.remove(path.size() - 1);\n }\n}", "solution_cpp": "vector> subsets(vector& nums) {\n vector> result;\n vector path;\n backtrack(nums, 0, path, result);\n return result;\n}\nvoid backtrack(vector& nums, int start, vector& path, vector>& result) {\n result.push_back(path);\n for (int i = start; i < nums.size(); i++) {\n path.push_back(nums[i]);\n backtrack(nums, i + 1, path, result);\n path.pop_back();\n }\n}", "test_cases": ["nums=[1,2,3] -> [[],[1],[2],[1,2],[3],[1,3],[2,3],[1,2,3]]"], "key_points": ["选或不选", "DFS遍历子集树"], "tags": ["backtracking", "medium", "Google", "Microsoft"]} {"problem_id": "algo_00034", "original_id": "permutations", "title": "全排列", "category": "backtracking", "difficulty": "medium", "companies": ["Google", "Facebook"], "description": "给定一个不含重复数字的数组 nums,返回其所有可能的全排列。", "solution_python": "def permute(nums):\n result = []\n def backtrack(path, used):\n if len(path) == len(nums):\n result.append(path[:])\n return\n for i in range(len(nums)):\n if used[i]: continue\n used[i] = True\n path.append(nums[i])\n backtrack(path, used)\n path.pop()\n used[i] = False\n backtrack([], [False]*len(nums))\n return result", "solution_java": "public List> permute(int[] nums) {\n List> result = new ArrayList<>();\n boolean[] used = new boolean[nums.length];\n backtrack(nums, used, new ArrayList<>(), result);\n return result;\n}\nprivate void backtrack(int[] nums, boolean[] used, List path, List> result) {\n if (path.size() == nums.length) { result.add(new ArrayList<>(path)); return; }\n for (int i = 0; i < nums.length; i++) {\n if (used[i]) continue;\n used[i] = true;\n path.add(nums[i]);\n backtrack(nums, used, path, result);\n path.remove(path.size() - 1);\n used[i] = false;\n }\n}", "solution_cpp": "vector> permute(vector& nums) {\n vector> result;\n vector used(nums.size(), false);\n vector path;\n backtrack(nums, used, path, result);\n return result;\n}\nvoid backtrack(vector& nums, vector& used, vector& path, vector>& result) {\n if (path.size() == nums.size()) { result.push_back(path); return; }\n for (int i = 0; i < nums.size(); i++) {\n if (used[i]) continue;\n used[i] = true;\n path.push_back(nums[i]);\n backtrack(nums, used, path, result);\n path.pop_back();\n used[i] = false;\n }\n}", "test_cases": ["nums=[1,2,3] -> [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]"], "key_points": ["标记已使用元素", "回溯经典模板"], "tags": ["backtracking", "medium", "Google", "Facebook"]} {"problem_id": "algo_00035", "original_id": "top-k-frequent", "title": "前K个高频元素", "category": "heap", "difficulty": "medium", "companies": ["Amazon", "Facebook"], "description": "给你一个整数数组 nums 和一个整数 k,请你返回其中出现频率前 k 高的元素。", "solution_python": "import heapq\nfrom collections import Counter\ndef topKFrequent(nums, k):\n count = Counter(nums)\n heap = []\n for num, freq in count.items():\n heapq.heappush(heap, (freq, num))\n if len(heap) > k: heapq.heappop(heap)\n return [num for freq, num in heap]", "solution_java": "public int[] topKFrequent(int[] nums, int k) {\n Map count = new HashMap<>();\n for (int n : nums) count.put(n, count.getOrDefault(n, 0) + 1);\n PriorityQueue> heap = \n new PriorityQueue<>((a, b) -> a.getValue() - b.getValue());\n for (Map.Entry e : count.entrySet()) {\n heap.offer(e);\n if (heap.size() > k) heap.poll();\n }\n int[] res = new int[k];\n for (int i = k - 1; i >= 0; i--) res[i] = heap.poll().getKey();\n return res;\n}", "solution_cpp": "vector topKFrequent(vector& nums, int k) {\n unordered_map count;\n for (int n : nums) count[n]++;\n priority_queue, vector>, greater>> heap;\n for (auto& [num, freq] : count) {\n heap.push({freq, num});\n if (heap.size() > k) heap.pop();\n }\n vector res;\n while (!heap.empty()) { res.push_back(heap.top().second); heap.pop(); }\n reverse(res.begin(), res.end());\n return res;\n}", "test_cases": ["nums=[1,1,1,2,2,3], k=2 -> [1,2]", "nums=[1], k=1 -> [1]"], "key_points": ["小顶堆保持大小k", "时间复杂度O(nlogk)"], "tags": ["heap", "medium", "Amazon", "Facebook"]} {"problem_id": "algo_00036", "original_id": "3sum", "title": "三数之和", "category": "two-pointers", "difficulty": "medium", "companies": ["Google", "Amazon"], "description": "给你一个整数数组 nums,判断是否存在三元组满足和为0,返回所有不重复的三元组。", "solution_python": "def threeSum(nums):\n nums.sort()\n result = []\n for i in range(len(nums) - 2):\n if i > 0 and nums[i] == nums[i-1]: continue\n left, right = i + 1, len(nums) - 1\n while left < right:\n total = nums[i] + nums[left] + nums[right]\n if total < 0: left += 1\n elif total > 0: right -= 1\n else:\n result.append([nums[i], nums[left], nums[right]])\n while left < right and nums[left] == nums[left+1]: left += 1\n while left < right and nums[right] == nums[right-1]: right -= 1\n left += 1; right -= 1\n return result", "solution_java": "public List> threeSum(int[] nums) {\n Arrays.sort(nums);\n List> result = new ArrayList<>();\n for (int i = 0; i < nums.length - 2; i++) {\n if (i > 0 && nums[i] == nums[i-1]) continue;\n int left = i + 1, right = nums.length - 1;\n while (left < right) {\n int total = nums[i] + nums[left] + nums[right];\n if (total < 0) left++;\n else if (total > 0) right--;\n else {\n result.add(Arrays.asList(nums[i], nums[left], nums[right]));\n while (left < right && nums[left] == nums[left+1]) left++;\n while (left < right && nums[right] == nums[right-1]) right--;\n left++; right--;\n }\n }\n }\n return result;\n}", "solution_cpp": "vector> threeSum(vector& nums) {\n sort(nums.begin(), nums.end());\n vector> result;\n for (int i = 0; i < nums.size() - 2; i++) {\n if (i > 0 && nums[i] == nums[i-1]) continue;\n int left = i + 1, right = nums.size() - 1;\n while (left < right) {\n int total = nums[i] + nums[left] + nums[right];\n if (total < 0) left++;\n else if (total > 0) right--;\n else {\n result.push_back({nums[i], nums[left], nums[right]});\n while (left < right && nums[left] == nums[left+1]) left++;\n while (left < right && nums[right] == nums[right-1]) right--;\n left++; right--;\n }\n }\n }\n return result;\n}", "test_cases": ["nums=[-1,0,1,2,-1,-4] -> [[-1,-1,2],[-1,0,1]]"], "key_points": ["排序+双指针", "去重是关键"], "tags": ["two-pointers", "medium", "Google", "Amazon"]} {"problem_id": "algo_00037", "original_id": "container-water", "title": "盛最多水的容器", "category": "two-pointers", "difficulty": "medium", "companies": ["Google", "Uber"], "description": "给定一个长度为 n 的整数数组 height,找出其中的两条线,使得它们与 x 轴共同构成的容器可以容纳最多的水。", "solution_python": "def maxArea(height):\n left, right = 0, len(height) - 1\n max_area = 0\n while left < right:\n h = min(height[left], height[right])\n max_area = max(max_area, h * (right - left))\n if height[left] < height[right]: left += 1\n else: right -= 1\n return max_area", "solution_java": "public int maxArea(int[] height) {\n int left = 0, right = height.length - 1, maxArea = 0;\n while (left < right) {\n int h = Math.min(height[left], height[right]);\n maxArea = Math.max(maxArea, h * (right - left));\n if (height[left] < height[right]) left++;\n else right--;\n }\n return maxArea;\n}", "solution_cpp": "int maxArea(vector& height) {\n int left = 0, right = height.size() - 1, maxArea = 0;\n while (left < right) {\n int h = min(height[left], height[right]);\n maxArea = max(maxArea, h * (right - left));\n if (height[left] < height[right]) left++;\n else right--;\n }\n return maxArea;\n}", "test_cases": ["height=[1,8,6,2,5,4,8,3,7] -> 49"], "key_points": ["移动短边指针", "面积=min(h1,h2)*width"], "tags": ["two-pointers", "medium", "Google", "Uber"]} {"problem_id": "algo_00038", "original_id": "min-stack", "title": "最小栈", "category": "stack", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "设计一个支持 push,pop,top 操作,并能在常数时间内检索到最小元素的栈。", "solution_python": "class MinStack:\n def __init__(self):\n self.stack = []\n self.min_stack = []\n def push(self, val):\n self.stack.append(val)\n self.min_stack.append(min(val, self.min_stack[-1] if self.min_stack else val))\n def pop(self):\n self.stack.pop(); self.min_stack.pop()\n def top(self): return self.stack[-1]\n def getMin(self): return self.min_stack[-1]", "solution_java": "class MinStack {\n Stack stack = new Stack<>();\n Stack minStack = new Stack<>();\n public void push(int val) { stack.push(val); minStack.push(Math.min(val, minStack.isEmpty() ? val : minStack.peek())); }\n public void pop() { stack.pop(); minStack.pop(); }\n public int top() { return stack.peek(); }\n public int getMin() { return minStack.peek(); }\n}", "solution_cpp": "class MinStack {\n stack st, minSt;\npublic:\n void push(int val) { st.push(val); minSt.push(min(val, minSt.empty() ? val : minSt.top())); }\n void pop() { st.pop(); minSt.pop(); }\n int top() { return st.top(); }\n int getMin() { return minSt.top(); }\n};", "test_cases": ["push(-2), push(0), push(-3) -> getMin() returns -3"], "key_points": ["辅助栈记录最小值", "O(1)时间获取最小值"], "tags": ["stack", "medium", "Google", "Microsoft"]} {"problem_id": "algo_00039", "original_id": "lru-cache", "title": "LRU缓存", "category": "design", "difficulty": "hard", "companies": ["Google", "Amazon"], "description": "设计和实现一个 LRU(最近最少使用)缓存机制。", "solution_python": "class LRUCache:\n def __init__(self, capacity):\n self.capacity = capacity\n self.cache = {}\n self.order = []\n def get(self, key):\n if key not in self.cache: return -1\n self.order.remove(key); self.order.append(key)\n return self.cache[key]\n def put(self, key, value):\n if key in self.cache:\n self.order.remove(key)\n elif len(self.cache) >= self.capacity:\n del self.cache[self.order.pop(0)]\n self.cache[key] = value; self.order.append(key)", "solution_java": "class LRUCache {\n int capacity;\n LinkedHashMap cache = new LinkedHashMap<>();\n public LRUCache(int cap) { capacity = cap; }\n public int get(int key) { return cache.containsKey(key) ? cache.remove(key) : -1; }\n public void put(int key, int val) {\n if (cache.containsKey(key)) cache.remove(key);\n else if (cache.size() >= capacity) cache.remove(cache.keySet().iterator().next());\n cache.put(key, val);\n }\n}", "solution_cpp": "class LRUCache {\n int cap;\n list> dll;\n unordered_map>::iterator> cache;\npublic:\n LRUCache(int capacity) : cap(capacity) {}\n int get(int key) {\n auto it = cache.find(key);\n if (it == cache.end()) return -1;\n dll.splice(dll.end(), dll, it->second);\n return it->second->second;\n }\n void put(int key, int value) {\n auto it = cache.find(key);\n if (it != cache.end()) dll.erase(it->second);\n else if (cache.size() >= cap) { cache.erase(dll.front().first); dll.pop_front(); }\n dll.push_back({key, value});\n cache[key] = --dll.end();\n }\n};", "test_cases": ["put(1,1), put(2,2), get(1) -> 1"], "key_points": ["HashMap + 双向链表", "O(1)时间操作"], "tags": ["design", "hard", "Google", "Amazon"]} {"problem_id": "algo_00040", "original_id": "num-islands", "title": "岛屿数量", "category": "graph", "difficulty": "medium", "companies": ["Google", "Facebook"], "description": "给你一个由 '1'(陆地)和 '0'(水)组成的二维网格,请你计算网格中岛屿的数量。岛屿总是被水包围,且只能由水平或垂直方向相邻的陆地连接形成。", "solution_python": "def numIslands(grid):\n if not grid: return 0\n rows, cols = len(grid), len(grid[0])\n count = 0\n def dfs(r, c):\n if r < 0 or r >= rows or c < 0 or c >= cols or grid[r][c] != '1': return\n grid[r][c] = '0'\n dfs(r+1, c); dfs(r-1, c); dfs(r, c+1); dfs(r, c-1)\n for r in range(rows):\n for c in range(cols):\n if grid[r][c] == '1': count += 1; dfs(r, c)\n return count", "solution_java": "public int numIslands(char[][] grid) {\n if (grid.length == 0) return 0;\n int count = 0;\n for (int i = 0; i < grid.length; i++)\n for (int j = 0; j < grid[0].length; j++)\n if (grid[i][j] == '1') { count++; dfs(grid, i, j); }\n return count;\n}\nprivate void dfs(char[][] grid, int r, int c) {\n if (r < 0 || r >= grid.length || c < 0 || c >= grid[0].length || grid[r][c] != '1') return;\n grid[r][c] = '0';\n dfs(grid, r+1, c); dfs(grid, r-1, c); dfs(grid, r, c+1); dfs(grid, r, c-1);\n}", "solution_cpp": "int numIslands(vector>& grid) {\n if (grid.empty()) return 0;\n int count = 0;\n for (int i = 0; i < grid.size(); i++)\n for (int j = 0; j < grid[0].size(); j++)\n if (grid[i][j] == '1') { count++; dfs(grid, i, j); }\n return count;\n}\nvoid dfs(vector>& grid, int r, int c) {\n if (r < 0 || r >= grid.size() || c < 0 || c >= grid[0].size() || grid[r][c] != '1') return;\n grid[r][c] = '0';\n dfs(grid, r+1, c); dfs(grid, r-1, c); dfs(grid, r, c+1); dfs(grid, r, c-1);\n}", "test_cases": ["grid=[[1,1,1,1,0],[1,1,0,1,0],[1,1,0,0,0],[0,0,0,0,0]] -> 1"], "key_points": ["DFS/BFS遍历", "访问后标记为0避免重复"], "tags": ["graph", "medium", "Google", "Facebook"]} {"problem_id": "algo_00041", "original_id": "two-sum", "title": "两数之和", "category": "array", "difficulty": "easy", "companies": ["Amazon", "Google"], "description": "给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那两个整数,并返回他们的数组下标。", "solution_python": "def twoSum(nums, target):\n hashmap = {}\n for i, num in enumerate(nums):\n complement = target - num\n if complement in hashmap:\n return [hashmap[complement], i]\n hashmap[num] = i\n return []", "solution_java": "public int[] twoSum(int[] nums, int target) {\n Map map = new HashMap<>();\n for (int i = 0; i < nums.length; i++) {\n int complement = target - nums[i];\n if (map.containsKey(complement)) return new int[]{map.get(complement), i};\n map.put(nums[i], i);\n }\n return new int[]{};\n}", "solution_cpp": "vector twoSum(vector& nums, int target) {\n unordered_map m;\n for (int i = 0; i < nums.size(); i++) {\n if (m.count(target - nums[i])) return {m[target - nums[i]], i};\n m[nums[i]] = i;\n }\n return {};\n}", "test_cases": ["nums=[2,7,11,15], target=9 -> [0,1]", "nums=[3,2,4], target=6 -> [1,2]"], "key_points": ["哈希表一次遍历", "空间换时间"], "tags": ["array", "easy", "Amazon", "Google"]} {"problem_id": "algo_00042", "original_id": "merge-sorted", "title": "合并两个有序数组", "category": "array", "difficulty": "easy", "companies": ["Microsoft", "Uber"], "description": "给你两个按非递减顺序排列的整数数组 nums1 和 nums2,另有两个整数 m 和 n,分别表示 nums1 和 nums2 中的元素数目。请你合并 nums2 到 nums1 中。", "solution_python": "def merge(nums1, m, nums2, n):\n p1, p2, p = m-1, n-1, m+n-1\n while p1 >= 0 and p2 >= 0:\n if nums1[p1] > nums2[p2]: nums1[p] = nums1[p1]; p1 -= 1\n else: nums1[p] = nums2[p2]; p2 -= 1\n p -= 1\n while p2 >= 0: nums1[p] = nums2[p2]; p2 -= 1; p -= 1", "solution_java": "public void merge(int[] nums1, int m, int[] nums2, int n) {\n int p1 = m-1, p2 = n-1, p = m+n-1;\n while (p1 >= 0 && p2 >= 0) {\n nums1[p--] = nums1[p1] > nums2[p2] ? nums1[p1--] : nums2[p2--];\n }\n while (p2 >= 0) nums1[p--] = nums2[p2--];\n}", "solution_cpp": "void merge(vector& nums1, int m, vector& nums2, int n) {\n int p1 = m-1, p2 = n-1, p = m+n-1;\n while (p1 >= 0 && p2 >= 0) nums1[p--] = nums1[p1] > nums2[p2] ? nums1[p1--] : nums2[p2--];\n while (p2 >= 0) nums1[p--] = nums2[p2--];\n}", "test_cases": ["nums1=[1,2,3], m=3, nums2=[2,5,6], n=3 -> [1,2,2,3,5,6]", "nums1=[], m=0, nums2=[1], n=1 -> [1]"], "key_points": ["从后往前合并", "三指针技巧"], "tags": ["array", "easy", "Microsoft", "Uber"]} {"problem_id": "algo_00043", "original_id": "max-subarray", "title": "最大子数组和", "category": "array", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "给你一个整数数组 nums ,请你找出一个具有最大和的连续子数组,返回其最大和。", "solution_python": "def maxSubArray(nums):\n max_sum = current = nums[0]\n for num in nums[1:]:\n current = max(num, current + num)\n max_sum = max(max_sum, current)\n return max_sum", "solution_java": "public int maxSubArray(int[] nums) {\n int maxSum = nums[0], curr = nums[0];\n for (int i = 1; i < nums.length; i++) {\n curr = Math.max(nums[i], curr + nums[i]);\n maxSum = Math.max(maxSum, curr);\n }\n return maxSum;\n}", "solution_cpp": "int maxSubArray(vector& nums) {\n int maxSum = nums[0], curr = nums[0];\n for (int i = 1; i < nums.size(); i++) {\n curr = max(nums[i], curr + nums[i]);\n maxSum = max(maxSum, curr);\n }\n return maxSum;\n}", "test_cases": ["nums=[-2,1,-3,4,-1,2,1,-5,4] -> 6", "nums=[1] -> 1"], "key_points": ["Kadane算法", "动态规划基础题"], "tags": ["array", "medium", "Google", "Microsoft"]} {"problem_id": "algo_00044", "original_id": "valid-parentheses", "title": "有效的括号", "category": "string", "difficulty": "easy", "companies": ["Google", "Uber"], "description": "给定一个只包括 '(',')','{','}','[',']' 的字符串 s,判断字符串是否有效。", "solution_python": "def isValid(s):\n stack = []\n mapping = {')': '(', ']': '[', '}': '{'}\n for c in s:\n if c in mapping:\n if not stack or stack[-1] != mapping[c]: return False\n stack.pop()\n else: stack.append(c)\n return not stack", "solution_java": "public boolean isValid(String s) {\n Stack stack = new Stack<>();\n Map map = Map.of(')', '(', ']', '[', '}', '{');\n for (char c : s.toCharArray()) {\n if (map.containsValue(c)) stack.push(c);\n else if (!stack.isEmpty() && stack.pop() != map.get(c)) return false;\n }\n return stack.isEmpty();\n}", "solution_cpp": "bool isValid(string s) {\n stack st;\n unordered_map m = {{')','('},{']','['},{'}','{'}};\n for (char c : s) {\n if (m.find(c) == m.end()) st.push(c);\n else if (st.empty() || st.top() != m[c]) return false;\n else st.pop();\n }\n return st.empty();\n}", "test_cases": ["s=\"()\" -> true", "s=\"()[]{}\" -> true", "s=\"(]\" -> false"], "key_points": ["栈匹配法", "注意空栈边界"], "tags": ["string", "easy", "Google", "Uber"]} {"problem_id": "algo_00045", "original_id": "longest-palindrome", "title": "最长回文子串", "category": "string", "difficulty": "medium", "companies": ["Google", "Amazon"], "description": "给你一个字符串 s,找到 s 中最长的回文子串。", "solution_python": "def longestPalindrome(s):\n def expand(l, r):\n while l >= 0 and r < len(s) and s[l] == s[r]: l -= 1; r += 1\n return l + 1, r - 1\n start = end = 0\n for i in range(len(s)):\n l1, r1 = expand(i, i)\n l2, r2 = expand(i, i + 1)\n if r1 - l1 > end - start: start, end = l1, r1\n if r2 - l2 > end - start: start, end = l2, r2\n return s[start:end+1]", "solution_java": "public String longestPalindrome(String s) {\n int start = 0, end = 0;\n for (int i = 0; i < s.length(); i++) {\n int len1 = expand(s, i, i), len2 = expand(s, i, i+1);\n int len = Math.max(len1, len2);\n if (len > end - start) { start = i - (len-1)/2; end = i + len/2; }\n }\n return s.substring(start, end + 1);\n}\nprivate int expand(String s, int l, int r) {\n while (l >= 0 && r < s.length() && s.charAt(l) == s.charAt(r)) { l--; r++; }\n return r - l - 1;\n}", "solution_cpp": "string longestPalindrome(string s) {\n int start = 0, end = 0;\n for (int i = 0; i < s.size(); i++) {\n int len1 = expand(s, i, i), len2 = expand(s, i, i+1);\n if (max(len1, len2) > end - start) { start = i - (max(len1,len2)-1)/2; end = i + max(len1,len2)/2; }\n }\n return s.substr(start, end - start + 1);\n}", "test_cases": ["s=\"babad\" -> bab或aba", "s=\"cbbd\" -> bb"], "key_points": ["中心扩展法", "处理奇偶长度"], "tags": ["string", "medium", "Google", "Amazon"]} {"problem_id": "algo_00046", "original_id": "reverse-list", "title": "反转链表", "category": "linkedlist", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "给你单链表的头节点 head,请你反转链表,并返回反转后的链表。", "solution_python": "def reverseList(head):\n prev = None\n curr = head\n while curr:\n nxt = curr.next\n curr.next = prev\n prev = curr\n curr = nxt\n return prev", "solution_java": "public ListNode reverseList(ListNode head) {\n ListNode prev = null, curr = head;\n while (curr != null) {\n ListNode next = curr.next;\n curr.next = prev;\n prev = curr;\n curr = next;\n }\n return prev;\n}", "solution_cpp": "ListNode* reverseList(ListNode* head) {\n ListNode* prev = nullptr, *curr = head;\n while (curr) {\n ListNode* next = curr->next;\n curr->next = prev;\n prev = curr;\n curr = next;\n }\n return prev;\n}", "test_cases": ["head=[1,2,3,4,5] -> [5,4,3,2,1]", "head=[1,2] -> [2,1]"], "key_points": ["迭代法 O(1)空间", "递归法 O(n)空间"], "tags": ["linkedlist", "medium", "Google", "Microsoft"]} {"problem_id": "algo_00047", "original_id": "middle-node", "title": "链表的中间结点", "category": "linkedlist", "difficulty": "easy", "companies": ["Amazon", "Facebook"], "description": "给你单链表的头节点 head,请你找出并返回链表的中间结点。如果有两个中间结点,则返回第二个中间结点。", "solution_python": "def middleNode(head):\n slow = fast = head\n while fast and fast.next:\n slow = slow.next\n fast = fast.next.next\n return slow", "solution_java": "public ListNode middleNode(ListNode head) {\n ListNode slow = head, fast = head;\n while (fast != null && fast.next != null) {\n slow = slow.next;\n fast = fast.next.next;\n }\n return slow;\n}", "solution_cpp": "ListNode* middleNode(ListNode* head) {\n ListNode* slow = head, *fast = head;\n while (fast && fast->next) { slow = slow->next; fast = fast->next->next; }\n return slow;\n}", "test_cases": ["head=[1,2,3,4,5] -> 3", "head=[1,2,3,4,5,6] -> 4"], "key_points": ["快慢指针", "O(n)时间O(1)空间"], "tags": ["linkedlist", "easy", "Amazon", "Facebook"]} {"problem_id": "algo_00048", "original_id": "max-depth", "title": "二叉树的最大深度", "category": "tree", "difficulty": "easy", "companies": ["Microsoft", "Apple"], "description": "给定一个二叉树 root,返回其最大深度。", "solution_python": "def maxDepth(root):\n if not root: return 0\n return max(maxDepth(root.left), maxDepth(root.right)) + 1", "solution_java": "public int maxDepth(TreeNode root) {\n if (root == null) return 0;\n return Math.max(maxDepth(root.left), maxDepth(root.right)) + 1;\n}", "solution_cpp": "int maxDepth(TreeNode* root) {\n if (!root) return 0;\n return max(maxDepth(root->left), maxDepth(root->right)) + 1;\n}", "test_cases": ["root=[3,9,20,null,null,15,7] -> 3", "root=[1,null,2] -> 2"], "key_points": ["DFS递归", "层序遍历也可"], "tags": ["tree", "easy", "Microsoft", "Apple"]} {"problem_id": "algo_00049", "original_id": "inorder-traversal", "title": "二叉树的中序遍历", "category": "tree", "difficulty": "easy", "companies": ["Google", "Microsoft"], "description": "给定一个二叉树的根节点 root,返回它的中序遍历结果。", "solution_python": "def inorderTraversal(root):\n result = []\n def dfs(node):\n if node:\n dfs(node.left)\n result.append(node.val)\n dfs(node.right)\n dfs(root)\n return result", "solution_java": "public List inorderTraversal(TreeNode root) {\n List res = new ArrayList<>();\n dfs(root, res);\n return res;\n}\nprivate void dfs(TreeNode node, List res) {\n if (node == null) return;\n dfs(node.left, res); res.add(node.val); dfs(node.right, res);\n}", "solution_cpp": "vector inorderTraversal(TreeNode* root) {\n vector res;\n dfs(root, res);\n return res;\n}\nvoid dfs(TreeNode* node, vector& res) {\n if (!node) return;\n dfs(node->left, res); res.push_back(node->val); dfs(node->right, res);\n}", "test_cases": ["root=[1,null,2,3] -> [1,3,2]", "root=[] -> []"], "key_points": ["左-根-右顺序", "递归最简洁"], "tags": ["tree", "easy", "Google", "Microsoft"]} {"problem_id": "algo_00050", "original_id": "binary-search", "title": "二分查找", "category": "binarysearch", "difficulty": "easy", "companies": ["Google", "Amazon"], "description": "给定一个 n 个元素有序的(升序)整型数组 nums 和一个目标值 target,写一个函数搜索 nums 中的 target,如果目标值存在返回下标,否则返回 -1。", "solution_python": "def search(nums, target):\n left, right = 0, len(nums) - 1\n while left <= right:\n mid = (left + right) // 2\n if nums[mid] == target: return mid\n elif nums[mid] < target: left = mid + 1\n else: right = mid - 1\n return -1", "solution_java": "public int search(int[] nums, int target) {\n int left = 0, right = nums.length - 1;\n while (left <= right) {\n int mid = left + (right - left) / 2;\n if (nums[mid] == target) return mid;\n else if (nums[mid] < target) left = mid + 1;\n else right = mid - 1;\n }\n return -1;\n}", "solution_cpp": "int search(vector& nums, int target) {\n int left = 0, right = nums.size() - 1;\n while (left <= right) {\n int mid = left + (right - left) / 2;\n if (nums[mid] == target) return mid;\n else if (nums[mid] < target) left = mid + 1;\n else right = mid - 1;\n }\n return -1;\n}", "test_cases": ["nums=[-1,0,3,5,9,12], target=9 -> 4", "nums=[-1,0,3,5,9,12], target=2 -> -1"], "key_points": ["标准模板", "注意防溢出写法"], "tags": ["binarysearch", "easy", "Google", "Amazon"]} {"problem_id": "algo_00051", "original_id": "climbing-stairs", "title": "爬楼梯", "category": "dp", "difficulty": "easy", "companies": ["Amazon", "Google"], "description": "假设你正在爬楼梯。需要 n 阶你才能到达楼顶。每次你可以爬 1 或 2 个台阶。你有多少种不同的方法可以爬到楼顶?", "solution_python": "def climbStairs(n):\n if n <= 2: return n\n a, b = 1, 2\n for _ in range(3, n+1):\n a, b = b, a + b\n return b", "solution_java": "public int climbStairs(int n) {\n if (n <= 2) return n;\n int a = 1, b = 2;\n for (int i = 3; i <= n; i++) { int temp = a + b; a = b; b = temp; }\n return b;\n}", "solution_cpp": "int climbStairs(int n) {\n if (n <= 2) return n;\n int a = 1, b = 2;\n for (int i = 3; i <= n; i++) { int temp = a + b; a = b; b = temp; }\n return b;\n}", "test_cases": ["n=2 -> 2", "n=3 -> 3", "n=5 -> 8"], "key_points": ["斐波那契数列", "滚动数组优化空间"], "tags": ["dp", "easy", "Amazon", "Google"]} {"problem_id": "algo_00052", "original_id": "coin-change", "title": "零钱兑换", "category": "dp", "difficulty": "medium", "companies": ["Google", "Amazon"], "description": "给你一个整数数组 coins 表示不同面额的硬币,以及一个整数 amount 表示总金额。计算并返回可以凑成总金额所需的最少的硬币个数。如果没有任何一种硬币组合能组成总金额,返回 -1。", "solution_python": "def coinChange(coins, amount):\n dp = [float('inf')] * (amount + 1)\n dp[0] = 0\n for coin in coins:\n for x in range(coin, amount + 1):\n dp[x] = min(dp[x], dp[x - coin] + 1)\n return dp[amount] if dp[amount] != float('inf') else -1", "solution_java": "public int coinChange(int[] coins, int amount) {\n int[] dp = new int[amount + 1];\n Arrays.fill(dp, amount + 1);\n dp[0] = 0;\n for (int coin : coins) {\n for (int x = coin; x <= amount; x++) {\n dp[x] = Math.min(dp[x], dp[x - coin] + 1);\n }\n }\n return dp[amount] > amount ? -1 : dp[amount];\n}", "solution_cpp": "int coinChange(vector& coins, int amount) {\n vector dp(amount + 1, amount + 1);\n dp[0] = 0;\n for (int coin : coins) {\n for (int x = coin; x <= amount; x++) {\n dp[x] = min(dp[x], dp[x - coin] + 1);\n }\n }\n return dp[amount] > amount ? -1 : dp[amount];\n}", "test_cases": ["coins=[1,2,5], amount=11 -> 3", "coins=[2], amount=3 -> -1"], "key_points": ["完全背包问题", "dp[x] = min(dp[x-coin]+1)"], "tags": ["dp", "medium", "Google", "Amazon"]} {"problem_id": "algo_00053", "original_id": "subsets", "title": "子集", "category": "backtracking", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "给你一个整数数组 nums ,数组中的元素 互不相同 。返回该数组所有可能的子集(幂集)。", "solution_python": "def subsets(nums):\n result = []\n def backtrack(start, path):\n result.append(path[:])\n for i in range(start, len(nums)):\n path.append(nums[i])\n backtrack(i + 1, path)\n path.pop()\n backtrack(0, [])\n return result", "solution_java": "public List> subsets(int[] nums) {\n List> result = new ArrayList<>();\n backtrack(nums, 0, new ArrayList<>(), result);\n return result;\n}\nprivate void backtrack(int[] nums, int start, List path, List> result) {\n result.add(new ArrayList<>(path));\n for (int i = start; i < nums.length; i++) {\n path.add(nums[i]);\n backtrack(nums, i + 1, path, result);\n path.remove(path.size() - 1);\n }\n}", "solution_cpp": "vector> subsets(vector& nums) {\n vector> result;\n vector path;\n backtrack(nums, 0, path, result);\n return result;\n}\nvoid backtrack(vector& nums, int start, vector& path, vector>& result) {\n result.push_back(path);\n for (int i = start; i < nums.size(); i++) {\n path.push_back(nums[i]);\n backtrack(nums, i + 1, path, result);\n path.pop_back();\n }\n}", "test_cases": ["nums=[1,2,3] -> [[],[1],[2],[1,2],[3],[1,3],[2,3],[1,2,3]]"], "key_points": ["选或不选", "DFS遍历子集树"], "tags": ["backtracking", "medium", "Google", "Microsoft"]} {"problem_id": "algo_00054", "original_id": "permutations", "title": "全排列", "category": "backtracking", "difficulty": "medium", "companies": ["Google", "Facebook"], "description": "给定一个不含重复数字的数组 nums,返回其所有可能的全排列。", "solution_python": "def permute(nums):\n result = []\n def backtrack(path, used):\n if len(path) == len(nums):\n result.append(path[:])\n return\n for i in range(len(nums)):\n if used[i]: continue\n used[i] = True\n path.append(nums[i])\n backtrack(path, used)\n path.pop()\n used[i] = False\n backtrack([], [False]*len(nums))\n return result", "solution_java": "public List> permute(int[] nums) {\n List> result = new ArrayList<>();\n boolean[] used = new boolean[nums.length];\n backtrack(nums, used, new ArrayList<>(), result);\n return result;\n}\nprivate void backtrack(int[] nums, boolean[] used, List path, List> result) {\n if (path.size() == nums.length) { result.add(new ArrayList<>(path)); return; }\n for (int i = 0; i < nums.length; i++) {\n if (used[i]) continue;\n used[i] = true;\n path.add(nums[i]);\n backtrack(nums, used, path, result);\n path.remove(path.size() - 1);\n used[i] = false;\n }\n}", "solution_cpp": "vector> permute(vector& nums) {\n vector> result;\n vector used(nums.size(), false);\n vector path;\n backtrack(nums, used, path, result);\n return result;\n}\nvoid backtrack(vector& nums, vector& used, vector& path, vector>& result) {\n if (path.size() == nums.size()) { result.push_back(path); return; }\n for (int i = 0; i < nums.size(); i++) {\n if (used[i]) continue;\n used[i] = true;\n path.push_back(nums[i]);\n backtrack(nums, used, path, result);\n path.pop_back();\n used[i] = false;\n }\n}", "test_cases": ["nums=[1,2,3] -> [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]"], "key_points": ["标记已使用元素", "回溯经典模板"], "tags": ["backtracking", "medium", "Google", "Facebook"]} {"problem_id": "algo_00055", "original_id": "top-k-frequent", "title": "前K个高频元素", "category": "heap", "difficulty": "medium", "companies": ["Amazon", "Facebook"], "description": "给你一个整数数组 nums 和一个整数 k,请你返回其中出现频率前 k 高的元素。", "solution_python": "import heapq\nfrom collections import Counter\ndef topKFrequent(nums, k):\n count = Counter(nums)\n heap = []\n for num, freq in count.items():\n heapq.heappush(heap, (freq, num))\n if len(heap) > k: heapq.heappop(heap)\n return [num for freq, num in heap]", "solution_java": "public int[] topKFrequent(int[] nums, int k) {\n Map count = new HashMap<>();\n for (int n : nums) count.put(n, count.getOrDefault(n, 0) + 1);\n PriorityQueue> heap = \n new PriorityQueue<>((a, b) -> a.getValue() - b.getValue());\n for (Map.Entry e : count.entrySet()) {\n heap.offer(e);\n if (heap.size() > k) heap.poll();\n }\n int[] res = new int[k];\n for (int i = k - 1; i >= 0; i--) res[i] = heap.poll().getKey();\n return res;\n}", "solution_cpp": "vector topKFrequent(vector& nums, int k) {\n unordered_map count;\n for (int n : nums) count[n]++;\n priority_queue, vector>, greater>> heap;\n for (auto& [num, freq] : count) {\n heap.push({freq, num});\n if (heap.size() > k) heap.pop();\n }\n vector res;\n while (!heap.empty()) { res.push_back(heap.top().second); heap.pop(); }\n reverse(res.begin(), res.end());\n return res;\n}", "test_cases": ["nums=[1,1,1,2,2,3], k=2 -> [1,2]", "nums=[1], k=1 -> [1]"], "key_points": ["小顶堆保持大小k", "时间复杂度O(nlogk)"], "tags": ["heap", "medium", "Amazon", "Facebook"]} {"problem_id": "algo_00056", "original_id": "3sum", "title": "三数之和", "category": "two-pointers", "difficulty": "medium", "companies": ["Google", "Amazon"], "description": "给你一个整数数组 nums,判断是否存在三元组满足和为0,返回所有不重复的三元组。", "solution_python": "def threeSum(nums):\n nums.sort()\n result = []\n for i in range(len(nums) - 2):\n if i > 0 and nums[i] == nums[i-1]: continue\n left, right = i + 1, len(nums) - 1\n while left < right:\n total = nums[i] + nums[left] + nums[right]\n if total < 0: left += 1\n elif total > 0: right -= 1\n else:\n result.append([nums[i], nums[left], nums[right]])\n while left < right and nums[left] == nums[left+1]: left += 1\n while left < right and nums[right] == nums[right-1]: right -= 1\n left += 1; right -= 1\n return result", "solution_java": "public List> threeSum(int[] nums) {\n Arrays.sort(nums);\n List> result = new ArrayList<>();\n for (int i = 0; i < nums.length - 2; i++) {\n if (i > 0 && nums[i] == nums[i-1]) continue;\n int left = i + 1, right = nums.length - 1;\n while (left < right) {\n int total = nums[i] + nums[left] + nums[right];\n if (total < 0) left++;\n else if (total > 0) right--;\n else {\n result.add(Arrays.asList(nums[i], nums[left], nums[right]));\n while (left < right && nums[left] == nums[left+1]) left++;\n while (left < right && nums[right] == nums[right-1]) right--;\n left++; right--;\n }\n }\n }\n return result;\n}", "solution_cpp": "vector> threeSum(vector& nums) {\n sort(nums.begin(), nums.end());\n vector> result;\n for (int i = 0; i < nums.size() - 2; i++) {\n if (i > 0 && nums[i] == nums[i-1]) continue;\n int left = i + 1, right = nums.size() - 1;\n while (left < right) {\n int total = nums[i] + nums[left] + nums[right];\n if (total < 0) left++;\n else if (total > 0) right--;\n else {\n result.push_back({nums[i], nums[left], nums[right]});\n while (left < right && nums[left] == nums[left+1]) left++;\n while (left < right && nums[right] == nums[right-1]) right--;\n left++; right--;\n }\n }\n }\n return result;\n}", "test_cases": ["nums=[-1,0,1,2,-1,-4] -> [[-1,-1,2],[-1,0,1]]"], "key_points": ["排序+双指针", "去重是关键"], "tags": ["two-pointers", "medium", "Google", "Amazon"]} {"problem_id": "algo_00057", "original_id": "container-water", "title": "盛最多水的容器", "category": "two-pointers", "difficulty": "medium", "companies": ["Google", "Uber"], "description": "给定一个长度为 n 的整数数组 height,找出其中的两条线,使得它们与 x 轴共同构成的容器可以容纳最多的水。", "solution_python": "def maxArea(height):\n left, right = 0, len(height) - 1\n max_area = 0\n while left < right:\n h = min(height[left], height[right])\n max_area = max(max_area, h * (right - left))\n if height[left] < height[right]: left += 1\n else: right -= 1\n return max_area", "solution_java": "public int maxArea(int[] height) {\n int left = 0, right = height.length - 1, maxArea = 0;\n while (left < right) {\n int h = Math.min(height[left], height[right]);\n maxArea = Math.max(maxArea, h * (right - left));\n if (height[left] < height[right]) left++;\n else right--;\n }\n return maxArea;\n}", "solution_cpp": "int maxArea(vector& height) {\n int left = 0, right = height.size() - 1, maxArea = 0;\n while (left < right) {\n int h = min(height[left], height[right]);\n maxArea = max(maxArea, h * (right - left));\n if (height[left] < height[right]) left++;\n else right--;\n }\n return maxArea;\n}", "test_cases": ["height=[1,8,6,2,5,4,8,3,7] -> 49"], "key_points": ["移动短边指针", "面积=min(h1,h2)*width"], "tags": ["two-pointers", "medium", "Google", "Uber"]} {"problem_id": "algo_00058", "original_id": "min-stack", "title": "最小栈", "category": "stack", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "设计一个支持 push,pop,top 操作,并能在常数时间内检索到最小元素的栈。", "solution_python": "class MinStack:\n def __init__(self):\n self.stack = []\n self.min_stack = []\n def push(self, val):\n self.stack.append(val)\n self.min_stack.append(min(val, self.min_stack[-1] if self.min_stack else val))\n def pop(self):\n self.stack.pop(); self.min_stack.pop()\n def top(self): return self.stack[-1]\n def getMin(self): return self.min_stack[-1]", "solution_java": "class MinStack {\n Stack stack = new Stack<>();\n Stack minStack = new Stack<>();\n public void push(int val) { stack.push(val); minStack.push(Math.min(val, minStack.isEmpty() ? val : minStack.peek())); }\n public void pop() { stack.pop(); minStack.pop(); }\n public int top() { return stack.peek(); }\n public int getMin() { return minStack.peek(); }\n}", "solution_cpp": "class MinStack {\n stack st, minSt;\npublic:\n void push(int val) { st.push(val); minSt.push(min(val, minSt.empty() ? val : minSt.top())); }\n void pop() { st.pop(); minSt.pop(); }\n int top() { return st.top(); }\n int getMin() { return minSt.top(); }\n};", "test_cases": ["push(-2), push(0), push(-3) -> getMin() returns -3"], "key_points": ["辅助栈记录最小值", "O(1)时间获取最小值"], "tags": ["stack", "medium", "Google", "Microsoft"]} {"problem_id": "algo_00059", "original_id": "lru-cache", "title": "LRU缓存", "category": "design", "difficulty": "hard", "companies": ["Google", "Amazon"], "description": "设计和实现一个 LRU(最近最少使用)缓存机制。", "solution_python": "class LRUCache:\n def __init__(self, capacity):\n self.capacity = capacity\n self.cache = {}\n self.order = []\n def get(self, key):\n if key not in self.cache: return -1\n self.order.remove(key); self.order.append(key)\n return self.cache[key]\n def put(self, key, value):\n if key in self.cache:\n self.order.remove(key)\n elif len(self.cache) >= self.capacity:\n del self.cache[self.order.pop(0)]\n self.cache[key] = value; self.order.append(key)", "solution_java": "class LRUCache {\n int capacity;\n LinkedHashMap cache = new LinkedHashMap<>();\n public LRUCache(int cap) { capacity = cap; }\n public int get(int key) { return cache.containsKey(key) ? cache.remove(key) : -1; }\n public void put(int key, int val) {\n if (cache.containsKey(key)) cache.remove(key);\n else if (cache.size() >= capacity) cache.remove(cache.keySet().iterator().next());\n cache.put(key, val);\n }\n}", "solution_cpp": "class LRUCache {\n int cap;\n list> dll;\n unordered_map>::iterator> cache;\npublic:\n LRUCache(int capacity) : cap(capacity) {}\n int get(int key) {\n auto it = cache.find(key);\n if (it == cache.end()) return -1;\n dll.splice(dll.end(), dll, it->second);\n return it->second->second;\n }\n void put(int key, int value) {\n auto it = cache.find(key);\n if (it != cache.end()) dll.erase(it->second);\n else if (cache.size() >= cap) { cache.erase(dll.front().first); dll.pop_front(); }\n dll.push_back({key, value});\n cache[key] = --dll.end();\n }\n};", "test_cases": ["put(1,1), put(2,2), get(1) -> 1"], "key_points": ["HashMap + 双向链表", "O(1)时间操作"], "tags": ["design", "hard", "Google", "Amazon"]} {"problem_id": "algo_00060", "original_id": "num-islands", "title": "岛屿数量", "category": "graph", "difficulty": "medium", "companies": ["Google", "Facebook"], "description": "给你一个由 '1'(陆地)和 '0'(水)组成的二维网格,请你计算网格中岛屿的数量。岛屿总是被水包围,且只能由水平或垂直方向相邻的陆地连接形成。", "solution_python": "def numIslands(grid):\n if not grid: return 0\n rows, cols = len(grid), len(grid[0])\n count = 0\n def dfs(r, c):\n if r < 0 or r >= rows or c < 0 or c >= cols or grid[r][c] != '1': return\n grid[r][c] = '0'\n dfs(r+1, c); dfs(r-1, c); dfs(r, c+1); dfs(r, c-1)\n for r in range(rows):\n for c in range(cols):\n if grid[r][c] == '1': count += 1; dfs(r, c)\n return count", "solution_java": "public int numIslands(char[][] grid) {\n if (grid.length == 0) return 0;\n int count = 0;\n for (int i = 0; i < grid.length; i++)\n for (int j = 0; j < grid[0].length; j++)\n if (grid[i][j] == '1') { count++; dfs(grid, i, j); }\n return count;\n}\nprivate void dfs(char[][] grid, int r, int c) {\n if (r < 0 || r >= grid.length || c < 0 || c >= grid[0].length || grid[r][c] != '1') return;\n grid[r][c] = '0';\n dfs(grid, r+1, c); dfs(grid, r-1, c); dfs(grid, r, c+1); dfs(grid, r, c-1);\n}", "solution_cpp": "int numIslands(vector>& grid) {\n if (grid.empty()) return 0;\n int count = 0;\n for (int i = 0; i < grid.size(); i++)\n for (int j = 0; j < grid[0].size(); j++)\n if (grid[i][j] == '1') { count++; dfs(grid, i, j); }\n return count;\n}\nvoid dfs(vector>& grid, int r, int c) {\n if (r < 0 || r >= grid.size() || c < 0 || c >= grid[0].size() || grid[r][c] != '1') return;\n grid[r][c] = '0';\n dfs(grid, r+1, c); dfs(grid, r-1, c); dfs(grid, r, c+1); dfs(grid, r, c-1);\n}", "test_cases": ["grid=[[1,1,1,1,0],[1,1,0,1,0],[1,1,0,0,0],[0,0,0,0,0]] -> 1"], "key_points": ["DFS/BFS遍历", "访问后标记为0避免重复"], "tags": ["graph", "medium", "Google", "Facebook"]} {"problem_id": "algo_00061", "original_id": "two-sum", "title": "两数之和", "category": "array", "difficulty": "easy", "companies": ["Amazon", "Google"], "description": "给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那两个整数,并返回他们的数组下标。", "solution_python": "def twoSum(nums, target):\n hashmap = {}\n for i, num in enumerate(nums):\n complement = target - num\n if complement in hashmap:\n return [hashmap[complement], i]\n hashmap[num] = i\n return []", "solution_java": "public int[] twoSum(int[] nums, int target) {\n Map map = new HashMap<>();\n for (int i = 0; i < nums.length; i++) {\n int complement = target - nums[i];\n if (map.containsKey(complement)) return new int[]{map.get(complement), i};\n map.put(nums[i], i);\n }\n return new int[]{};\n}", "solution_cpp": "vector twoSum(vector& nums, int target) {\n unordered_map m;\n for (int i = 0; i < nums.size(); i++) {\n if (m.count(target - nums[i])) return {m[target - nums[i]], i};\n m[nums[i]] = i;\n }\n return {};\n}", "test_cases": ["nums=[2,7,11,15], target=9 -> [0,1]", "nums=[3,2,4], target=6 -> [1,2]"], "key_points": ["哈希表一次遍历", "空间换时间"], "tags": ["array", "easy", "Amazon", "Google"]} {"problem_id": "algo_00062", "original_id": "merge-sorted", "title": "合并两个有序数组", "category": "array", "difficulty": "easy", "companies": ["Microsoft", "Uber"], "description": "给你两个按非递减顺序排列的整数数组 nums1 和 nums2,另有两个整数 m 和 n,分别表示 nums1 和 nums2 中的元素数目。请你合并 nums2 到 nums1 中。", "solution_python": "def merge(nums1, m, nums2, n):\n p1, p2, p = m-1, n-1, m+n-1\n while p1 >= 0 and p2 >= 0:\n if nums1[p1] > nums2[p2]: nums1[p] = nums1[p1]; p1 -= 1\n else: nums1[p] = nums2[p2]; p2 -= 1\n p -= 1\n while p2 >= 0: nums1[p] = nums2[p2]; p2 -= 1; p -= 1", "solution_java": "public void merge(int[] nums1, int m, int[] nums2, int n) {\n int p1 = m-1, p2 = n-1, p = m+n-1;\n while (p1 >= 0 && p2 >= 0) {\n nums1[p--] = nums1[p1] > nums2[p2] ? nums1[p1--] : nums2[p2--];\n }\n while (p2 >= 0) nums1[p--] = nums2[p2--];\n}", "solution_cpp": "void merge(vector& nums1, int m, vector& nums2, int n) {\n int p1 = m-1, p2 = n-1, p = m+n-1;\n while (p1 >= 0 && p2 >= 0) nums1[p--] = nums1[p1] > nums2[p2] ? nums1[p1--] : nums2[p2--];\n while (p2 >= 0) nums1[p--] = nums2[p2--];\n}", "test_cases": ["nums1=[1,2,3], m=3, nums2=[2,5,6], n=3 -> [1,2,2,3,5,6]", "nums1=[], m=0, nums2=[1], n=1 -> [1]"], "key_points": ["从后往前合并", "三指针技巧"], "tags": ["array", "easy", "Microsoft", "Uber"]} {"problem_id": "algo_00063", "original_id": "max-subarray", "title": "最大子数组和", "category": "array", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "给你一个整数数组 nums ,请你找出一个具有最大和的连续子数组,返回其最大和。", "solution_python": "def maxSubArray(nums):\n max_sum = current = nums[0]\n for num in nums[1:]:\n current = max(num, current + num)\n max_sum = max(max_sum, current)\n return max_sum", "solution_java": "public int maxSubArray(int[] nums) {\n int maxSum = nums[0], curr = nums[0];\n for (int i = 1; i < nums.length; i++) {\n curr = Math.max(nums[i], curr + nums[i]);\n maxSum = Math.max(maxSum, curr);\n }\n return maxSum;\n}", "solution_cpp": "int maxSubArray(vector& nums) {\n int maxSum = nums[0], curr = nums[0];\n for (int i = 1; i < nums.size(); i++) {\n curr = max(nums[i], curr + nums[i]);\n maxSum = max(maxSum, curr);\n }\n return maxSum;\n}", "test_cases": ["nums=[-2,1,-3,4,-1,2,1,-5,4] -> 6", "nums=[1] -> 1"], "key_points": ["Kadane算法", "动态规划基础题"], "tags": ["array", "medium", "Google", "Microsoft"]} {"problem_id": "algo_00064", "original_id": "valid-parentheses", "title": "有效的括号", "category": "string", "difficulty": "easy", "companies": ["Google", "Uber"], "description": "给定一个只包括 '(',')','{','}','[',']' 的字符串 s,判断字符串是否有效。", "solution_python": "def isValid(s):\n stack = []\n mapping = {')': '(', ']': '[', '}': '{'}\n for c in s:\n if c in mapping:\n if not stack or stack[-1] != mapping[c]: return False\n stack.pop()\n else: stack.append(c)\n return not stack", "solution_java": "public boolean isValid(String s) {\n Stack stack = new Stack<>();\n Map map = Map.of(')', '(', ']', '[', '}', '{');\n for (char c : s.toCharArray()) {\n if (map.containsValue(c)) stack.push(c);\n else if (!stack.isEmpty() && stack.pop() != map.get(c)) return false;\n }\n return stack.isEmpty();\n}", "solution_cpp": "bool isValid(string s) {\n stack st;\n unordered_map m = {{')','('},{']','['},{'}','{'}};\n for (char c : s) {\n if (m.find(c) == m.end()) st.push(c);\n else if (st.empty() || st.top() != m[c]) return false;\n else st.pop();\n }\n return st.empty();\n}", "test_cases": ["s=\"()\" -> true", "s=\"()[]{}\" -> true", "s=\"(]\" -> false"], "key_points": ["栈匹配法", "注意空栈边界"], "tags": ["string", "easy", "Google", "Uber"]} {"problem_id": "algo_00065", "original_id": "longest-palindrome", "title": "最长回文子串", "category": "string", "difficulty": "medium", "companies": ["Google", "Amazon"], "description": "给你一个字符串 s,找到 s 中最长的回文子串。", "solution_python": "def longestPalindrome(s):\n def expand(l, r):\n while l >= 0 and r < len(s) and s[l] == s[r]: l -= 1; r += 1\n return l + 1, r - 1\n start = end = 0\n for i in range(len(s)):\n l1, r1 = expand(i, i)\n l2, r2 = expand(i, i + 1)\n if r1 - l1 > end - start: start, end = l1, r1\n if r2 - l2 > end - start: start, end = l2, r2\n return s[start:end+1]", "solution_java": "public String longestPalindrome(String s) {\n int start = 0, end = 0;\n for (int i = 0; i < s.length(); i++) {\n int len1 = expand(s, i, i), len2 = expand(s, i, i+1);\n int len = Math.max(len1, len2);\n if (len > end - start) { start = i - (len-1)/2; end = i + len/2; }\n }\n return s.substring(start, end + 1);\n}\nprivate int expand(String s, int l, int r) {\n while (l >= 0 && r < s.length() && s.charAt(l) == s.charAt(r)) { l--; r++; }\n return r - l - 1;\n}", "solution_cpp": "string longestPalindrome(string s) {\n int start = 0, end = 0;\n for (int i = 0; i < s.size(); i++) {\n int len1 = expand(s, i, i), len2 = expand(s, i, i+1);\n if (max(len1, len2) > end - start) { start = i - (max(len1,len2)-1)/2; end = i + max(len1,len2)/2; }\n }\n return s.substr(start, end - start + 1);\n}", "test_cases": ["s=\"babad\" -> bab或aba", "s=\"cbbd\" -> bb"], "key_points": ["中心扩展法", "处理奇偶长度"], "tags": ["string", "medium", "Google", "Amazon"]} {"problem_id": "algo_00066", "original_id": "reverse-list", "title": "反转链表", "category": "linkedlist", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "给你单链表的头节点 head,请你反转链表,并返回反转后的链表。", "solution_python": "def reverseList(head):\n prev = None\n curr = head\n while curr:\n nxt = curr.next\n curr.next = prev\n prev = curr\n curr = nxt\n return prev", "solution_java": "public ListNode reverseList(ListNode head) {\n ListNode prev = null, curr = head;\n while (curr != null) {\n ListNode next = curr.next;\n curr.next = prev;\n prev = curr;\n curr = next;\n }\n return prev;\n}", "solution_cpp": "ListNode* reverseList(ListNode* head) {\n ListNode* prev = nullptr, *curr = head;\n while (curr) {\n ListNode* next = curr->next;\n curr->next = prev;\n prev = curr;\n curr = next;\n }\n return prev;\n}", "test_cases": ["head=[1,2,3,4,5] -> [5,4,3,2,1]", "head=[1,2] -> [2,1]"], "key_points": ["迭代法 O(1)空间", "递归法 O(n)空间"], "tags": ["linkedlist", "medium", "Google", "Microsoft"]} {"problem_id": "algo_00067", "original_id": "middle-node", "title": "链表的中间结点", "category": "linkedlist", "difficulty": "easy", "companies": ["Amazon", "Facebook"], "description": "给你单链表的头节点 head,请你找出并返回链表的中间结点。如果有两个中间结点,则返回第二个中间结点。", "solution_python": "def middleNode(head):\n slow = fast = head\n while fast and fast.next:\n slow = slow.next\n fast = fast.next.next\n return slow", "solution_java": "public ListNode middleNode(ListNode head) {\n ListNode slow = head, fast = head;\n while (fast != null && fast.next != null) {\n slow = slow.next;\n fast = fast.next.next;\n }\n return slow;\n}", "solution_cpp": "ListNode* middleNode(ListNode* head) {\n ListNode* slow = head, *fast = head;\n while (fast && fast->next) { slow = slow->next; fast = fast->next->next; }\n return slow;\n}", "test_cases": ["head=[1,2,3,4,5] -> 3", "head=[1,2,3,4,5,6] -> 4"], "key_points": ["快慢指针", "O(n)时间O(1)空间"], "tags": ["linkedlist", "easy", "Amazon", "Facebook"]} {"problem_id": "algo_00068", "original_id": "max-depth", "title": "二叉树的最大深度", "category": "tree", "difficulty": "easy", "companies": ["Microsoft", "Apple"], "description": "给定一个二叉树 root,返回其最大深度。", "solution_python": "def maxDepth(root):\n if not root: return 0\n return max(maxDepth(root.left), maxDepth(root.right)) + 1", "solution_java": "public int maxDepth(TreeNode root) {\n if (root == null) return 0;\n return Math.max(maxDepth(root.left), maxDepth(root.right)) + 1;\n}", "solution_cpp": "int maxDepth(TreeNode* root) {\n if (!root) return 0;\n return max(maxDepth(root->left), maxDepth(root->right)) + 1;\n}", "test_cases": ["root=[3,9,20,null,null,15,7] -> 3", "root=[1,null,2] -> 2"], "key_points": ["DFS递归", "层序遍历也可"], "tags": ["tree", "easy", "Microsoft", "Apple"]} {"problem_id": "algo_00069", "original_id": "inorder-traversal", "title": "二叉树的中序遍历", "category": "tree", "difficulty": "easy", "companies": ["Google", "Microsoft"], "description": "给定一个二叉树的根节点 root,返回它的中序遍历结果。", "solution_python": "def inorderTraversal(root):\n result = []\n def dfs(node):\n if node:\n dfs(node.left)\n result.append(node.val)\n dfs(node.right)\n dfs(root)\n return result", "solution_java": "public List inorderTraversal(TreeNode root) {\n List res = new ArrayList<>();\n dfs(root, res);\n return res;\n}\nprivate void dfs(TreeNode node, List res) {\n if (node == null) return;\n dfs(node.left, res); res.add(node.val); dfs(node.right, res);\n}", "solution_cpp": "vector inorderTraversal(TreeNode* root) {\n vector res;\n dfs(root, res);\n return res;\n}\nvoid dfs(TreeNode* node, vector& res) {\n if (!node) return;\n dfs(node->left, res); res.push_back(node->val); dfs(node->right, res);\n}", "test_cases": ["root=[1,null,2,3] -> [1,3,2]", "root=[] -> []"], "key_points": ["左-根-右顺序", "递归最简洁"], "tags": ["tree", "easy", "Google", "Microsoft"]} {"problem_id": "algo_00070", "original_id": "binary-search", "title": "二分查找", "category": "binarysearch", "difficulty": "easy", "companies": ["Google", "Amazon"], "description": "给定一个 n 个元素有序的(升序)整型数组 nums 和一个目标值 target,写一个函数搜索 nums 中的 target,如果目标值存在返回下标,否则返回 -1。", "solution_python": "def search(nums, target):\n left, right = 0, len(nums) - 1\n while left <= right:\n mid = (left + right) // 2\n if nums[mid] == target: return mid\n elif nums[mid] < target: left = mid + 1\n else: right = mid - 1\n return -1", "solution_java": "public int search(int[] nums, int target) {\n int left = 0, right = nums.length - 1;\n while (left <= right) {\n int mid = left + (right - left) / 2;\n if (nums[mid] == target) return mid;\n else if (nums[mid] < target) left = mid + 1;\n else right = mid - 1;\n }\n return -1;\n}", "solution_cpp": "int search(vector& nums, int target) {\n int left = 0, right = nums.size() - 1;\n while (left <= right) {\n int mid = left + (right - left) / 2;\n if (nums[mid] == target) return mid;\n else if (nums[mid] < target) left = mid + 1;\n else right = mid - 1;\n }\n return -1;\n}", "test_cases": ["nums=[-1,0,3,5,9,12], target=9 -> 4", "nums=[-1,0,3,5,9,12], target=2 -> -1"], "key_points": ["标准模板", "注意防溢出写法"], "tags": ["binarysearch", "easy", "Google", "Amazon"]} {"problem_id": "algo_00071", "original_id": "climbing-stairs", "title": "爬楼梯", "category": "dp", "difficulty": "easy", "companies": ["Amazon", "Google"], "description": "假设你正在爬楼梯。需要 n 阶你才能到达楼顶。每次你可以爬 1 或 2 个台阶。你有多少种不同的方法可以爬到楼顶?", "solution_python": "def climbStairs(n):\n if n <= 2: return n\n a, b = 1, 2\n for _ in range(3, n+1):\n a, b = b, a + b\n return b", "solution_java": "public int climbStairs(int n) {\n if (n <= 2) return n;\n int a = 1, b = 2;\n for (int i = 3; i <= n; i++) { int temp = a + b; a = b; b = temp; }\n return b;\n}", "solution_cpp": "int climbStairs(int n) {\n if (n <= 2) return n;\n int a = 1, b = 2;\n for (int i = 3; i <= n; i++) { int temp = a + b; a = b; b = temp; }\n return b;\n}", "test_cases": ["n=2 -> 2", "n=3 -> 3", "n=5 -> 8"], "key_points": ["斐波那契数列", "滚动数组优化空间"], "tags": ["dp", "easy", "Amazon", "Google"]} {"problem_id": "algo_00072", "original_id": "coin-change", "title": "零钱兑换", "category": "dp", "difficulty": "medium", "companies": ["Google", "Amazon"], "description": "给你一个整数数组 coins 表示不同面额的硬币,以及一个整数 amount 表示总金额。计算并返回可以凑成总金额所需的最少的硬币个数。如果没有任何一种硬币组合能组成总金额,返回 -1。", "solution_python": "def coinChange(coins, amount):\n dp = [float('inf')] * (amount + 1)\n dp[0] = 0\n for coin in coins:\n for x in range(coin, amount + 1):\n dp[x] = min(dp[x], dp[x - coin] + 1)\n return dp[amount] if dp[amount] != float('inf') else -1", "solution_java": "public int coinChange(int[] coins, int amount) {\n int[] dp = new int[amount + 1];\n Arrays.fill(dp, amount + 1);\n dp[0] = 0;\n for (int coin : coins) {\n for (int x = coin; x <= amount; x++) {\n dp[x] = Math.min(dp[x], dp[x - coin] + 1);\n }\n }\n return dp[amount] > amount ? -1 : dp[amount];\n}", "solution_cpp": "int coinChange(vector& coins, int amount) {\n vector dp(amount + 1, amount + 1);\n dp[0] = 0;\n for (int coin : coins) {\n for (int x = coin; x <= amount; x++) {\n dp[x] = min(dp[x], dp[x - coin] + 1);\n }\n }\n return dp[amount] > amount ? -1 : dp[amount];\n}", "test_cases": ["coins=[1,2,5], amount=11 -> 3", "coins=[2], amount=3 -> -1"], "key_points": ["完全背包问题", "dp[x] = min(dp[x-coin]+1)"], "tags": ["dp", "medium", "Google", "Amazon"]} {"problem_id": "algo_00073", "original_id": "subsets", "title": "子集", "category": "backtracking", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "给你一个整数数组 nums ,数组中的元素 互不相同 。返回该数组所有可能的子集(幂集)。", "solution_python": "def subsets(nums):\n result = []\n def backtrack(start, path):\n result.append(path[:])\n for i in range(start, len(nums)):\n path.append(nums[i])\n backtrack(i + 1, path)\n path.pop()\n backtrack(0, [])\n return result", "solution_java": "public List> subsets(int[] nums) {\n List> result = new ArrayList<>();\n backtrack(nums, 0, new ArrayList<>(), result);\n return result;\n}\nprivate void backtrack(int[] nums, int start, List path, List> result) {\n result.add(new ArrayList<>(path));\n for (int i = start; i < nums.length; i++) {\n path.add(nums[i]);\n backtrack(nums, i + 1, path, result);\n path.remove(path.size() - 1);\n }\n}", "solution_cpp": "vector> subsets(vector& nums) {\n vector> result;\n vector path;\n backtrack(nums, 0, path, result);\n return result;\n}\nvoid backtrack(vector& nums, int start, vector& path, vector>& result) {\n result.push_back(path);\n for (int i = start; i < nums.size(); i++) {\n path.push_back(nums[i]);\n backtrack(nums, i + 1, path, result);\n path.pop_back();\n }\n}", "test_cases": ["nums=[1,2,3] -> [[],[1],[2],[1,2],[3],[1,3],[2,3],[1,2,3]]"], "key_points": ["选或不选", "DFS遍历子集树"], "tags": ["backtracking", "medium", "Google", "Microsoft"]} {"problem_id": "algo_00074", "original_id": "permutations", "title": "全排列", "category": "backtracking", "difficulty": "medium", "companies": ["Google", "Facebook"], "description": "给定一个不含重复数字的数组 nums,返回其所有可能的全排列。", "solution_python": "def permute(nums):\n result = []\n def backtrack(path, used):\n if len(path) == len(nums):\n result.append(path[:])\n return\n for i in range(len(nums)):\n if used[i]: continue\n used[i] = True\n path.append(nums[i])\n backtrack(path, used)\n path.pop()\n used[i] = False\n backtrack([], [False]*len(nums))\n return result", "solution_java": "public List> permute(int[] nums) {\n List> result = new ArrayList<>();\n boolean[] used = new boolean[nums.length];\n backtrack(nums, used, new ArrayList<>(), result);\n return result;\n}\nprivate void backtrack(int[] nums, boolean[] used, List path, List> result) {\n if (path.size() == nums.length) { result.add(new ArrayList<>(path)); return; }\n for (int i = 0; i < nums.length; i++) {\n if (used[i]) continue;\n used[i] = true;\n path.add(nums[i]);\n backtrack(nums, used, path, result);\n path.remove(path.size() - 1);\n used[i] = false;\n }\n}", "solution_cpp": "vector> permute(vector& nums) {\n vector> result;\n vector used(nums.size(), false);\n vector path;\n backtrack(nums, used, path, result);\n return result;\n}\nvoid backtrack(vector& nums, vector& used, vector& path, vector>& result) {\n if (path.size() == nums.size()) { result.push_back(path); return; }\n for (int i = 0; i < nums.size(); i++) {\n if (used[i]) continue;\n used[i] = true;\n path.push_back(nums[i]);\n backtrack(nums, used, path, result);\n path.pop_back();\n used[i] = false;\n }\n}", "test_cases": ["nums=[1,2,3] -> [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]"], "key_points": ["标记已使用元素", "回溯经典模板"], "tags": ["backtracking", "medium", "Google", "Facebook"]} {"problem_id": "algo_00075", "original_id": "top-k-frequent", "title": "前K个高频元素", "category": "heap", "difficulty": "medium", "companies": ["Amazon", "Facebook"], "description": "给你一个整数数组 nums 和一个整数 k,请你返回其中出现频率前 k 高的元素。", "solution_python": "import heapq\nfrom collections import Counter\ndef topKFrequent(nums, k):\n count = Counter(nums)\n heap = []\n for num, freq in count.items():\n heapq.heappush(heap, (freq, num))\n if len(heap) > k: heapq.heappop(heap)\n return [num for freq, num in heap]", "solution_java": "public int[] topKFrequent(int[] nums, int k) {\n Map count = new HashMap<>();\n for (int n : nums) count.put(n, count.getOrDefault(n, 0) + 1);\n PriorityQueue> heap = \n new PriorityQueue<>((a, b) -> a.getValue() - b.getValue());\n for (Map.Entry e : count.entrySet()) {\n heap.offer(e);\n if (heap.size() > k) heap.poll();\n }\n int[] res = new int[k];\n for (int i = k - 1; i >= 0; i--) res[i] = heap.poll().getKey();\n return res;\n}", "solution_cpp": "vector topKFrequent(vector& nums, int k) {\n unordered_map count;\n for (int n : nums) count[n]++;\n priority_queue, vector>, greater>> heap;\n for (auto& [num, freq] : count) {\n heap.push({freq, num});\n if (heap.size() > k) heap.pop();\n }\n vector res;\n while (!heap.empty()) { res.push_back(heap.top().second); heap.pop(); }\n reverse(res.begin(), res.end());\n return res;\n}", "test_cases": ["nums=[1,1,1,2,2,3], k=2 -> [1,2]", "nums=[1], k=1 -> [1]"], "key_points": ["小顶堆保持大小k", "时间复杂度O(nlogk)"], "tags": ["heap", "medium", "Amazon", "Facebook"]} {"problem_id": "algo_00076", "original_id": "3sum", "title": "三数之和", "category": "two-pointers", "difficulty": "medium", "companies": ["Google", "Amazon"], "description": "给你一个整数数组 nums,判断是否存在三元组满足和为0,返回所有不重复的三元组。", "solution_python": "def threeSum(nums):\n nums.sort()\n result = []\n for i in range(len(nums) - 2):\n if i > 0 and nums[i] == nums[i-1]: continue\n left, right = i + 1, len(nums) - 1\n while left < right:\n total = nums[i] + nums[left] + nums[right]\n if total < 0: left += 1\n elif total > 0: right -= 1\n else:\n result.append([nums[i], nums[left], nums[right]])\n while left < right and nums[left] == nums[left+1]: left += 1\n while left < right and nums[right] == nums[right-1]: right -= 1\n left += 1; right -= 1\n return result", "solution_java": "public List> threeSum(int[] nums) {\n Arrays.sort(nums);\n List> result = new ArrayList<>();\n for (int i = 0; i < nums.length - 2; i++) {\n if (i > 0 && nums[i] == nums[i-1]) continue;\n int left = i + 1, right = nums.length - 1;\n while (left < right) {\n int total = nums[i] + nums[left] + nums[right];\n if (total < 0) left++;\n else if (total > 0) right--;\n else {\n result.add(Arrays.asList(nums[i], nums[left], nums[right]));\n while (left < right && nums[left] == nums[left+1]) left++;\n while (left < right && nums[right] == nums[right-1]) right--;\n left++; right--;\n }\n }\n }\n return result;\n}", "solution_cpp": "vector> threeSum(vector& nums) {\n sort(nums.begin(), nums.end());\n vector> result;\n for (int i = 0; i < nums.size() - 2; i++) {\n if (i > 0 && nums[i] == nums[i-1]) continue;\n int left = i + 1, right = nums.size() - 1;\n while (left < right) {\n int total = nums[i] + nums[left] + nums[right];\n if (total < 0) left++;\n else if (total > 0) right--;\n else {\n result.push_back({nums[i], nums[left], nums[right]});\n while (left < right && nums[left] == nums[left+1]) left++;\n while (left < right && nums[right] == nums[right-1]) right--;\n left++; right--;\n }\n }\n }\n return result;\n}", "test_cases": ["nums=[-1,0,1,2,-1,-4] -> [[-1,-1,2],[-1,0,1]]"], "key_points": ["排序+双指针", "去重是关键"], "tags": ["two-pointers", "medium", "Google", "Amazon"]} {"problem_id": "algo_00077", "original_id": "container-water", "title": "盛最多水的容器", "category": "two-pointers", "difficulty": "medium", "companies": ["Google", "Uber"], "description": "给定一个长度为 n 的整数数组 height,找出其中的两条线,使得它们与 x 轴共同构成的容器可以容纳最多的水。", "solution_python": "def maxArea(height):\n left, right = 0, len(height) - 1\n max_area = 0\n while left < right:\n h = min(height[left], height[right])\n max_area = max(max_area, h * (right - left))\n if height[left] < height[right]: left += 1\n else: right -= 1\n return max_area", "solution_java": "public int maxArea(int[] height) {\n int left = 0, right = height.length - 1, maxArea = 0;\n while (left < right) {\n int h = Math.min(height[left], height[right]);\n maxArea = Math.max(maxArea, h * (right - left));\n if (height[left] < height[right]) left++;\n else right--;\n }\n return maxArea;\n}", "solution_cpp": "int maxArea(vector& height) {\n int left = 0, right = height.size() - 1, maxArea = 0;\n while (left < right) {\n int h = min(height[left], height[right]);\n maxArea = max(maxArea, h * (right - left));\n if (height[left] < height[right]) left++;\n else right--;\n }\n return maxArea;\n}", "test_cases": ["height=[1,8,6,2,5,4,8,3,7] -> 49"], "key_points": ["移动短边指针", "面积=min(h1,h2)*width"], "tags": ["two-pointers", "medium", "Google", "Uber"]} {"problem_id": "algo_00078", "original_id": "min-stack", "title": "最小栈", "category": "stack", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "设计一个支持 push,pop,top 操作,并能在常数时间内检索到最小元素的栈。", "solution_python": "class MinStack:\n def __init__(self):\n self.stack = []\n self.min_stack = []\n def push(self, val):\n self.stack.append(val)\n self.min_stack.append(min(val, self.min_stack[-1] if self.min_stack else val))\n def pop(self):\n self.stack.pop(); self.min_stack.pop()\n def top(self): return self.stack[-1]\n def getMin(self): return self.min_stack[-1]", "solution_java": "class MinStack {\n Stack stack = new Stack<>();\n Stack minStack = new Stack<>();\n public void push(int val) { stack.push(val); minStack.push(Math.min(val, minStack.isEmpty() ? val : minStack.peek())); }\n public void pop() { stack.pop(); minStack.pop(); }\n public int top() { return stack.peek(); }\n public int getMin() { return minStack.peek(); }\n}", "solution_cpp": "class MinStack {\n stack st, minSt;\npublic:\n void push(int val) { st.push(val); minSt.push(min(val, minSt.empty() ? val : minSt.top())); }\n void pop() { st.pop(); minSt.pop(); }\n int top() { return st.top(); }\n int getMin() { return minSt.top(); }\n};", "test_cases": ["push(-2), push(0), push(-3) -> getMin() returns -3"], "key_points": ["辅助栈记录最小值", "O(1)时间获取最小值"], "tags": ["stack", "medium", "Google", "Microsoft"]} {"problem_id": "algo_00079", "original_id": "lru-cache", "title": "LRU缓存", "category": "design", "difficulty": "hard", "companies": ["Google", "Amazon"], "description": "设计和实现一个 LRU(最近最少使用)缓存机制。", "solution_python": "class LRUCache:\n def __init__(self, capacity):\n self.capacity = capacity\n self.cache = {}\n self.order = []\n def get(self, key):\n if key not in self.cache: return -1\n self.order.remove(key); self.order.append(key)\n return self.cache[key]\n def put(self, key, value):\n if key in self.cache:\n self.order.remove(key)\n elif len(self.cache) >= self.capacity:\n del self.cache[self.order.pop(0)]\n self.cache[key] = value; self.order.append(key)", "solution_java": "class LRUCache {\n int capacity;\n LinkedHashMap cache = new LinkedHashMap<>();\n public LRUCache(int cap) { capacity = cap; }\n public int get(int key) { return cache.containsKey(key) ? cache.remove(key) : -1; }\n public void put(int key, int val) {\n if (cache.containsKey(key)) cache.remove(key);\n else if (cache.size() >= capacity) cache.remove(cache.keySet().iterator().next());\n cache.put(key, val);\n }\n}", "solution_cpp": "class LRUCache {\n int cap;\n list> dll;\n unordered_map>::iterator> cache;\npublic:\n LRUCache(int capacity) : cap(capacity) {}\n int get(int key) {\n auto it = cache.find(key);\n if (it == cache.end()) return -1;\n dll.splice(dll.end(), dll, it->second);\n return it->second->second;\n }\n void put(int key, int value) {\n auto it = cache.find(key);\n if (it != cache.end()) dll.erase(it->second);\n else if (cache.size() >= cap) { cache.erase(dll.front().first); dll.pop_front(); }\n dll.push_back({key, value});\n cache[key] = --dll.end();\n }\n};", "test_cases": ["put(1,1), put(2,2), get(1) -> 1"], "key_points": ["HashMap + 双向链表", "O(1)时间操作"], "tags": ["design", "hard", "Google", "Amazon"]} {"problem_id": "algo_00080", "original_id": "num-islands", "title": "岛屿数量", "category": "graph", "difficulty": "medium", "companies": ["Google", "Facebook"], "description": "给你一个由 '1'(陆地)和 '0'(水)组成的二维网格,请你计算网格中岛屿的数量。岛屿总是被水包围,且只能由水平或垂直方向相邻的陆地连接形成。", "solution_python": "def numIslands(grid):\n if not grid: return 0\n rows, cols = len(grid), len(grid[0])\n count = 0\n def dfs(r, c):\n if r < 0 or r >= rows or c < 0 or c >= cols or grid[r][c] != '1': return\n grid[r][c] = '0'\n dfs(r+1, c); dfs(r-1, c); dfs(r, c+1); dfs(r, c-1)\n for r in range(rows):\n for c in range(cols):\n if grid[r][c] == '1': count += 1; dfs(r, c)\n return count", "solution_java": "public int numIslands(char[][] grid) {\n if (grid.length == 0) return 0;\n int count = 0;\n for (int i = 0; i < grid.length; i++)\n for (int j = 0; j < grid[0].length; j++)\n if (grid[i][j] == '1') { count++; dfs(grid, i, j); }\n return count;\n}\nprivate void dfs(char[][] grid, int r, int c) {\n if (r < 0 || r >= grid.length || c < 0 || c >= grid[0].length || grid[r][c] != '1') return;\n grid[r][c] = '0';\n dfs(grid, r+1, c); dfs(grid, r-1, c); dfs(grid, r, c+1); dfs(grid, r, c-1);\n}", "solution_cpp": "int numIslands(vector>& grid) {\n if (grid.empty()) return 0;\n int count = 0;\n for (int i = 0; i < grid.size(); i++)\n for (int j = 0; j < grid[0].size(); j++)\n if (grid[i][j] == '1') { count++; dfs(grid, i, j); }\n return count;\n}\nvoid dfs(vector>& grid, int r, int c) {\n if (r < 0 || r >= grid.size() || c < 0 || c >= grid[0].size() || grid[r][c] != '1') return;\n grid[r][c] = '0';\n dfs(grid, r+1, c); dfs(grid, r-1, c); dfs(grid, r, c+1); dfs(grid, r, c-1);\n}", "test_cases": ["grid=[[1,1,1,1,0],[1,1,0,1,0],[1,1,0,0,0],[0,0,0,0,0]] -> 1"], "key_points": ["DFS/BFS遍历", "访问后标记为0避免重复"], "tags": ["graph", "medium", "Google", "Facebook"]} {"problem_id": "algo_00081", "original_id": "two-sum", "title": "两数之和", "category": "array", "difficulty": "easy", "companies": ["Amazon", "Google"], "description": "给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那两个整数,并返回他们的数组下标。", "solution_python": "def twoSum(nums, target):\n hashmap = {}\n for i, num in enumerate(nums):\n complement = target - num\n if complement in hashmap:\n return [hashmap[complement], i]\n hashmap[num] = i\n return []", "solution_java": "public int[] twoSum(int[] nums, int target) {\n Map map = new HashMap<>();\n for (int i = 0; i < nums.length; i++) {\n int complement = target - nums[i];\n if (map.containsKey(complement)) return new int[]{map.get(complement), i};\n map.put(nums[i], i);\n }\n return new int[]{};\n}", "solution_cpp": "vector twoSum(vector& nums, int target) {\n unordered_map m;\n for (int i = 0; i < nums.size(); i++) {\n if (m.count(target - nums[i])) return {m[target - nums[i]], i};\n m[nums[i]] = i;\n }\n return {};\n}", "test_cases": ["nums=[2,7,11,15], target=9 -> [0,1]", "nums=[3,2,4], target=6 -> [1,2]"], "key_points": ["哈希表一次遍历", "空间换时间"], "tags": ["array", "easy", "Amazon", "Google"]} {"problem_id": "algo_00082", "original_id": "merge-sorted", "title": "合并两个有序数组", "category": "array", "difficulty": "easy", "companies": ["Microsoft", "Uber"], "description": "给你两个按非递减顺序排列的整数数组 nums1 和 nums2,另有两个整数 m 和 n,分别表示 nums1 和 nums2 中的元素数目。请你合并 nums2 到 nums1 中。", "solution_python": "def merge(nums1, m, nums2, n):\n p1, p2, p = m-1, n-1, m+n-1\n while p1 >= 0 and p2 >= 0:\n if nums1[p1] > nums2[p2]: nums1[p] = nums1[p1]; p1 -= 1\n else: nums1[p] = nums2[p2]; p2 -= 1\n p -= 1\n while p2 >= 0: nums1[p] = nums2[p2]; p2 -= 1; p -= 1", "solution_java": "public void merge(int[] nums1, int m, int[] nums2, int n) {\n int p1 = m-1, p2 = n-1, p = m+n-1;\n while (p1 >= 0 && p2 >= 0) {\n nums1[p--] = nums1[p1] > nums2[p2] ? nums1[p1--] : nums2[p2--];\n }\n while (p2 >= 0) nums1[p--] = nums2[p2--];\n}", "solution_cpp": "void merge(vector& nums1, int m, vector& nums2, int n) {\n int p1 = m-1, p2 = n-1, p = m+n-1;\n while (p1 >= 0 && p2 >= 0) nums1[p--] = nums1[p1] > nums2[p2] ? nums1[p1--] : nums2[p2--];\n while (p2 >= 0) nums1[p--] = nums2[p2--];\n}", "test_cases": ["nums1=[1,2,3], m=3, nums2=[2,5,6], n=3 -> [1,2,2,3,5,6]", "nums1=[], m=0, nums2=[1], n=1 -> [1]"], "key_points": ["从后往前合并", "三指针技巧"], "tags": ["array", "easy", "Microsoft", "Uber"]} {"problem_id": "algo_00083", "original_id": "max-subarray", "title": "最大子数组和", "category": "array", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "给你一个整数数组 nums ,请你找出一个具有最大和的连续子数组,返回其最大和。", "solution_python": "def maxSubArray(nums):\n max_sum = current = nums[0]\n for num in nums[1:]:\n current = max(num, current + num)\n max_sum = max(max_sum, current)\n return max_sum", "solution_java": "public int maxSubArray(int[] nums) {\n int maxSum = nums[0], curr = nums[0];\n for (int i = 1; i < nums.length; i++) {\n curr = Math.max(nums[i], curr + nums[i]);\n maxSum = Math.max(maxSum, curr);\n }\n return maxSum;\n}", "solution_cpp": "int maxSubArray(vector& nums) {\n int maxSum = nums[0], curr = nums[0];\n for (int i = 1; i < nums.size(); i++) {\n curr = max(nums[i], curr + nums[i]);\n maxSum = max(maxSum, curr);\n }\n return maxSum;\n}", "test_cases": ["nums=[-2,1,-3,4,-1,2,1,-5,4] -> 6", "nums=[1] -> 1"], "key_points": ["Kadane算法", "动态规划基础题"], "tags": ["array", "medium", "Google", "Microsoft"]} {"problem_id": "algo_00084", "original_id": "valid-parentheses", "title": "有效的括号", "category": "string", "difficulty": "easy", "companies": ["Google", "Uber"], "description": "给定一个只包括 '(',')','{','}','[',']' 的字符串 s,判断字符串是否有效。", "solution_python": "def isValid(s):\n stack = []\n mapping = {')': '(', ']': '[', '}': '{'}\n for c in s:\n if c in mapping:\n if not stack or stack[-1] != mapping[c]: return False\n stack.pop()\n else: stack.append(c)\n return not stack", "solution_java": "public boolean isValid(String s) {\n Stack stack = new Stack<>();\n Map map = Map.of(')', '(', ']', '[', '}', '{');\n for (char c : s.toCharArray()) {\n if (map.containsValue(c)) stack.push(c);\n else if (!stack.isEmpty() && stack.pop() != map.get(c)) return false;\n }\n return stack.isEmpty();\n}", "solution_cpp": "bool isValid(string s) {\n stack st;\n unordered_map m = {{')','('},{']','['},{'}','{'}};\n for (char c : s) {\n if (m.find(c) == m.end()) st.push(c);\n else if (st.empty() || st.top() != m[c]) return false;\n else st.pop();\n }\n return st.empty();\n}", "test_cases": ["s=\"()\" -> true", "s=\"()[]{}\" -> true", "s=\"(]\" -> false"], "key_points": ["栈匹配法", "注意空栈边界"], "tags": ["string", "easy", "Google", "Uber"]} {"problem_id": "algo_00085", "original_id": "longest-palindrome", "title": "最长回文子串", "category": "string", "difficulty": "medium", "companies": ["Google", "Amazon"], "description": "给你一个字符串 s,找到 s 中最长的回文子串。", "solution_python": "def longestPalindrome(s):\n def expand(l, r):\n while l >= 0 and r < len(s) and s[l] == s[r]: l -= 1; r += 1\n return l + 1, r - 1\n start = end = 0\n for i in range(len(s)):\n l1, r1 = expand(i, i)\n l2, r2 = expand(i, i + 1)\n if r1 - l1 > end - start: start, end = l1, r1\n if r2 - l2 > end - start: start, end = l2, r2\n return s[start:end+1]", "solution_java": "public String longestPalindrome(String s) {\n int start = 0, end = 0;\n for (int i = 0; i < s.length(); i++) {\n int len1 = expand(s, i, i), len2 = expand(s, i, i+1);\n int len = Math.max(len1, len2);\n if (len > end - start) { start = i - (len-1)/2; end = i + len/2; }\n }\n return s.substring(start, end + 1);\n}\nprivate int expand(String s, int l, int r) {\n while (l >= 0 && r < s.length() && s.charAt(l) == s.charAt(r)) { l--; r++; }\n return r - l - 1;\n}", "solution_cpp": "string longestPalindrome(string s) {\n int start = 0, end = 0;\n for (int i = 0; i < s.size(); i++) {\n int len1 = expand(s, i, i), len2 = expand(s, i, i+1);\n if (max(len1, len2) > end - start) { start = i - (max(len1,len2)-1)/2; end = i + max(len1,len2)/2; }\n }\n return s.substr(start, end - start + 1);\n}", "test_cases": ["s=\"babad\" -> bab或aba", "s=\"cbbd\" -> bb"], "key_points": ["中心扩展法", "处理奇偶长度"], "tags": ["string", "medium", "Google", "Amazon"]} {"problem_id": "algo_00086", "original_id": "reverse-list", "title": "反转链表", "category": "linkedlist", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "给你单链表的头节点 head,请你反转链表,并返回反转后的链表。", "solution_python": "def reverseList(head):\n prev = None\n curr = head\n while curr:\n nxt = curr.next\n curr.next = prev\n prev = curr\n curr = nxt\n return prev", "solution_java": "public ListNode reverseList(ListNode head) {\n ListNode prev = null, curr = head;\n while (curr != null) {\n ListNode next = curr.next;\n curr.next = prev;\n prev = curr;\n curr = next;\n }\n return prev;\n}", "solution_cpp": "ListNode* reverseList(ListNode* head) {\n ListNode* prev = nullptr, *curr = head;\n while (curr) {\n ListNode* next = curr->next;\n curr->next = prev;\n prev = curr;\n curr = next;\n }\n return prev;\n}", "test_cases": ["head=[1,2,3,4,5] -> [5,4,3,2,1]", "head=[1,2] -> [2,1]"], "key_points": ["迭代法 O(1)空间", "递归法 O(n)空间"], "tags": ["linkedlist", "medium", "Google", "Microsoft"]} {"problem_id": "algo_00087", "original_id": "middle-node", "title": "链表的中间结点", "category": "linkedlist", "difficulty": "easy", "companies": ["Amazon", "Facebook"], "description": "给你单链表的头节点 head,请你找出并返回链表的中间结点。如果有两个中间结点,则返回第二个中间结点。", "solution_python": "def middleNode(head):\n slow = fast = head\n while fast and fast.next:\n slow = slow.next\n fast = fast.next.next\n return slow", "solution_java": "public ListNode middleNode(ListNode head) {\n ListNode slow = head, fast = head;\n while (fast != null && fast.next != null) {\n slow = slow.next;\n fast = fast.next.next;\n }\n return slow;\n}", "solution_cpp": "ListNode* middleNode(ListNode* head) {\n ListNode* slow = head, *fast = head;\n while (fast && fast->next) { slow = slow->next; fast = fast->next->next; }\n return slow;\n}", "test_cases": ["head=[1,2,3,4,5] -> 3", "head=[1,2,3,4,5,6] -> 4"], "key_points": ["快慢指针", "O(n)时间O(1)空间"], "tags": ["linkedlist", "easy", "Amazon", "Facebook"]} {"problem_id": "algo_00088", "original_id": "max-depth", "title": "二叉树的最大深度", "category": "tree", "difficulty": "easy", "companies": ["Microsoft", "Apple"], "description": "给定一个二叉树 root,返回其最大深度。", "solution_python": "def maxDepth(root):\n if not root: return 0\n return max(maxDepth(root.left), maxDepth(root.right)) + 1", "solution_java": "public int maxDepth(TreeNode root) {\n if (root == null) return 0;\n return Math.max(maxDepth(root.left), maxDepth(root.right)) + 1;\n}", "solution_cpp": "int maxDepth(TreeNode* root) {\n if (!root) return 0;\n return max(maxDepth(root->left), maxDepth(root->right)) + 1;\n}", "test_cases": ["root=[3,9,20,null,null,15,7] -> 3", "root=[1,null,2] -> 2"], "key_points": ["DFS递归", "层序遍历也可"], "tags": ["tree", "easy", "Microsoft", "Apple"]} {"problem_id": "algo_00089", "original_id": "inorder-traversal", "title": "二叉树的中序遍历", "category": "tree", "difficulty": "easy", "companies": ["Google", "Microsoft"], "description": "给定一个二叉树的根节点 root,返回它的中序遍历结果。", "solution_python": "def inorderTraversal(root):\n result = []\n def dfs(node):\n if node:\n dfs(node.left)\n result.append(node.val)\n dfs(node.right)\n dfs(root)\n return result", "solution_java": "public List inorderTraversal(TreeNode root) {\n List res = new ArrayList<>();\n dfs(root, res);\n return res;\n}\nprivate void dfs(TreeNode node, List res) {\n if (node == null) return;\n dfs(node.left, res); res.add(node.val); dfs(node.right, res);\n}", "solution_cpp": "vector inorderTraversal(TreeNode* root) {\n vector res;\n dfs(root, res);\n return res;\n}\nvoid dfs(TreeNode* node, vector& res) {\n if (!node) return;\n dfs(node->left, res); res.push_back(node->val); dfs(node->right, res);\n}", "test_cases": ["root=[1,null,2,3] -> [1,3,2]", "root=[] -> []"], "key_points": ["左-根-右顺序", "递归最简洁"], "tags": ["tree", "easy", "Google", "Microsoft"]} {"problem_id": "algo_00090", "original_id": "binary-search", "title": "二分查找", "category": "binarysearch", "difficulty": "easy", "companies": ["Google", "Amazon"], "description": "给定一个 n 个元素有序的(升序)整型数组 nums 和一个目标值 target,写一个函数搜索 nums 中的 target,如果目标值存在返回下标,否则返回 -1。", "solution_python": "def search(nums, target):\n left, right = 0, len(nums) - 1\n while left <= right:\n mid = (left + right) // 2\n if nums[mid] == target: return mid\n elif nums[mid] < target: left = mid + 1\n else: right = mid - 1\n return -1", "solution_java": "public int search(int[] nums, int target) {\n int left = 0, right = nums.length - 1;\n while (left <= right) {\n int mid = left + (right - left) / 2;\n if (nums[mid] == target) return mid;\n else if (nums[mid] < target) left = mid + 1;\n else right = mid - 1;\n }\n return -1;\n}", "solution_cpp": "int search(vector& nums, int target) {\n int left = 0, right = nums.size() - 1;\n while (left <= right) {\n int mid = left + (right - left) / 2;\n if (nums[mid] == target) return mid;\n else if (nums[mid] < target) left = mid + 1;\n else right = mid - 1;\n }\n return -1;\n}", "test_cases": ["nums=[-1,0,3,5,9,12], target=9 -> 4", "nums=[-1,0,3,5,9,12], target=2 -> -1"], "key_points": ["标准模板", "注意防溢出写法"], "tags": ["binarysearch", "easy", "Google", "Amazon"]} {"problem_id": "algo_00091", "original_id": "climbing-stairs", "title": "爬楼梯", "category": "dp", "difficulty": "easy", "companies": ["Amazon", "Google"], "description": "假设你正在爬楼梯。需要 n 阶你才能到达楼顶。每次你可以爬 1 或 2 个台阶。你有多少种不同的方法可以爬到楼顶?", "solution_python": "def climbStairs(n):\n if n <= 2: return n\n a, b = 1, 2\n for _ in range(3, n+1):\n a, b = b, a + b\n return b", "solution_java": "public int climbStairs(int n) {\n if (n <= 2) return n;\n int a = 1, b = 2;\n for (int i = 3; i <= n; i++) { int temp = a + b; a = b; b = temp; }\n return b;\n}", "solution_cpp": "int climbStairs(int n) {\n if (n <= 2) return n;\n int a = 1, b = 2;\n for (int i = 3; i <= n; i++) { int temp = a + b; a = b; b = temp; }\n return b;\n}", "test_cases": ["n=2 -> 2", "n=3 -> 3", "n=5 -> 8"], "key_points": ["斐波那契数列", "滚动数组优化空间"], "tags": ["dp", "easy", "Amazon", "Google"]} {"problem_id": "algo_00092", "original_id": "coin-change", "title": "零钱兑换", "category": "dp", "difficulty": "medium", "companies": ["Google", "Amazon"], "description": "给你一个整数数组 coins 表示不同面额的硬币,以及一个整数 amount 表示总金额。计算并返回可以凑成总金额所需的最少的硬币个数。如果没有任何一种硬币组合能组成总金额,返回 -1。", "solution_python": "def coinChange(coins, amount):\n dp = [float('inf')] * (amount + 1)\n dp[0] = 0\n for coin in coins:\n for x in range(coin, amount + 1):\n dp[x] = min(dp[x], dp[x - coin] + 1)\n return dp[amount] if dp[amount] != float('inf') else -1", "solution_java": "public int coinChange(int[] coins, int amount) {\n int[] dp = new int[amount + 1];\n Arrays.fill(dp, amount + 1);\n dp[0] = 0;\n for (int coin : coins) {\n for (int x = coin; x <= amount; x++) {\n dp[x] = Math.min(dp[x], dp[x - coin] + 1);\n }\n }\n return dp[amount] > amount ? -1 : dp[amount];\n}", "solution_cpp": "int coinChange(vector& coins, int amount) {\n vector dp(amount + 1, amount + 1);\n dp[0] = 0;\n for (int coin : coins) {\n for (int x = coin; x <= amount; x++) {\n dp[x] = min(dp[x], dp[x - coin] + 1);\n }\n }\n return dp[amount] > amount ? -1 : dp[amount];\n}", "test_cases": ["coins=[1,2,5], amount=11 -> 3", "coins=[2], amount=3 -> -1"], "key_points": ["完全背包问题", "dp[x] = min(dp[x-coin]+1)"], "tags": ["dp", "medium", "Google", "Amazon"]} {"problem_id": "algo_00093", "original_id": "subsets", "title": "子集", "category": "backtracking", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "给你一个整数数组 nums ,数组中的元素 互不相同 。返回该数组所有可能的子集(幂集)。", "solution_python": "def subsets(nums):\n result = []\n def backtrack(start, path):\n result.append(path[:])\n for i in range(start, len(nums)):\n path.append(nums[i])\n backtrack(i + 1, path)\n path.pop()\n backtrack(0, [])\n return result", "solution_java": "public List> subsets(int[] nums) {\n List> result = new ArrayList<>();\n backtrack(nums, 0, new ArrayList<>(), result);\n return result;\n}\nprivate void backtrack(int[] nums, int start, List path, List> result) {\n result.add(new ArrayList<>(path));\n for (int i = start; i < nums.length; i++) {\n path.add(nums[i]);\n backtrack(nums, i + 1, path, result);\n path.remove(path.size() - 1);\n }\n}", "solution_cpp": "vector> subsets(vector& nums) {\n vector> result;\n vector path;\n backtrack(nums, 0, path, result);\n return result;\n}\nvoid backtrack(vector& nums, int start, vector& path, vector>& result) {\n result.push_back(path);\n for (int i = start; i < nums.size(); i++) {\n path.push_back(nums[i]);\n backtrack(nums, i + 1, path, result);\n path.pop_back();\n }\n}", "test_cases": ["nums=[1,2,3] -> [[],[1],[2],[1,2],[3],[1,3],[2,3],[1,2,3]]"], "key_points": ["选或不选", "DFS遍历子集树"], "tags": ["backtracking", "medium", "Google", "Microsoft"]} {"problem_id": "algo_00094", "original_id": "permutations", "title": "全排列", "category": "backtracking", "difficulty": "medium", "companies": ["Google", "Facebook"], "description": "给定一个不含重复数字的数组 nums,返回其所有可能的全排列。", "solution_python": "def permute(nums):\n result = []\n def backtrack(path, used):\n if len(path) == len(nums):\n result.append(path[:])\n return\n for i in range(len(nums)):\n if used[i]: continue\n used[i] = True\n path.append(nums[i])\n backtrack(path, used)\n path.pop()\n used[i] = False\n backtrack([], [False]*len(nums))\n return result", "solution_java": "public List> permute(int[] nums) {\n List> result = new ArrayList<>();\n boolean[] used = new boolean[nums.length];\n backtrack(nums, used, new ArrayList<>(), result);\n return result;\n}\nprivate void backtrack(int[] nums, boolean[] used, List path, List> result) {\n if (path.size() == nums.length) { result.add(new ArrayList<>(path)); return; }\n for (int i = 0; i < nums.length; i++) {\n if (used[i]) continue;\n used[i] = true;\n path.add(nums[i]);\n backtrack(nums, used, path, result);\n path.remove(path.size() - 1);\n used[i] = false;\n }\n}", "solution_cpp": "vector> permute(vector& nums) {\n vector> result;\n vector used(nums.size(), false);\n vector path;\n backtrack(nums, used, path, result);\n return result;\n}\nvoid backtrack(vector& nums, vector& used, vector& path, vector>& result) {\n if (path.size() == nums.size()) { result.push_back(path); return; }\n for (int i = 0; i < nums.size(); i++) {\n if (used[i]) continue;\n used[i] = true;\n path.push_back(nums[i]);\n backtrack(nums, used, path, result);\n path.pop_back();\n used[i] = false;\n }\n}", "test_cases": ["nums=[1,2,3] -> [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]"], "key_points": ["标记已使用元素", "回溯经典模板"], "tags": ["backtracking", "medium", "Google", "Facebook"]} {"problem_id": "algo_00095", "original_id": "top-k-frequent", "title": "前K个高频元素", "category": "heap", "difficulty": "medium", "companies": ["Amazon", "Facebook"], "description": "给你一个整数数组 nums 和一个整数 k,请你返回其中出现频率前 k 高的元素。", "solution_python": "import heapq\nfrom collections import Counter\ndef topKFrequent(nums, k):\n count = Counter(nums)\n heap = []\n for num, freq in count.items():\n heapq.heappush(heap, (freq, num))\n if len(heap) > k: heapq.heappop(heap)\n return [num for freq, num in heap]", "solution_java": "public int[] topKFrequent(int[] nums, int k) {\n Map count = new HashMap<>();\n for (int n : nums) count.put(n, count.getOrDefault(n, 0) + 1);\n PriorityQueue> heap = \n new PriorityQueue<>((a, b) -> a.getValue() - b.getValue());\n for (Map.Entry e : count.entrySet()) {\n heap.offer(e);\n if (heap.size() > k) heap.poll();\n }\n int[] res = new int[k];\n for (int i = k - 1; i >= 0; i--) res[i] = heap.poll().getKey();\n return res;\n}", "solution_cpp": "vector topKFrequent(vector& nums, int k) {\n unordered_map count;\n for (int n : nums) count[n]++;\n priority_queue, vector>, greater>> heap;\n for (auto& [num, freq] : count) {\n heap.push({freq, num});\n if (heap.size() > k) heap.pop();\n }\n vector res;\n while (!heap.empty()) { res.push_back(heap.top().second); heap.pop(); }\n reverse(res.begin(), res.end());\n return res;\n}", "test_cases": ["nums=[1,1,1,2,2,3], k=2 -> [1,2]", "nums=[1], k=1 -> [1]"], "key_points": ["小顶堆保持大小k", "时间复杂度O(nlogk)"], "tags": ["heap", "medium", "Amazon", "Facebook"]} {"problem_id": "algo_00096", "original_id": "3sum", "title": "三数之和", "category": "two-pointers", "difficulty": "medium", "companies": ["Google", "Amazon"], "description": "给你一个整数数组 nums,判断是否存在三元组满足和为0,返回所有不重复的三元组。", "solution_python": "def threeSum(nums):\n nums.sort()\n result = []\n for i in range(len(nums) - 2):\n if i > 0 and nums[i] == nums[i-1]: continue\n left, right = i + 1, len(nums) - 1\n while left < right:\n total = nums[i] + nums[left] + nums[right]\n if total < 0: left += 1\n elif total > 0: right -= 1\n else:\n result.append([nums[i], nums[left], nums[right]])\n while left < right and nums[left] == nums[left+1]: left += 1\n while left < right and nums[right] == nums[right-1]: right -= 1\n left += 1; right -= 1\n return result", "solution_java": "public List> threeSum(int[] nums) {\n Arrays.sort(nums);\n List> result = new ArrayList<>();\n for (int i = 0; i < nums.length - 2; i++) {\n if (i > 0 && nums[i] == nums[i-1]) continue;\n int left = i + 1, right = nums.length - 1;\n while (left < right) {\n int total = nums[i] + nums[left] + nums[right];\n if (total < 0) left++;\n else if (total > 0) right--;\n else {\n result.add(Arrays.asList(nums[i], nums[left], nums[right]));\n while (left < right && nums[left] == nums[left+1]) left++;\n while (left < right && nums[right] == nums[right-1]) right--;\n left++; right--;\n }\n }\n }\n return result;\n}", "solution_cpp": "vector> threeSum(vector& nums) {\n sort(nums.begin(), nums.end());\n vector> result;\n for (int i = 0; i < nums.size() - 2; i++) {\n if (i > 0 && nums[i] == nums[i-1]) continue;\n int left = i + 1, right = nums.size() - 1;\n while (left < right) {\n int total = nums[i] + nums[left] + nums[right];\n if (total < 0) left++;\n else if (total > 0) right--;\n else {\n result.push_back({nums[i], nums[left], nums[right]});\n while (left < right && nums[left] == nums[left+1]) left++;\n while (left < right && nums[right] == nums[right-1]) right--;\n left++; right--;\n }\n }\n }\n return result;\n}", "test_cases": ["nums=[-1,0,1,2,-1,-4] -> [[-1,-1,2],[-1,0,1]]"], "key_points": ["排序+双指针", "去重是关键"], "tags": ["two-pointers", "medium", "Google", "Amazon"]} {"problem_id": "algo_00097", "original_id": "container-water", "title": "盛最多水的容器", "category": "two-pointers", "difficulty": "medium", "companies": ["Google", "Uber"], "description": "给定一个长度为 n 的整数数组 height,找出其中的两条线,使得它们与 x 轴共同构成的容器可以容纳最多的水。", "solution_python": "def maxArea(height):\n left, right = 0, len(height) - 1\n max_area = 0\n while left < right:\n h = min(height[left], height[right])\n max_area = max(max_area, h * (right - left))\n if height[left] < height[right]: left += 1\n else: right -= 1\n return max_area", "solution_java": "public int maxArea(int[] height) {\n int left = 0, right = height.length - 1, maxArea = 0;\n while (left < right) {\n int h = Math.min(height[left], height[right]);\n maxArea = Math.max(maxArea, h * (right - left));\n if (height[left] < height[right]) left++;\n else right--;\n }\n return maxArea;\n}", "solution_cpp": "int maxArea(vector& height) {\n int left = 0, right = height.size() - 1, maxArea = 0;\n while (left < right) {\n int h = min(height[left], height[right]);\n maxArea = max(maxArea, h * (right - left));\n if (height[left] < height[right]) left++;\n else right--;\n }\n return maxArea;\n}", "test_cases": ["height=[1,8,6,2,5,4,8,3,7] -> 49"], "key_points": ["移动短边指针", "面积=min(h1,h2)*width"], "tags": ["two-pointers", "medium", "Google", "Uber"]} {"problem_id": "algo_00098", "original_id": "min-stack", "title": "最小栈", "category": "stack", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "设计一个支持 push,pop,top 操作,并能在常数时间内检索到最小元素的栈。", "solution_python": "class MinStack:\n def __init__(self):\n self.stack = []\n self.min_stack = []\n def push(self, val):\n self.stack.append(val)\n self.min_stack.append(min(val, self.min_stack[-1] if self.min_stack else val))\n def pop(self):\n self.stack.pop(); self.min_stack.pop()\n def top(self): return self.stack[-1]\n def getMin(self): return self.min_stack[-1]", "solution_java": "class MinStack {\n Stack stack = new Stack<>();\n Stack minStack = new Stack<>();\n public void push(int val) { stack.push(val); minStack.push(Math.min(val, minStack.isEmpty() ? val : minStack.peek())); }\n public void pop() { stack.pop(); minStack.pop(); }\n public int top() { return stack.peek(); }\n public int getMin() { return minStack.peek(); }\n}", "solution_cpp": "class MinStack {\n stack st, minSt;\npublic:\n void push(int val) { st.push(val); minSt.push(min(val, minSt.empty() ? val : minSt.top())); }\n void pop() { st.pop(); minSt.pop(); }\n int top() { return st.top(); }\n int getMin() { return minSt.top(); }\n};", "test_cases": ["push(-2), push(0), push(-3) -> getMin() returns -3"], "key_points": ["辅助栈记录最小值", "O(1)时间获取最小值"], "tags": ["stack", "medium", "Google", "Microsoft"]} {"problem_id": "algo_00099", "original_id": "lru-cache", "title": "LRU缓存", "category": "design", "difficulty": "hard", "companies": ["Google", "Amazon"], "description": "设计和实现一个 LRU(最近最少使用)缓存机制。", "solution_python": "class LRUCache:\n def __init__(self, capacity):\n self.capacity = capacity\n self.cache = {}\n self.order = []\n def get(self, key):\n if key not in self.cache: return -1\n self.order.remove(key); self.order.append(key)\n return self.cache[key]\n def put(self, key, value):\n if key in self.cache:\n self.order.remove(key)\n elif len(self.cache) >= self.capacity:\n del self.cache[self.order.pop(0)]\n self.cache[key] = value; self.order.append(key)", "solution_java": "class LRUCache {\n int capacity;\n LinkedHashMap cache = new LinkedHashMap<>();\n public LRUCache(int cap) { capacity = cap; }\n public int get(int key) { return cache.containsKey(key) ? cache.remove(key) : -1; }\n public void put(int key, int val) {\n if (cache.containsKey(key)) cache.remove(key);\n else if (cache.size() >= capacity) cache.remove(cache.keySet().iterator().next());\n cache.put(key, val);\n }\n}", "solution_cpp": "class LRUCache {\n int cap;\n list> dll;\n unordered_map>::iterator> cache;\npublic:\n LRUCache(int capacity) : cap(capacity) {}\n int get(int key) {\n auto it = cache.find(key);\n if (it == cache.end()) return -1;\n dll.splice(dll.end(), dll, it->second);\n return it->second->second;\n }\n void put(int key, int value) {\n auto it = cache.find(key);\n if (it != cache.end()) dll.erase(it->second);\n else if (cache.size() >= cap) { cache.erase(dll.front().first); dll.pop_front(); }\n dll.push_back({key, value});\n cache[key] = --dll.end();\n }\n};", "test_cases": ["put(1,1), put(2,2), get(1) -> 1"], "key_points": ["HashMap + 双向链表", "O(1)时间操作"], "tags": ["design", "hard", "Google", "Amazon"]} {"problem_id": "algo_00100", "original_id": "num-islands", "title": "岛屿数量", "category": "graph", "difficulty": "medium", "companies": ["Google", "Facebook"], "description": "给你一个由 '1'(陆地)和 '0'(水)组成的二维网格,请你计算网格中岛屿的数量。岛屿总是被水包围,且只能由水平或垂直方向相邻的陆地连接形成。", "solution_python": "def numIslands(grid):\n if not grid: return 0\n rows, cols = len(grid), len(grid[0])\n count = 0\n def dfs(r, c):\n if r < 0 or r >= rows or c < 0 or c >= cols or grid[r][c] != '1': return\n grid[r][c] = '0'\n dfs(r+1, c); dfs(r-1, c); dfs(r, c+1); dfs(r, c-1)\n for r in range(rows):\n for c in range(cols):\n if grid[r][c] == '1': count += 1; dfs(r, c)\n return count", "solution_java": "public int numIslands(char[][] grid) {\n if (grid.length == 0) return 0;\n int count = 0;\n for (int i = 0; i < grid.length; i++)\n for (int j = 0; j < grid[0].length; j++)\n if (grid[i][j] == '1') { count++; dfs(grid, i, j); }\n return count;\n}\nprivate void dfs(char[][] grid, int r, int c) {\n if (r < 0 || r >= grid.length || c < 0 || c >= grid[0].length || grid[r][c] != '1') return;\n grid[r][c] = '0';\n dfs(grid, r+1, c); dfs(grid, r-1, c); dfs(grid, r, c+1); dfs(grid, r, c-1);\n}", "solution_cpp": "int numIslands(vector>& grid) {\n if (grid.empty()) return 0;\n int count = 0;\n for (int i = 0; i < grid.size(); i++)\n for (int j = 0; j < grid[0].size(); j++)\n if (grid[i][j] == '1') { count++; dfs(grid, i, j); }\n return count;\n}\nvoid dfs(vector>& grid, int r, int c) {\n if (r < 0 || r >= grid.size() || c < 0 || c >= grid[0].size() || grid[r][c] != '1') return;\n grid[r][c] = '0';\n dfs(grid, r+1, c); dfs(grid, r-1, c); dfs(grid, r, c+1); dfs(grid, r, c-1);\n}", "test_cases": ["grid=[[1,1,1,1,0],[1,1,0,1,0],[1,1,0,0,0],[0,0,0,0,0]] -> 1"], "key_points": ["DFS/BFS遍历", "访问后标记为0避免重复"], "tags": ["graph", "medium", "Google", "Facebook"]} {"problem_id": "algo_00101", "original_id": "two-sum", "title": "两数之和", "category": "array", "difficulty": "easy", "companies": ["Amazon", "Google"], "description": "给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那两个整数,并返回他们的数组下标。", "solution_python": "def twoSum(nums, target):\n hashmap = {}\n for i, num in enumerate(nums):\n complement = target - num\n if complement in hashmap:\n return [hashmap[complement], i]\n hashmap[num] = i\n return []", "solution_java": "public int[] twoSum(int[] nums, int target) {\n Map map = new HashMap<>();\n for (int i = 0; i < nums.length; i++) {\n int complement = target - nums[i];\n if (map.containsKey(complement)) return new int[]{map.get(complement), i};\n map.put(nums[i], i);\n }\n return new int[]{};\n}", "solution_cpp": "vector twoSum(vector& nums, int target) {\n unordered_map m;\n for (int i = 0; i < nums.size(); i++) {\n if (m.count(target - nums[i])) return {m[target - nums[i]], i};\n m[nums[i]] = i;\n }\n return {};\n}", "test_cases": ["nums=[2,7,11,15], target=9 -> [0,1]", "nums=[3,2,4], target=6 -> [1,2]"], "key_points": ["哈希表一次遍历", "空间换时间"], "tags": ["array", "easy", "Amazon", "Google"]} {"problem_id": "algo_00102", "original_id": "merge-sorted", "title": "合并两个有序数组", "category": "array", "difficulty": "easy", "companies": ["Microsoft", "Uber"], "description": "给你两个按非递减顺序排列的整数数组 nums1 和 nums2,另有两个整数 m 和 n,分别表示 nums1 和 nums2 中的元素数目。请你合并 nums2 到 nums1 中。", "solution_python": "def merge(nums1, m, nums2, n):\n p1, p2, p = m-1, n-1, m+n-1\n while p1 >= 0 and p2 >= 0:\n if nums1[p1] > nums2[p2]: nums1[p] = nums1[p1]; p1 -= 1\n else: nums1[p] = nums2[p2]; p2 -= 1\n p -= 1\n while p2 >= 0: nums1[p] = nums2[p2]; p2 -= 1; p -= 1", "solution_java": "public void merge(int[] nums1, int m, int[] nums2, int n) {\n int p1 = m-1, p2 = n-1, p = m+n-1;\n while (p1 >= 0 && p2 >= 0) {\n nums1[p--] = nums1[p1] > nums2[p2] ? nums1[p1--] : nums2[p2--];\n }\n while (p2 >= 0) nums1[p--] = nums2[p2--];\n}", "solution_cpp": "void merge(vector& nums1, int m, vector& nums2, int n) {\n int p1 = m-1, p2 = n-1, p = m+n-1;\n while (p1 >= 0 && p2 >= 0) nums1[p--] = nums1[p1] > nums2[p2] ? nums1[p1--] : nums2[p2--];\n while (p2 >= 0) nums1[p--] = nums2[p2--];\n}", "test_cases": ["nums1=[1,2,3], m=3, nums2=[2,5,6], n=3 -> [1,2,2,3,5,6]", "nums1=[], m=0, nums2=[1], n=1 -> [1]"], "key_points": ["从后往前合并", "三指针技巧"], "tags": ["array", "easy", "Microsoft", "Uber"]} {"problem_id": "algo_00103", "original_id": "max-subarray", "title": "最大子数组和", "category": "array", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "给你一个整数数组 nums ,请你找出一个具有最大和的连续子数组,返回其最大和。", "solution_python": "def maxSubArray(nums):\n max_sum = current = nums[0]\n for num in nums[1:]:\n current = max(num, current + num)\n max_sum = max(max_sum, current)\n return max_sum", "solution_java": "public int maxSubArray(int[] nums) {\n int maxSum = nums[0], curr = nums[0];\n for (int i = 1; i < nums.length; i++) {\n curr = Math.max(nums[i], curr + nums[i]);\n maxSum = Math.max(maxSum, curr);\n }\n return maxSum;\n}", "solution_cpp": "int maxSubArray(vector& nums) {\n int maxSum = nums[0], curr = nums[0];\n for (int i = 1; i < nums.size(); i++) {\n curr = max(nums[i], curr + nums[i]);\n maxSum = max(maxSum, curr);\n }\n return maxSum;\n}", "test_cases": ["nums=[-2,1,-3,4,-1,2,1,-5,4] -> 6", "nums=[1] -> 1"], "key_points": ["Kadane算法", "动态规划基础题"], "tags": ["array", "medium", "Google", "Microsoft"]} {"problem_id": "algo_00104", "original_id": "valid-parentheses", "title": "有效的括号", "category": "string", "difficulty": "easy", "companies": ["Google", "Uber"], "description": "给定一个只包括 '(',')','{','}','[',']' 的字符串 s,判断字符串是否有效。", "solution_python": "def isValid(s):\n stack = []\n mapping = {')': '(', ']': '[', '}': '{'}\n for c in s:\n if c in mapping:\n if not stack or stack[-1] != mapping[c]: return False\n stack.pop()\n else: stack.append(c)\n return not stack", "solution_java": "public boolean isValid(String s) {\n Stack stack = new Stack<>();\n Map map = Map.of(')', '(', ']', '[', '}', '{');\n for (char c : s.toCharArray()) {\n if (map.containsValue(c)) stack.push(c);\n else if (!stack.isEmpty() && stack.pop() != map.get(c)) return false;\n }\n return stack.isEmpty();\n}", "solution_cpp": "bool isValid(string s) {\n stack st;\n unordered_map m = {{')','('},{']','['},{'}','{'}};\n for (char c : s) {\n if (m.find(c) == m.end()) st.push(c);\n else if (st.empty() || st.top() != m[c]) return false;\n else st.pop();\n }\n return st.empty();\n}", "test_cases": ["s=\"()\" -> true", "s=\"()[]{}\" -> true", "s=\"(]\" -> false"], "key_points": ["栈匹配法", "注意空栈边界"], "tags": ["string", "easy", "Google", "Uber"]} {"problem_id": "algo_00105", "original_id": "longest-palindrome", "title": "最长回文子串", "category": "string", "difficulty": "medium", "companies": ["Google", "Amazon"], "description": "给你一个字符串 s,找到 s 中最长的回文子串。", "solution_python": "def longestPalindrome(s):\n def expand(l, r):\n while l >= 0 and r < len(s) and s[l] == s[r]: l -= 1; r += 1\n return l + 1, r - 1\n start = end = 0\n for i in range(len(s)):\n l1, r1 = expand(i, i)\n l2, r2 = expand(i, i + 1)\n if r1 - l1 > end - start: start, end = l1, r1\n if r2 - l2 > end - start: start, end = l2, r2\n return s[start:end+1]", "solution_java": "public String longestPalindrome(String s) {\n int start = 0, end = 0;\n for (int i = 0; i < s.length(); i++) {\n int len1 = expand(s, i, i), len2 = expand(s, i, i+1);\n int len = Math.max(len1, len2);\n if (len > end - start) { start = i - (len-1)/2; end = i + len/2; }\n }\n return s.substring(start, end + 1);\n}\nprivate int expand(String s, int l, int r) {\n while (l >= 0 && r < s.length() && s.charAt(l) == s.charAt(r)) { l--; r++; }\n return r - l - 1;\n}", "solution_cpp": "string longestPalindrome(string s) {\n int start = 0, end = 0;\n for (int i = 0; i < s.size(); i++) {\n int len1 = expand(s, i, i), len2 = expand(s, i, i+1);\n if (max(len1, len2) > end - start) { start = i - (max(len1,len2)-1)/2; end = i + max(len1,len2)/2; }\n }\n return s.substr(start, end - start + 1);\n}", "test_cases": ["s=\"babad\" -> bab或aba", "s=\"cbbd\" -> bb"], "key_points": ["中心扩展法", "处理奇偶长度"], "tags": ["string", "medium", "Google", "Amazon"]} {"problem_id": "algo_00106", "original_id": "reverse-list", "title": "反转链表", "category": "linkedlist", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "给你单链表的头节点 head,请你反转链表,并返回反转后的链表。", "solution_python": "def reverseList(head):\n prev = None\n curr = head\n while curr:\n nxt = curr.next\n curr.next = prev\n prev = curr\n curr = nxt\n return prev", "solution_java": "public ListNode reverseList(ListNode head) {\n ListNode prev = null, curr = head;\n while (curr != null) {\n ListNode next = curr.next;\n curr.next = prev;\n prev = curr;\n curr = next;\n }\n return prev;\n}", "solution_cpp": "ListNode* reverseList(ListNode* head) {\n ListNode* prev = nullptr, *curr = head;\n while (curr) {\n ListNode* next = curr->next;\n curr->next = prev;\n prev = curr;\n curr = next;\n }\n return prev;\n}", "test_cases": ["head=[1,2,3,4,5] -> [5,4,3,2,1]", "head=[1,2] -> [2,1]"], "key_points": ["迭代法 O(1)空间", "递归法 O(n)空间"], "tags": ["linkedlist", "medium", "Google", "Microsoft"]} {"problem_id": "algo_00107", "original_id": "middle-node", "title": "链表的中间结点", "category": "linkedlist", "difficulty": "easy", "companies": ["Amazon", "Facebook"], "description": "给你单链表的头节点 head,请你找出并返回链表的中间结点。如果有两个中间结点,则返回第二个中间结点。", "solution_python": "def middleNode(head):\n slow = fast = head\n while fast and fast.next:\n slow = slow.next\n fast = fast.next.next\n return slow", "solution_java": "public ListNode middleNode(ListNode head) {\n ListNode slow = head, fast = head;\n while (fast != null && fast.next != null) {\n slow = slow.next;\n fast = fast.next.next;\n }\n return slow;\n}", "solution_cpp": "ListNode* middleNode(ListNode* head) {\n ListNode* slow = head, *fast = head;\n while (fast && fast->next) { slow = slow->next; fast = fast->next->next; }\n return slow;\n}", "test_cases": ["head=[1,2,3,4,5] -> 3", "head=[1,2,3,4,5,6] -> 4"], "key_points": ["快慢指针", "O(n)时间O(1)空间"], "tags": ["linkedlist", "easy", "Amazon", "Facebook"]} {"problem_id": "algo_00108", "original_id": "max-depth", "title": "二叉树的最大深度", "category": "tree", "difficulty": "easy", "companies": ["Microsoft", "Apple"], "description": "给定一个二叉树 root,返回其最大深度。", "solution_python": "def maxDepth(root):\n if not root: return 0\n return max(maxDepth(root.left), maxDepth(root.right)) + 1", "solution_java": "public int maxDepth(TreeNode root) {\n if (root == null) return 0;\n return Math.max(maxDepth(root.left), maxDepth(root.right)) + 1;\n}", "solution_cpp": "int maxDepth(TreeNode* root) {\n if (!root) return 0;\n return max(maxDepth(root->left), maxDepth(root->right)) + 1;\n}", "test_cases": ["root=[3,9,20,null,null,15,7] -> 3", "root=[1,null,2] -> 2"], "key_points": ["DFS递归", "层序遍历也可"], "tags": ["tree", "easy", "Microsoft", "Apple"]} {"problem_id": "algo_00109", "original_id": "inorder-traversal", "title": "二叉树的中序遍历", "category": "tree", "difficulty": "easy", "companies": ["Google", "Microsoft"], "description": "给定一个二叉树的根节点 root,返回它的中序遍历结果。", "solution_python": "def inorderTraversal(root):\n result = []\n def dfs(node):\n if node:\n dfs(node.left)\n result.append(node.val)\n dfs(node.right)\n dfs(root)\n return result", "solution_java": "public List inorderTraversal(TreeNode root) {\n List res = new ArrayList<>();\n dfs(root, res);\n return res;\n}\nprivate void dfs(TreeNode node, List res) {\n if (node == null) return;\n dfs(node.left, res); res.add(node.val); dfs(node.right, res);\n}", "solution_cpp": "vector inorderTraversal(TreeNode* root) {\n vector res;\n dfs(root, res);\n return res;\n}\nvoid dfs(TreeNode* node, vector& res) {\n if (!node) return;\n dfs(node->left, res); res.push_back(node->val); dfs(node->right, res);\n}", "test_cases": ["root=[1,null,2,3] -> [1,3,2]", "root=[] -> []"], "key_points": ["左-根-右顺序", "递归最简洁"], "tags": ["tree", "easy", "Google", "Microsoft"]} {"problem_id": "algo_00110", "original_id": "binary-search", "title": "二分查找", "category": "binarysearch", "difficulty": "easy", "companies": ["Google", "Amazon"], "description": "给定一个 n 个元素有序的(升序)整型数组 nums 和一个目标值 target,写一个函数搜索 nums 中的 target,如果目标值存在返回下标,否则返回 -1。", "solution_python": "def search(nums, target):\n left, right = 0, len(nums) - 1\n while left <= right:\n mid = (left + right) // 2\n if nums[mid] == target: return mid\n elif nums[mid] < target: left = mid + 1\n else: right = mid - 1\n return -1", "solution_java": "public int search(int[] nums, int target) {\n int left = 0, right = nums.length - 1;\n while (left <= right) {\n int mid = left + (right - left) / 2;\n if (nums[mid] == target) return mid;\n else if (nums[mid] < target) left = mid + 1;\n else right = mid - 1;\n }\n return -1;\n}", "solution_cpp": "int search(vector& nums, int target) {\n int left = 0, right = nums.size() - 1;\n while (left <= right) {\n int mid = left + (right - left) / 2;\n if (nums[mid] == target) return mid;\n else if (nums[mid] < target) left = mid + 1;\n else right = mid - 1;\n }\n return -1;\n}", "test_cases": ["nums=[-1,0,3,5,9,12], target=9 -> 4", "nums=[-1,0,3,5,9,12], target=2 -> -1"], "key_points": ["标准模板", "注意防溢出写法"], "tags": ["binarysearch", "easy", "Google", "Amazon"]} {"problem_id": "algo_00111", "original_id": "climbing-stairs", "title": "爬楼梯", "category": "dp", "difficulty": "easy", "companies": ["Amazon", "Google"], "description": "假设你正在爬楼梯。需要 n 阶你才能到达楼顶。每次你可以爬 1 或 2 个台阶。你有多少种不同的方法可以爬到楼顶?", "solution_python": "def climbStairs(n):\n if n <= 2: return n\n a, b = 1, 2\n for _ in range(3, n+1):\n a, b = b, a + b\n return b", "solution_java": "public int climbStairs(int n) {\n if (n <= 2) return n;\n int a = 1, b = 2;\n for (int i = 3; i <= n; i++) { int temp = a + b; a = b; b = temp; }\n return b;\n}", "solution_cpp": "int climbStairs(int n) {\n if (n <= 2) return n;\n int a = 1, b = 2;\n for (int i = 3; i <= n; i++) { int temp = a + b; a = b; b = temp; }\n return b;\n}", "test_cases": ["n=2 -> 2", "n=3 -> 3", "n=5 -> 8"], "key_points": ["斐波那契数列", "滚动数组优化空间"], "tags": ["dp", "easy", "Amazon", "Google"]} {"problem_id": "algo_00112", "original_id": "coin-change", "title": "零钱兑换", "category": "dp", "difficulty": "medium", "companies": ["Google", "Amazon"], "description": "给你一个整数数组 coins 表示不同面额的硬币,以及一个整数 amount 表示总金额。计算并返回可以凑成总金额所需的最少的硬币个数。如果没有任何一种硬币组合能组成总金额,返回 -1。", "solution_python": "def coinChange(coins, amount):\n dp = [float('inf')] * (amount + 1)\n dp[0] = 0\n for coin in coins:\n for x in range(coin, amount + 1):\n dp[x] = min(dp[x], dp[x - coin] + 1)\n return dp[amount] if dp[amount] != float('inf') else -1", "solution_java": "public int coinChange(int[] coins, int amount) {\n int[] dp = new int[amount + 1];\n Arrays.fill(dp, amount + 1);\n dp[0] = 0;\n for (int coin : coins) {\n for (int x = coin; x <= amount; x++) {\n dp[x] = Math.min(dp[x], dp[x - coin] + 1);\n }\n }\n return dp[amount] > amount ? -1 : dp[amount];\n}", "solution_cpp": "int coinChange(vector& coins, int amount) {\n vector dp(amount + 1, amount + 1);\n dp[0] = 0;\n for (int coin : coins) {\n for (int x = coin; x <= amount; x++) {\n dp[x] = min(dp[x], dp[x - coin] + 1);\n }\n }\n return dp[amount] > amount ? -1 : dp[amount];\n}", "test_cases": ["coins=[1,2,5], amount=11 -> 3", "coins=[2], amount=3 -> -1"], "key_points": ["完全背包问题", "dp[x] = min(dp[x-coin]+1)"], "tags": ["dp", "medium", "Google", "Amazon"]} {"problem_id": "algo_00113", "original_id": "subsets", "title": "子集", "category": "backtracking", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "给你一个整数数组 nums ,数组中的元素 互不相同 。返回该数组所有可能的子集(幂集)。", "solution_python": "def subsets(nums):\n result = []\n def backtrack(start, path):\n result.append(path[:])\n for i in range(start, len(nums)):\n path.append(nums[i])\n backtrack(i + 1, path)\n path.pop()\n backtrack(0, [])\n return result", "solution_java": "public List> subsets(int[] nums) {\n List> result = new ArrayList<>();\n backtrack(nums, 0, new ArrayList<>(), result);\n return result;\n}\nprivate void backtrack(int[] nums, int start, List path, List> result) {\n result.add(new ArrayList<>(path));\n for (int i = start; i < nums.length; i++) {\n path.add(nums[i]);\n backtrack(nums, i + 1, path, result);\n path.remove(path.size() - 1);\n }\n}", "solution_cpp": "vector> subsets(vector& nums) {\n vector> result;\n vector path;\n backtrack(nums, 0, path, result);\n return result;\n}\nvoid backtrack(vector& nums, int start, vector& path, vector>& result) {\n result.push_back(path);\n for (int i = start; i < nums.size(); i++) {\n path.push_back(nums[i]);\n backtrack(nums, i + 1, path, result);\n path.pop_back();\n }\n}", "test_cases": ["nums=[1,2,3] -> [[],[1],[2],[1,2],[3],[1,3],[2,3],[1,2,3]]"], "key_points": ["选或不选", "DFS遍历子集树"], "tags": ["backtracking", "medium", "Google", "Microsoft"]} {"problem_id": "algo_00114", "original_id": "permutations", "title": "全排列", "category": "backtracking", "difficulty": "medium", "companies": ["Google", "Facebook"], "description": "给定一个不含重复数字的数组 nums,返回其所有可能的全排列。", "solution_python": "def permute(nums):\n result = []\n def backtrack(path, used):\n if len(path) == len(nums):\n result.append(path[:])\n return\n for i in range(len(nums)):\n if used[i]: continue\n used[i] = True\n path.append(nums[i])\n backtrack(path, used)\n path.pop()\n used[i] = False\n backtrack([], [False]*len(nums))\n return result", "solution_java": "public List> permute(int[] nums) {\n List> result = new ArrayList<>();\n boolean[] used = new boolean[nums.length];\n backtrack(nums, used, new ArrayList<>(), result);\n return result;\n}\nprivate void backtrack(int[] nums, boolean[] used, List path, List> result) {\n if (path.size() == nums.length) { result.add(new ArrayList<>(path)); return; }\n for (int i = 0; i < nums.length; i++) {\n if (used[i]) continue;\n used[i] = true;\n path.add(nums[i]);\n backtrack(nums, used, path, result);\n path.remove(path.size() - 1);\n used[i] = false;\n }\n}", "solution_cpp": "vector> permute(vector& nums) {\n vector> result;\n vector used(nums.size(), false);\n vector path;\n backtrack(nums, used, path, result);\n return result;\n}\nvoid backtrack(vector& nums, vector& used, vector& path, vector>& result) {\n if (path.size() == nums.size()) { result.push_back(path); return; }\n for (int i = 0; i < nums.size(); i++) {\n if (used[i]) continue;\n used[i] = true;\n path.push_back(nums[i]);\n backtrack(nums, used, path, result);\n path.pop_back();\n used[i] = false;\n }\n}", "test_cases": ["nums=[1,2,3] -> [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]"], "key_points": ["标记已使用元素", "回溯经典模板"], "tags": ["backtracking", "medium", "Google", "Facebook"]} {"problem_id": "algo_00115", "original_id": "top-k-frequent", "title": "前K个高频元素", "category": "heap", "difficulty": "medium", "companies": ["Amazon", "Facebook"], "description": "给你一个整数数组 nums 和一个整数 k,请你返回其中出现频率前 k 高的元素。", "solution_python": "import heapq\nfrom collections import Counter\ndef topKFrequent(nums, k):\n count = Counter(nums)\n heap = []\n for num, freq in count.items():\n heapq.heappush(heap, (freq, num))\n if len(heap) > k: heapq.heappop(heap)\n return [num for freq, num in heap]", "solution_java": "public int[] topKFrequent(int[] nums, int k) {\n Map count = new HashMap<>();\n for (int n : nums) count.put(n, count.getOrDefault(n, 0) + 1);\n PriorityQueue> heap = \n new PriorityQueue<>((a, b) -> a.getValue() - b.getValue());\n for (Map.Entry e : count.entrySet()) {\n heap.offer(e);\n if (heap.size() > k) heap.poll();\n }\n int[] res = new int[k];\n for (int i = k - 1; i >= 0; i--) res[i] = heap.poll().getKey();\n return res;\n}", "solution_cpp": "vector topKFrequent(vector& nums, int k) {\n unordered_map count;\n for (int n : nums) count[n]++;\n priority_queue, vector>, greater>> heap;\n for (auto& [num, freq] : count) {\n heap.push({freq, num});\n if (heap.size() > k) heap.pop();\n }\n vector res;\n while (!heap.empty()) { res.push_back(heap.top().second); heap.pop(); }\n reverse(res.begin(), res.end());\n return res;\n}", "test_cases": ["nums=[1,1,1,2,2,3], k=2 -> [1,2]", "nums=[1], k=1 -> [1]"], "key_points": ["小顶堆保持大小k", "时间复杂度O(nlogk)"], "tags": ["heap", "medium", "Amazon", "Facebook"]} {"problem_id": "algo_00116", "original_id": "3sum", "title": "三数之和", "category": "two-pointers", "difficulty": "medium", "companies": ["Google", "Amazon"], "description": "给你一个整数数组 nums,判断是否存在三元组满足和为0,返回所有不重复的三元组。", "solution_python": "def threeSum(nums):\n nums.sort()\n result = []\n for i in range(len(nums) - 2):\n if i > 0 and nums[i] == nums[i-1]: continue\n left, right = i + 1, len(nums) - 1\n while left < right:\n total = nums[i] + nums[left] + nums[right]\n if total < 0: left += 1\n elif total > 0: right -= 1\n else:\n result.append([nums[i], nums[left], nums[right]])\n while left < right and nums[left] == nums[left+1]: left += 1\n while left < right and nums[right] == nums[right-1]: right -= 1\n left += 1; right -= 1\n return result", "solution_java": "public List> threeSum(int[] nums) {\n Arrays.sort(nums);\n List> result = new ArrayList<>();\n for (int i = 0; i < nums.length - 2; i++) {\n if (i > 0 && nums[i] == nums[i-1]) continue;\n int left = i + 1, right = nums.length - 1;\n while (left < right) {\n int total = nums[i] + nums[left] + nums[right];\n if (total < 0) left++;\n else if (total > 0) right--;\n else {\n result.add(Arrays.asList(nums[i], nums[left], nums[right]));\n while (left < right && nums[left] == nums[left+1]) left++;\n while (left < right && nums[right] == nums[right-1]) right--;\n left++; right--;\n }\n }\n }\n return result;\n}", "solution_cpp": "vector> threeSum(vector& nums) {\n sort(nums.begin(), nums.end());\n vector> result;\n for (int i = 0; i < nums.size() - 2; i++) {\n if (i > 0 && nums[i] == nums[i-1]) continue;\n int left = i + 1, right = nums.size() - 1;\n while (left < right) {\n int total = nums[i] + nums[left] + nums[right];\n if (total < 0) left++;\n else if (total > 0) right--;\n else {\n result.push_back({nums[i], nums[left], nums[right]});\n while (left < right && nums[left] == nums[left+1]) left++;\n while (left < right && nums[right] == nums[right-1]) right--;\n left++; right--;\n }\n }\n }\n return result;\n}", "test_cases": ["nums=[-1,0,1,2,-1,-4] -> [[-1,-1,2],[-1,0,1]]"], "key_points": ["排序+双指针", "去重是关键"], "tags": ["two-pointers", "medium", "Google", "Amazon"]} {"problem_id": "algo_00117", "original_id": "container-water", "title": "盛最多水的容器", "category": "two-pointers", "difficulty": "medium", "companies": ["Google", "Uber"], "description": "给定一个长度为 n 的整数数组 height,找出其中的两条线,使得它们与 x 轴共同构成的容器可以容纳最多的水。", "solution_python": "def maxArea(height):\n left, right = 0, len(height) - 1\n max_area = 0\n while left < right:\n h = min(height[left], height[right])\n max_area = max(max_area, h * (right - left))\n if height[left] < height[right]: left += 1\n else: right -= 1\n return max_area", "solution_java": "public int maxArea(int[] height) {\n int left = 0, right = height.length - 1, maxArea = 0;\n while (left < right) {\n int h = Math.min(height[left], height[right]);\n maxArea = Math.max(maxArea, h * (right - left));\n if (height[left] < height[right]) left++;\n else right--;\n }\n return maxArea;\n}", "solution_cpp": "int maxArea(vector& height) {\n int left = 0, right = height.size() - 1, maxArea = 0;\n while (left < right) {\n int h = min(height[left], height[right]);\n maxArea = max(maxArea, h * (right - left));\n if (height[left] < height[right]) left++;\n else right--;\n }\n return maxArea;\n}", "test_cases": ["height=[1,8,6,2,5,4,8,3,7] -> 49"], "key_points": ["移动短边指针", "面积=min(h1,h2)*width"], "tags": ["two-pointers", "medium", "Google", "Uber"]} {"problem_id": "algo_00118", "original_id": "min-stack", "title": "最小栈", "category": "stack", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "设计一个支持 push,pop,top 操作,并能在常数时间内检索到最小元素的栈。", "solution_python": "class MinStack:\n def __init__(self):\n self.stack = []\n self.min_stack = []\n def push(self, val):\n self.stack.append(val)\n self.min_stack.append(min(val, self.min_stack[-1] if self.min_stack else val))\n def pop(self):\n self.stack.pop(); self.min_stack.pop()\n def top(self): return self.stack[-1]\n def getMin(self): return self.min_stack[-1]", "solution_java": "class MinStack {\n Stack stack = new Stack<>();\n Stack minStack = new Stack<>();\n public void push(int val) { stack.push(val); minStack.push(Math.min(val, minStack.isEmpty() ? val : minStack.peek())); }\n public void pop() { stack.pop(); minStack.pop(); }\n public int top() { return stack.peek(); }\n public int getMin() { return minStack.peek(); }\n}", "solution_cpp": "class MinStack {\n stack st, minSt;\npublic:\n void push(int val) { st.push(val); minSt.push(min(val, minSt.empty() ? val : minSt.top())); }\n void pop() { st.pop(); minSt.pop(); }\n int top() { return st.top(); }\n int getMin() { return minSt.top(); }\n};", "test_cases": ["push(-2), push(0), push(-3) -> getMin() returns -3"], "key_points": ["辅助栈记录最小值", "O(1)时间获取最小值"], "tags": ["stack", "medium", "Google", "Microsoft"]} {"problem_id": "algo_00119", "original_id": "lru-cache", "title": "LRU缓存", "category": "design", "difficulty": "hard", "companies": ["Google", "Amazon"], "description": "设计和实现一个 LRU(最近最少使用)缓存机制。", "solution_python": "class LRUCache:\n def __init__(self, capacity):\n self.capacity = capacity\n self.cache = {}\n self.order = []\n def get(self, key):\n if key not in self.cache: return -1\n self.order.remove(key); self.order.append(key)\n return self.cache[key]\n def put(self, key, value):\n if key in self.cache:\n self.order.remove(key)\n elif len(self.cache) >= self.capacity:\n del self.cache[self.order.pop(0)]\n self.cache[key] = value; self.order.append(key)", "solution_java": "class LRUCache {\n int capacity;\n LinkedHashMap cache = new LinkedHashMap<>();\n public LRUCache(int cap) { capacity = cap; }\n public int get(int key) { return cache.containsKey(key) ? cache.remove(key) : -1; }\n public void put(int key, int val) {\n if (cache.containsKey(key)) cache.remove(key);\n else if (cache.size() >= capacity) cache.remove(cache.keySet().iterator().next());\n cache.put(key, val);\n }\n}", "solution_cpp": "class LRUCache {\n int cap;\n list> dll;\n unordered_map>::iterator> cache;\npublic:\n LRUCache(int capacity) : cap(capacity) {}\n int get(int key) {\n auto it = cache.find(key);\n if (it == cache.end()) return -1;\n dll.splice(dll.end(), dll, it->second);\n return it->second->second;\n }\n void put(int key, int value) {\n auto it = cache.find(key);\n if (it != cache.end()) dll.erase(it->second);\n else if (cache.size() >= cap) { cache.erase(dll.front().first); dll.pop_front(); }\n dll.push_back({key, value});\n cache[key] = --dll.end();\n }\n};", "test_cases": ["put(1,1), put(2,2), get(1) -> 1"], "key_points": ["HashMap + 双向链表", "O(1)时间操作"], "tags": ["design", "hard", "Google", "Amazon"]} {"problem_id": "algo_00120", "original_id": "num-islands", "title": "岛屿数量", "category": "graph", "difficulty": "medium", "companies": ["Google", "Facebook"], "description": "给你一个由 '1'(陆地)和 '0'(水)组成的二维网格,请你计算网格中岛屿的数量。岛屿总是被水包围,且只能由水平或垂直方向相邻的陆地连接形成。", "solution_python": "def numIslands(grid):\n if not grid: return 0\n rows, cols = len(grid), len(grid[0])\n count = 0\n def dfs(r, c):\n if r < 0 or r >= rows or c < 0 or c >= cols or grid[r][c] != '1': return\n grid[r][c] = '0'\n dfs(r+1, c); dfs(r-1, c); dfs(r, c+1); dfs(r, c-1)\n for r in range(rows):\n for c in range(cols):\n if grid[r][c] == '1': count += 1; dfs(r, c)\n return count", "solution_java": "public int numIslands(char[][] grid) {\n if (grid.length == 0) return 0;\n int count = 0;\n for (int i = 0; i < grid.length; i++)\n for (int j = 0; j < grid[0].length; j++)\n if (grid[i][j] == '1') { count++; dfs(grid, i, j); }\n return count;\n}\nprivate void dfs(char[][] grid, int r, int c) {\n if (r < 0 || r >= grid.length || c < 0 || c >= grid[0].length || grid[r][c] != '1') return;\n grid[r][c] = '0';\n dfs(grid, r+1, c); dfs(grid, r-1, c); dfs(grid, r, c+1); dfs(grid, r, c-1);\n}", "solution_cpp": "int numIslands(vector>& grid) {\n if (grid.empty()) return 0;\n int count = 0;\n for (int i = 0; i < grid.size(); i++)\n for (int j = 0; j < grid[0].size(); j++)\n if (grid[i][j] == '1') { count++; dfs(grid, i, j); }\n return count;\n}\nvoid dfs(vector>& grid, int r, int c) {\n if (r < 0 || r >= grid.size() || c < 0 || c >= grid[0].size() || grid[r][c] != '1') return;\n grid[r][c] = '0';\n dfs(grid, r+1, c); dfs(grid, r-1, c); dfs(grid, r, c+1); dfs(grid, r, c-1);\n}", "test_cases": ["grid=[[1,1,1,1,0],[1,1,0,1,0],[1,1,0,0,0],[0,0,0,0,0]] -> 1"], "key_points": ["DFS/BFS遍历", "访问后标记为0避免重复"], "tags": ["graph", "medium", "Google", "Facebook"]} {"problem_id": "algo_00121", "original_id": "two-sum", "title": "两数之和", "category": "array", "difficulty": "easy", "companies": ["Amazon", "Google"], "description": "给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那两个整数,并返回他们的数组下标。", "solution_python": "def twoSum(nums, target):\n hashmap = {}\n for i, num in enumerate(nums):\n complement = target - num\n if complement in hashmap:\n return [hashmap[complement], i]\n hashmap[num] = i\n return []", "solution_java": "public int[] twoSum(int[] nums, int target) {\n Map map = new HashMap<>();\n for (int i = 0; i < nums.length; i++) {\n int complement = target - nums[i];\n if (map.containsKey(complement)) return new int[]{map.get(complement), i};\n map.put(nums[i], i);\n }\n return new int[]{};\n}", "solution_cpp": "vector twoSum(vector& nums, int target) {\n unordered_map m;\n for (int i = 0; i < nums.size(); i++) {\n if (m.count(target - nums[i])) return {m[target - nums[i]], i};\n m[nums[i]] = i;\n }\n return {};\n}", "test_cases": ["nums=[2,7,11,15], target=9 -> [0,1]", "nums=[3,2,4], target=6 -> [1,2]"], "key_points": ["哈希表一次遍历", "空间换时间"], "tags": ["array", "easy", "Amazon", "Google"]} {"problem_id": "algo_00122", "original_id": "merge-sorted", "title": "合并两个有序数组", "category": "array", "difficulty": "easy", "companies": ["Microsoft", "Uber"], "description": "给你两个按非递减顺序排列的整数数组 nums1 和 nums2,另有两个整数 m 和 n,分别表示 nums1 和 nums2 中的元素数目。请你合并 nums2 到 nums1 中。", "solution_python": "def merge(nums1, m, nums2, n):\n p1, p2, p = m-1, n-1, m+n-1\n while p1 >= 0 and p2 >= 0:\n if nums1[p1] > nums2[p2]: nums1[p] = nums1[p1]; p1 -= 1\n else: nums1[p] = nums2[p2]; p2 -= 1\n p -= 1\n while p2 >= 0: nums1[p] = nums2[p2]; p2 -= 1; p -= 1", "solution_java": "public void merge(int[] nums1, int m, int[] nums2, int n) {\n int p1 = m-1, p2 = n-1, p = m+n-1;\n while (p1 >= 0 && p2 >= 0) {\n nums1[p--] = nums1[p1] > nums2[p2] ? nums1[p1--] : nums2[p2--];\n }\n while (p2 >= 0) nums1[p--] = nums2[p2--];\n}", "solution_cpp": "void merge(vector& nums1, int m, vector& nums2, int n) {\n int p1 = m-1, p2 = n-1, p = m+n-1;\n while (p1 >= 0 && p2 >= 0) nums1[p--] = nums1[p1] > nums2[p2] ? nums1[p1--] : nums2[p2--];\n while (p2 >= 0) nums1[p--] = nums2[p2--];\n}", "test_cases": ["nums1=[1,2,3], m=3, nums2=[2,5,6], n=3 -> [1,2,2,3,5,6]", "nums1=[], m=0, nums2=[1], n=1 -> [1]"], "key_points": ["从后往前合并", "三指针技巧"], "tags": ["array", "easy", "Microsoft", "Uber"]} {"problem_id": "algo_00123", "original_id": "max-subarray", "title": "最大子数组和", "category": "array", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "给你一个整数数组 nums ,请你找出一个具有最大和的连续子数组,返回其最大和。", "solution_python": "def maxSubArray(nums):\n max_sum = current = nums[0]\n for num in nums[1:]:\n current = max(num, current + num)\n max_sum = max(max_sum, current)\n return max_sum", "solution_java": "public int maxSubArray(int[] nums) {\n int maxSum = nums[0], curr = nums[0];\n for (int i = 1; i < nums.length; i++) {\n curr = Math.max(nums[i], curr + nums[i]);\n maxSum = Math.max(maxSum, curr);\n }\n return maxSum;\n}", "solution_cpp": "int maxSubArray(vector& nums) {\n int maxSum = nums[0], curr = nums[0];\n for (int i = 1; i < nums.size(); i++) {\n curr = max(nums[i], curr + nums[i]);\n maxSum = max(maxSum, curr);\n }\n return maxSum;\n}", "test_cases": ["nums=[-2,1,-3,4,-1,2,1,-5,4] -> 6", "nums=[1] -> 1"], "key_points": ["Kadane算法", "动态规划基础题"], "tags": ["array", "medium", "Google", "Microsoft"]} {"problem_id": "algo_00124", "original_id": "valid-parentheses", "title": "有效的括号", "category": "string", "difficulty": "easy", "companies": ["Google", "Uber"], "description": "给定一个只包括 '(',')','{','}','[',']' 的字符串 s,判断字符串是否有效。", "solution_python": "def isValid(s):\n stack = []\n mapping = {')': '(', ']': '[', '}': '{'}\n for c in s:\n if c in mapping:\n if not stack or stack[-1] != mapping[c]: return False\n stack.pop()\n else: stack.append(c)\n return not stack", "solution_java": "public boolean isValid(String s) {\n Stack stack = new Stack<>();\n Map map = Map.of(')', '(', ']', '[', '}', '{');\n for (char c : s.toCharArray()) {\n if (map.containsValue(c)) stack.push(c);\n else if (!stack.isEmpty() && stack.pop() != map.get(c)) return false;\n }\n return stack.isEmpty();\n}", "solution_cpp": "bool isValid(string s) {\n stack st;\n unordered_map m = {{')','('},{']','['},{'}','{'}};\n for (char c : s) {\n if (m.find(c) == m.end()) st.push(c);\n else if (st.empty() || st.top() != m[c]) return false;\n else st.pop();\n }\n return st.empty();\n}", "test_cases": ["s=\"()\" -> true", "s=\"()[]{}\" -> true", "s=\"(]\" -> false"], "key_points": ["栈匹配法", "注意空栈边界"], "tags": ["string", "easy", "Google", "Uber"]} {"problem_id": "algo_00125", "original_id": "longest-palindrome", "title": "最长回文子串", "category": "string", "difficulty": "medium", "companies": ["Google", "Amazon"], "description": "给你一个字符串 s,找到 s 中最长的回文子串。", "solution_python": "def longestPalindrome(s):\n def expand(l, r):\n while l >= 0 and r < len(s) and s[l] == s[r]: l -= 1; r += 1\n return l + 1, r - 1\n start = end = 0\n for i in range(len(s)):\n l1, r1 = expand(i, i)\n l2, r2 = expand(i, i + 1)\n if r1 - l1 > end - start: start, end = l1, r1\n if r2 - l2 > end - start: start, end = l2, r2\n return s[start:end+1]", "solution_java": "public String longestPalindrome(String s) {\n int start = 0, end = 0;\n for (int i = 0; i < s.length(); i++) {\n int len1 = expand(s, i, i), len2 = expand(s, i, i+1);\n int len = Math.max(len1, len2);\n if (len > end - start) { start = i - (len-1)/2; end = i + len/2; }\n }\n return s.substring(start, end + 1);\n}\nprivate int expand(String s, int l, int r) {\n while (l >= 0 && r < s.length() && s.charAt(l) == s.charAt(r)) { l--; r++; }\n return r - l - 1;\n}", "solution_cpp": "string longestPalindrome(string s) {\n int start = 0, end = 0;\n for (int i = 0; i < s.size(); i++) {\n int len1 = expand(s, i, i), len2 = expand(s, i, i+1);\n if (max(len1, len2) > end - start) { start = i - (max(len1,len2)-1)/2; end = i + max(len1,len2)/2; }\n }\n return s.substr(start, end - start + 1);\n}", "test_cases": ["s=\"babad\" -> bab或aba", "s=\"cbbd\" -> bb"], "key_points": ["中心扩展法", "处理奇偶长度"], "tags": ["string", "medium", "Google", "Amazon"]} {"problem_id": "algo_00126", "original_id": "reverse-list", "title": "反转链表", "category": "linkedlist", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "给你单链表的头节点 head,请你反转链表,并返回反转后的链表。", "solution_python": "def reverseList(head):\n prev = None\n curr = head\n while curr:\n nxt = curr.next\n curr.next = prev\n prev = curr\n curr = nxt\n return prev", "solution_java": "public ListNode reverseList(ListNode head) {\n ListNode prev = null, curr = head;\n while (curr != null) {\n ListNode next = curr.next;\n curr.next = prev;\n prev = curr;\n curr = next;\n }\n return prev;\n}", "solution_cpp": "ListNode* reverseList(ListNode* head) {\n ListNode* prev = nullptr, *curr = head;\n while (curr) {\n ListNode* next = curr->next;\n curr->next = prev;\n prev = curr;\n curr = next;\n }\n return prev;\n}", "test_cases": ["head=[1,2,3,4,5] -> [5,4,3,2,1]", "head=[1,2] -> [2,1]"], "key_points": ["迭代法 O(1)空间", "递归法 O(n)空间"], "tags": ["linkedlist", "medium", "Google", "Microsoft"]} {"problem_id": "algo_00127", "original_id": "middle-node", "title": "链表的中间结点", "category": "linkedlist", "difficulty": "easy", "companies": ["Amazon", "Facebook"], "description": "给你单链表的头节点 head,请你找出并返回链表的中间结点。如果有两个中间结点,则返回第二个中间结点。", "solution_python": "def middleNode(head):\n slow = fast = head\n while fast and fast.next:\n slow = slow.next\n fast = fast.next.next\n return slow", "solution_java": "public ListNode middleNode(ListNode head) {\n ListNode slow = head, fast = head;\n while (fast != null && fast.next != null) {\n slow = slow.next;\n fast = fast.next.next;\n }\n return slow;\n}", "solution_cpp": "ListNode* middleNode(ListNode* head) {\n ListNode* slow = head, *fast = head;\n while (fast && fast->next) { slow = slow->next; fast = fast->next->next; }\n return slow;\n}", "test_cases": ["head=[1,2,3,4,5] -> 3", "head=[1,2,3,4,5,6] -> 4"], "key_points": ["快慢指针", "O(n)时间O(1)空间"], "tags": ["linkedlist", "easy", "Amazon", "Facebook"]} {"problem_id": "algo_00128", "original_id": "max-depth", "title": "二叉树的最大深度", "category": "tree", "difficulty": "easy", "companies": ["Microsoft", "Apple"], "description": "给定一个二叉树 root,返回其最大深度。", "solution_python": "def maxDepth(root):\n if not root: return 0\n return max(maxDepth(root.left), maxDepth(root.right)) + 1", "solution_java": "public int maxDepth(TreeNode root) {\n if (root == null) return 0;\n return Math.max(maxDepth(root.left), maxDepth(root.right)) + 1;\n}", "solution_cpp": "int maxDepth(TreeNode* root) {\n if (!root) return 0;\n return max(maxDepth(root->left), maxDepth(root->right)) + 1;\n}", "test_cases": ["root=[3,9,20,null,null,15,7] -> 3", "root=[1,null,2] -> 2"], "key_points": ["DFS递归", "层序遍历也可"], "tags": ["tree", "easy", "Microsoft", "Apple"]} {"problem_id": "algo_00129", "original_id": "inorder-traversal", "title": "二叉树的中序遍历", "category": "tree", "difficulty": "easy", "companies": ["Google", "Microsoft"], "description": "给定一个二叉树的根节点 root,返回它的中序遍历结果。", "solution_python": "def inorderTraversal(root):\n result = []\n def dfs(node):\n if node:\n dfs(node.left)\n result.append(node.val)\n dfs(node.right)\n dfs(root)\n return result", "solution_java": "public List inorderTraversal(TreeNode root) {\n List res = new ArrayList<>();\n dfs(root, res);\n return res;\n}\nprivate void dfs(TreeNode node, List res) {\n if (node == null) return;\n dfs(node.left, res); res.add(node.val); dfs(node.right, res);\n}", "solution_cpp": "vector inorderTraversal(TreeNode* root) {\n vector res;\n dfs(root, res);\n return res;\n}\nvoid dfs(TreeNode* node, vector& res) {\n if (!node) return;\n dfs(node->left, res); res.push_back(node->val); dfs(node->right, res);\n}", "test_cases": ["root=[1,null,2,3] -> [1,3,2]", "root=[] -> []"], "key_points": ["左-根-右顺序", "递归最简洁"], "tags": ["tree", "easy", "Google", "Microsoft"]} {"problem_id": "algo_00130", "original_id": "binary-search", "title": "二分查找", "category": "binarysearch", "difficulty": "easy", "companies": ["Google", "Amazon"], "description": "给定一个 n 个元素有序的(升序)整型数组 nums 和一个目标值 target,写一个函数搜索 nums 中的 target,如果目标值存在返回下标,否则返回 -1。", "solution_python": "def search(nums, target):\n left, right = 0, len(nums) - 1\n while left <= right:\n mid = (left + right) // 2\n if nums[mid] == target: return mid\n elif nums[mid] < target: left = mid + 1\n else: right = mid - 1\n return -1", "solution_java": "public int search(int[] nums, int target) {\n int left = 0, right = nums.length - 1;\n while (left <= right) {\n int mid = left + (right - left) / 2;\n if (nums[mid] == target) return mid;\n else if (nums[mid] < target) left = mid + 1;\n else right = mid - 1;\n }\n return -1;\n}", "solution_cpp": "int search(vector& nums, int target) {\n int left = 0, right = nums.size() - 1;\n while (left <= right) {\n int mid = left + (right - left) / 2;\n if (nums[mid] == target) return mid;\n else if (nums[mid] < target) left = mid + 1;\n else right = mid - 1;\n }\n return -1;\n}", "test_cases": ["nums=[-1,0,3,5,9,12], target=9 -> 4", "nums=[-1,0,3,5,9,12], target=2 -> -1"], "key_points": ["标准模板", "注意防溢出写法"], "tags": ["binarysearch", "easy", "Google", "Amazon"]} {"problem_id": "algo_00131", "original_id": "climbing-stairs", "title": "爬楼梯", "category": "dp", "difficulty": "easy", "companies": ["Amazon", "Google"], "description": "假设你正在爬楼梯。需要 n 阶你才能到达楼顶。每次你可以爬 1 或 2 个台阶。你有多少种不同的方法可以爬到楼顶?", "solution_python": "def climbStairs(n):\n if n <= 2: return n\n a, b = 1, 2\n for _ in range(3, n+1):\n a, b = b, a + b\n return b", "solution_java": "public int climbStairs(int n) {\n if (n <= 2) return n;\n int a = 1, b = 2;\n for (int i = 3; i <= n; i++) { int temp = a + b; a = b; b = temp; }\n return b;\n}", "solution_cpp": "int climbStairs(int n) {\n if (n <= 2) return n;\n int a = 1, b = 2;\n for (int i = 3; i <= n; i++) { int temp = a + b; a = b; b = temp; }\n return b;\n}", "test_cases": ["n=2 -> 2", "n=3 -> 3", "n=5 -> 8"], "key_points": ["斐波那契数列", "滚动数组优化空间"], "tags": ["dp", "easy", "Amazon", "Google"]} {"problem_id": "algo_00132", "original_id": "coin-change", "title": "零钱兑换", "category": "dp", "difficulty": "medium", "companies": ["Google", "Amazon"], "description": "给你一个整数数组 coins 表示不同面额的硬币,以及一个整数 amount 表示总金额。计算并返回可以凑成总金额所需的最少的硬币个数。如果没有任何一种硬币组合能组成总金额,返回 -1。", "solution_python": "def coinChange(coins, amount):\n dp = [float('inf')] * (amount + 1)\n dp[0] = 0\n for coin in coins:\n for x in range(coin, amount + 1):\n dp[x] = min(dp[x], dp[x - coin] + 1)\n return dp[amount] if dp[amount] != float('inf') else -1", "solution_java": "public int coinChange(int[] coins, int amount) {\n int[] dp = new int[amount + 1];\n Arrays.fill(dp, amount + 1);\n dp[0] = 0;\n for (int coin : coins) {\n for (int x = coin; x <= amount; x++) {\n dp[x] = Math.min(dp[x], dp[x - coin] + 1);\n }\n }\n return dp[amount] > amount ? -1 : dp[amount];\n}", "solution_cpp": "int coinChange(vector& coins, int amount) {\n vector dp(amount + 1, amount + 1);\n dp[0] = 0;\n for (int coin : coins) {\n for (int x = coin; x <= amount; x++) {\n dp[x] = min(dp[x], dp[x - coin] + 1);\n }\n }\n return dp[amount] > amount ? -1 : dp[amount];\n}", "test_cases": ["coins=[1,2,5], amount=11 -> 3", "coins=[2], amount=3 -> -1"], "key_points": ["完全背包问题", "dp[x] = min(dp[x-coin]+1)"], "tags": ["dp", "medium", "Google", "Amazon"]} {"problem_id": "algo_00133", "original_id": "subsets", "title": "子集", "category": "backtracking", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "给你一个整数数组 nums ,数组中的元素 互不相同 。返回该数组所有可能的子集(幂集)。", "solution_python": "def subsets(nums):\n result = []\n def backtrack(start, path):\n result.append(path[:])\n for i in range(start, len(nums)):\n path.append(nums[i])\n backtrack(i + 1, path)\n path.pop()\n backtrack(0, [])\n return result", "solution_java": "public List> subsets(int[] nums) {\n List> result = new ArrayList<>();\n backtrack(nums, 0, new ArrayList<>(), result);\n return result;\n}\nprivate void backtrack(int[] nums, int start, List path, List> result) {\n result.add(new ArrayList<>(path));\n for (int i = start; i < nums.length; i++) {\n path.add(nums[i]);\n backtrack(nums, i + 1, path, result);\n path.remove(path.size() - 1);\n }\n}", "solution_cpp": "vector> subsets(vector& nums) {\n vector> result;\n vector path;\n backtrack(nums, 0, path, result);\n return result;\n}\nvoid backtrack(vector& nums, int start, vector& path, vector>& result) {\n result.push_back(path);\n for (int i = start; i < nums.size(); i++) {\n path.push_back(nums[i]);\n backtrack(nums, i + 1, path, result);\n path.pop_back();\n }\n}", "test_cases": ["nums=[1,2,3] -> [[],[1],[2],[1,2],[3],[1,3],[2,3],[1,2,3]]"], "key_points": ["选或不选", "DFS遍历子集树"], "tags": ["backtracking", "medium", "Google", "Microsoft"]} {"problem_id": "algo_00134", "original_id": "permutations", "title": "全排列", "category": "backtracking", "difficulty": "medium", "companies": ["Google", "Facebook"], "description": "给定一个不含重复数字的数组 nums,返回其所有可能的全排列。", "solution_python": "def permute(nums):\n result = []\n def backtrack(path, used):\n if len(path) == len(nums):\n result.append(path[:])\n return\n for i in range(len(nums)):\n if used[i]: continue\n used[i] = True\n path.append(nums[i])\n backtrack(path, used)\n path.pop()\n used[i] = False\n backtrack([], [False]*len(nums))\n return result", "solution_java": "public List> permute(int[] nums) {\n List> result = new ArrayList<>();\n boolean[] used = new boolean[nums.length];\n backtrack(nums, used, new ArrayList<>(), result);\n return result;\n}\nprivate void backtrack(int[] nums, boolean[] used, List path, List> result) {\n if (path.size() == nums.length) { result.add(new ArrayList<>(path)); return; }\n for (int i = 0; i < nums.length; i++) {\n if (used[i]) continue;\n used[i] = true;\n path.add(nums[i]);\n backtrack(nums, used, path, result);\n path.remove(path.size() - 1);\n used[i] = false;\n }\n}", "solution_cpp": "vector> permute(vector& nums) {\n vector> result;\n vector used(nums.size(), false);\n vector path;\n backtrack(nums, used, path, result);\n return result;\n}\nvoid backtrack(vector& nums, vector& used, vector& path, vector>& result) {\n if (path.size() == nums.size()) { result.push_back(path); return; }\n for (int i = 0; i < nums.size(); i++) {\n if (used[i]) continue;\n used[i] = true;\n path.push_back(nums[i]);\n backtrack(nums, used, path, result);\n path.pop_back();\n used[i] = false;\n }\n}", "test_cases": ["nums=[1,2,3] -> [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]"], "key_points": ["标记已使用元素", "回溯经典模板"], "tags": ["backtracking", "medium", "Google", "Facebook"]} {"problem_id": "algo_00135", "original_id": "top-k-frequent", "title": "前K个高频元素", "category": "heap", "difficulty": "medium", "companies": ["Amazon", "Facebook"], "description": "给你一个整数数组 nums 和一个整数 k,请你返回其中出现频率前 k 高的元素。", "solution_python": "import heapq\nfrom collections import Counter\ndef topKFrequent(nums, k):\n count = Counter(nums)\n heap = []\n for num, freq in count.items():\n heapq.heappush(heap, (freq, num))\n if len(heap) > k: heapq.heappop(heap)\n return [num for freq, num in heap]", "solution_java": "public int[] topKFrequent(int[] nums, int k) {\n Map count = new HashMap<>();\n for (int n : nums) count.put(n, count.getOrDefault(n, 0) + 1);\n PriorityQueue> heap = \n new PriorityQueue<>((a, b) -> a.getValue() - b.getValue());\n for (Map.Entry e : count.entrySet()) {\n heap.offer(e);\n if (heap.size() > k) heap.poll();\n }\n int[] res = new int[k];\n for (int i = k - 1; i >= 0; i--) res[i] = heap.poll().getKey();\n return res;\n}", "solution_cpp": "vector topKFrequent(vector& nums, int k) {\n unordered_map count;\n for (int n : nums) count[n]++;\n priority_queue, vector>, greater>> heap;\n for (auto& [num, freq] : count) {\n heap.push({freq, num});\n if (heap.size() > k) heap.pop();\n }\n vector res;\n while (!heap.empty()) { res.push_back(heap.top().second); heap.pop(); }\n reverse(res.begin(), res.end());\n return res;\n}", "test_cases": ["nums=[1,1,1,2,2,3], k=2 -> [1,2]", "nums=[1], k=1 -> [1]"], "key_points": ["小顶堆保持大小k", "时间复杂度O(nlogk)"], "tags": ["heap", "medium", "Amazon", "Facebook"]} {"problem_id": "algo_00136", "original_id": "3sum", "title": "三数之和", "category": "two-pointers", "difficulty": "medium", "companies": ["Google", "Amazon"], "description": "给你一个整数数组 nums,判断是否存在三元组满足和为0,返回所有不重复的三元组。", "solution_python": "def threeSum(nums):\n nums.sort()\n result = []\n for i in range(len(nums) - 2):\n if i > 0 and nums[i] == nums[i-1]: continue\n left, right = i + 1, len(nums) - 1\n while left < right:\n total = nums[i] + nums[left] + nums[right]\n if total < 0: left += 1\n elif total > 0: right -= 1\n else:\n result.append([nums[i], nums[left], nums[right]])\n while left < right and nums[left] == nums[left+1]: left += 1\n while left < right and nums[right] == nums[right-1]: right -= 1\n left += 1; right -= 1\n return result", "solution_java": "public List> threeSum(int[] nums) {\n Arrays.sort(nums);\n List> result = new ArrayList<>();\n for (int i = 0; i < nums.length - 2; i++) {\n if (i > 0 && nums[i] == nums[i-1]) continue;\n int left = i + 1, right = nums.length - 1;\n while (left < right) {\n int total = nums[i] + nums[left] + nums[right];\n if (total < 0) left++;\n else if (total > 0) right--;\n else {\n result.add(Arrays.asList(nums[i], nums[left], nums[right]));\n while (left < right && nums[left] == nums[left+1]) left++;\n while (left < right && nums[right] == nums[right-1]) right--;\n left++; right--;\n }\n }\n }\n return result;\n}", "solution_cpp": "vector> threeSum(vector& nums) {\n sort(nums.begin(), nums.end());\n vector> result;\n for (int i = 0; i < nums.size() - 2; i++) {\n if (i > 0 && nums[i] == nums[i-1]) continue;\n int left = i + 1, right = nums.size() - 1;\n while (left < right) {\n int total = nums[i] + nums[left] + nums[right];\n if (total < 0) left++;\n else if (total > 0) right--;\n else {\n result.push_back({nums[i], nums[left], nums[right]});\n while (left < right && nums[left] == nums[left+1]) left++;\n while (left < right && nums[right] == nums[right-1]) right--;\n left++; right--;\n }\n }\n }\n return result;\n}", "test_cases": ["nums=[-1,0,1,2,-1,-4] -> [[-1,-1,2],[-1,0,1]]"], "key_points": ["排序+双指针", "去重是关键"], "tags": ["two-pointers", "medium", "Google", "Amazon"]} {"problem_id": "algo_00137", "original_id": "container-water", "title": "盛最多水的容器", "category": "two-pointers", "difficulty": "medium", "companies": ["Google", "Uber"], "description": "给定一个长度为 n 的整数数组 height,找出其中的两条线,使得它们与 x 轴共同构成的容器可以容纳最多的水。", "solution_python": "def maxArea(height):\n left, right = 0, len(height) - 1\n max_area = 0\n while left < right:\n h = min(height[left], height[right])\n max_area = max(max_area, h * (right - left))\n if height[left] < height[right]: left += 1\n else: right -= 1\n return max_area", "solution_java": "public int maxArea(int[] height) {\n int left = 0, right = height.length - 1, maxArea = 0;\n while (left < right) {\n int h = Math.min(height[left], height[right]);\n maxArea = Math.max(maxArea, h * (right - left));\n if (height[left] < height[right]) left++;\n else right--;\n }\n return maxArea;\n}", "solution_cpp": "int maxArea(vector& height) {\n int left = 0, right = height.size() - 1, maxArea = 0;\n while (left < right) {\n int h = min(height[left], height[right]);\n maxArea = max(maxArea, h * (right - left));\n if (height[left] < height[right]) left++;\n else right--;\n }\n return maxArea;\n}", "test_cases": ["height=[1,8,6,2,5,4,8,3,7] -> 49"], "key_points": ["移动短边指针", "面积=min(h1,h2)*width"], "tags": ["two-pointers", "medium", "Google", "Uber"]} {"problem_id": "algo_00138", "original_id": "min-stack", "title": "最小栈", "category": "stack", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "设计一个支持 push,pop,top 操作,并能在常数时间内检索到最小元素的栈。", "solution_python": "class MinStack:\n def __init__(self):\n self.stack = []\n self.min_stack = []\n def push(self, val):\n self.stack.append(val)\n self.min_stack.append(min(val, self.min_stack[-1] if self.min_stack else val))\n def pop(self):\n self.stack.pop(); self.min_stack.pop()\n def top(self): return self.stack[-1]\n def getMin(self): return self.min_stack[-1]", "solution_java": "class MinStack {\n Stack stack = new Stack<>();\n Stack minStack = new Stack<>();\n public void push(int val) { stack.push(val); minStack.push(Math.min(val, minStack.isEmpty() ? val : minStack.peek())); }\n public void pop() { stack.pop(); minStack.pop(); }\n public int top() { return stack.peek(); }\n public int getMin() { return minStack.peek(); }\n}", "solution_cpp": "class MinStack {\n stack st, minSt;\npublic:\n void push(int val) { st.push(val); minSt.push(min(val, minSt.empty() ? val : minSt.top())); }\n void pop() { st.pop(); minSt.pop(); }\n int top() { return st.top(); }\n int getMin() { return minSt.top(); }\n};", "test_cases": ["push(-2), push(0), push(-3) -> getMin() returns -3"], "key_points": ["辅助栈记录最小值", "O(1)时间获取最小值"], "tags": ["stack", "medium", "Google", "Microsoft"]} {"problem_id": "algo_00139", "original_id": "lru-cache", "title": "LRU缓存", "category": "design", "difficulty": "hard", "companies": ["Google", "Amazon"], "description": "设计和实现一个 LRU(最近最少使用)缓存机制。", "solution_python": "class LRUCache:\n def __init__(self, capacity):\n self.capacity = capacity\n self.cache = {}\n self.order = []\n def get(self, key):\n if key not in self.cache: return -1\n self.order.remove(key); self.order.append(key)\n return self.cache[key]\n def put(self, key, value):\n if key in self.cache:\n self.order.remove(key)\n elif len(self.cache) >= self.capacity:\n del self.cache[self.order.pop(0)]\n self.cache[key] = value; self.order.append(key)", "solution_java": "class LRUCache {\n int capacity;\n LinkedHashMap cache = new LinkedHashMap<>();\n public LRUCache(int cap) { capacity = cap; }\n public int get(int key) { return cache.containsKey(key) ? cache.remove(key) : -1; }\n public void put(int key, int val) {\n if (cache.containsKey(key)) cache.remove(key);\n else if (cache.size() >= capacity) cache.remove(cache.keySet().iterator().next());\n cache.put(key, val);\n }\n}", "solution_cpp": "class LRUCache {\n int cap;\n list> dll;\n unordered_map>::iterator> cache;\npublic:\n LRUCache(int capacity) : cap(capacity) {}\n int get(int key) {\n auto it = cache.find(key);\n if (it == cache.end()) return -1;\n dll.splice(dll.end(), dll, it->second);\n return it->second->second;\n }\n void put(int key, int value) {\n auto it = cache.find(key);\n if (it != cache.end()) dll.erase(it->second);\n else if (cache.size() >= cap) { cache.erase(dll.front().first); dll.pop_front(); }\n dll.push_back({key, value});\n cache[key] = --dll.end();\n }\n};", "test_cases": ["put(1,1), put(2,2), get(1) -> 1"], "key_points": ["HashMap + 双向链表", "O(1)时间操作"], "tags": ["design", "hard", "Google", "Amazon"]} {"problem_id": "algo_00140", "original_id": "num-islands", "title": "岛屿数量", "category": "graph", "difficulty": "medium", "companies": ["Google", "Facebook"], "description": "给你一个由 '1'(陆地)和 '0'(水)组成的二维网格,请你计算网格中岛屿的数量。岛屿总是被水包围,且只能由水平或垂直方向相邻的陆地连接形成。", "solution_python": "def numIslands(grid):\n if not grid: return 0\n rows, cols = len(grid), len(grid[0])\n count = 0\n def dfs(r, c):\n if r < 0 or r >= rows or c < 0 or c >= cols or grid[r][c] != '1': return\n grid[r][c] = '0'\n dfs(r+1, c); dfs(r-1, c); dfs(r, c+1); dfs(r, c-1)\n for r in range(rows):\n for c in range(cols):\n if grid[r][c] == '1': count += 1; dfs(r, c)\n return count", "solution_java": "public int numIslands(char[][] grid) {\n if (grid.length == 0) return 0;\n int count = 0;\n for (int i = 0; i < grid.length; i++)\n for (int j = 0; j < grid[0].length; j++)\n if (grid[i][j] == '1') { count++; dfs(grid, i, j); }\n return count;\n}\nprivate void dfs(char[][] grid, int r, int c) {\n if (r < 0 || r >= grid.length || c < 0 || c >= grid[0].length || grid[r][c] != '1') return;\n grid[r][c] = '0';\n dfs(grid, r+1, c); dfs(grid, r-1, c); dfs(grid, r, c+1); dfs(grid, r, c-1);\n}", "solution_cpp": "int numIslands(vector>& grid) {\n if (grid.empty()) return 0;\n int count = 0;\n for (int i = 0; i < grid.size(); i++)\n for (int j = 0; j < grid[0].size(); j++)\n if (grid[i][j] == '1') { count++; dfs(grid, i, j); }\n return count;\n}\nvoid dfs(vector>& grid, int r, int c) {\n if (r < 0 || r >= grid.size() || c < 0 || c >= grid[0].size() || grid[r][c] != '1') return;\n grid[r][c] = '0';\n dfs(grid, r+1, c); dfs(grid, r-1, c); dfs(grid, r, c+1); dfs(grid, r, c-1);\n}", "test_cases": ["grid=[[1,1,1,1,0],[1,1,0,1,0],[1,1,0,0,0],[0,0,0,0,0]] -> 1"], "key_points": ["DFS/BFS遍历", "访问后标记为0避免重复"], "tags": ["graph", "medium", "Google", "Facebook"]} {"problem_id": "algo_00141", "original_id": "two-sum", "title": "两数之和", "category": "array", "difficulty": "easy", "companies": ["Amazon", "Google"], "description": "给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那两个整数,并返回他们的数组下标。", "solution_python": "def twoSum(nums, target):\n hashmap = {}\n for i, num in enumerate(nums):\n complement = target - num\n if complement in hashmap:\n return [hashmap[complement], i]\n hashmap[num] = i\n return []", "solution_java": "public int[] twoSum(int[] nums, int target) {\n Map map = new HashMap<>();\n for (int i = 0; i < nums.length; i++) {\n int complement = target - nums[i];\n if (map.containsKey(complement)) return new int[]{map.get(complement), i};\n map.put(nums[i], i);\n }\n return new int[]{};\n}", "solution_cpp": "vector twoSum(vector& nums, int target) {\n unordered_map m;\n for (int i = 0; i < nums.size(); i++) {\n if (m.count(target - nums[i])) return {m[target - nums[i]], i};\n m[nums[i]] = i;\n }\n return {};\n}", "test_cases": ["nums=[2,7,11,15], target=9 -> [0,1]", "nums=[3,2,4], target=6 -> [1,2]"], "key_points": ["哈希表一次遍历", "空间换时间"], "tags": ["array", "easy", "Amazon", "Google"]} {"problem_id": "algo_00142", "original_id": "merge-sorted", "title": "合并两个有序数组", "category": "array", "difficulty": "easy", "companies": ["Microsoft", "Uber"], "description": "给你两个按非递减顺序排列的整数数组 nums1 和 nums2,另有两个整数 m 和 n,分别表示 nums1 和 nums2 中的元素数目。请你合并 nums2 到 nums1 中。", "solution_python": "def merge(nums1, m, nums2, n):\n p1, p2, p = m-1, n-1, m+n-1\n while p1 >= 0 and p2 >= 0:\n if nums1[p1] > nums2[p2]: nums1[p] = nums1[p1]; p1 -= 1\n else: nums1[p] = nums2[p2]; p2 -= 1\n p -= 1\n while p2 >= 0: nums1[p] = nums2[p2]; p2 -= 1; p -= 1", "solution_java": "public void merge(int[] nums1, int m, int[] nums2, int n) {\n int p1 = m-1, p2 = n-1, p = m+n-1;\n while (p1 >= 0 && p2 >= 0) {\n nums1[p--] = nums1[p1] > nums2[p2] ? nums1[p1--] : nums2[p2--];\n }\n while (p2 >= 0) nums1[p--] = nums2[p2--];\n}", "solution_cpp": "void merge(vector& nums1, int m, vector& nums2, int n) {\n int p1 = m-1, p2 = n-1, p = m+n-1;\n while (p1 >= 0 && p2 >= 0) nums1[p--] = nums1[p1] > nums2[p2] ? nums1[p1--] : nums2[p2--];\n while (p2 >= 0) nums1[p--] = nums2[p2--];\n}", "test_cases": ["nums1=[1,2,3], m=3, nums2=[2,5,6], n=3 -> [1,2,2,3,5,6]", "nums1=[], m=0, nums2=[1], n=1 -> [1]"], "key_points": ["从后往前合并", "三指针技巧"], "tags": ["array", "easy", "Microsoft", "Uber"]} {"problem_id": "algo_00143", "original_id": "max-subarray", "title": "最大子数组和", "category": "array", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "给你一个整数数组 nums ,请你找出一个具有最大和的连续子数组,返回其最大和。", "solution_python": "def maxSubArray(nums):\n max_sum = current = nums[0]\n for num in nums[1:]:\n current = max(num, current + num)\n max_sum = max(max_sum, current)\n return max_sum", "solution_java": "public int maxSubArray(int[] nums) {\n int maxSum = nums[0], curr = nums[0];\n for (int i = 1; i < nums.length; i++) {\n curr = Math.max(nums[i], curr + nums[i]);\n maxSum = Math.max(maxSum, curr);\n }\n return maxSum;\n}", "solution_cpp": "int maxSubArray(vector& nums) {\n int maxSum = nums[0], curr = nums[0];\n for (int i = 1; i < nums.size(); i++) {\n curr = max(nums[i], curr + nums[i]);\n maxSum = max(maxSum, curr);\n }\n return maxSum;\n}", "test_cases": ["nums=[-2,1,-3,4,-1,2,1,-5,4] -> 6", "nums=[1] -> 1"], "key_points": ["Kadane算法", "动态规划基础题"], "tags": ["array", "medium", "Google", "Microsoft"]} {"problem_id": "algo_00144", "original_id": "valid-parentheses", "title": "有效的括号", "category": "string", "difficulty": "easy", "companies": ["Google", "Uber"], "description": "给定一个只包括 '(',')','{','}','[',']' 的字符串 s,判断字符串是否有效。", "solution_python": "def isValid(s):\n stack = []\n mapping = {')': '(', ']': '[', '}': '{'}\n for c in s:\n if c in mapping:\n if not stack or stack[-1] != mapping[c]: return False\n stack.pop()\n else: stack.append(c)\n return not stack", "solution_java": "public boolean isValid(String s) {\n Stack stack = new Stack<>();\n Map map = Map.of(')', '(', ']', '[', '}', '{');\n for (char c : s.toCharArray()) {\n if (map.containsValue(c)) stack.push(c);\n else if (!stack.isEmpty() && stack.pop() != map.get(c)) return false;\n }\n return stack.isEmpty();\n}", "solution_cpp": "bool isValid(string s) {\n stack st;\n unordered_map m = {{')','('},{']','['},{'}','{'}};\n for (char c : s) {\n if (m.find(c) == m.end()) st.push(c);\n else if (st.empty() || st.top() != m[c]) return false;\n else st.pop();\n }\n return st.empty();\n}", "test_cases": ["s=\"()\" -> true", "s=\"()[]{}\" -> true", "s=\"(]\" -> false"], "key_points": ["栈匹配法", "注意空栈边界"], "tags": ["string", "easy", "Google", "Uber"]} {"problem_id": "algo_00145", "original_id": "longest-palindrome", "title": "最长回文子串", "category": "string", "difficulty": "medium", "companies": ["Google", "Amazon"], "description": "给你一个字符串 s,找到 s 中最长的回文子串。", "solution_python": "def longestPalindrome(s):\n def expand(l, r):\n while l >= 0 and r < len(s) and s[l] == s[r]: l -= 1; r += 1\n return l + 1, r - 1\n start = end = 0\n for i in range(len(s)):\n l1, r1 = expand(i, i)\n l2, r2 = expand(i, i + 1)\n if r1 - l1 > end - start: start, end = l1, r1\n if r2 - l2 > end - start: start, end = l2, r2\n return s[start:end+1]", "solution_java": "public String longestPalindrome(String s) {\n int start = 0, end = 0;\n for (int i = 0; i < s.length(); i++) {\n int len1 = expand(s, i, i), len2 = expand(s, i, i+1);\n int len = Math.max(len1, len2);\n if (len > end - start) { start = i - (len-1)/2; end = i + len/2; }\n }\n return s.substring(start, end + 1);\n}\nprivate int expand(String s, int l, int r) {\n while (l >= 0 && r < s.length() && s.charAt(l) == s.charAt(r)) { l--; r++; }\n return r - l - 1;\n}", "solution_cpp": "string longestPalindrome(string s) {\n int start = 0, end = 0;\n for (int i = 0; i < s.size(); i++) {\n int len1 = expand(s, i, i), len2 = expand(s, i, i+1);\n if (max(len1, len2) > end - start) { start = i - (max(len1,len2)-1)/2; end = i + max(len1,len2)/2; }\n }\n return s.substr(start, end - start + 1);\n}", "test_cases": ["s=\"babad\" -> bab或aba", "s=\"cbbd\" -> bb"], "key_points": ["中心扩展法", "处理奇偶长度"], "tags": ["string", "medium", "Google", "Amazon"]} {"problem_id": "algo_00146", "original_id": "reverse-list", "title": "反转链表", "category": "linkedlist", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "给你单链表的头节点 head,请你反转链表,并返回反转后的链表。", "solution_python": "def reverseList(head):\n prev = None\n curr = head\n while curr:\n nxt = curr.next\n curr.next = prev\n prev = curr\n curr = nxt\n return prev", "solution_java": "public ListNode reverseList(ListNode head) {\n ListNode prev = null, curr = head;\n while (curr != null) {\n ListNode next = curr.next;\n curr.next = prev;\n prev = curr;\n curr = next;\n }\n return prev;\n}", "solution_cpp": "ListNode* reverseList(ListNode* head) {\n ListNode* prev = nullptr, *curr = head;\n while (curr) {\n ListNode* next = curr->next;\n curr->next = prev;\n prev = curr;\n curr = next;\n }\n return prev;\n}", "test_cases": ["head=[1,2,3,4,5] -> [5,4,3,2,1]", "head=[1,2] -> [2,1]"], "key_points": ["迭代法 O(1)空间", "递归法 O(n)空间"], "tags": ["linkedlist", "medium", "Google", "Microsoft"]} {"problem_id": "algo_00147", "original_id": "middle-node", "title": "链表的中间结点", "category": "linkedlist", "difficulty": "easy", "companies": ["Amazon", "Facebook"], "description": "给你单链表的头节点 head,请你找出并返回链表的中间结点。如果有两个中间结点,则返回第二个中间结点。", "solution_python": "def middleNode(head):\n slow = fast = head\n while fast and fast.next:\n slow = slow.next\n fast = fast.next.next\n return slow", "solution_java": "public ListNode middleNode(ListNode head) {\n ListNode slow = head, fast = head;\n while (fast != null && fast.next != null) {\n slow = slow.next;\n fast = fast.next.next;\n }\n return slow;\n}", "solution_cpp": "ListNode* middleNode(ListNode* head) {\n ListNode* slow = head, *fast = head;\n while (fast && fast->next) { slow = slow->next; fast = fast->next->next; }\n return slow;\n}", "test_cases": ["head=[1,2,3,4,5] -> 3", "head=[1,2,3,4,5,6] -> 4"], "key_points": ["快慢指针", "O(n)时间O(1)空间"], "tags": ["linkedlist", "easy", "Amazon", "Facebook"]} {"problem_id": "algo_00148", "original_id": "max-depth", "title": "二叉树的最大深度", "category": "tree", "difficulty": "easy", "companies": ["Microsoft", "Apple"], "description": "给定一个二叉树 root,返回其最大深度。", "solution_python": "def maxDepth(root):\n if not root: return 0\n return max(maxDepth(root.left), maxDepth(root.right)) + 1", "solution_java": "public int maxDepth(TreeNode root) {\n if (root == null) return 0;\n return Math.max(maxDepth(root.left), maxDepth(root.right)) + 1;\n}", "solution_cpp": "int maxDepth(TreeNode* root) {\n if (!root) return 0;\n return max(maxDepth(root->left), maxDepth(root->right)) + 1;\n}", "test_cases": ["root=[3,9,20,null,null,15,7] -> 3", "root=[1,null,2] -> 2"], "key_points": ["DFS递归", "层序遍历也可"], "tags": ["tree", "easy", "Microsoft", "Apple"]} {"problem_id": "algo_00149", "original_id": "inorder-traversal", "title": "二叉树的中序遍历", "category": "tree", "difficulty": "easy", "companies": ["Google", "Microsoft"], "description": "给定一个二叉树的根节点 root,返回它的中序遍历结果。", "solution_python": "def inorderTraversal(root):\n result = []\n def dfs(node):\n if node:\n dfs(node.left)\n result.append(node.val)\n dfs(node.right)\n dfs(root)\n return result", "solution_java": "public List inorderTraversal(TreeNode root) {\n List res = new ArrayList<>();\n dfs(root, res);\n return res;\n}\nprivate void dfs(TreeNode node, List res) {\n if (node == null) return;\n dfs(node.left, res); res.add(node.val); dfs(node.right, res);\n}", "solution_cpp": "vector inorderTraversal(TreeNode* root) {\n vector res;\n dfs(root, res);\n return res;\n}\nvoid dfs(TreeNode* node, vector& res) {\n if (!node) return;\n dfs(node->left, res); res.push_back(node->val); dfs(node->right, res);\n}", "test_cases": ["root=[1,null,2,3] -> [1,3,2]", "root=[] -> []"], "key_points": ["左-根-右顺序", "递归最简洁"], "tags": ["tree", "easy", "Google", "Microsoft"]} {"problem_id": "algo_00150", "original_id": "binary-search", "title": "二分查找", "category": "binarysearch", "difficulty": "easy", "companies": ["Google", "Amazon"], "description": "给定一个 n 个元素有序的(升序)整型数组 nums 和一个目标值 target,写一个函数搜索 nums 中的 target,如果目标值存在返回下标,否则返回 -1。", "solution_python": "def search(nums, target):\n left, right = 0, len(nums) - 1\n while left <= right:\n mid = (left + right) // 2\n if nums[mid] == target: return mid\n elif nums[mid] < target: left = mid + 1\n else: right = mid - 1\n return -1", "solution_java": "public int search(int[] nums, int target) {\n int left = 0, right = nums.length - 1;\n while (left <= right) {\n int mid = left + (right - left) / 2;\n if (nums[mid] == target) return mid;\n else if (nums[mid] < target) left = mid + 1;\n else right = mid - 1;\n }\n return -1;\n}", "solution_cpp": "int search(vector& nums, int target) {\n int left = 0, right = nums.size() - 1;\n while (left <= right) {\n int mid = left + (right - left) / 2;\n if (nums[mid] == target) return mid;\n else if (nums[mid] < target) left = mid + 1;\n else right = mid - 1;\n }\n return -1;\n}", "test_cases": ["nums=[-1,0,3,5,9,12], target=9 -> 4", "nums=[-1,0,3,5,9,12], target=2 -> -1"], "key_points": ["标准模板", "注意防溢出写法"], "tags": ["binarysearch", "easy", "Google", "Amazon"]} {"problem_id": "algo_00151", "original_id": "climbing-stairs", "title": "爬楼梯", "category": "dp", "difficulty": "easy", "companies": ["Amazon", "Google"], "description": "假设你正在爬楼梯。需要 n 阶你才能到达楼顶。每次你可以爬 1 或 2 个台阶。你有多少种不同的方法可以爬到楼顶?", "solution_python": "def climbStairs(n):\n if n <= 2: return n\n a, b = 1, 2\n for _ in range(3, n+1):\n a, b = b, a + b\n return b", "solution_java": "public int climbStairs(int n) {\n if (n <= 2) return n;\n int a = 1, b = 2;\n for (int i = 3; i <= n; i++) { int temp = a + b; a = b; b = temp; }\n return b;\n}", "solution_cpp": "int climbStairs(int n) {\n if (n <= 2) return n;\n int a = 1, b = 2;\n for (int i = 3; i <= n; i++) { int temp = a + b; a = b; b = temp; }\n return b;\n}", "test_cases": ["n=2 -> 2", "n=3 -> 3", "n=5 -> 8"], "key_points": ["斐波那契数列", "滚动数组优化空间"], "tags": ["dp", "easy", "Amazon", "Google"]} {"problem_id": "algo_00152", "original_id": "coin-change", "title": "零钱兑换", "category": "dp", "difficulty": "medium", "companies": ["Google", "Amazon"], "description": "给你一个整数数组 coins 表示不同面额的硬币,以及一个整数 amount 表示总金额。计算并返回可以凑成总金额所需的最少的硬币个数。如果没有任何一种硬币组合能组成总金额,返回 -1。", "solution_python": "def coinChange(coins, amount):\n dp = [float('inf')] * (amount + 1)\n dp[0] = 0\n for coin in coins:\n for x in range(coin, amount + 1):\n dp[x] = min(dp[x], dp[x - coin] + 1)\n return dp[amount] if dp[amount] != float('inf') else -1", "solution_java": "public int coinChange(int[] coins, int amount) {\n int[] dp = new int[amount + 1];\n Arrays.fill(dp, amount + 1);\n dp[0] = 0;\n for (int coin : coins) {\n for (int x = coin; x <= amount; x++) {\n dp[x] = Math.min(dp[x], dp[x - coin] + 1);\n }\n }\n return dp[amount] > amount ? -1 : dp[amount];\n}", "solution_cpp": "int coinChange(vector& coins, int amount) {\n vector dp(amount + 1, amount + 1);\n dp[0] = 0;\n for (int coin : coins) {\n for (int x = coin; x <= amount; x++) {\n dp[x] = min(dp[x], dp[x - coin] + 1);\n }\n }\n return dp[amount] > amount ? -1 : dp[amount];\n}", "test_cases": ["coins=[1,2,5], amount=11 -> 3", "coins=[2], amount=3 -> -1"], "key_points": ["完全背包问题", "dp[x] = min(dp[x-coin]+1)"], "tags": ["dp", "medium", "Google", "Amazon"]} {"problem_id": "algo_00153", "original_id": "subsets", "title": "子集", "category": "backtracking", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "给你一个整数数组 nums ,数组中的元素 互不相同 。返回该数组所有可能的子集(幂集)。", "solution_python": "def subsets(nums):\n result = []\n def backtrack(start, path):\n result.append(path[:])\n for i in range(start, len(nums)):\n path.append(nums[i])\n backtrack(i + 1, path)\n path.pop()\n backtrack(0, [])\n return result", "solution_java": "public List> subsets(int[] nums) {\n List> result = new ArrayList<>();\n backtrack(nums, 0, new ArrayList<>(), result);\n return result;\n}\nprivate void backtrack(int[] nums, int start, List path, List> result) {\n result.add(new ArrayList<>(path));\n for (int i = start; i < nums.length; i++) {\n path.add(nums[i]);\n backtrack(nums, i + 1, path, result);\n path.remove(path.size() - 1);\n }\n}", "solution_cpp": "vector> subsets(vector& nums) {\n vector> result;\n vector path;\n backtrack(nums, 0, path, result);\n return result;\n}\nvoid backtrack(vector& nums, int start, vector& path, vector>& result) {\n result.push_back(path);\n for (int i = start; i < nums.size(); i++) {\n path.push_back(nums[i]);\n backtrack(nums, i + 1, path, result);\n path.pop_back();\n }\n}", "test_cases": ["nums=[1,2,3] -> [[],[1],[2],[1,2],[3],[1,3],[2,3],[1,2,3]]"], "key_points": ["选或不选", "DFS遍历子集树"], "tags": ["backtracking", "medium", "Google", "Microsoft"]} {"problem_id": "algo_00154", "original_id": "permutations", "title": "全排列", "category": "backtracking", "difficulty": "medium", "companies": ["Google", "Facebook"], "description": "给定一个不含重复数字的数组 nums,返回其所有可能的全排列。", "solution_python": "def permute(nums):\n result = []\n def backtrack(path, used):\n if len(path) == len(nums):\n result.append(path[:])\n return\n for i in range(len(nums)):\n if used[i]: continue\n used[i] = True\n path.append(nums[i])\n backtrack(path, used)\n path.pop()\n used[i] = False\n backtrack([], [False]*len(nums))\n return result", "solution_java": "public List> permute(int[] nums) {\n List> result = new ArrayList<>();\n boolean[] used = new boolean[nums.length];\n backtrack(nums, used, new ArrayList<>(), result);\n return result;\n}\nprivate void backtrack(int[] nums, boolean[] used, List path, List> result) {\n if (path.size() == nums.length) { result.add(new ArrayList<>(path)); return; }\n for (int i = 0; i < nums.length; i++) {\n if (used[i]) continue;\n used[i] = true;\n path.add(nums[i]);\n backtrack(nums, used, path, result);\n path.remove(path.size() - 1);\n used[i] = false;\n }\n}", "solution_cpp": "vector> permute(vector& nums) {\n vector> result;\n vector used(nums.size(), false);\n vector path;\n backtrack(nums, used, path, result);\n return result;\n}\nvoid backtrack(vector& nums, vector& used, vector& path, vector>& result) {\n if (path.size() == nums.size()) { result.push_back(path); return; }\n for (int i = 0; i < nums.size(); i++) {\n if (used[i]) continue;\n used[i] = true;\n path.push_back(nums[i]);\n backtrack(nums, used, path, result);\n path.pop_back();\n used[i] = false;\n }\n}", "test_cases": ["nums=[1,2,3] -> [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]"], "key_points": ["标记已使用元素", "回溯经典模板"], "tags": ["backtracking", "medium", "Google", "Facebook"]} {"problem_id": "algo_00155", "original_id": "top-k-frequent", "title": "前K个高频元素", "category": "heap", "difficulty": "medium", "companies": ["Amazon", "Facebook"], "description": "给你一个整数数组 nums 和一个整数 k,请你返回其中出现频率前 k 高的元素。", "solution_python": "import heapq\nfrom collections import Counter\ndef topKFrequent(nums, k):\n count = Counter(nums)\n heap = []\n for num, freq in count.items():\n heapq.heappush(heap, (freq, num))\n if len(heap) > k: heapq.heappop(heap)\n return [num for freq, num in heap]", "solution_java": "public int[] topKFrequent(int[] nums, int k) {\n Map count = new HashMap<>();\n for (int n : nums) count.put(n, count.getOrDefault(n, 0) + 1);\n PriorityQueue> heap = \n new PriorityQueue<>((a, b) -> a.getValue() - b.getValue());\n for (Map.Entry e : count.entrySet()) {\n heap.offer(e);\n if (heap.size() > k) heap.poll();\n }\n int[] res = new int[k];\n for (int i = k - 1; i >= 0; i--) res[i] = heap.poll().getKey();\n return res;\n}", "solution_cpp": "vector topKFrequent(vector& nums, int k) {\n unordered_map count;\n for (int n : nums) count[n]++;\n priority_queue, vector>, greater>> heap;\n for (auto& [num, freq] : count) {\n heap.push({freq, num});\n if (heap.size() > k) heap.pop();\n }\n vector res;\n while (!heap.empty()) { res.push_back(heap.top().second); heap.pop(); }\n reverse(res.begin(), res.end());\n return res;\n}", "test_cases": ["nums=[1,1,1,2,2,3], k=2 -> [1,2]", "nums=[1], k=1 -> [1]"], "key_points": ["小顶堆保持大小k", "时间复杂度O(nlogk)"], "tags": ["heap", "medium", "Amazon", "Facebook"]} {"problem_id": "algo_00156", "original_id": "3sum", "title": "三数之和", "category": "two-pointers", "difficulty": "medium", "companies": ["Google", "Amazon"], "description": "给你一个整数数组 nums,判断是否存在三元组满足和为0,返回所有不重复的三元组。", "solution_python": "def threeSum(nums):\n nums.sort()\n result = []\n for i in range(len(nums) - 2):\n if i > 0 and nums[i] == nums[i-1]: continue\n left, right = i + 1, len(nums) - 1\n while left < right:\n total = nums[i] + nums[left] + nums[right]\n if total < 0: left += 1\n elif total > 0: right -= 1\n else:\n result.append([nums[i], nums[left], nums[right]])\n while left < right and nums[left] == nums[left+1]: left += 1\n while left < right and nums[right] == nums[right-1]: right -= 1\n left += 1; right -= 1\n return result", "solution_java": "public List> threeSum(int[] nums) {\n Arrays.sort(nums);\n List> result = new ArrayList<>();\n for (int i = 0; i < nums.length - 2; i++) {\n if (i > 0 && nums[i] == nums[i-1]) continue;\n int left = i + 1, right = nums.length - 1;\n while (left < right) {\n int total = nums[i] + nums[left] + nums[right];\n if (total < 0) left++;\n else if (total > 0) right--;\n else {\n result.add(Arrays.asList(nums[i], nums[left], nums[right]));\n while (left < right && nums[left] == nums[left+1]) left++;\n while (left < right && nums[right] == nums[right-1]) right--;\n left++; right--;\n }\n }\n }\n return result;\n}", "solution_cpp": "vector> threeSum(vector& nums) {\n sort(nums.begin(), nums.end());\n vector> result;\n for (int i = 0; i < nums.size() - 2; i++) {\n if (i > 0 && nums[i] == nums[i-1]) continue;\n int left = i + 1, right = nums.size() - 1;\n while (left < right) {\n int total = nums[i] + nums[left] + nums[right];\n if (total < 0) left++;\n else if (total > 0) right--;\n else {\n result.push_back({nums[i], nums[left], nums[right]});\n while (left < right && nums[left] == nums[left+1]) left++;\n while (left < right && nums[right] == nums[right-1]) right--;\n left++; right--;\n }\n }\n }\n return result;\n}", "test_cases": ["nums=[-1,0,1,2,-1,-4] -> [[-1,-1,2],[-1,0,1]]"], "key_points": ["排序+双指针", "去重是关键"], "tags": ["two-pointers", "medium", "Google", "Amazon"]} {"problem_id": "algo_00157", "original_id": "container-water", "title": "盛最多水的容器", "category": "two-pointers", "difficulty": "medium", "companies": ["Google", "Uber"], "description": "给定一个长度为 n 的整数数组 height,找出其中的两条线,使得它们与 x 轴共同构成的容器可以容纳最多的水。", "solution_python": "def maxArea(height):\n left, right = 0, len(height) - 1\n max_area = 0\n while left < right:\n h = min(height[left], height[right])\n max_area = max(max_area, h * (right - left))\n if height[left] < height[right]: left += 1\n else: right -= 1\n return max_area", "solution_java": "public int maxArea(int[] height) {\n int left = 0, right = height.length - 1, maxArea = 0;\n while (left < right) {\n int h = Math.min(height[left], height[right]);\n maxArea = Math.max(maxArea, h * (right - left));\n if (height[left] < height[right]) left++;\n else right--;\n }\n return maxArea;\n}", "solution_cpp": "int maxArea(vector& height) {\n int left = 0, right = height.size() - 1, maxArea = 0;\n while (left < right) {\n int h = min(height[left], height[right]);\n maxArea = max(maxArea, h * (right - left));\n if (height[left] < height[right]) left++;\n else right--;\n }\n return maxArea;\n}", "test_cases": ["height=[1,8,6,2,5,4,8,3,7] -> 49"], "key_points": ["移动短边指针", "面积=min(h1,h2)*width"], "tags": ["two-pointers", "medium", "Google", "Uber"]} {"problem_id": "algo_00158", "original_id": "min-stack", "title": "最小栈", "category": "stack", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "设计一个支持 push,pop,top 操作,并能在常数时间内检索到最小元素的栈。", "solution_python": "class MinStack:\n def __init__(self):\n self.stack = []\n self.min_stack = []\n def push(self, val):\n self.stack.append(val)\n self.min_stack.append(min(val, self.min_stack[-1] if self.min_stack else val))\n def pop(self):\n self.stack.pop(); self.min_stack.pop()\n def top(self): return self.stack[-1]\n def getMin(self): return self.min_stack[-1]", "solution_java": "class MinStack {\n Stack stack = new Stack<>();\n Stack minStack = new Stack<>();\n public void push(int val) { stack.push(val); minStack.push(Math.min(val, minStack.isEmpty() ? val : minStack.peek())); }\n public void pop() { stack.pop(); minStack.pop(); }\n public int top() { return stack.peek(); }\n public int getMin() { return minStack.peek(); }\n}", "solution_cpp": "class MinStack {\n stack st, minSt;\npublic:\n void push(int val) { st.push(val); minSt.push(min(val, minSt.empty() ? val : minSt.top())); }\n void pop() { st.pop(); minSt.pop(); }\n int top() { return st.top(); }\n int getMin() { return minSt.top(); }\n};", "test_cases": ["push(-2), push(0), push(-3) -> getMin() returns -3"], "key_points": ["辅助栈记录最小值", "O(1)时间获取最小值"], "tags": ["stack", "medium", "Google", "Microsoft"]} {"problem_id": "algo_00159", "original_id": "lru-cache", "title": "LRU缓存", "category": "design", "difficulty": "hard", "companies": ["Google", "Amazon"], "description": "设计和实现一个 LRU(最近最少使用)缓存机制。", "solution_python": "class LRUCache:\n def __init__(self, capacity):\n self.capacity = capacity\n self.cache = {}\n self.order = []\n def get(self, key):\n if key not in self.cache: return -1\n self.order.remove(key); self.order.append(key)\n return self.cache[key]\n def put(self, key, value):\n if key in self.cache:\n self.order.remove(key)\n elif len(self.cache) >= self.capacity:\n del self.cache[self.order.pop(0)]\n self.cache[key] = value; self.order.append(key)", "solution_java": "class LRUCache {\n int capacity;\n LinkedHashMap cache = new LinkedHashMap<>();\n public LRUCache(int cap) { capacity = cap; }\n public int get(int key) { return cache.containsKey(key) ? cache.remove(key) : -1; }\n public void put(int key, int val) {\n if (cache.containsKey(key)) cache.remove(key);\n else if (cache.size() >= capacity) cache.remove(cache.keySet().iterator().next());\n cache.put(key, val);\n }\n}", "solution_cpp": "class LRUCache {\n int cap;\n list> dll;\n unordered_map>::iterator> cache;\npublic:\n LRUCache(int capacity) : cap(capacity) {}\n int get(int key) {\n auto it = cache.find(key);\n if (it == cache.end()) return -1;\n dll.splice(dll.end(), dll, it->second);\n return it->second->second;\n }\n void put(int key, int value) {\n auto it = cache.find(key);\n if (it != cache.end()) dll.erase(it->second);\n else if (cache.size() >= cap) { cache.erase(dll.front().first); dll.pop_front(); }\n dll.push_back({key, value});\n cache[key] = --dll.end();\n }\n};", "test_cases": ["put(1,1), put(2,2), get(1) -> 1"], "key_points": ["HashMap + 双向链表", "O(1)时间操作"], "tags": ["design", "hard", "Google", "Amazon"]} {"problem_id": "algo_00160", "original_id": "num-islands", "title": "岛屿数量", "category": "graph", "difficulty": "medium", "companies": ["Google", "Facebook"], "description": "给你一个由 '1'(陆地)和 '0'(水)组成的二维网格,请你计算网格中岛屿的数量。岛屿总是被水包围,且只能由水平或垂直方向相邻的陆地连接形成。", "solution_python": "def numIslands(grid):\n if not grid: return 0\n rows, cols = len(grid), len(grid[0])\n count = 0\n def dfs(r, c):\n if r < 0 or r >= rows or c < 0 or c >= cols or grid[r][c] != '1': return\n grid[r][c] = '0'\n dfs(r+1, c); dfs(r-1, c); dfs(r, c+1); dfs(r, c-1)\n for r in range(rows):\n for c in range(cols):\n if grid[r][c] == '1': count += 1; dfs(r, c)\n return count", "solution_java": "public int numIslands(char[][] grid) {\n if (grid.length == 0) return 0;\n int count = 0;\n for (int i = 0; i < grid.length; i++)\n for (int j = 0; j < grid[0].length; j++)\n if (grid[i][j] == '1') { count++; dfs(grid, i, j); }\n return count;\n}\nprivate void dfs(char[][] grid, int r, int c) {\n if (r < 0 || r >= grid.length || c < 0 || c >= grid[0].length || grid[r][c] != '1') return;\n grid[r][c] = '0';\n dfs(grid, r+1, c); dfs(grid, r-1, c); dfs(grid, r, c+1); dfs(grid, r, c-1);\n}", "solution_cpp": "int numIslands(vector>& grid) {\n if (grid.empty()) return 0;\n int count = 0;\n for (int i = 0; i < grid.size(); i++)\n for (int j = 0; j < grid[0].size(); j++)\n if (grid[i][j] == '1') { count++; dfs(grid, i, j); }\n return count;\n}\nvoid dfs(vector>& grid, int r, int c) {\n if (r < 0 || r >= grid.size() || c < 0 || c >= grid[0].size() || grid[r][c] != '1') return;\n grid[r][c] = '0';\n dfs(grid, r+1, c); dfs(grid, r-1, c); dfs(grid, r, c+1); dfs(grid, r, c-1);\n}", "test_cases": ["grid=[[1,1,1,1,0],[1,1,0,1,0],[1,1,0,0,0],[0,0,0,0,0]] -> 1"], "key_points": ["DFS/BFS遍历", "访问后标记为0避免重复"], "tags": ["graph", "medium", "Google", "Facebook"]} {"problem_id": "algo_00161", "original_id": "two-sum", "title": "两数之和", "category": "array", "difficulty": "easy", "companies": ["Amazon", "Google"], "description": "给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那两个整数,并返回他们的数组下标。", "solution_python": "def twoSum(nums, target):\n hashmap = {}\n for i, num in enumerate(nums):\n complement = target - num\n if complement in hashmap:\n return [hashmap[complement], i]\n hashmap[num] = i\n return []", "solution_java": "public int[] twoSum(int[] nums, int target) {\n Map map = new HashMap<>();\n for (int i = 0; i < nums.length; i++) {\n int complement = target - nums[i];\n if (map.containsKey(complement)) return new int[]{map.get(complement), i};\n map.put(nums[i], i);\n }\n return new int[]{};\n}", "solution_cpp": "vector twoSum(vector& nums, int target) {\n unordered_map m;\n for (int i = 0; i < nums.size(); i++) {\n if (m.count(target - nums[i])) return {m[target - nums[i]], i};\n m[nums[i]] = i;\n }\n return {};\n}", "test_cases": ["nums=[2,7,11,15], target=9 -> [0,1]", "nums=[3,2,4], target=6 -> [1,2]"], "key_points": ["哈希表一次遍历", "空间换时间"], "tags": ["array", "easy", "Amazon", "Google"]} {"problem_id": "algo_00162", "original_id": "merge-sorted", "title": "合并两个有序数组", "category": "array", "difficulty": "easy", "companies": ["Microsoft", "Uber"], "description": "给你两个按非递减顺序排列的整数数组 nums1 和 nums2,另有两个整数 m 和 n,分别表示 nums1 和 nums2 中的元素数目。请你合并 nums2 到 nums1 中。", "solution_python": "def merge(nums1, m, nums2, n):\n p1, p2, p = m-1, n-1, m+n-1\n while p1 >= 0 and p2 >= 0:\n if nums1[p1] > nums2[p2]: nums1[p] = nums1[p1]; p1 -= 1\n else: nums1[p] = nums2[p2]; p2 -= 1\n p -= 1\n while p2 >= 0: nums1[p] = nums2[p2]; p2 -= 1; p -= 1", "solution_java": "public void merge(int[] nums1, int m, int[] nums2, int n) {\n int p1 = m-1, p2 = n-1, p = m+n-1;\n while (p1 >= 0 && p2 >= 0) {\n nums1[p--] = nums1[p1] > nums2[p2] ? nums1[p1--] : nums2[p2--];\n }\n while (p2 >= 0) nums1[p--] = nums2[p2--];\n}", "solution_cpp": "void merge(vector& nums1, int m, vector& nums2, int n) {\n int p1 = m-1, p2 = n-1, p = m+n-1;\n while (p1 >= 0 && p2 >= 0) nums1[p--] = nums1[p1] > nums2[p2] ? nums1[p1--] : nums2[p2--];\n while (p2 >= 0) nums1[p--] = nums2[p2--];\n}", "test_cases": ["nums1=[1,2,3], m=3, nums2=[2,5,6], n=3 -> [1,2,2,3,5,6]", "nums1=[], m=0, nums2=[1], n=1 -> [1]"], "key_points": ["从后往前合并", "三指针技巧"], "tags": ["array", "easy", "Microsoft", "Uber"]} {"problem_id": "algo_00163", "original_id": "max-subarray", "title": "最大子数组和", "category": "array", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "给你一个整数数组 nums ,请你找出一个具有最大和的连续子数组,返回其最大和。", "solution_python": "def maxSubArray(nums):\n max_sum = current = nums[0]\n for num in nums[1:]:\n current = max(num, current + num)\n max_sum = max(max_sum, current)\n return max_sum", "solution_java": "public int maxSubArray(int[] nums) {\n int maxSum = nums[0], curr = nums[0];\n for (int i = 1; i < nums.length; i++) {\n curr = Math.max(nums[i], curr + nums[i]);\n maxSum = Math.max(maxSum, curr);\n }\n return maxSum;\n}", "solution_cpp": "int maxSubArray(vector& nums) {\n int maxSum = nums[0], curr = nums[0];\n for (int i = 1; i < nums.size(); i++) {\n curr = max(nums[i], curr + nums[i]);\n maxSum = max(maxSum, curr);\n }\n return maxSum;\n}", "test_cases": ["nums=[-2,1,-3,4,-1,2,1,-5,4] -> 6", "nums=[1] -> 1"], "key_points": ["Kadane算法", "动态规划基础题"], "tags": ["array", "medium", "Google", "Microsoft"]} {"problem_id": "algo_00164", "original_id": "valid-parentheses", "title": "有效的括号", "category": "string", "difficulty": "easy", "companies": ["Google", "Uber"], "description": "给定一个只包括 '(',')','{','}','[',']' 的字符串 s,判断字符串是否有效。", "solution_python": "def isValid(s):\n stack = []\n mapping = {')': '(', ']': '[', '}': '{'}\n for c in s:\n if c in mapping:\n if not stack or stack[-1] != mapping[c]: return False\n stack.pop()\n else: stack.append(c)\n return not stack", "solution_java": "public boolean isValid(String s) {\n Stack stack = new Stack<>();\n Map map = Map.of(')', '(', ']', '[', '}', '{');\n for (char c : s.toCharArray()) {\n if (map.containsValue(c)) stack.push(c);\n else if (!stack.isEmpty() && stack.pop() != map.get(c)) return false;\n }\n return stack.isEmpty();\n}", "solution_cpp": "bool isValid(string s) {\n stack st;\n unordered_map m = {{')','('},{']','['},{'}','{'}};\n for (char c : s) {\n if (m.find(c) == m.end()) st.push(c);\n else if (st.empty() || st.top() != m[c]) return false;\n else st.pop();\n }\n return st.empty();\n}", "test_cases": ["s=\"()\" -> true", "s=\"()[]{}\" -> true", "s=\"(]\" -> false"], "key_points": ["栈匹配法", "注意空栈边界"], "tags": ["string", "easy", "Google", "Uber"]} {"problem_id": "algo_00165", "original_id": "longest-palindrome", "title": "最长回文子串", "category": "string", "difficulty": "medium", "companies": ["Google", "Amazon"], "description": "给你一个字符串 s,找到 s 中最长的回文子串。", "solution_python": "def longestPalindrome(s):\n def expand(l, r):\n while l >= 0 and r < len(s) and s[l] == s[r]: l -= 1; r += 1\n return l + 1, r - 1\n start = end = 0\n for i in range(len(s)):\n l1, r1 = expand(i, i)\n l2, r2 = expand(i, i + 1)\n if r1 - l1 > end - start: start, end = l1, r1\n if r2 - l2 > end - start: start, end = l2, r2\n return s[start:end+1]", "solution_java": "public String longestPalindrome(String s) {\n int start = 0, end = 0;\n for (int i = 0; i < s.length(); i++) {\n int len1 = expand(s, i, i), len2 = expand(s, i, i+1);\n int len = Math.max(len1, len2);\n if (len > end - start) { start = i - (len-1)/2; end = i + len/2; }\n }\n return s.substring(start, end + 1);\n}\nprivate int expand(String s, int l, int r) {\n while (l >= 0 && r < s.length() && s.charAt(l) == s.charAt(r)) { l--; r++; }\n return r - l - 1;\n}", "solution_cpp": "string longestPalindrome(string s) {\n int start = 0, end = 0;\n for (int i = 0; i < s.size(); i++) {\n int len1 = expand(s, i, i), len2 = expand(s, i, i+1);\n if (max(len1, len2) > end - start) { start = i - (max(len1,len2)-1)/2; end = i + max(len1,len2)/2; }\n }\n return s.substr(start, end - start + 1);\n}", "test_cases": ["s=\"babad\" -> bab或aba", "s=\"cbbd\" -> bb"], "key_points": ["中心扩展法", "处理奇偶长度"], "tags": ["string", "medium", "Google", "Amazon"]} {"problem_id": "algo_00166", "original_id": "reverse-list", "title": "反转链表", "category": "linkedlist", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "给你单链表的头节点 head,请你反转链表,并返回反转后的链表。", "solution_python": "def reverseList(head):\n prev = None\n curr = head\n while curr:\n nxt = curr.next\n curr.next = prev\n prev = curr\n curr = nxt\n return prev", "solution_java": "public ListNode reverseList(ListNode head) {\n ListNode prev = null, curr = head;\n while (curr != null) {\n ListNode next = curr.next;\n curr.next = prev;\n prev = curr;\n curr = next;\n }\n return prev;\n}", "solution_cpp": "ListNode* reverseList(ListNode* head) {\n ListNode* prev = nullptr, *curr = head;\n while (curr) {\n ListNode* next = curr->next;\n curr->next = prev;\n prev = curr;\n curr = next;\n }\n return prev;\n}", "test_cases": ["head=[1,2,3,4,5] -> [5,4,3,2,1]", "head=[1,2] -> [2,1]"], "key_points": ["迭代法 O(1)空间", "递归法 O(n)空间"], "tags": ["linkedlist", "medium", "Google", "Microsoft"]} {"problem_id": "algo_00167", "original_id": "middle-node", "title": "链表的中间结点", "category": "linkedlist", "difficulty": "easy", "companies": ["Amazon", "Facebook"], "description": "给你单链表的头节点 head,请你找出并返回链表的中间结点。如果有两个中间结点,则返回第二个中间结点。", "solution_python": "def middleNode(head):\n slow = fast = head\n while fast and fast.next:\n slow = slow.next\n fast = fast.next.next\n return slow", "solution_java": "public ListNode middleNode(ListNode head) {\n ListNode slow = head, fast = head;\n while (fast != null && fast.next != null) {\n slow = slow.next;\n fast = fast.next.next;\n }\n return slow;\n}", "solution_cpp": "ListNode* middleNode(ListNode* head) {\n ListNode* slow = head, *fast = head;\n while (fast && fast->next) { slow = slow->next; fast = fast->next->next; }\n return slow;\n}", "test_cases": ["head=[1,2,3,4,5] -> 3", "head=[1,2,3,4,5,6] -> 4"], "key_points": ["快慢指针", "O(n)时间O(1)空间"], "tags": ["linkedlist", "easy", "Amazon", "Facebook"]} {"problem_id": "algo_00168", "original_id": "max-depth", "title": "二叉树的最大深度", "category": "tree", "difficulty": "easy", "companies": ["Microsoft", "Apple"], "description": "给定一个二叉树 root,返回其最大深度。", "solution_python": "def maxDepth(root):\n if not root: return 0\n return max(maxDepth(root.left), maxDepth(root.right)) + 1", "solution_java": "public int maxDepth(TreeNode root) {\n if (root == null) return 0;\n return Math.max(maxDepth(root.left), maxDepth(root.right)) + 1;\n}", "solution_cpp": "int maxDepth(TreeNode* root) {\n if (!root) return 0;\n return max(maxDepth(root->left), maxDepth(root->right)) + 1;\n}", "test_cases": ["root=[3,9,20,null,null,15,7] -> 3", "root=[1,null,2] -> 2"], "key_points": ["DFS递归", "层序遍历也可"], "tags": ["tree", "easy", "Microsoft", "Apple"]} {"problem_id": "algo_00169", "original_id": "inorder-traversal", "title": "二叉树的中序遍历", "category": "tree", "difficulty": "easy", "companies": ["Google", "Microsoft"], "description": "给定一个二叉树的根节点 root,返回它的中序遍历结果。", "solution_python": "def inorderTraversal(root):\n result = []\n def dfs(node):\n if node:\n dfs(node.left)\n result.append(node.val)\n dfs(node.right)\n dfs(root)\n return result", "solution_java": "public List inorderTraversal(TreeNode root) {\n List res = new ArrayList<>();\n dfs(root, res);\n return res;\n}\nprivate void dfs(TreeNode node, List res) {\n if (node == null) return;\n dfs(node.left, res); res.add(node.val); dfs(node.right, res);\n}", "solution_cpp": "vector inorderTraversal(TreeNode* root) {\n vector res;\n dfs(root, res);\n return res;\n}\nvoid dfs(TreeNode* node, vector& res) {\n if (!node) return;\n dfs(node->left, res); res.push_back(node->val); dfs(node->right, res);\n}", "test_cases": ["root=[1,null,2,3] -> [1,3,2]", "root=[] -> []"], "key_points": ["左-根-右顺序", "递归最简洁"], "tags": ["tree", "easy", "Google", "Microsoft"]} {"problem_id": "algo_00170", "original_id": "binary-search", "title": "二分查找", "category": "binarysearch", "difficulty": "easy", "companies": ["Google", "Amazon"], "description": "给定一个 n 个元素有序的(升序)整型数组 nums 和一个目标值 target,写一个函数搜索 nums 中的 target,如果目标值存在返回下标,否则返回 -1。", "solution_python": "def search(nums, target):\n left, right = 0, len(nums) - 1\n while left <= right:\n mid = (left + right) // 2\n if nums[mid] == target: return mid\n elif nums[mid] < target: left = mid + 1\n else: right = mid - 1\n return -1", "solution_java": "public int search(int[] nums, int target) {\n int left = 0, right = nums.length - 1;\n while (left <= right) {\n int mid = left + (right - left) / 2;\n if (nums[mid] == target) return mid;\n else if (nums[mid] < target) left = mid + 1;\n else right = mid - 1;\n }\n return -1;\n}", "solution_cpp": "int search(vector& nums, int target) {\n int left = 0, right = nums.size() - 1;\n while (left <= right) {\n int mid = left + (right - left) / 2;\n if (nums[mid] == target) return mid;\n else if (nums[mid] < target) left = mid + 1;\n else right = mid - 1;\n }\n return -1;\n}", "test_cases": ["nums=[-1,0,3,5,9,12], target=9 -> 4", "nums=[-1,0,3,5,9,12], target=2 -> -1"], "key_points": ["标准模板", "注意防溢出写法"], "tags": ["binarysearch", "easy", "Google", "Amazon"]} {"problem_id": "algo_00171", "original_id": "climbing-stairs", "title": "爬楼梯", "category": "dp", "difficulty": "easy", "companies": ["Amazon", "Google"], "description": "假设你正在爬楼梯。需要 n 阶你才能到达楼顶。每次你可以爬 1 或 2 个台阶。你有多少种不同的方法可以爬到楼顶?", "solution_python": "def climbStairs(n):\n if n <= 2: return n\n a, b = 1, 2\n for _ in range(3, n+1):\n a, b = b, a + b\n return b", "solution_java": "public int climbStairs(int n) {\n if (n <= 2) return n;\n int a = 1, b = 2;\n for (int i = 3; i <= n; i++) { int temp = a + b; a = b; b = temp; }\n return b;\n}", "solution_cpp": "int climbStairs(int n) {\n if (n <= 2) return n;\n int a = 1, b = 2;\n for (int i = 3; i <= n; i++) { int temp = a + b; a = b; b = temp; }\n return b;\n}", "test_cases": ["n=2 -> 2", "n=3 -> 3", "n=5 -> 8"], "key_points": ["斐波那契数列", "滚动数组优化空间"], "tags": ["dp", "easy", "Amazon", "Google"]} {"problem_id": "algo_00172", "original_id": "coin-change", "title": "零钱兑换", "category": "dp", "difficulty": "medium", "companies": ["Google", "Amazon"], "description": "给你一个整数数组 coins 表示不同面额的硬币,以及一个整数 amount 表示总金额。计算并返回可以凑成总金额所需的最少的硬币个数。如果没有任何一种硬币组合能组成总金额,返回 -1。", "solution_python": "def coinChange(coins, amount):\n dp = [float('inf')] * (amount + 1)\n dp[0] = 0\n for coin in coins:\n for x in range(coin, amount + 1):\n dp[x] = min(dp[x], dp[x - coin] + 1)\n return dp[amount] if dp[amount] != float('inf') else -1", "solution_java": "public int coinChange(int[] coins, int amount) {\n int[] dp = new int[amount + 1];\n Arrays.fill(dp, amount + 1);\n dp[0] = 0;\n for (int coin : coins) {\n for (int x = coin; x <= amount; x++) {\n dp[x] = Math.min(dp[x], dp[x - coin] + 1);\n }\n }\n return dp[amount] > amount ? -1 : dp[amount];\n}", "solution_cpp": "int coinChange(vector& coins, int amount) {\n vector dp(amount + 1, amount + 1);\n dp[0] = 0;\n for (int coin : coins) {\n for (int x = coin; x <= amount; x++) {\n dp[x] = min(dp[x], dp[x - coin] + 1);\n }\n }\n return dp[amount] > amount ? -1 : dp[amount];\n}", "test_cases": ["coins=[1,2,5], amount=11 -> 3", "coins=[2], amount=3 -> -1"], "key_points": ["完全背包问题", "dp[x] = min(dp[x-coin]+1)"], "tags": ["dp", "medium", "Google", "Amazon"]} {"problem_id": "algo_00173", "original_id": "subsets", "title": "子集", "category": "backtracking", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "给你一个整数数组 nums ,数组中的元素 互不相同 。返回该数组所有可能的子集(幂集)。", "solution_python": "def subsets(nums):\n result = []\n def backtrack(start, path):\n result.append(path[:])\n for i in range(start, len(nums)):\n path.append(nums[i])\n backtrack(i + 1, path)\n path.pop()\n backtrack(0, [])\n return result", "solution_java": "public List> subsets(int[] nums) {\n List> result = new ArrayList<>();\n backtrack(nums, 0, new ArrayList<>(), result);\n return result;\n}\nprivate void backtrack(int[] nums, int start, List path, List> result) {\n result.add(new ArrayList<>(path));\n for (int i = start; i < nums.length; i++) {\n path.add(nums[i]);\n backtrack(nums, i + 1, path, result);\n path.remove(path.size() - 1);\n }\n}", "solution_cpp": "vector> subsets(vector& nums) {\n vector> result;\n vector path;\n backtrack(nums, 0, path, result);\n return result;\n}\nvoid backtrack(vector& nums, int start, vector& path, vector>& result) {\n result.push_back(path);\n for (int i = start; i < nums.size(); i++) {\n path.push_back(nums[i]);\n backtrack(nums, i + 1, path, result);\n path.pop_back();\n }\n}", "test_cases": ["nums=[1,2,3] -> [[],[1],[2],[1,2],[3],[1,3],[2,3],[1,2,3]]"], "key_points": ["选或不选", "DFS遍历子集树"], "tags": ["backtracking", "medium", "Google", "Microsoft"]} {"problem_id": "algo_00174", "original_id": "permutations", "title": "全排列", "category": "backtracking", "difficulty": "medium", "companies": ["Google", "Facebook"], "description": "给定一个不含重复数字的数组 nums,返回其所有可能的全排列。", "solution_python": "def permute(nums):\n result = []\n def backtrack(path, used):\n if len(path) == len(nums):\n result.append(path[:])\n return\n for i in range(len(nums)):\n if used[i]: continue\n used[i] = True\n path.append(nums[i])\n backtrack(path, used)\n path.pop()\n used[i] = False\n backtrack([], [False]*len(nums))\n return result", "solution_java": "public List> permute(int[] nums) {\n List> result = new ArrayList<>();\n boolean[] used = new boolean[nums.length];\n backtrack(nums, used, new ArrayList<>(), result);\n return result;\n}\nprivate void backtrack(int[] nums, boolean[] used, List path, List> result) {\n if (path.size() == nums.length) { result.add(new ArrayList<>(path)); return; }\n for (int i = 0; i < nums.length; i++) {\n if (used[i]) continue;\n used[i] = true;\n path.add(nums[i]);\n backtrack(nums, used, path, result);\n path.remove(path.size() - 1);\n used[i] = false;\n }\n}", "solution_cpp": "vector> permute(vector& nums) {\n vector> result;\n vector used(nums.size(), false);\n vector path;\n backtrack(nums, used, path, result);\n return result;\n}\nvoid backtrack(vector& nums, vector& used, vector& path, vector>& result) {\n if (path.size() == nums.size()) { result.push_back(path); return; }\n for (int i = 0; i < nums.size(); i++) {\n if (used[i]) continue;\n used[i] = true;\n path.push_back(nums[i]);\n backtrack(nums, used, path, result);\n path.pop_back();\n used[i] = false;\n }\n}", "test_cases": ["nums=[1,2,3] -> [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]"], "key_points": ["标记已使用元素", "回溯经典模板"], "tags": ["backtracking", "medium", "Google", "Facebook"]} {"problem_id": "algo_00175", "original_id": "top-k-frequent", "title": "前K个高频元素", "category": "heap", "difficulty": "medium", "companies": ["Amazon", "Facebook"], "description": "给你一个整数数组 nums 和一个整数 k,请你返回其中出现频率前 k 高的元素。", "solution_python": "import heapq\nfrom collections import Counter\ndef topKFrequent(nums, k):\n count = Counter(nums)\n heap = []\n for num, freq in count.items():\n heapq.heappush(heap, (freq, num))\n if len(heap) > k: heapq.heappop(heap)\n return [num for freq, num in heap]", "solution_java": "public int[] topKFrequent(int[] nums, int k) {\n Map count = new HashMap<>();\n for (int n : nums) count.put(n, count.getOrDefault(n, 0) + 1);\n PriorityQueue> heap = \n new PriorityQueue<>((a, b) -> a.getValue() - b.getValue());\n for (Map.Entry e : count.entrySet()) {\n heap.offer(e);\n if (heap.size() > k) heap.poll();\n }\n int[] res = new int[k];\n for (int i = k - 1; i >= 0; i--) res[i] = heap.poll().getKey();\n return res;\n}", "solution_cpp": "vector topKFrequent(vector& nums, int k) {\n unordered_map count;\n for (int n : nums) count[n]++;\n priority_queue, vector>, greater>> heap;\n for (auto& [num, freq] : count) {\n heap.push({freq, num});\n if (heap.size() > k) heap.pop();\n }\n vector res;\n while (!heap.empty()) { res.push_back(heap.top().second); heap.pop(); }\n reverse(res.begin(), res.end());\n return res;\n}", "test_cases": ["nums=[1,1,1,2,2,3], k=2 -> [1,2]", "nums=[1], k=1 -> [1]"], "key_points": ["小顶堆保持大小k", "时间复杂度O(nlogk)"], "tags": ["heap", "medium", "Amazon", "Facebook"]} {"problem_id": "algo_00176", "original_id": "3sum", "title": "三数之和", "category": "two-pointers", "difficulty": "medium", "companies": ["Google", "Amazon"], "description": "给你一个整数数组 nums,判断是否存在三元组满足和为0,返回所有不重复的三元组。", "solution_python": "def threeSum(nums):\n nums.sort()\n result = []\n for i in range(len(nums) - 2):\n if i > 0 and nums[i] == nums[i-1]: continue\n left, right = i + 1, len(nums) - 1\n while left < right:\n total = nums[i] + nums[left] + nums[right]\n if total < 0: left += 1\n elif total > 0: right -= 1\n else:\n result.append([nums[i], nums[left], nums[right]])\n while left < right and nums[left] == nums[left+1]: left += 1\n while left < right and nums[right] == nums[right-1]: right -= 1\n left += 1; right -= 1\n return result", "solution_java": "public List> threeSum(int[] nums) {\n Arrays.sort(nums);\n List> result = new ArrayList<>();\n for (int i = 0; i < nums.length - 2; i++) {\n if (i > 0 && nums[i] == nums[i-1]) continue;\n int left = i + 1, right = nums.length - 1;\n while (left < right) {\n int total = nums[i] + nums[left] + nums[right];\n if (total < 0) left++;\n else if (total > 0) right--;\n else {\n result.add(Arrays.asList(nums[i], nums[left], nums[right]));\n while (left < right && nums[left] == nums[left+1]) left++;\n while (left < right && nums[right] == nums[right-1]) right--;\n left++; right--;\n }\n }\n }\n return result;\n}", "solution_cpp": "vector> threeSum(vector& nums) {\n sort(nums.begin(), nums.end());\n vector> result;\n for (int i = 0; i < nums.size() - 2; i++) {\n if (i > 0 && nums[i] == nums[i-1]) continue;\n int left = i + 1, right = nums.size() - 1;\n while (left < right) {\n int total = nums[i] + nums[left] + nums[right];\n if (total < 0) left++;\n else if (total > 0) right--;\n else {\n result.push_back({nums[i], nums[left], nums[right]});\n while (left < right && nums[left] == nums[left+1]) left++;\n while (left < right && nums[right] == nums[right-1]) right--;\n left++; right--;\n }\n }\n }\n return result;\n}", "test_cases": ["nums=[-1,0,1,2,-1,-4] -> [[-1,-1,2],[-1,0,1]]"], "key_points": ["排序+双指针", "去重是关键"], "tags": ["two-pointers", "medium", "Google", "Amazon"]} {"problem_id": "algo_00177", "original_id": "container-water", "title": "盛最多水的容器", "category": "two-pointers", "difficulty": "medium", "companies": ["Google", "Uber"], "description": "给定一个长度为 n 的整数数组 height,找出其中的两条线,使得它们与 x 轴共同构成的容器可以容纳最多的水。", "solution_python": "def maxArea(height):\n left, right = 0, len(height) - 1\n max_area = 0\n while left < right:\n h = min(height[left], height[right])\n max_area = max(max_area, h * (right - left))\n if height[left] < height[right]: left += 1\n else: right -= 1\n return max_area", "solution_java": "public int maxArea(int[] height) {\n int left = 0, right = height.length - 1, maxArea = 0;\n while (left < right) {\n int h = Math.min(height[left], height[right]);\n maxArea = Math.max(maxArea, h * (right - left));\n if (height[left] < height[right]) left++;\n else right--;\n }\n return maxArea;\n}", "solution_cpp": "int maxArea(vector& height) {\n int left = 0, right = height.size() - 1, maxArea = 0;\n while (left < right) {\n int h = min(height[left], height[right]);\n maxArea = max(maxArea, h * (right - left));\n if (height[left] < height[right]) left++;\n else right--;\n }\n return maxArea;\n}", "test_cases": ["height=[1,8,6,2,5,4,8,3,7] -> 49"], "key_points": ["移动短边指针", "面积=min(h1,h2)*width"], "tags": ["two-pointers", "medium", "Google", "Uber"]} {"problem_id": "algo_00178", "original_id": "min-stack", "title": "最小栈", "category": "stack", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "设计一个支持 push,pop,top 操作,并能在常数时间内检索到最小元素的栈。", "solution_python": "class MinStack:\n def __init__(self):\n self.stack = []\n self.min_stack = []\n def push(self, val):\n self.stack.append(val)\n self.min_stack.append(min(val, self.min_stack[-1] if self.min_stack else val))\n def pop(self):\n self.stack.pop(); self.min_stack.pop()\n def top(self): return self.stack[-1]\n def getMin(self): return self.min_stack[-1]", "solution_java": "class MinStack {\n Stack stack = new Stack<>();\n Stack minStack = new Stack<>();\n public void push(int val) { stack.push(val); minStack.push(Math.min(val, minStack.isEmpty() ? val : minStack.peek())); }\n public void pop() { stack.pop(); minStack.pop(); }\n public int top() { return stack.peek(); }\n public int getMin() { return minStack.peek(); }\n}", "solution_cpp": "class MinStack {\n stack st, minSt;\npublic:\n void push(int val) { st.push(val); minSt.push(min(val, minSt.empty() ? val : minSt.top())); }\n void pop() { st.pop(); minSt.pop(); }\n int top() { return st.top(); }\n int getMin() { return minSt.top(); }\n};", "test_cases": ["push(-2), push(0), push(-3) -> getMin() returns -3"], "key_points": ["辅助栈记录最小值", "O(1)时间获取最小值"], "tags": ["stack", "medium", "Google", "Microsoft"]} {"problem_id": "algo_00179", "original_id": "lru-cache", "title": "LRU缓存", "category": "design", "difficulty": "hard", "companies": ["Google", "Amazon"], "description": "设计和实现一个 LRU(最近最少使用)缓存机制。", "solution_python": "class LRUCache:\n def __init__(self, capacity):\n self.capacity = capacity\n self.cache = {}\n self.order = []\n def get(self, key):\n if key not in self.cache: return -1\n self.order.remove(key); self.order.append(key)\n return self.cache[key]\n def put(self, key, value):\n if key in self.cache:\n self.order.remove(key)\n elif len(self.cache) >= self.capacity:\n del self.cache[self.order.pop(0)]\n self.cache[key] = value; self.order.append(key)", "solution_java": "class LRUCache {\n int capacity;\n LinkedHashMap cache = new LinkedHashMap<>();\n public LRUCache(int cap) { capacity = cap; }\n public int get(int key) { return cache.containsKey(key) ? cache.remove(key) : -1; }\n public void put(int key, int val) {\n if (cache.containsKey(key)) cache.remove(key);\n else if (cache.size() >= capacity) cache.remove(cache.keySet().iterator().next());\n cache.put(key, val);\n }\n}", "solution_cpp": "class LRUCache {\n int cap;\n list> dll;\n unordered_map>::iterator> cache;\npublic:\n LRUCache(int capacity) : cap(capacity) {}\n int get(int key) {\n auto it = cache.find(key);\n if (it == cache.end()) return -1;\n dll.splice(dll.end(), dll, it->second);\n return it->second->second;\n }\n void put(int key, int value) {\n auto it = cache.find(key);\n if (it != cache.end()) dll.erase(it->second);\n else if (cache.size() >= cap) { cache.erase(dll.front().first); dll.pop_front(); }\n dll.push_back({key, value});\n cache[key] = --dll.end();\n }\n};", "test_cases": ["put(1,1), put(2,2), get(1) -> 1"], "key_points": ["HashMap + 双向链表", "O(1)时间操作"], "tags": ["design", "hard", "Google", "Amazon"]} {"problem_id": "algo_00180", "original_id": "num-islands", "title": "岛屿数量", "category": "graph", "difficulty": "medium", "companies": ["Google", "Facebook"], "description": "给你一个由 '1'(陆地)和 '0'(水)组成的二维网格,请你计算网格中岛屿的数量。岛屿总是被水包围,且只能由水平或垂直方向相邻的陆地连接形成。", "solution_python": "def numIslands(grid):\n if not grid: return 0\n rows, cols = len(grid), len(grid[0])\n count = 0\n def dfs(r, c):\n if r < 0 or r >= rows or c < 0 or c >= cols or grid[r][c] != '1': return\n grid[r][c] = '0'\n dfs(r+1, c); dfs(r-1, c); dfs(r, c+1); dfs(r, c-1)\n for r in range(rows):\n for c in range(cols):\n if grid[r][c] == '1': count += 1; dfs(r, c)\n return count", "solution_java": "public int numIslands(char[][] grid) {\n if (grid.length == 0) return 0;\n int count = 0;\n for (int i = 0; i < grid.length; i++)\n for (int j = 0; j < grid[0].length; j++)\n if (grid[i][j] == '1') { count++; dfs(grid, i, j); }\n return count;\n}\nprivate void dfs(char[][] grid, int r, int c) {\n if (r < 0 || r >= grid.length || c < 0 || c >= grid[0].length || grid[r][c] != '1') return;\n grid[r][c] = '0';\n dfs(grid, r+1, c); dfs(grid, r-1, c); dfs(grid, r, c+1); dfs(grid, r, c-1);\n}", "solution_cpp": "int numIslands(vector>& grid) {\n if (grid.empty()) return 0;\n int count = 0;\n for (int i = 0; i < grid.size(); i++)\n for (int j = 0; j < grid[0].size(); j++)\n if (grid[i][j] == '1') { count++; dfs(grid, i, j); }\n return count;\n}\nvoid dfs(vector>& grid, int r, int c) {\n if (r < 0 || r >= grid.size() || c < 0 || c >= grid[0].size() || grid[r][c] != '1') return;\n grid[r][c] = '0';\n dfs(grid, r+1, c); dfs(grid, r-1, c); dfs(grid, r, c+1); dfs(grid, r, c-1);\n}", "test_cases": ["grid=[[1,1,1,1,0],[1,1,0,1,0],[1,1,0,0,0],[0,0,0,0,0]] -> 1"], "key_points": ["DFS/BFS遍历", "访问后标记为0避免重复"], "tags": ["graph", "medium", "Google", "Facebook"]} {"problem_id": "algo_00181", "original_id": "two-sum", "title": "两数之和", "category": "array", "difficulty": "easy", "companies": ["Amazon", "Google"], "description": "给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那两个整数,并返回他们的数组下标。", "solution_python": "def twoSum(nums, target):\n hashmap = {}\n for i, num in enumerate(nums):\n complement = target - num\n if complement in hashmap:\n return [hashmap[complement], i]\n hashmap[num] = i\n return []", "solution_java": "public int[] twoSum(int[] nums, int target) {\n Map map = new HashMap<>();\n for (int i = 0; i < nums.length; i++) {\n int complement = target - nums[i];\n if (map.containsKey(complement)) return new int[]{map.get(complement), i};\n map.put(nums[i], i);\n }\n return new int[]{};\n}", "solution_cpp": "vector twoSum(vector& nums, int target) {\n unordered_map m;\n for (int i = 0; i < nums.size(); i++) {\n if (m.count(target - nums[i])) return {m[target - nums[i]], i};\n m[nums[i]] = i;\n }\n return {};\n}", "test_cases": ["nums=[2,7,11,15], target=9 -> [0,1]", "nums=[3,2,4], target=6 -> [1,2]"], "key_points": ["哈希表一次遍历", "空间换时间"], "tags": ["array", "easy", "Amazon", "Google"]} {"problem_id": "algo_00182", "original_id": "merge-sorted", "title": "合并两个有序数组", "category": "array", "difficulty": "easy", "companies": ["Microsoft", "Uber"], "description": "给你两个按非递减顺序排列的整数数组 nums1 和 nums2,另有两个整数 m 和 n,分别表示 nums1 和 nums2 中的元素数目。请你合并 nums2 到 nums1 中。", "solution_python": "def merge(nums1, m, nums2, n):\n p1, p2, p = m-1, n-1, m+n-1\n while p1 >= 0 and p2 >= 0:\n if nums1[p1] > nums2[p2]: nums1[p] = nums1[p1]; p1 -= 1\n else: nums1[p] = nums2[p2]; p2 -= 1\n p -= 1\n while p2 >= 0: nums1[p] = nums2[p2]; p2 -= 1; p -= 1", "solution_java": "public void merge(int[] nums1, int m, int[] nums2, int n) {\n int p1 = m-1, p2 = n-1, p = m+n-1;\n while (p1 >= 0 && p2 >= 0) {\n nums1[p--] = nums1[p1] > nums2[p2] ? nums1[p1--] : nums2[p2--];\n }\n while (p2 >= 0) nums1[p--] = nums2[p2--];\n}", "solution_cpp": "void merge(vector& nums1, int m, vector& nums2, int n) {\n int p1 = m-1, p2 = n-1, p = m+n-1;\n while (p1 >= 0 && p2 >= 0) nums1[p--] = nums1[p1] > nums2[p2] ? nums1[p1--] : nums2[p2--];\n while (p2 >= 0) nums1[p--] = nums2[p2--];\n}", "test_cases": ["nums1=[1,2,3], m=3, nums2=[2,5,6], n=3 -> [1,2,2,3,5,6]", "nums1=[], m=0, nums2=[1], n=1 -> [1]"], "key_points": ["从后往前合并", "三指针技巧"], "tags": ["array", "easy", "Microsoft", "Uber"]} {"problem_id": "algo_00183", "original_id": "max-subarray", "title": "最大子数组和", "category": "array", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "给你一个整数数组 nums ,请你找出一个具有最大和的连续子数组,返回其最大和。", "solution_python": "def maxSubArray(nums):\n max_sum = current = nums[0]\n for num in nums[1:]:\n current = max(num, current + num)\n max_sum = max(max_sum, current)\n return max_sum", "solution_java": "public int maxSubArray(int[] nums) {\n int maxSum = nums[0], curr = nums[0];\n for (int i = 1; i < nums.length; i++) {\n curr = Math.max(nums[i], curr + nums[i]);\n maxSum = Math.max(maxSum, curr);\n }\n return maxSum;\n}", "solution_cpp": "int maxSubArray(vector& nums) {\n int maxSum = nums[0], curr = nums[0];\n for (int i = 1; i < nums.size(); i++) {\n curr = max(nums[i], curr + nums[i]);\n maxSum = max(maxSum, curr);\n }\n return maxSum;\n}", "test_cases": ["nums=[-2,1,-3,4,-1,2,1,-5,4] -> 6", "nums=[1] -> 1"], "key_points": ["Kadane算法", "动态规划基础题"], "tags": ["array", "medium", "Google", "Microsoft"]} {"problem_id": "algo_00184", "original_id": "valid-parentheses", "title": "有效的括号", "category": "string", "difficulty": "easy", "companies": ["Google", "Uber"], "description": "给定一个只包括 '(',')','{','}','[',']' 的字符串 s,判断字符串是否有效。", "solution_python": "def isValid(s):\n stack = []\n mapping = {')': '(', ']': '[', '}': '{'}\n for c in s:\n if c in mapping:\n if not stack or stack[-1] != mapping[c]: return False\n stack.pop()\n else: stack.append(c)\n return not stack", "solution_java": "public boolean isValid(String s) {\n Stack stack = new Stack<>();\n Map map = Map.of(')', '(', ']', '[', '}', '{');\n for (char c : s.toCharArray()) {\n if (map.containsValue(c)) stack.push(c);\n else if (!stack.isEmpty() && stack.pop() != map.get(c)) return false;\n }\n return stack.isEmpty();\n}", "solution_cpp": "bool isValid(string s) {\n stack st;\n unordered_map m = {{')','('},{']','['},{'}','{'}};\n for (char c : s) {\n if (m.find(c) == m.end()) st.push(c);\n else if (st.empty() || st.top() != m[c]) return false;\n else st.pop();\n }\n return st.empty();\n}", "test_cases": ["s=\"()\" -> true", "s=\"()[]{}\" -> true", "s=\"(]\" -> false"], "key_points": ["栈匹配法", "注意空栈边界"], "tags": ["string", "easy", "Google", "Uber"]} {"problem_id": "algo_00185", "original_id": "longest-palindrome", "title": "最长回文子串", "category": "string", "difficulty": "medium", "companies": ["Google", "Amazon"], "description": "给你一个字符串 s,找到 s 中最长的回文子串。", "solution_python": "def longestPalindrome(s):\n def expand(l, r):\n while l >= 0 and r < len(s) and s[l] == s[r]: l -= 1; r += 1\n return l + 1, r - 1\n start = end = 0\n for i in range(len(s)):\n l1, r1 = expand(i, i)\n l2, r2 = expand(i, i + 1)\n if r1 - l1 > end - start: start, end = l1, r1\n if r2 - l2 > end - start: start, end = l2, r2\n return s[start:end+1]", "solution_java": "public String longestPalindrome(String s) {\n int start = 0, end = 0;\n for (int i = 0; i < s.length(); i++) {\n int len1 = expand(s, i, i), len2 = expand(s, i, i+1);\n int len = Math.max(len1, len2);\n if (len > end - start) { start = i - (len-1)/2; end = i + len/2; }\n }\n return s.substring(start, end + 1);\n}\nprivate int expand(String s, int l, int r) {\n while (l >= 0 && r < s.length() && s.charAt(l) == s.charAt(r)) { l--; r++; }\n return r - l - 1;\n}", "solution_cpp": "string longestPalindrome(string s) {\n int start = 0, end = 0;\n for (int i = 0; i < s.size(); i++) {\n int len1 = expand(s, i, i), len2 = expand(s, i, i+1);\n if (max(len1, len2) > end - start) { start = i - (max(len1,len2)-1)/2; end = i + max(len1,len2)/2; }\n }\n return s.substr(start, end - start + 1);\n}", "test_cases": ["s=\"babad\" -> bab或aba", "s=\"cbbd\" -> bb"], "key_points": ["中心扩展法", "处理奇偶长度"], "tags": ["string", "medium", "Google", "Amazon"]} {"problem_id": "algo_00186", "original_id": "reverse-list", "title": "反转链表", "category": "linkedlist", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "给你单链表的头节点 head,请你反转链表,并返回反转后的链表。", "solution_python": "def reverseList(head):\n prev = None\n curr = head\n while curr:\n nxt = curr.next\n curr.next = prev\n prev = curr\n curr = nxt\n return prev", "solution_java": "public ListNode reverseList(ListNode head) {\n ListNode prev = null, curr = head;\n while (curr != null) {\n ListNode next = curr.next;\n curr.next = prev;\n prev = curr;\n curr = next;\n }\n return prev;\n}", "solution_cpp": "ListNode* reverseList(ListNode* head) {\n ListNode* prev = nullptr, *curr = head;\n while (curr) {\n ListNode* next = curr->next;\n curr->next = prev;\n prev = curr;\n curr = next;\n }\n return prev;\n}", "test_cases": ["head=[1,2,3,4,5] -> [5,4,3,2,1]", "head=[1,2] -> [2,1]"], "key_points": ["迭代法 O(1)空间", "递归法 O(n)空间"], "tags": ["linkedlist", "medium", "Google", "Microsoft"]} {"problem_id": "algo_00187", "original_id": "middle-node", "title": "链表的中间结点", "category": "linkedlist", "difficulty": "easy", "companies": ["Amazon", "Facebook"], "description": "给你单链表的头节点 head,请你找出并返回链表的中间结点。如果有两个中间结点,则返回第二个中间结点。", "solution_python": "def middleNode(head):\n slow = fast = head\n while fast and fast.next:\n slow = slow.next\n fast = fast.next.next\n return slow", "solution_java": "public ListNode middleNode(ListNode head) {\n ListNode slow = head, fast = head;\n while (fast != null && fast.next != null) {\n slow = slow.next;\n fast = fast.next.next;\n }\n return slow;\n}", "solution_cpp": "ListNode* middleNode(ListNode* head) {\n ListNode* slow = head, *fast = head;\n while (fast && fast->next) { slow = slow->next; fast = fast->next->next; }\n return slow;\n}", "test_cases": ["head=[1,2,3,4,5] -> 3", "head=[1,2,3,4,5,6] -> 4"], "key_points": ["快慢指针", "O(n)时间O(1)空间"], "tags": ["linkedlist", "easy", "Amazon", "Facebook"]} {"problem_id": "algo_00188", "original_id": "max-depth", "title": "二叉树的最大深度", "category": "tree", "difficulty": "easy", "companies": ["Microsoft", "Apple"], "description": "给定一个二叉树 root,返回其最大深度。", "solution_python": "def maxDepth(root):\n if not root: return 0\n return max(maxDepth(root.left), maxDepth(root.right)) + 1", "solution_java": "public int maxDepth(TreeNode root) {\n if (root == null) return 0;\n return Math.max(maxDepth(root.left), maxDepth(root.right)) + 1;\n}", "solution_cpp": "int maxDepth(TreeNode* root) {\n if (!root) return 0;\n return max(maxDepth(root->left), maxDepth(root->right)) + 1;\n}", "test_cases": ["root=[3,9,20,null,null,15,7] -> 3", "root=[1,null,2] -> 2"], "key_points": ["DFS递归", "层序遍历也可"], "tags": ["tree", "easy", "Microsoft", "Apple"]} {"problem_id": "algo_00189", "original_id": "inorder-traversal", "title": "二叉树的中序遍历", "category": "tree", "difficulty": "easy", "companies": ["Google", "Microsoft"], "description": "给定一个二叉树的根节点 root,返回它的中序遍历结果。", "solution_python": "def inorderTraversal(root):\n result = []\n def dfs(node):\n if node:\n dfs(node.left)\n result.append(node.val)\n dfs(node.right)\n dfs(root)\n return result", "solution_java": "public List inorderTraversal(TreeNode root) {\n List res = new ArrayList<>();\n dfs(root, res);\n return res;\n}\nprivate void dfs(TreeNode node, List res) {\n if (node == null) return;\n dfs(node.left, res); res.add(node.val); dfs(node.right, res);\n}", "solution_cpp": "vector inorderTraversal(TreeNode* root) {\n vector res;\n dfs(root, res);\n return res;\n}\nvoid dfs(TreeNode* node, vector& res) {\n if (!node) return;\n dfs(node->left, res); res.push_back(node->val); dfs(node->right, res);\n}", "test_cases": ["root=[1,null,2,3] -> [1,3,2]", "root=[] -> []"], "key_points": ["左-根-右顺序", "递归最简洁"], "tags": ["tree", "easy", "Google", "Microsoft"]} {"problem_id": "algo_00190", "original_id": "binary-search", "title": "二分查找", "category": "binarysearch", "difficulty": "easy", "companies": ["Google", "Amazon"], "description": "给定一个 n 个元素有序的(升序)整型数组 nums 和一个目标值 target,写一个函数搜索 nums 中的 target,如果目标值存在返回下标,否则返回 -1。", "solution_python": "def search(nums, target):\n left, right = 0, len(nums) - 1\n while left <= right:\n mid = (left + right) // 2\n if nums[mid] == target: return mid\n elif nums[mid] < target: left = mid + 1\n else: right = mid - 1\n return -1", "solution_java": "public int search(int[] nums, int target) {\n int left = 0, right = nums.length - 1;\n while (left <= right) {\n int mid = left + (right - left) / 2;\n if (nums[mid] == target) return mid;\n else if (nums[mid] < target) left = mid + 1;\n else right = mid - 1;\n }\n return -1;\n}", "solution_cpp": "int search(vector& nums, int target) {\n int left = 0, right = nums.size() - 1;\n while (left <= right) {\n int mid = left + (right - left) / 2;\n if (nums[mid] == target) return mid;\n else if (nums[mid] < target) left = mid + 1;\n else right = mid - 1;\n }\n return -1;\n}", "test_cases": ["nums=[-1,0,3,5,9,12], target=9 -> 4", "nums=[-1,0,3,5,9,12], target=2 -> -1"], "key_points": ["标准模板", "注意防溢出写法"], "tags": ["binarysearch", "easy", "Google", "Amazon"]} {"problem_id": "algo_00191", "original_id": "climbing-stairs", "title": "爬楼梯", "category": "dp", "difficulty": "easy", "companies": ["Amazon", "Google"], "description": "假设你正在爬楼梯。需要 n 阶你才能到达楼顶。每次你可以爬 1 或 2 个台阶。你有多少种不同的方法可以爬到楼顶?", "solution_python": "def climbStairs(n):\n if n <= 2: return n\n a, b = 1, 2\n for _ in range(3, n+1):\n a, b = b, a + b\n return b", "solution_java": "public int climbStairs(int n) {\n if (n <= 2) return n;\n int a = 1, b = 2;\n for (int i = 3; i <= n; i++) { int temp = a + b; a = b; b = temp; }\n return b;\n}", "solution_cpp": "int climbStairs(int n) {\n if (n <= 2) return n;\n int a = 1, b = 2;\n for (int i = 3; i <= n; i++) { int temp = a + b; a = b; b = temp; }\n return b;\n}", "test_cases": ["n=2 -> 2", "n=3 -> 3", "n=5 -> 8"], "key_points": ["斐波那契数列", "滚动数组优化空间"], "tags": ["dp", "easy", "Amazon", "Google"]} {"problem_id": "algo_00192", "original_id": "coin-change", "title": "零钱兑换", "category": "dp", "difficulty": "medium", "companies": ["Google", "Amazon"], "description": "给你一个整数数组 coins 表示不同面额的硬币,以及一个整数 amount 表示总金额。计算并返回可以凑成总金额所需的最少的硬币个数。如果没有任何一种硬币组合能组成总金额,返回 -1。", "solution_python": "def coinChange(coins, amount):\n dp = [float('inf')] * (amount + 1)\n dp[0] = 0\n for coin in coins:\n for x in range(coin, amount + 1):\n dp[x] = min(dp[x], dp[x - coin] + 1)\n return dp[amount] if dp[amount] != float('inf') else -1", "solution_java": "public int coinChange(int[] coins, int amount) {\n int[] dp = new int[amount + 1];\n Arrays.fill(dp, amount + 1);\n dp[0] = 0;\n for (int coin : coins) {\n for (int x = coin; x <= amount; x++) {\n dp[x] = Math.min(dp[x], dp[x - coin] + 1);\n }\n }\n return dp[amount] > amount ? -1 : dp[amount];\n}", "solution_cpp": "int coinChange(vector& coins, int amount) {\n vector dp(amount + 1, amount + 1);\n dp[0] = 0;\n for (int coin : coins) {\n for (int x = coin; x <= amount; x++) {\n dp[x] = min(dp[x], dp[x - coin] + 1);\n }\n }\n return dp[amount] > amount ? -1 : dp[amount];\n}", "test_cases": ["coins=[1,2,5], amount=11 -> 3", "coins=[2], amount=3 -> -1"], "key_points": ["完全背包问题", "dp[x] = min(dp[x-coin]+1)"], "tags": ["dp", "medium", "Google", "Amazon"]} {"problem_id": "algo_00193", "original_id": "subsets", "title": "子集", "category": "backtracking", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "给你一个整数数组 nums ,数组中的元素 互不相同 。返回该数组所有可能的子集(幂集)。", "solution_python": "def subsets(nums):\n result = []\n def backtrack(start, path):\n result.append(path[:])\n for i in range(start, len(nums)):\n path.append(nums[i])\n backtrack(i + 1, path)\n path.pop()\n backtrack(0, [])\n return result", "solution_java": "public List> subsets(int[] nums) {\n List> result = new ArrayList<>();\n backtrack(nums, 0, new ArrayList<>(), result);\n return result;\n}\nprivate void backtrack(int[] nums, int start, List path, List> result) {\n result.add(new ArrayList<>(path));\n for (int i = start; i < nums.length; i++) {\n path.add(nums[i]);\n backtrack(nums, i + 1, path, result);\n path.remove(path.size() - 1);\n }\n}", "solution_cpp": "vector> subsets(vector& nums) {\n vector> result;\n vector path;\n backtrack(nums, 0, path, result);\n return result;\n}\nvoid backtrack(vector& nums, int start, vector& path, vector>& result) {\n result.push_back(path);\n for (int i = start; i < nums.size(); i++) {\n path.push_back(nums[i]);\n backtrack(nums, i + 1, path, result);\n path.pop_back();\n }\n}", "test_cases": ["nums=[1,2,3] -> [[],[1],[2],[1,2],[3],[1,3],[2,3],[1,2,3]]"], "key_points": ["选或不选", "DFS遍历子集树"], "tags": ["backtracking", "medium", "Google", "Microsoft"]} {"problem_id": "algo_00194", "original_id": "permutations", "title": "全排列", "category": "backtracking", "difficulty": "medium", "companies": ["Google", "Facebook"], "description": "给定一个不含重复数字的数组 nums,返回其所有可能的全排列。", "solution_python": "def permute(nums):\n result = []\n def backtrack(path, used):\n if len(path) == len(nums):\n result.append(path[:])\n return\n for i in range(len(nums)):\n if used[i]: continue\n used[i] = True\n path.append(nums[i])\n backtrack(path, used)\n path.pop()\n used[i] = False\n backtrack([], [False]*len(nums))\n return result", "solution_java": "public List> permute(int[] nums) {\n List> result = new ArrayList<>();\n boolean[] used = new boolean[nums.length];\n backtrack(nums, used, new ArrayList<>(), result);\n return result;\n}\nprivate void backtrack(int[] nums, boolean[] used, List path, List> result) {\n if (path.size() == nums.length) { result.add(new ArrayList<>(path)); return; }\n for (int i = 0; i < nums.length; i++) {\n if (used[i]) continue;\n used[i] = true;\n path.add(nums[i]);\n backtrack(nums, used, path, result);\n path.remove(path.size() - 1);\n used[i] = false;\n }\n}", "solution_cpp": "vector> permute(vector& nums) {\n vector> result;\n vector used(nums.size(), false);\n vector path;\n backtrack(nums, used, path, result);\n return result;\n}\nvoid backtrack(vector& nums, vector& used, vector& path, vector>& result) {\n if (path.size() == nums.size()) { result.push_back(path); return; }\n for (int i = 0; i < nums.size(); i++) {\n if (used[i]) continue;\n used[i] = true;\n path.push_back(nums[i]);\n backtrack(nums, used, path, result);\n path.pop_back();\n used[i] = false;\n }\n}", "test_cases": ["nums=[1,2,3] -> [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]"], "key_points": ["标记已使用元素", "回溯经典模板"], "tags": ["backtracking", "medium", "Google", "Facebook"]} {"problem_id": "algo_00195", "original_id": "top-k-frequent", "title": "前K个高频元素", "category": "heap", "difficulty": "medium", "companies": ["Amazon", "Facebook"], "description": "给你一个整数数组 nums 和一个整数 k,请你返回其中出现频率前 k 高的元素。", "solution_python": "import heapq\nfrom collections import Counter\ndef topKFrequent(nums, k):\n count = Counter(nums)\n heap = []\n for num, freq in count.items():\n heapq.heappush(heap, (freq, num))\n if len(heap) > k: heapq.heappop(heap)\n return [num for freq, num in heap]", "solution_java": "public int[] topKFrequent(int[] nums, int k) {\n Map count = new HashMap<>();\n for (int n : nums) count.put(n, count.getOrDefault(n, 0) + 1);\n PriorityQueue> heap = \n new PriorityQueue<>((a, b) -> a.getValue() - b.getValue());\n for (Map.Entry e : count.entrySet()) {\n heap.offer(e);\n if (heap.size() > k) heap.poll();\n }\n int[] res = new int[k];\n for (int i = k - 1; i >= 0; i--) res[i] = heap.poll().getKey();\n return res;\n}", "solution_cpp": "vector topKFrequent(vector& nums, int k) {\n unordered_map count;\n for (int n : nums) count[n]++;\n priority_queue, vector>, greater>> heap;\n for (auto& [num, freq] : count) {\n heap.push({freq, num});\n if (heap.size() > k) heap.pop();\n }\n vector res;\n while (!heap.empty()) { res.push_back(heap.top().second); heap.pop(); }\n reverse(res.begin(), res.end());\n return res;\n}", "test_cases": ["nums=[1,1,1,2,2,3], k=2 -> [1,2]", "nums=[1], k=1 -> [1]"], "key_points": ["小顶堆保持大小k", "时间复杂度O(nlogk)"], "tags": ["heap", "medium", "Amazon", "Facebook"]} {"problem_id": "algo_00196", "original_id": "3sum", "title": "三数之和", "category": "two-pointers", "difficulty": "medium", "companies": ["Google", "Amazon"], "description": "给你一个整数数组 nums,判断是否存在三元组满足和为0,返回所有不重复的三元组。", "solution_python": "def threeSum(nums):\n nums.sort()\n result = []\n for i in range(len(nums) - 2):\n if i > 0 and nums[i] == nums[i-1]: continue\n left, right = i + 1, len(nums) - 1\n while left < right:\n total = nums[i] + nums[left] + nums[right]\n if total < 0: left += 1\n elif total > 0: right -= 1\n else:\n result.append([nums[i], nums[left], nums[right]])\n while left < right and nums[left] == nums[left+1]: left += 1\n while left < right and nums[right] == nums[right-1]: right -= 1\n left += 1; right -= 1\n return result", "solution_java": "public List> threeSum(int[] nums) {\n Arrays.sort(nums);\n List> result = new ArrayList<>();\n for (int i = 0; i < nums.length - 2; i++) {\n if (i > 0 && nums[i] == nums[i-1]) continue;\n int left = i + 1, right = nums.length - 1;\n while (left < right) {\n int total = nums[i] + nums[left] + nums[right];\n if (total < 0) left++;\n else if (total > 0) right--;\n else {\n result.add(Arrays.asList(nums[i], nums[left], nums[right]));\n while (left < right && nums[left] == nums[left+1]) left++;\n while (left < right && nums[right] == nums[right-1]) right--;\n left++; right--;\n }\n }\n }\n return result;\n}", "solution_cpp": "vector> threeSum(vector& nums) {\n sort(nums.begin(), nums.end());\n vector> result;\n for (int i = 0; i < nums.size() - 2; i++) {\n if (i > 0 && nums[i] == nums[i-1]) continue;\n int left = i + 1, right = nums.size() - 1;\n while (left < right) {\n int total = nums[i] + nums[left] + nums[right];\n if (total < 0) left++;\n else if (total > 0) right--;\n else {\n result.push_back({nums[i], nums[left], nums[right]});\n while (left < right && nums[left] == nums[left+1]) left++;\n while (left < right && nums[right] == nums[right-1]) right--;\n left++; right--;\n }\n }\n }\n return result;\n}", "test_cases": ["nums=[-1,0,1,2,-1,-4] -> [[-1,-1,2],[-1,0,1]]"], "key_points": ["排序+双指针", "去重是关键"], "tags": ["two-pointers", "medium", "Google", "Amazon"]} {"problem_id": "algo_00197", "original_id": "container-water", "title": "盛最多水的容器", "category": "two-pointers", "difficulty": "medium", "companies": ["Google", "Uber"], "description": "给定一个长度为 n 的整数数组 height,找出其中的两条线,使得它们与 x 轴共同构成的容器可以容纳最多的水。", "solution_python": "def maxArea(height):\n left, right = 0, len(height) - 1\n max_area = 0\n while left < right:\n h = min(height[left], height[right])\n max_area = max(max_area, h * (right - left))\n if height[left] < height[right]: left += 1\n else: right -= 1\n return max_area", "solution_java": "public int maxArea(int[] height) {\n int left = 0, right = height.length - 1, maxArea = 0;\n while (left < right) {\n int h = Math.min(height[left], height[right]);\n maxArea = Math.max(maxArea, h * (right - left));\n if (height[left] < height[right]) left++;\n else right--;\n }\n return maxArea;\n}", "solution_cpp": "int maxArea(vector& height) {\n int left = 0, right = height.size() - 1, maxArea = 0;\n while (left < right) {\n int h = min(height[left], height[right]);\n maxArea = max(maxArea, h * (right - left));\n if (height[left] < height[right]) left++;\n else right--;\n }\n return maxArea;\n}", "test_cases": ["height=[1,8,6,2,5,4,8,3,7] -> 49"], "key_points": ["移动短边指针", "面积=min(h1,h2)*width"], "tags": ["two-pointers", "medium", "Google", "Uber"]} {"problem_id": "algo_00198", "original_id": "min-stack", "title": "最小栈", "category": "stack", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "设计一个支持 push,pop,top 操作,并能在常数时间内检索到最小元素的栈。", "solution_python": "class MinStack:\n def __init__(self):\n self.stack = []\n self.min_stack = []\n def push(self, val):\n self.stack.append(val)\n self.min_stack.append(min(val, self.min_stack[-1] if self.min_stack else val))\n def pop(self):\n self.stack.pop(); self.min_stack.pop()\n def top(self): return self.stack[-1]\n def getMin(self): return self.min_stack[-1]", "solution_java": "class MinStack {\n Stack stack = new Stack<>();\n Stack minStack = new Stack<>();\n public void push(int val) { stack.push(val); minStack.push(Math.min(val, minStack.isEmpty() ? val : minStack.peek())); }\n public void pop() { stack.pop(); minStack.pop(); }\n public int top() { return stack.peek(); }\n public int getMin() { return minStack.peek(); }\n}", "solution_cpp": "class MinStack {\n stack st, minSt;\npublic:\n void push(int val) { st.push(val); minSt.push(min(val, minSt.empty() ? val : minSt.top())); }\n void pop() { st.pop(); minSt.pop(); }\n int top() { return st.top(); }\n int getMin() { return minSt.top(); }\n};", "test_cases": ["push(-2), push(0), push(-3) -> getMin() returns -3"], "key_points": ["辅助栈记录最小值", "O(1)时间获取最小值"], "tags": ["stack", "medium", "Google", "Microsoft"]} {"problem_id": "algo_00199", "original_id": "lru-cache", "title": "LRU缓存", "category": "design", "difficulty": "hard", "companies": ["Google", "Amazon"], "description": "设计和实现一个 LRU(最近最少使用)缓存机制。", "solution_python": "class LRUCache:\n def __init__(self, capacity):\n self.capacity = capacity\n self.cache = {}\n self.order = []\n def get(self, key):\n if key not in self.cache: return -1\n self.order.remove(key); self.order.append(key)\n return self.cache[key]\n def put(self, key, value):\n if key in self.cache:\n self.order.remove(key)\n elif len(self.cache) >= self.capacity:\n del self.cache[self.order.pop(0)]\n self.cache[key] = value; self.order.append(key)", "solution_java": "class LRUCache {\n int capacity;\n LinkedHashMap cache = new LinkedHashMap<>();\n public LRUCache(int cap) { capacity = cap; }\n public int get(int key) { return cache.containsKey(key) ? cache.remove(key) : -1; }\n public void put(int key, int val) {\n if (cache.containsKey(key)) cache.remove(key);\n else if (cache.size() >= capacity) cache.remove(cache.keySet().iterator().next());\n cache.put(key, val);\n }\n}", "solution_cpp": "class LRUCache {\n int cap;\n list> dll;\n unordered_map>::iterator> cache;\npublic:\n LRUCache(int capacity) : cap(capacity) {}\n int get(int key) {\n auto it = cache.find(key);\n if (it == cache.end()) return -1;\n dll.splice(dll.end(), dll, it->second);\n return it->second->second;\n }\n void put(int key, int value) {\n auto it = cache.find(key);\n if (it != cache.end()) dll.erase(it->second);\n else if (cache.size() >= cap) { cache.erase(dll.front().first); dll.pop_front(); }\n dll.push_back({key, value});\n cache[key] = --dll.end();\n }\n};", "test_cases": ["put(1,1), put(2,2), get(1) -> 1"], "key_points": ["HashMap + 双向链表", "O(1)时间操作"], "tags": ["design", "hard", "Google", "Amazon"]} {"problem_id": "algo_00200", "original_id": "num-islands", "title": "岛屿数量", "category": "graph", "difficulty": "medium", "companies": ["Google", "Facebook"], "description": "给你一个由 '1'(陆地)和 '0'(水)组成的二维网格,请你计算网格中岛屿的数量。岛屿总是被水包围,且只能由水平或垂直方向相邻的陆地连接形成。", "solution_python": "def numIslands(grid):\n if not grid: return 0\n rows, cols = len(grid), len(grid[0])\n count = 0\n def dfs(r, c):\n if r < 0 or r >= rows or c < 0 or c >= cols or grid[r][c] != '1': return\n grid[r][c] = '0'\n dfs(r+1, c); dfs(r-1, c); dfs(r, c+1); dfs(r, c-1)\n for r in range(rows):\n for c in range(cols):\n if grid[r][c] == '1': count += 1; dfs(r, c)\n return count", "solution_java": "public int numIslands(char[][] grid) {\n if (grid.length == 0) return 0;\n int count = 0;\n for (int i = 0; i < grid.length; i++)\n for (int j = 0; j < grid[0].length; j++)\n if (grid[i][j] == '1') { count++; dfs(grid, i, j); }\n return count;\n}\nprivate void dfs(char[][] grid, int r, int c) {\n if (r < 0 || r >= grid.length || c < 0 || c >= grid[0].length || grid[r][c] != '1') return;\n grid[r][c] = '0';\n dfs(grid, r+1, c); dfs(grid, r-1, c); dfs(grid, r, c+1); dfs(grid, r, c-1);\n}", "solution_cpp": "int numIslands(vector>& grid) {\n if (grid.empty()) return 0;\n int count = 0;\n for (int i = 0; i < grid.size(); i++)\n for (int j = 0; j < grid[0].size(); j++)\n if (grid[i][j] == '1') { count++; dfs(grid, i, j); }\n return count;\n}\nvoid dfs(vector>& grid, int r, int c) {\n if (r < 0 || r >= grid.size() || c < 0 || c >= grid[0].size() || grid[r][c] != '1') return;\n grid[r][c] = '0';\n dfs(grid, r+1, c); dfs(grid, r-1, c); dfs(grid, r, c+1); dfs(grid, r, c-1);\n}", "test_cases": ["grid=[[1,1,1,1,0],[1,1,0,1,0],[1,1,0,0,0],[0,0,0,0,0]] -> 1"], "key_points": ["DFS/BFS遍历", "访问后标记为0避免重复"], "tags": ["graph", "medium", "Google", "Facebook"]} {"problem_id": "algo_00201", "original_id": "two-sum", "title": "两数之和", "category": "array", "difficulty": "easy", "companies": ["Amazon", "Google"], "description": "给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那两个整数,并返回他们的数组下标。", "solution_python": "def twoSum(nums, target):\n hashmap = {}\n for i, num in enumerate(nums):\n complement = target - num\n if complement in hashmap:\n return [hashmap[complement], i]\n hashmap[num] = i\n return []", "solution_java": "public int[] twoSum(int[] nums, int target) {\n Map map = new HashMap<>();\n for (int i = 0; i < nums.length; i++) {\n int complement = target - nums[i];\n if (map.containsKey(complement)) return new int[]{map.get(complement), i};\n map.put(nums[i], i);\n }\n return new int[]{};\n}", "solution_cpp": "vector twoSum(vector& nums, int target) {\n unordered_map m;\n for (int i = 0; i < nums.size(); i++) {\n if (m.count(target - nums[i])) return {m[target - nums[i]], i};\n m[nums[i]] = i;\n }\n return {};\n}", "test_cases": ["nums=[2,7,11,15], target=9 -> [0,1]", "nums=[3,2,4], target=6 -> [1,2]"], "key_points": ["哈希表一次遍历", "空间换时间"], "tags": ["array", "easy", "Amazon", "Google"]} {"problem_id": "algo_00202", "original_id": "merge-sorted", "title": "合并两个有序数组", "category": "array", "difficulty": "easy", "companies": ["Microsoft", "Uber"], "description": "给你两个按非递减顺序排列的整数数组 nums1 和 nums2,另有两个整数 m 和 n,分别表示 nums1 和 nums2 中的元素数目。请你合并 nums2 到 nums1 中。", "solution_python": "def merge(nums1, m, nums2, n):\n p1, p2, p = m-1, n-1, m+n-1\n while p1 >= 0 and p2 >= 0:\n if nums1[p1] > nums2[p2]: nums1[p] = nums1[p1]; p1 -= 1\n else: nums1[p] = nums2[p2]; p2 -= 1\n p -= 1\n while p2 >= 0: nums1[p] = nums2[p2]; p2 -= 1; p -= 1", "solution_java": "public void merge(int[] nums1, int m, int[] nums2, int n) {\n int p1 = m-1, p2 = n-1, p = m+n-1;\n while (p1 >= 0 && p2 >= 0) {\n nums1[p--] = nums1[p1] > nums2[p2] ? nums1[p1--] : nums2[p2--];\n }\n while (p2 >= 0) nums1[p--] = nums2[p2--];\n}", "solution_cpp": "void merge(vector& nums1, int m, vector& nums2, int n) {\n int p1 = m-1, p2 = n-1, p = m+n-1;\n while (p1 >= 0 && p2 >= 0) nums1[p--] = nums1[p1] > nums2[p2] ? nums1[p1--] : nums2[p2--];\n while (p2 >= 0) nums1[p--] = nums2[p2--];\n}", "test_cases": ["nums1=[1,2,3], m=3, nums2=[2,5,6], n=3 -> [1,2,2,3,5,6]", "nums1=[], m=0, nums2=[1], n=1 -> [1]"], "key_points": ["从后往前合并", "三指针技巧"], "tags": ["array", "easy", "Microsoft", "Uber"]} {"problem_id": "algo_00203", "original_id": "max-subarray", "title": "最大子数组和", "category": "array", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "给你一个整数数组 nums ,请你找出一个具有最大和的连续子数组,返回其最大和。", "solution_python": "def maxSubArray(nums):\n max_sum = current = nums[0]\n for num in nums[1:]:\n current = max(num, current + num)\n max_sum = max(max_sum, current)\n return max_sum", "solution_java": "public int maxSubArray(int[] nums) {\n int maxSum = nums[0], curr = nums[0];\n for (int i = 1; i < nums.length; i++) {\n curr = Math.max(nums[i], curr + nums[i]);\n maxSum = Math.max(maxSum, curr);\n }\n return maxSum;\n}", "solution_cpp": "int maxSubArray(vector& nums) {\n int maxSum = nums[0], curr = nums[0];\n for (int i = 1; i < nums.size(); i++) {\n curr = max(nums[i], curr + nums[i]);\n maxSum = max(maxSum, curr);\n }\n return maxSum;\n}", "test_cases": ["nums=[-2,1,-3,4,-1,2,1,-5,4] -> 6", "nums=[1] -> 1"], "key_points": ["Kadane算法", "动态规划基础题"], "tags": ["array", "medium", "Google", "Microsoft"]} {"problem_id": "algo_00204", "original_id": "valid-parentheses", "title": "有效的括号", "category": "string", "difficulty": "easy", "companies": ["Google", "Uber"], "description": "给定一个只包括 '(',')','{','}','[',']' 的字符串 s,判断字符串是否有效。", "solution_python": "def isValid(s):\n stack = []\n mapping = {')': '(', ']': '[', '}': '{'}\n for c in s:\n if c in mapping:\n if not stack or stack[-1] != mapping[c]: return False\n stack.pop()\n else: stack.append(c)\n return not stack", "solution_java": "public boolean isValid(String s) {\n Stack stack = new Stack<>();\n Map map = Map.of(')', '(', ']', '[', '}', '{');\n for (char c : s.toCharArray()) {\n if (map.containsValue(c)) stack.push(c);\n else if (!stack.isEmpty() && stack.pop() != map.get(c)) return false;\n }\n return stack.isEmpty();\n}", "solution_cpp": "bool isValid(string s) {\n stack st;\n unordered_map m = {{')','('},{']','['},{'}','{'}};\n for (char c : s) {\n if (m.find(c) == m.end()) st.push(c);\n else if (st.empty() || st.top() != m[c]) return false;\n else st.pop();\n }\n return st.empty();\n}", "test_cases": ["s=\"()\" -> true", "s=\"()[]{}\" -> true", "s=\"(]\" -> false"], "key_points": ["栈匹配法", "注意空栈边界"], "tags": ["string", "easy", "Google", "Uber"]} {"problem_id": "algo_00205", "original_id": "longest-palindrome", "title": "最长回文子串", "category": "string", "difficulty": "medium", "companies": ["Google", "Amazon"], "description": "给你一个字符串 s,找到 s 中最长的回文子串。", "solution_python": "def longestPalindrome(s):\n def expand(l, r):\n while l >= 0 and r < len(s) and s[l] == s[r]: l -= 1; r += 1\n return l + 1, r - 1\n start = end = 0\n for i in range(len(s)):\n l1, r1 = expand(i, i)\n l2, r2 = expand(i, i + 1)\n if r1 - l1 > end - start: start, end = l1, r1\n if r2 - l2 > end - start: start, end = l2, r2\n return s[start:end+1]", "solution_java": "public String longestPalindrome(String s) {\n int start = 0, end = 0;\n for (int i = 0; i < s.length(); i++) {\n int len1 = expand(s, i, i), len2 = expand(s, i, i+1);\n int len = Math.max(len1, len2);\n if (len > end - start) { start = i - (len-1)/2; end = i + len/2; }\n }\n return s.substring(start, end + 1);\n}\nprivate int expand(String s, int l, int r) {\n while (l >= 0 && r < s.length() && s.charAt(l) == s.charAt(r)) { l--; r++; }\n return r - l - 1;\n}", "solution_cpp": "string longestPalindrome(string s) {\n int start = 0, end = 0;\n for (int i = 0; i < s.size(); i++) {\n int len1 = expand(s, i, i), len2 = expand(s, i, i+1);\n if (max(len1, len2) > end - start) { start = i - (max(len1,len2)-1)/2; end = i + max(len1,len2)/2; }\n }\n return s.substr(start, end - start + 1);\n}", "test_cases": ["s=\"babad\" -> bab或aba", "s=\"cbbd\" -> bb"], "key_points": ["中心扩展法", "处理奇偶长度"], "tags": ["string", "medium", "Google", "Amazon"]} {"problem_id": "algo_00206", "original_id": "reverse-list", "title": "反转链表", "category": "linkedlist", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "给你单链表的头节点 head,请你反转链表,并返回反转后的链表。", "solution_python": "def reverseList(head):\n prev = None\n curr = head\n while curr:\n nxt = curr.next\n curr.next = prev\n prev = curr\n curr = nxt\n return prev", "solution_java": "public ListNode reverseList(ListNode head) {\n ListNode prev = null, curr = head;\n while (curr != null) {\n ListNode next = curr.next;\n curr.next = prev;\n prev = curr;\n curr = next;\n }\n return prev;\n}", "solution_cpp": "ListNode* reverseList(ListNode* head) {\n ListNode* prev = nullptr, *curr = head;\n while (curr) {\n ListNode* next = curr->next;\n curr->next = prev;\n prev = curr;\n curr = next;\n }\n return prev;\n}", "test_cases": ["head=[1,2,3,4,5] -> [5,4,3,2,1]", "head=[1,2] -> [2,1]"], "key_points": ["迭代法 O(1)空间", "递归法 O(n)空间"], "tags": ["linkedlist", "medium", "Google", "Microsoft"]} {"problem_id": "algo_00207", "original_id": "middle-node", "title": "链表的中间结点", "category": "linkedlist", "difficulty": "easy", "companies": ["Amazon", "Facebook"], "description": "给你单链表的头节点 head,请你找出并返回链表的中间结点。如果有两个中间结点,则返回第二个中间结点。", "solution_python": "def middleNode(head):\n slow = fast = head\n while fast and fast.next:\n slow = slow.next\n fast = fast.next.next\n return slow", "solution_java": "public ListNode middleNode(ListNode head) {\n ListNode slow = head, fast = head;\n while (fast != null && fast.next != null) {\n slow = slow.next;\n fast = fast.next.next;\n }\n return slow;\n}", "solution_cpp": "ListNode* middleNode(ListNode* head) {\n ListNode* slow = head, *fast = head;\n while (fast && fast->next) { slow = slow->next; fast = fast->next->next; }\n return slow;\n}", "test_cases": ["head=[1,2,3,4,5] -> 3", "head=[1,2,3,4,5,6] -> 4"], "key_points": ["快慢指针", "O(n)时间O(1)空间"], "tags": ["linkedlist", "easy", "Amazon", "Facebook"]} {"problem_id": "algo_00208", "original_id": "max-depth", "title": "二叉树的最大深度", "category": "tree", "difficulty": "easy", "companies": ["Microsoft", "Apple"], "description": "给定一个二叉树 root,返回其最大深度。", "solution_python": "def maxDepth(root):\n if not root: return 0\n return max(maxDepth(root.left), maxDepth(root.right)) + 1", "solution_java": "public int maxDepth(TreeNode root) {\n if (root == null) return 0;\n return Math.max(maxDepth(root.left), maxDepth(root.right)) + 1;\n}", "solution_cpp": "int maxDepth(TreeNode* root) {\n if (!root) return 0;\n return max(maxDepth(root->left), maxDepth(root->right)) + 1;\n}", "test_cases": ["root=[3,9,20,null,null,15,7] -> 3", "root=[1,null,2] -> 2"], "key_points": ["DFS递归", "层序遍历也可"], "tags": ["tree", "easy", "Microsoft", "Apple"]} {"problem_id": "algo_00209", "original_id": "inorder-traversal", "title": "二叉树的中序遍历", "category": "tree", "difficulty": "easy", "companies": ["Google", "Microsoft"], "description": "给定一个二叉树的根节点 root,返回它的中序遍历结果。", "solution_python": "def inorderTraversal(root):\n result = []\n def dfs(node):\n if node:\n dfs(node.left)\n result.append(node.val)\n dfs(node.right)\n dfs(root)\n return result", "solution_java": "public List inorderTraversal(TreeNode root) {\n List res = new ArrayList<>();\n dfs(root, res);\n return res;\n}\nprivate void dfs(TreeNode node, List res) {\n if (node == null) return;\n dfs(node.left, res); res.add(node.val); dfs(node.right, res);\n}", "solution_cpp": "vector inorderTraversal(TreeNode* root) {\n vector res;\n dfs(root, res);\n return res;\n}\nvoid dfs(TreeNode* node, vector& res) {\n if (!node) return;\n dfs(node->left, res); res.push_back(node->val); dfs(node->right, res);\n}", "test_cases": ["root=[1,null,2,3] -> [1,3,2]", "root=[] -> []"], "key_points": ["左-根-右顺序", "递归最简洁"], "tags": ["tree", "easy", "Google", "Microsoft"]} {"problem_id": "algo_00210", "original_id": "binary-search", "title": "二分查找", "category": "binarysearch", "difficulty": "easy", "companies": ["Google", "Amazon"], "description": "给定一个 n 个元素有序的(升序)整型数组 nums 和一个目标值 target,写一个函数搜索 nums 中的 target,如果目标值存在返回下标,否则返回 -1。", "solution_python": "def search(nums, target):\n left, right = 0, len(nums) - 1\n while left <= right:\n mid = (left + right) // 2\n if nums[mid] == target: return mid\n elif nums[mid] < target: left = mid + 1\n else: right = mid - 1\n return -1", "solution_java": "public int search(int[] nums, int target) {\n int left = 0, right = nums.length - 1;\n while (left <= right) {\n int mid = left + (right - left) / 2;\n if (nums[mid] == target) return mid;\n else if (nums[mid] < target) left = mid + 1;\n else right = mid - 1;\n }\n return -1;\n}", "solution_cpp": "int search(vector& nums, int target) {\n int left = 0, right = nums.size() - 1;\n while (left <= right) {\n int mid = left + (right - left) / 2;\n if (nums[mid] == target) return mid;\n else if (nums[mid] < target) left = mid + 1;\n else right = mid - 1;\n }\n return -1;\n}", "test_cases": ["nums=[-1,0,3,5,9,12], target=9 -> 4", "nums=[-1,0,3,5,9,12], target=2 -> -1"], "key_points": ["标准模板", "注意防溢出写法"], "tags": ["binarysearch", "easy", "Google", "Amazon"]} {"problem_id": "algo_00211", "original_id": "climbing-stairs", "title": "爬楼梯", "category": "dp", "difficulty": "easy", "companies": ["Amazon", "Google"], "description": "假设你正在爬楼梯。需要 n 阶你才能到达楼顶。每次你可以爬 1 或 2 个台阶。你有多少种不同的方法可以爬到楼顶?", "solution_python": "def climbStairs(n):\n if n <= 2: return n\n a, b = 1, 2\n for _ in range(3, n+1):\n a, b = b, a + b\n return b", "solution_java": "public int climbStairs(int n) {\n if (n <= 2) return n;\n int a = 1, b = 2;\n for (int i = 3; i <= n; i++) { int temp = a + b; a = b; b = temp; }\n return b;\n}", "solution_cpp": "int climbStairs(int n) {\n if (n <= 2) return n;\n int a = 1, b = 2;\n for (int i = 3; i <= n; i++) { int temp = a + b; a = b; b = temp; }\n return b;\n}", "test_cases": ["n=2 -> 2", "n=3 -> 3", "n=5 -> 8"], "key_points": ["斐波那契数列", "滚动数组优化空间"], "tags": ["dp", "easy", "Amazon", "Google"]} {"problem_id": "algo_00212", "original_id": "coin-change", "title": "零钱兑换", "category": "dp", "difficulty": "medium", "companies": ["Google", "Amazon"], "description": "给你一个整数数组 coins 表示不同面额的硬币,以及一个整数 amount 表示总金额。计算并返回可以凑成总金额所需的最少的硬币个数。如果没有任何一种硬币组合能组成总金额,返回 -1。", "solution_python": "def coinChange(coins, amount):\n dp = [float('inf')] * (amount + 1)\n dp[0] = 0\n for coin in coins:\n for x in range(coin, amount + 1):\n dp[x] = min(dp[x], dp[x - coin] + 1)\n return dp[amount] if dp[amount] != float('inf') else -1", "solution_java": "public int coinChange(int[] coins, int amount) {\n int[] dp = new int[amount + 1];\n Arrays.fill(dp, amount + 1);\n dp[0] = 0;\n for (int coin : coins) {\n for (int x = coin; x <= amount; x++) {\n dp[x] = Math.min(dp[x], dp[x - coin] + 1);\n }\n }\n return dp[amount] > amount ? -1 : dp[amount];\n}", "solution_cpp": "int coinChange(vector& coins, int amount) {\n vector dp(amount + 1, amount + 1);\n dp[0] = 0;\n for (int coin : coins) {\n for (int x = coin; x <= amount; x++) {\n dp[x] = min(dp[x], dp[x - coin] + 1);\n }\n }\n return dp[amount] > amount ? -1 : dp[amount];\n}", "test_cases": ["coins=[1,2,5], amount=11 -> 3", "coins=[2], amount=3 -> -1"], "key_points": ["完全背包问题", "dp[x] = min(dp[x-coin]+1)"], "tags": ["dp", "medium", "Google", "Amazon"]} {"problem_id": "algo_00213", "original_id": "subsets", "title": "子集", "category": "backtracking", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "给你一个整数数组 nums ,数组中的元素 互不相同 。返回该数组所有可能的子集(幂集)。", "solution_python": "def subsets(nums):\n result = []\n def backtrack(start, path):\n result.append(path[:])\n for i in range(start, len(nums)):\n path.append(nums[i])\n backtrack(i + 1, path)\n path.pop()\n backtrack(0, [])\n return result", "solution_java": "public List> subsets(int[] nums) {\n List> result = new ArrayList<>();\n backtrack(nums, 0, new ArrayList<>(), result);\n return result;\n}\nprivate void backtrack(int[] nums, int start, List path, List> result) {\n result.add(new ArrayList<>(path));\n for (int i = start; i < nums.length; i++) {\n path.add(nums[i]);\n backtrack(nums, i + 1, path, result);\n path.remove(path.size() - 1);\n }\n}", "solution_cpp": "vector> subsets(vector& nums) {\n vector> result;\n vector path;\n backtrack(nums, 0, path, result);\n return result;\n}\nvoid backtrack(vector& nums, int start, vector& path, vector>& result) {\n result.push_back(path);\n for (int i = start; i < nums.size(); i++) {\n path.push_back(nums[i]);\n backtrack(nums, i + 1, path, result);\n path.pop_back();\n }\n}", "test_cases": ["nums=[1,2,3] -> [[],[1],[2],[1,2],[3],[1,3],[2,3],[1,2,3]]"], "key_points": ["选或不选", "DFS遍历子集树"], "tags": ["backtracking", "medium", "Google", "Microsoft"]} {"problem_id": "algo_00214", "original_id": "permutations", "title": "全排列", "category": "backtracking", "difficulty": "medium", "companies": ["Google", "Facebook"], "description": "给定一个不含重复数字的数组 nums,返回其所有可能的全排列。", "solution_python": "def permute(nums):\n result = []\n def backtrack(path, used):\n if len(path) == len(nums):\n result.append(path[:])\n return\n for i in range(len(nums)):\n if used[i]: continue\n used[i] = True\n path.append(nums[i])\n backtrack(path, used)\n path.pop()\n used[i] = False\n backtrack([], [False]*len(nums))\n return result", "solution_java": "public List> permute(int[] nums) {\n List> result = new ArrayList<>();\n boolean[] used = new boolean[nums.length];\n backtrack(nums, used, new ArrayList<>(), result);\n return result;\n}\nprivate void backtrack(int[] nums, boolean[] used, List path, List> result) {\n if (path.size() == nums.length) { result.add(new ArrayList<>(path)); return; }\n for (int i = 0; i < nums.length; i++) {\n if (used[i]) continue;\n used[i] = true;\n path.add(nums[i]);\n backtrack(nums, used, path, result);\n path.remove(path.size() - 1);\n used[i] = false;\n }\n}", "solution_cpp": "vector> permute(vector& nums) {\n vector> result;\n vector used(nums.size(), false);\n vector path;\n backtrack(nums, used, path, result);\n return result;\n}\nvoid backtrack(vector& nums, vector& used, vector& path, vector>& result) {\n if (path.size() == nums.size()) { result.push_back(path); return; }\n for (int i = 0; i < nums.size(); i++) {\n if (used[i]) continue;\n used[i] = true;\n path.push_back(nums[i]);\n backtrack(nums, used, path, result);\n path.pop_back();\n used[i] = false;\n }\n}", "test_cases": ["nums=[1,2,3] -> [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]"], "key_points": ["标记已使用元素", "回溯经典模板"], "tags": ["backtracking", "medium", "Google", "Facebook"]} {"problem_id": "algo_00215", "original_id": "top-k-frequent", "title": "前K个高频元素", "category": "heap", "difficulty": "medium", "companies": ["Amazon", "Facebook"], "description": "给你一个整数数组 nums 和一个整数 k,请你返回其中出现频率前 k 高的元素。", "solution_python": "import heapq\nfrom collections import Counter\ndef topKFrequent(nums, k):\n count = Counter(nums)\n heap = []\n for num, freq in count.items():\n heapq.heappush(heap, (freq, num))\n if len(heap) > k: heapq.heappop(heap)\n return [num for freq, num in heap]", "solution_java": "public int[] topKFrequent(int[] nums, int k) {\n Map count = new HashMap<>();\n for (int n : nums) count.put(n, count.getOrDefault(n, 0) + 1);\n PriorityQueue> heap = \n new PriorityQueue<>((a, b) -> a.getValue() - b.getValue());\n for (Map.Entry e : count.entrySet()) {\n heap.offer(e);\n if (heap.size() > k) heap.poll();\n }\n int[] res = new int[k];\n for (int i = k - 1; i >= 0; i--) res[i] = heap.poll().getKey();\n return res;\n}", "solution_cpp": "vector topKFrequent(vector& nums, int k) {\n unordered_map count;\n for (int n : nums) count[n]++;\n priority_queue, vector>, greater>> heap;\n for (auto& [num, freq] : count) {\n heap.push({freq, num});\n if (heap.size() > k) heap.pop();\n }\n vector res;\n while (!heap.empty()) { res.push_back(heap.top().second); heap.pop(); }\n reverse(res.begin(), res.end());\n return res;\n}", "test_cases": ["nums=[1,1,1,2,2,3], k=2 -> [1,2]", "nums=[1], k=1 -> [1]"], "key_points": ["小顶堆保持大小k", "时间复杂度O(nlogk)"], "tags": ["heap", "medium", "Amazon", "Facebook"]} {"problem_id": "algo_00216", "original_id": "3sum", "title": "三数之和", "category": "two-pointers", "difficulty": "medium", "companies": ["Google", "Amazon"], "description": "给你一个整数数组 nums,判断是否存在三元组满足和为0,返回所有不重复的三元组。", "solution_python": "def threeSum(nums):\n nums.sort()\n result = []\n for i in range(len(nums) - 2):\n if i > 0 and nums[i] == nums[i-1]: continue\n left, right = i + 1, len(nums) - 1\n while left < right:\n total = nums[i] + nums[left] + nums[right]\n if total < 0: left += 1\n elif total > 0: right -= 1\n else:\n result.append([nums[i], nums[left], nums[right]])\n while left < right and nums[left] == nums[left+1]: left += 1\n while left < right and nums[right] == nums[right-1]: right -= 1\n left += 1; right -= 1\n return result", "solution_java": "public List> threeSum(int[] nums) {\n Arrays.sort(nums);\n List> result = new ArrayList<>();\n for (int i = 0; i < nums.length - 2; i++) {\n if (i > 0 && nums[i] == nums[i-1]) continue;\n int left = i + 1, right = nums.length - 1;\n while (left < right) {\n int total = nums[i] + nums[left] + nums[right];\n if (total < 0) left++;\n else if (total > 0) right--;\n else {\n result.add(Arrays.asList(nums[i], nums[left], nums[right]));\n while (left < right && nums[left] == nums[left+1]) left++;\n while (left < right && nums[right] == nums[right-1]) right--;\n left++; right--;\n }\n }\n }\n return result;\n}", "solution_cpp": "vector> threeSum(vector& nums) {\n sort(nums.begin(), nums.end());\n vector> result;\n for (int i = 0; i < nums.size() - 2; i++) {\n if (i > 0 && nums[i] == nums[i-1]) continue;\n int left = i + 1, right = nums.size() - 1;\n while (left < right) {\n int total = nums[i] + nums[left] + nums[right];\n if (total < 0) left++;\n else if (total > 0) right--;\n else {\n result.push_back({nums[i], nums[left], nums[right]});\n while (left < right && nums[left] == nums[left+1]) left++;\n while (left < right && nums[right] == nums[right-1]) right--;\n left++; right--;\n }\n }\n }\n return result;\n}", "test_cases": ["nums=[-1,0,1,2,-1,-4] -> [[-1,-1,2],[-1,0,1]]"], "key_points": ["排序+双指针", "去重是关键"], "tags": ["two-pointers", "medium", "Google", "Amazon"]} {"problem_id": "algo_00217", "original_id": "container-water", "title": "盛最多水的容器", "category": "two-pointers", "difficulty": "medium", "companies": ["Google", "Uber"], "description": "给定一个长度为 n 的整数数组 height,找出其中的两条线,使得它们与 x 轴共同构成的容器可以容纳最多的水。", "solution_python": "def maxArea(height):\n left, right = 0, len(height) - 1\n max_area = 0\n while left < right:\n h = min(height[left], height[right])\n max_area = max(max_area, h * (right - left))\n if height[left] < height[right]: left += 1\n else: right -= 1\n return max_area", "solution_java": "public int maxArea(int[] height) {\n int left = 0, right = height.length - 1, maxArea = 0;\n while (left < right) {\n int h = Math.min(height[left], height[right]);\n maxArea = Math.max(maxArea, h * (right - left));\n if (height[left] < height[right]) left++;\n else right--;\n }\n return maxArea;\n}", "solution_cpp": "int maxArea(vector& height) {\n int left = 0, right = height.size() - 1, maxArea = 0;\n while (left < right) {\n int h = min(height[left], height[right]);\n maxArea = max(maxArea, h * (right - left));\n if (height[left] < height[right]) left++;\n else right--;\n }\n return maxArea;\n}", "test_cases": ["height=[1,8,6,2,5,4,8,3,7] -> 49"], "key_points": ["移动短边指针", "面积=min(h1,h2)*width"], "tags": ["two-pointers", "medium", "Google", "Uber"]} {"problem_id": "algo_00218", "original_id": "min-stack", "title": "最小栈", "category": "stack", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "设计一个支持 push,pop,top 操作,并能在常数时间内检索到最小元素的栈。", "solution_python": "class MinStack:\n def __init__(self):\n self.stack = []\n self.min_stack = []\n def push(self, val):\n self.stack.append(val)\n self.min_stack.append(min(val, self.min_stack[-1] if self.min_stack else val))\n def pop(self):\n self.stack.pop(); self.min_stack.pop()\n def top(self): return self.stack[-1]\n def getMin(self): return self.min_stack[-1]", "solution_java": "class MinStack {\n Stack stack = new Stack<>();\n Stack minStack = new Stack<>();\n public void push(int val) { stack.push(val); minStack.push(Math.min(val, minStack.isEmpty() ? val : minStack.peek())); }\n public void pop() { stack.pop(); minStack.pop(); }\n public int top() { return stack.peek(); }\n public int getMin() { return minStack.peek(); }\n}", "solution_cpp": "class MinStack {\n stack st, minSt;\npublic:\n void push(int val) { st.push(val); minSt.push(min(val, minSt.empty() ? val : minSt.top())); }\n void pop() { st.pop(); minSt.pop(); }\n int top() { return st.top(); }\n int getMin() { return minSt.top(); }\n};", "test_cases": ["push(-2), push(0), push(-3) -> getMin() returns -3"], "key_points": ["辅助栈记录最小值", "O(1)时间获取最小值"], "tags": ["stack", "medium", "Google", "Microsoft"]} {"problem_id": "algo_00219", "original_id": "lru-cache", "title": "LRU缓存", "category": "design", "difficulty": "hard", "companies": ["Google", "Amazon"], "description": "设计和实现一个 LRU(最近最少使用)缓存机制。", "solution_python": "class LRUCache:\n def __init__(self, capacity):\n self.capacity = capacity\n self.cache = {}\n self.order = []\n def get(self, key):\n if key not in self.cache: return -1\n self.order.remove(key); self.order.append(key)\n return self.cache[key]\n def put(self, key, value):\n if key in self.cache:\n self.order.remove(key)\n elif len(self.cache) >= self.capacity:\n del self.cache[self.order.pop(0)]\n self.cache[key] = value; self.order.append(key)", "solution_java": "class LRUCache {\n int capacity;\n LinkedHashMap cache = new LinkedHashMap<>();\n public LRUCache(int cap) { capacity = cap; }\n public int get(int key) { return cache.containsKey(key) ? cache.remove(key) : -1; }\n public void put(int key, int val) {\n if (cache.containsKey(key)) cache.remove(key);\n else if (cache.size() >= capacity) cache.remove(cache.keySet().iterator().next());\n cache.put(key, val);\n }\n}", "solution_cpp": "class LRUCache {\n int cap;\n list> dll;\n unordered_map>::iterator> cache;\npublic:\n LRUCache(int capacity) : cap(capacity) {}\n int get(int key) {\n auto it = cache.find(key);\n if (it == cache.end()) return -1;\n dll.splice(dll.end(), dll, it->second);\n return it->second->second;\n }\n void put(int key, int value) {\n auto it = cache.find(key);\n if (it != cache.end()) dll.erase(it->second);\n else if (cache.size() >= cap) { cache.erase(dll.front().first); dll.pop_front(); }\n dll.push_back({key, value});\n cache[key] = --dll.end();\n }\n};", "test_cases": ["put(1,1), put(2,2), get(1) -> 1"], "key_points": ["HashMap + 双向链表", "O(1)时间操作"], "tags": ["design", "hard", "Google", "Amazon"]} {"problem_id": "algo_00220", "original_id": "num-islands", "title": "岛屿数量", "category": "graph", "difficulty": "medium", "companies": ["Google", "Facebook"], "description": "给你一个由 '1'(陆地)和 '0'(水)组成的二维网格,请你计算网格中岛屿的数量。岛屿总是被水包围,且只能由水平或垂直方向相邻的陆地连接形成。", "solution_python": "def numIslands(grid):\n if not grid: return 0\n rows, cols = len(grid), len(grid[0])\n count = 0\n def dfs(r, c):\n if r < 0 or r >= rows or c < 0 or c >= cols or grid[r][c] != '1': return\n grid[r][c] = '0'\n dfs(r+1, c); dfs(r-1, c); dfs(r, c+1); dfs(r, c-1)\n for r in range(rows):\n for c in range(cols):\n if grid[r][c] == '1': count += 1; dfs(r, c)\n return count", "solution_java": "public int numIslands(char[][] grid) {\n if (grid.length == 0) return 0;\n int count = 0;\n for (int i = 0; i < grid.length; i++)\n for (int j = 0; j < grid[0].length; j++)\n if (grid[i][j] == '1') { count++; dfs(grid, i, j); }\n return count;\n}\nprivate void dfs(char[][] grid, int r, int c) {\n if (r < 0 || r >= grid.length || c < 0 || c >= grid[0].length || grid[r][c] != '1') return;\n grid[r][c] = '0';\n dfs(grid, r+1, c); dfs(grid, r-1, c); dfs(grid, r, c+1); dfs(grid, r, c-1);\n}", "solution_cpp": "int numIslands(vector>& grid) {\n if (grid.empty()) return 0;\n int count = 0;\n for (int i = 0; i < grid.size(); i++)\n for (int j = 0; j < grid[0].size(); j++)\n if (grid[i][j] == '1') { count++; dfs(grid, i, j); }\n return count;\n}\nvoid dfs(vector>& grid, int r, int c) {\n if (r < 0 || r >= grid.size() || c < 0 || c >= grid[0].size() || grid[r][c] != '1') return;\n grid[r][c] = '0';\n dfs(grid, r+1, c); dfs(grid, r-1, c); dfs(grid, r, c+1); dfs(grid, r, c-1);\n}", "test_cases": ["grid=[[1,1,1,1,0],[1,1,0,1,0],[1,1,0,0,0],[0,0,0,0,0]] -> 1"], "key_points": ["DFS/BFS遍历", "访问后标记为0避免重复"], "tags": ["graph", "medium", "Google", "Facebook"]} {"problem_id": "algo_00221", "original_id": "two-sum", "title": "两数之和", "category": "array", "difficulty": "easy", "companies": ["Amazon", "Google"], "description": "给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那两个整数,并返回他们的数组下标。", "solution_python": "def twoSum(nums, target):\n hashmap = {}\n for i, num in enumerate(nums):\n complement = target - num\n if complement in hashmap:\n return [hashmap[complement], i]\n hashmap[num] = i\n return []", "solution_java": "public int[] twoSum(int[] nums, int target) {\n Map map = new HashMap<>();\n for (int i = 0; i < nums.length; i++) {\n int complement = target - nums[i];\n if (map.containsKey(complement)) return new int[]{map.get(complement), i};\n map.put(nums[i], i);\n }\n return new int[]{};\n}", "solution_cpp": "vector twoSum(vector& nums, int target) {\n unordered_map m;\n for (int i = 0; i < nums.size(); i++) {\n if (m.count(target - nums[i])) return {m[target - nums[i]], i};\n m[nums[i]] = i;\n }\n return {};\n}", "test_cases": ["nums=[2,7,11,15], target=9 -> [0,1]", "nums=[3,2,4], target=6 -> [1,2]"], "key_points": ["哈希表一次遍历", "空间换时间"], "tags": ["array", "easy", "Amazon", "Google"]} {"problem_id": "algo_00222", "original_id": "merge-sorted", "title": "合并两个有序数组", "category": "array", "difficulty": "easy", "companies": ["Microsoft", "Uber"], "description": "给你两个按非递减顺序排列的整数数组 nums1 和 nums2,另有两个整数 m 和 n,分别表示 nums1 和 nums2 中的元素数目。请你合并 nums2 到 nums1 中。", "solution_python": "def merge(nums1, m, nums2, n):\n p1, p2, p = m-1, n-1, m+n-1\n while p1 >= 0 and p2 >= 0:\n if nums1[p1] > nums2[p2]: nums1[p] = nums1[p1]; p1 -= 1\n else: nums1[p] = nums2[p2]; p2 -= 1\n p -= 1\n while p2 >= 0: nums1[p] = nums2[p2]; p2 -= 1; p -= 1", "solution_java": "public void merge(int[] nums1, int m, int[] nums2, int n) {\n int p1 = m-1, p2 = n-1, p = m+n-1;\n while (p1 >= 0 && p2 >= 0) {\n nums1[p--] = nums1[p1] > nums2[p2] ? nums1[p1--] : nums2[p2--];\n }\n while (p2 >= 0) nums1[p--] = nums2[p2--];\n}", "solution_cpp": "void merge(vector& nums1, int m, vector& nums2, int n) {\n int p1 = m-1, p2 = n-1, p = m+n-1;\n while (p1 >= 0 && p2 >= 0) nums1[p--] = nums1[p1] > nums2[p2] ? nums1[p1--] : nums2[p2--];\n while (p2 >= 0) nums1[p--] = nums2[p2--];\n}", "test_cases": ["nums1=[1,2,3], m=3, nums2=[2,5,6], n=3 -> [1,2,2,3,5,6]", "nums1=[], m=0, nums2=[1], n=1 -> [1]"], "key_points": ["从后往前合并", "三指针技巧"], "tags": ["array", "easy", "Microsoft", "Uber"]} {"problem_id": "algo_00223", "original_id": "max-subarray", "title": "最大子数组和", "category": "array", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "给你一个整数数组 nums ,请你找出一个具有最大和的连续子数组,返回其最大和。", "solution_python": "def maxSubArray(nums):\n max_sum = current = nums[0]\n for num in nums[1:]:\n current = max(num, current + num)\n max_sum = max(max_sum, current)\n return max_sum", "solution_java": "public int maxSubArray(int[] nums) {\n int maxSum = nums[0], curr = nums[0];\n for (int i = 1; i < nums.length; i++) {\n curr = Math.max(nums[i], curr + nums[i]);\n maxSum = Math.max(maxSum, curr);\n }\n return maxSum;\n}", "solution_cpp": "int maxSubArray(vector& nums) {\n int maxSum = nums[0], curr = nums[0];\n for (int i = 1; i < nums.size(); i++) {\n curr = max(nums[i], curr + nums[i]);\n maxSum = max(maxSum, curr);\n }\n return maxSum;\n}", "test_cases": ["nums=[-2,1,-3,4,-1,2,1,-5,4] -> 6", "nums=[1] -> 1"], "key_points": ["Kadane算法", "动态规划基础题"], "tags": ["array", "medium", "Google", "Microsoft"]} {"problem_id": "algo_00224", "original_id": "valid-parentheses", "title": "有效的括号", "category": "string", "difficulty": "easy", "companies": ["Google", "Uber"], "description": "给定一个只包括 '(',')','{','}','[',']' 的字符串 s,判断字符串是否有效。", "solution_python": "def isValid(s):\n stack = []\n mapping = {')': '(', ']': '[', '}': '{'}\n for c in s:\n if c in mapping:\n if not stack or stack[-1] != mapping[c]: return False\n stack.pop()\n else: stack.append(c)\n return not stack", "solution_java": "public boolean isValid(String s) {\n Stack stack = new Stack<>();\n Map map = Map.of(')', '(', ']', '[', '}', '{');\n for (char c : s.toCharArray()) {\n if (map.containsValue(c)) stack.push(c);\n else if (!stack.isEmpty() && stack.pop() != map.get(c)) return false;\n }\n return stack.isEmpty();\n}", "solution_cpp": "bool isValid(string s) {\n stack st;\n unordered_map m = {{')','('},{']','['},{'}','{'}};\n for (char c : s) {\n if (m.find(c) == m.end()) st.push(c);\n else if (st.empty() || st.top() != m[c]) return false;\n else st.pop();\n }\n return st.empty();\n}", "test_cases": ["s=\"()\" -> true", "s=\"()[]{}\" -> true", "s=\"(]\" -> false"], "key_points": ["栈匹配法", "注意空栈边界"], "tags": ["string", "easy", "Google", "Uber"]} {"problem_id": "algo_00225", "original_id": "longest-palindrome", "title": "最长回文子串", "category": "string", "difficulty": "medium", "companies": ["Google", "Amazon"], "description": "给你一个字符串 s,找到 s 中最长的回文子串。", "solution_python": "def longestPalindrome(s):\n def expand(l, r):\n while l >= 0 and r < len(s) and s[l] == s[r]: l -= 1; r += 1\n return l + 1, r - 1\n start = end = 0\n for i in range(len(s)):\n l1, r1 = expand(i, i)\n l2, r2 = expand(i, i + 1)\n if r1 - l1 > end - start: start, end = l1, r1\n if r2 - l2 > end - start: start, end = l2, r2\n return s[start:end+1]", "solution_java": "public String longestPalindrome(String s) {\n int start = 0, end = 0;\n for (int i = 0; i < s.length(); i++) {\n int len1 = expand(s, i, i), len2 = expand(s, i, i+1);\n int len = Math.max(len1, len2);\n if (len > end - start) { start = i - (len-1)/2; end = i + len/2; }\n }\n return s.substring(start, end + 1);\n}\nprivate int expand(String s, int l, int r) {\n while (l >= 0 && r < s.length() && s.charAt(l) == s.charAt(r)) { l--; r++; }\n return r - l - 1;\n}", "solution_cpp": "string longestPalindrome(string s) {\n int start = 0, end = 0;\n for (int i = 0; i < s.size(); i++) {\n int len1 = expand(s, i, i), len2 = expand(s, i, i+1);\n if (max(len1, len2) > end - start) { start = i - (max(len1,len2)-1)/2; end = i + max(len1,len2)/2; }\n }\n return s.substr(start, end - start + 1);\n}", "test_cases": ["s=\"babad\" -> bab或aba", "s=\"cbbd\" -> bb"], "key_points": ["中心扩展法", "处理奇偶长度"], "tags": ["string", "medium", "Google", "Amazon"]} {"problem_id": "algo_00226", "original_id": "reverse-list", "title": "反转链表", "category": "linkedlist", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "给你单链表的头节点 head,请你反转链表,并返回反转后的链表。", "solution_python": "def reverseList(head):\n prev = None\n curr = head\n while curr:\n nxt = curr.next\n curr.next = prev\n prev = curr\n curr = nxt\n return prev", "solution_java": "public ListNode reverseList(ListNode head) {\n ListNode prev = null, curr = head;\n while (curr != null) {\n ListNode next = curr.next;\n curr.next = prev;\n prev = curr;\n curr = next;\n }\n return prev;\n}", "solution_cpp": "ListNode* reverseList(ListNode* head) {\n ListNode* prev = nullptr, *curr = head;\n while (curr) {\n ListNode* next = curr->next;\n curr->next = prev;\n prev = curr;\n curr = next;\n }\n return prev;\n}", "test_cases": ["head=[1,2,3,4,5] -> [5,4,3,2,1]", "head=[1,2] -> [2,1]"], "key_points": ["迭代法 O(1)空间", "递归法 O(n)空间"], "tags": ["linkedlist", "medium", "Google", "Microsoft"]} {"problem_id": "algo_00227", "original_id": "middle-node", "title": "链表的中间结点", "category": "linkedlist", "difficulty": "easy", "companies": ["Amazon", "Facebook"], "description": "给你单链表的头节点 head,请你找出并返回链表的中间结点。如果有两个中间结点,则返回第二个中间结点。", "solution_python": "def middleNode(head):\n slow = fast = head\n while fast and fast.next:\n slow = slow.next\n fast = fast.next.next\n return slow", "solution_java": "public ListNode middleNode(ListNode head) {\n ListNode slow = head, fast = head;\n while (fast != null && fast.next != null) {\n slow = slow.next;\n fast = fast.next.next;\n }\n return slow;\n}", "solution_cpp": "ListNode* middleNode(ListNode* head) {\n ListNode* slow = head, *fast = head;\n while (fast && fast->next) { slow = slow->next; fast = fast->next->next; }\n return slow;\n}", "test_cases": ["head=[1,2,3,4,5] -> 3", "head=[1,2,3,4,5,6] -> 4"], "key_points": ["快慢指针", "O(n)时间O(1)空间"], "tags": ["linkedlist", "easy", "Amazon", "Facebook"]} {"problem_id": "algo_00228", "original_id": "max-depth", "title": "二叉树的最大深度", "category": "tree", "difficulty": "easy", "companies": ["Microsoft", "Apple"], "description": "给定一个二叉树 root,返回其最大深度。", "solution_python": "def maxDepth(root):\n if not root: return 0\n return max(maxDepth(root.left), maxDepth(root.right)) + 1", "solution_java": "public int maxDepth(TreeNode root) {\n if (root == null) return 0;\n return Math.max(maxDepth(root.left), maxDepth(root.right)) + 1;\n}", "solution_cpp": "int maxDepth(TreeNode* root) {\n if (!root) return 0;\n return max(maxDepth(root->left), maxDepth(root->right)) + 1;\n}", "test_cases": ["root=[3,9,20,null,null,15,7] -> 3", "root=[1,null,2] -> 2"], "key_points": ["DFS递归", "层序遍历也可"], "tags": ["tree", "easy", "Microsoft", "Apple"]} {"problem_id": "algo_00229", "original_id": "inorder-traversal", "title": "二叉树的中序遍历", "category": "tree", "difficulty": "easy", "companies": ["Google", "Microsoft"], "description": "给定一个二叉树的根节点 root,返回它的中序遍历结果。", "solution_python": "def inorderTraversal(root):\n result = []\n def dfs(node):\n if node:\n dfs(node.left)\n result.append(node.val)\n dfs(node.right)\n dfs(root)\n return result", "solution_java": "public List inorderTraversal(TreeNode root) {\n List res = new ArrayList<>();\n dfs(root, res);\n return res;\n}\nprivate void dfs(TreeNode node, List res) {\n if (node == null) return;\n dfs(node.left, res); res.add(node.val); dfs(node.right, res);\n}", "solution_cpp": "vector inorderTraversal(TreeNode* root) {\n vector res;\n dfs(root, res);\n return res;\n}\nvoid dfs(TreeNode* node, vector& res) {\n if (!node) return;\n dfs(node->left, res); res.push_back(node->val); dfs(node->right, res);\n}", "test_cases": ["root=[1,null,2,3] -> [1,3,2]", "root=[] -> []"], "key_points": ["左-根-右顺序", "递归最简洁"], "tags": ["tree", "easy", "Google", "Microsoft"]} {"problem_id": "algo_00230", "original_id": "binary-search", "title": "二分查找", "category": "binarysearch", "difficulty": "easy", "companies": ["Google", "Amazon"], "description": "给定一个 n 个元素有序的(升序)整型数组 nums 和一个目标值 target,写一个函数搜索 nums 中的 target,如果目标值存在返回下标,否则返回 -1。", "solution_python": "def search(nums, target):\n left, right = 0, len(nums) - 1\n while left <= right:\n mid = (left + right) // 2\n if nums[mid] == target: return mid\n elif nums[mid] < target: left = mid + 1\n else: right = mid - 1\n return -1", "solution_java": "public int search(int[] nums, int target) {\n int left = 0, right = nums.length - 1;\n while (left <= right) {\n int mid = left + (right - left) / 2;\n if (nums[mid] == target) return mid;\n else if (nums[mid] < target) left = mid + 1;\n else right = mid - 1;\n }\n return -1;\n}", "solution_cpp": "int search(vector& nums, int target) {\n int left = 0, right = nums.size() - 1;\n while (left <= right) {\n int mid = left + (right - left) / 2;\n if (nums[mid] == target) return mid;\n else if (nums[mid] < target) left = mid + 1;\n else right = mid - 1;\n }\n return -1;\n}", "test_cases": ["nums=[-1,0,3,5,9,12], target=9 -> 4", "nums=[-1,0,3,5,9,12], target=2 -> -1"], "key_points": ["标准模板", "注意防溢出写法"], "tags": ["binarysearch", "easy", "Google", "Amazon"]} {"problem_id": "algo_00231", "original_id": "climbing-stairs", "title": "爬楼梯", "category": "dp", "difficulty": "easy", "companies": ["Amazon", "Google"], "description": "假设你正在爬楼梯。需要 n 阶你才能到达楼顶。每次你可以爬 1 或 2 个台阶。你有多少种不同的方法可以爬到楼顶?", "solution_python": "def climbStairs(n):\n if n <= 2: return n\n a, b = 1, 2\n for _ in range(3, n+1):\n a, b = b, a + b\n return b", "solution_java": "public int climbStairs(int n) {\n if (n <= 2) return n;\n int a = 1, b = 2;\n for (int i = 3; i <= n; i++) { int temp = a + b; a = b; b = temp; }\n return b;\n}", "solution_cpp": "int climbStairs(int n) {\n if (n <= 2) return n;\n int a = 1, b = 2;\n for (int i = 3; i <= n; i++) { int temp = a + b; a = b; b = temp; }\n return b;\n}", "test_cases": ["n=2 -> 2", "n=3 -> 3", "n=5 -> 8"], "key_points": ["斐波那契数列", "滚动数组优化空间"], "tags": ["dp", "easy", "Amazon", "Google"]} {"problem_id": "algo_00232", "original_id": "coin-change", "title": "零钱兑换", "category": "dp", "difficulty": "medium", "companies": ["Google", "Amazon"], "description": "给你一个整数数组 coins 表示不同面额的硬币,以及一个整数 amount 表示总金额。计算并返回可以凑成总金额所需的最少的硬币个数。如果没有任何一种硬币组合能组成总金额,返回 -1。", "solution_python": "def coinChange(coins, amount):\n dp = [float('inf')] * (amount + 1)\n dp[0] = 0\n for coin in coins:\n for x in range(coin, amount + 1):\n dp[x] = min(dp[x], dp[x - coin] + 1)\n return dp[amount] if dp[amount] != float('inf') else -1", "solution_java": "public int coinChange(int[] coins, int amount) {\n int[] dp = new int[amount + 1];\n Arrays.fill(dp, amount + 1);\n dp[0] = 0;\n for (int coin : coins) {\n for (int x = coin; x <= amount; x++) {\n dp[x] = Math.min(dp[x], dp[x - coin] + 1);\n }\n }\n return dp[amount] > amount ? -1 : dp[amount];\n}", "solution_cpp": "int coinChange(vector& coins, int amount) {\n vector dp(amount + 1, amount + 1);\n dp[0] = 0;\n for (int coin : coins) {\n for (int x = coin; x <= amount; x++) {\n dp[x] = min(dp[x], dp[x - coin] + 1);\n }\n }\n return dp[amount] > amount ? -1 : dp[amount];\n}", "test_cases": ["coins=[1,2,5], amount=11 -> 3", "coins=[2], amount=3 -> -1"], "key_points": ["完全背包问题", "dp[x] = min(dp[x-coin]+1)"], "tags": ["dp", "medium", "Google", "Amazon"]} {"problem_id": "algo_00233", "original_id": "subsets", "title": "子集", "category": "backtracking", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "给你一个整数数组 nums ,数组中的元素 互不相同 。返回该数组所有可能的子集(幂集)。", "solution_python": "def subsets(nums):\n result = []\n def backtrack(start, path):\n result.append(path[:])\n for i in range(start, len(nums)):\n path.append(nums[i])\n backtrack(i + 1, path)\n path.pop()\n backtrack(0, [])\n return result", "solution_java": "public List> subsets(int[] nums) {\n List> result = new ArrayList<>();\n backtrack(nums, 0, new ArrayList<>(), result);\n return result;\n}\nprivate void backtrack(int[] nums, int start, List path, List> result) {\n result.add(new ArrayList<>(path));\n for (int i = start; i < nums.length; i++) {\n path.add(nums[i]);\n backtrack(nums, i + 1, path, result);\n path.remove(path.size() - 1);\n }\n}", "solution_cpp": "vector> subsets(vector& nums) {\n vector> result;\n vector path;\n backtrack(nums, 0, path, result);\n return result;\n}\nvoid backtrack(vector& nums, int start, vector& path, vector>& result) {\n result.push_back(path);\n for (int i = start; i < nums.size(); i++) {\n path.push_back(nums[i]);\n backtrack(nums, i + 1, path, result);\n path.pop_back();\n }\n}", "test_cases": ["nums=[1,2,3] -> [[],[1],[2],[1,2],[3],[1,3],[2,3],[1,2,3]]"], "key_points": ["选或不选", "DFS遍历子集树"], "tags": ["backtracking", "medium", "Google", "Microsoft"]} {"problem_id": "algo_00234", "original_id": "permutations", "title": "全排列", "category": "backtracking", "difficulty": "medium", "companies": ["Google", "Facebook"], "description": "给定一个不含重复数字的数组 nums,返回其所有可能的全排列。", "solution_python": "def permute(nums):\n result = []\n def backtrack(path, used):\n if len(path) == len(nums):\n result.append(path[:])\n return\n for i in range(len(nums)):\n if used[i]: continue\n used[i] = True\n path.append(nums[i])\n backtrack(path, used)\n path.pop()\n used[i] = False\n backtrack([], [False]*len(nums))\n return result", "solution_java": "public List> permute(int[] nums) {\n List> result = new ArrayList<>();\n boolean[] used = new boolean[nums.length];\n backtrack(nums, used, new ArrayList<>(), result);\n return result;\n}\nprivate void backtrack(int[] nums, boolean[] used, List path, List> result) {\n if (path.size() == nums.length) { result.add(new ArrayList<>(path)); return; }\n for (int i = 0; i < nums.length; i++) {\n if (used[i]) continue;\n used[i] = true;\n path.add(nums[i]);\n backtrack(nums, used, path, result);\n path.remove(path.size() - 1);\n used[i] = false;\n }\n}", "solution_cpp": "vector> permute(vector& nums) {\n vector> result;\n vector used(nums.size(), false);\n vector path;\n backtrack(nums, used, path, result);\n return result;\n}\nvoid backtrack(vector& nums, vector& used, vector& path, vector>& result) {\n if (path.size() == nums.size()) { result.push_back(path); return; }\n for (int i = 0; i < nums.size(); i++) {\n if (used[i]) continue;\n used[i] = true;\n path.push_back(nums[i]);\n backtrack(nums, used, path, result);\n path.pop_back();\n used[i] = false;\n }\n}", "test_cases": ["nums=[1,2,3] -> [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]"], "key_points": ["标记已使用元素", "回溯经典模板"], "tags": ["backtracking", "medium", "Google", "Facebook"]} {"problem_id": "algo_00235", "original_id": "top-k-frequent", "title": "前K个高频元素", "category": "heap", "difficulty": "medium", "companies": ["Amazon", "Facebook"], "description": "给你一个整数数组 nums 和一个整数 k,请你返回其中出现频率前 k 高的元素。", "solution_python": "import heapq\nfrom collections import Counter\ndef topKFrequent(nums, k):\n count = Counter(nums)\n heap = []\n for num, freq in count.items():\n heapq.heappush(heap, (freq, num))\n if len(heap) > k: heapq.heappop(heap)\n return [num for freq, num in heap]", "solution_java": "public int[] topKFrequent(int[] nums, int k) {\n Map count = new HashMap<>();\n for (int n : nums) count.put(n, count.getOrDefault(n, 0) + 1);\n PriorityQueue> heap = \n new PriorityQueue<>((a, b) -> a.getValue() - b.getValue());\n for (Map.Entry e : count.entrySet()) {\n heap.offer(e);\n if (heap.size() > k) heap.poll();\n }\n int[] res = new int[k];\n for (int i = k - 1; i >= 0; i--) res[i] = heap.poll().getKey();\n return res;\n}", "solution_cpp": "vector topKFrequent(vector& nums, int k) {\n unordered_map count;\n for (int n : nums) count[n]++;\n priority_queue, vector>, greater>> heap;\n for (auto& [num, freq] : count) {\n heap.push({freq, num});\n if (heap.size() > k) heap.pop();\n }\n vector res;\n while (!heap.empty()) { res.push_back(heap.top().second); heap.pop(); }\n reverse(res.begin(), res.end());\n return res;\n}", "test_cases": ["nums=[1,1,1,2,2,3], k=2 -> [1,2]", "nums=[1], k=1 -> [1]"], "key_points": ["小顶堆保持大小k", "时间复杂度O(nlogk)"], "tags": ["heap", "medium", "Amazon", "Facebook"]} {"problem_id": "algo_00236", "original_id": "3sum", "title": "三数之和", "category": "two-pointers", "difficulty": "medium", "companies": ["Google", "Amazon"], "description": "给你一个整数数组 nums,判断是否存在三元组满足和为0,返回所有不重复的三元组。", "solution_python": "def threeSum(nums):\n nums.sort()\n result = []\n for i in range(len(nums) - 2):\n if i > 0 and nums[i] == nums[i-1]: continue\n left, right = i + 1, len(nums) - 1\n while left < right:\n total = nums[i] + nums[left] + nums[right]\n if total < 0: left += 1\n elif total > 0: right -= 1\n else:\n result.append([nums[i], nums[left], nums[right]])\n while left < right and nums[left] == nums[left+1]: left += 1\n while left < right and nums[right] == nums[right-1]: right -= 1\n left += 1; right -= 1\n return result", "solution_java": "public List> threeSum(int[] nums) {\n Arrays.sort(nums);\n List> result = new ArrayList<>();\n for (int i = 0; i < nums.length - 2; i++) {\n if (i > 0 && nums[i] == nums[i-1]) continue;\n int left = i + 1, right = nums.length - 1;\n while (left < right) {\n int total = nums[i] + nums[left] + nums[right];\n if (total < 0) left++;\n else if (total > 0) right--;\n else {\n result.add(Arrays.asList(nums[i], nums[left], nums[right]));\n while (left < right && nums[left] == nums[left+1]) left++;\n while (left < right && nums[right] == nums[right-1]) right--;\n left++; right--;\n }\n }\n }\n return result;\n}", "solution_cpp": "vector> threeSum(vector& nums) {\n sort(nums.begin(), nums.end());\n vector> result;\n for (int i = 0; i < nums.size() - 2; i++) {\n if (i > 0 && nums[i] == nums[i-1]) continue;\n int left = i + 1, right = nums.size() - 1;\n while (left < right) {\n int total = nums[i] + nums[left] + nums[right];\n if (total < 0) left++;\n else if (total > 0) right--;\n else {\n result.push_back({nums[i], nums[left], nums[right]});\n while (left < right && nums[left] == nums[left+1]) left++;\n while (left < right && nums[right] == nums[right-1]) right--;\n left++; right--;\n }\n }\n }\n return result;\n}", "test_cases": ["nums=[-1,0,1,2,-1,-4] -> [[-1,-1,2],[-1,0,1]]"], "key_points": ["排序+双指针", "去重是关键"], "tags": ["two-pointers", "medium", "Google", "Amazon"]} {"problem_id": "algo_00237", "original_id": "container-water", "title": "盛最多水的容器", "category": "two-pointers", "difficulty": "medium", "companies": ["Google", "Uber"], "description": "给定一个长度为 n 的整数数组 height,找出其中的两条线,使得它们与 x 轴共同构成的容器可以容纳最多的水。", "solution_python": "def maxArea(height):\n left, right = 0, len(height) - 1\n max_area = 0\n while left < right:\n h = min(height[left], height[right])\n max_area = max(max_area, h * (right - left))\n if height[left] < height[right]: left += 1\n else: right -= 1\n return max_area", "solution_java": "public int maxArea(int[] height) {\n int left = 0, right = height.length - 1, maxArea = 0;\n while (left < right) {\n int h = Math.min(height[left], height[right]);\n maxArea = Math.max(maxArea, h * (right - left));\n if (height[left] < height[right]) left++;\n else right--;\n }\n return maxArea;\n}", "solution_cpp": "int maxArea(vector& height) {\n int left = 0, right = height.size() - 1, maxArea = 0;\n while (left < right) {\n int h = min(height[left], height[right]);\n maxArea = max(maxArea, h * (right - left));\n if (height[left] < height[right]) left++;\n else right--;\n }\n return maxArea;\n}", "test_cases": ["height=[1,8,6,2,5,4,8,3,7] -> 49"], "key_points": ["移动短边指针", "面积=min(h1,h2)*width"], "tags": ["two-pointers", "medium", "Google", "Uber"]} {"problem_id": "algo_00238", "original_id": "min-stack", "title": "最小栈", "category": "stack", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "设计一个支持 push,pop,top 操作,并能在常数时间内检索到最小元素的栈。", "solution_python": "class MinStack:\n def __init__(self):\n self.stack = []\n self.min_stack = []\n def push(self, val):\n self.stack.append(val)\n self.min_stack.append(min(val, self.min_stack[-1] if self.min_stack else val))\n def pop(self):\n self.stack.pop(); self.min_stack.pop()\n def top(self): return self.stack[-1]\n def getMin(self): return self.min_stack[-1]", "solution_java": "class MinStack {\n Stack stack = new Stack<>();\n Stack minStack = new Stack<>();\n public void push(int val) { stack.push(val); minStack.push(Math.min(val, minStack.isEmpty() ? val : minStack.peek())); }\n public void pop() { stack.pop(); minStack.pop(); }\n public int top() { return stack.peek(); }\n public int getMin() { return minStack.peek(); }\n}", "solution_cpp": "class MinStack {\n stack st, minSt;\npublic:\n void push(int val) { st.push(val); minSt.push(min(val, minSt.empty() ? val : minSt.top())); }\n void pop() { st.pop(); minSt.pop(); }\n int top() { return st.top(); }\n int getMin() { return minSt.top(); }\n};", "test_cases": ["push(-2), push(0), push(-3) -> getMin() returns -3"], "key_points": ["辅助栈记录最小值", "O(1)时间获取最小值"], "tags": ["stack", "medium", "Google", "Microsoft"]} {"problem_id": "algo_00239", "original_id": "lru-cache", "title": "LRU缓存", "category": "design", "difficulty": "hard", "companies": ["Google", "Amazon"], "description": "设计和实现一个 LRU(最近最少使用)缓存机制。", "solution_python": "class LRUCache:\n def __init__(self, capacity):\n self.capacity = capacity\n self.cache = {}\n self.order = []\n def get(self, key):\n if key not in self.cache: return -1\n self.order.remove(key); self.order.append(key)\n return self.cache[key]\n def put(self, key, value):\n if key in self.cache:\n self.order.remove(key)\n elif len(self.cache) >= self.capacity:\n del self.cache[self.order.pop(0)]\n self.cache[key] = value; self.order.append(key)", "solution_java": "class LRUCache {\n int capacity;\n LinkedHashMap cache = new LinkedHashMap<>();\n public LRUCache(int cap) { capacity = cap; }\n public int get(int key) { return cache.containsKey(key) ? cache.remove(key) : -1; }\n public void put(int key, int val) {\n if (cache.containsKey(key)) cache.remove(key);\n else if (cache.size() >= capacity) cache.remove(cache.keySet().iterator().next());\n cache.put(key, val);\n }\n}", "solution_cpp": "class LRUCache {\n int cap;\n list> dll;\n unordered_map>::iterator> cache;\npublic:\n LRUCache(int capacity) : cap(capacity) {}\n int get(int key) {\n auto it = cache.find(key);\n if (it == cache.end()) return -1;\n dll.splice(dll.end(), dll, it->second);\n return it->second->second;\n }\n void put(int key, int value) {\n auto it = cache.find(key);\n if (it != cache.end()) dll.erase(it->second);\n else if (cache.size() >= cap) { cache.erase(dll.front().first); dll.pop_front(); }\n dll.push_back({key, value});\n cache[key] = --dll.end();\n }\n};", "test_cases": ["put(1,1), put(2,2), get(1) -> 1"], "key_points": ["HashMap + 双向链表", "O(1)时间操作"], "tags": ["design", "hard", "Google", "Amazon"]} {"problem_id": "algo_00240", "original_id": "num-islands", "title": "岛屿数量", "category": "graph", "difficulty": "medium", "companies": ["Google", "Facebook"], "description": "给你一个由 '1'(陆地)和 '0'(水)组成的二维网格,请你计算网格中岛屿的数量。岛屿总是被水包围,且只能由水平或垂直方向相邻的陆地连接形成。", "solution_python": "def numIslands(grid):\n if not grid: return 0\n rows, cols = len(grid), len(grid[0])\n count = 0\n def dfs(r, c):\n if r < 0 or r >= rows or c < 0 or c >= cols or grid[r][c] != '1': return\n grid[r][c] = '0'\n dfs(r+1, c); dfs(r-1, c); dfs(r, c+1); dfs(r, c-1)\n for r in range(rows):\n for c in range(cols):\n if grid[r][c] == '1': count += 1; dfs(r, c)\n return count", "solution_java": "public int numIslands(char[][] grid) {\n if (grid.length == 0) return 0;\n int count = 0;\n for (int i = 0; i < grid.length; i++)\n for (int j = 0; j < grid[0].length; j++)\n if (grid[i][j] == '1') { count++; dfs(grid, i, j); }\n return count;\n}\nprivate void dfs(char[][] grid, int r, int c) {\n if (r < 0 || r >= grid.length || c < 0 || c >= grid[0].length || grid[r][c] != '1') return;\n grid[r][c] = '0';\n dfs(grid, r+1, c); dfs(grid, r-1, c); dfs(grid, r, c+1); dfs(grid, r, c-1);\n}", "solution_cpp": "int numIslands(vector>& grid) {\n if (grid.empty()) return 0;\n int count = 0;\n for (int i = 0; i < grid.size(); i++)\n for (int j = 0; j < grid[0].size(); j++)\n if (grid[i][j] == '1') { count++; dfs(grid, i, j); }\n return count;\n}\nvoid dfs(vector>& grid, int r, int c) {\n if (r < 0 || r >= grid.size() || c < 0 || c >= grid[0].size() || grid[r][c] != '1') return;\n grid[r][c] = '0';\n dfs(grid, r+1, c); dfs(grid, r-1, c); dfs(grid, r, c+1); dfs(grid, r, c-1);\n}", "test_cases": ["grid=[[1,1,1,1,0],[1,1,0,1,0],[1,1,0,0,0],[0,0,0,0,0]] -> 1"], "key_points": ["DFS/BFS遍历", "访问后标记为0避免重复"], "tags": ["graph", "medium", "Google", "Facebook"]} {"problem_id": "algo_00241", "original_id": "two-sum", "title": "两数之和", "category": "array", "difficulty": "easy", "companies": ["Amazon", "Google"], "description": "给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那两个整数,并返回他们的数组下标。", "solution_python": "def twoSum(nums, target):\n hashmap = {}\n for i, num in enumerate(nums):\n complement = target - num\n if complement in hashmap:\n return [hashmap[complement], i]\n hashmap[num] = i\n return []", "solution_java": "public int[] twoSum(int[] nums, int target) {\n Map map = new HashMap<>();\n for (int i = 0; i < nums.length; i++) {\n int complement = target - nums[i];\n if (map.containsKey(complement)) return new int[]{map.get(complement), i};\n map.put(nums[i], i);\n }\n return new int[]{};\n}", "solution_cpp": "vector twoSum(vector& nums, int target) {\n unordered_map m;\n for (int i = 0; i < nums.size(); i++) {\n if (m.count(target - nums[i])) return {m[target - nums[i]], i};\n m[nums[i]] = i;\n }\n return {};\n}", "test_cases": ["nums=[2,7,11,15], target=9 -> [0,1]", "nums=[3,2,4], target=6 -> [1,2]"], "key_points": ["哈希表一次遍历", "空间换时间"], "tags": ["array", "easy", "Amazon", "Google"]} {"problem_id": "algo_00242", "original_id": "merge-sorted", "title": "合并两个有序数组", "category": "array", "difficulty": "easy", "companies": ["Microsoft", "Uber"], "description": "给你两个按非递减顺序排列的整数数组 nums1 和 nums2,另有两个整数 m 和 n,分别表示 nums1 和 nums2 中的元素数目。请你合并 nums2 到 nums1 中。", "solution_python": "def merge(nums1, m, nums2, n):\n p1, p2, p = m-1, n-1, m+n-1\n while p1 >= 0 and p2 >= 0:\n if nums1[p1] > nums2[p2]: nums1[p] = nums1[p1]; p1 -= 1\n else: nums1[p] = nums2[p2]; p2 -= 1\n p -= 1\n while p2 >= 0: nums1[p] = nums2[p2]; p2 -= 1; p -= 1", "solution_java": "public void merge(int[] nums1, int m, int[] nums2, int n) {\n int p1 = m-1, p2 = n-1, p = m+n-1;\n while (p1 >= 0 && p2 >= 0) {\n nums1[p--] = nums1[p1] > nums2[p2] ? nums1[p1--] : nums2[p2--];\n }\n while (p2 >= 0) nums1[p--] = nums2[p2--];\n}", "solution_cpp": "void merge(vector& nums1, int m, vector& nums2, int n) {\n int p1 = m-1, p2 = n-1, p = m+n-1;\n while (p1 >= 0 && p2 >= 0) nums1[p--] = nums1[p1] > nums2[p2] ? nums1[p1--] : nums2[p2--];\n while (p2 >= 0) nums1[p--] = nums2[p2--];\n}", "test_cases": ["nums1=[1,2,3], m=3, nums2=[2,5,6], n=3 -> [1,2,2,3,5,6]", "nums1=[], m=0, nums2=[1], n=1 -> [1]"], "key_points": ["从后往前合并", "三指针技巧"], "tags": ["array", "easy", "Microsoft", "Uber"]} {"problem_id": "algo_00243", "original_id": "max-subarray", "title": "最大子数组和", "category": "array", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "给你一个整数数组 nums ,请你找出一个具有最大和的连续子数组,返回其最大和。", "solution_python": "def maxSubArray(nums):\n max_sum = current = nums[0]\n for num in nums[1:]:\n current = max(num, current + num)\n max_sum = max(max_sum, current)\n return max_sum", "solution_java": "public int maxSubArray(int[] nums) {\n int maxSum = nums[0], curr = nums[0];\n for (int i = 1; i < nums.length; i++) {\n curr = Math.max(nums[i], curr + nums[i]);\n maxSum = Math.max(maxSum, curr);\n }\n return maxSum;\n}", "solution_cpp": "int maxSubArray(vector& nums) {\n int maxSum = nums[0], curr = nums[0];\n for (int i = 1; i < nums.size(); i++) {\n curr = max(nums[i], curr + nums[i]);\n maxSum = max(maxSum, curr);\n }\n return maxSum;\n}", "test_cases": ["nums=[-2,1,-3,4,-1,2,1,-5,4] -> 6", "nums=[1] -> 1"], "key_points": ["Kadane算法", "动态规划基础题"], "tags": ["array", "medium", "Google", "Microsoft"]} {"problem_id": "algo_00244", "original_id": "valid-parentheses", "title": "有效的括号", "category": "string", "difficulty": "easy", "companies": ["Google", "Uber"], "description": "给定一个只包括 '(',')','{','}','[',']' 的字符串 s,判断字符串是否有效。", "solution_python": "def isValid(s):\n stack = []\n mapping = {')': '(', ']': '[', '}': '{'}\n for c in s:\n if c in mapping:\n if not stack or stack[-1] != mapping[c]: return False\n stack.pop()\n else: stack.append(c)\n return not stack", "solution_java": "public boolean isValid(String s) {\n Stack stack = new Stack<>();\n Map map = Map.of(')', '(', ']', '[', '}', '{');\n for (char c : s.toCharArray()) {\n if (map.containsValue(c)) stack.push(c);\n else if (!stack.isEmpty() && stack.pop() != map.get(c)) return false;\n }\n return stack.isEmpty();\n}", "solution_cpp": "bool isValid(string s) {\n stack st;\n unordered_map m = {{')','('},{']','['},{'}','{'}};\n for (char c : s) {\n if (m.find(c) == m.end()) st.push(c);\n else if (st.empty() || st.top() != m[c]) return false;\n else st.pop();\n }\n return st.empty();\n}", "test_cases": ["s=\"()\" -> true", "s=\"()[]{}\" -> true", "s=\"(]\" -> false"], "key_points": ["栈匹配法", "注意空栈边界"], "tags": ["string", "easy", "Google", "Uber"]} {"problem_id": "algo_00245", "original_id": "longest-palindrome", "title": "最长回文子串", "category": "string", "difficulty": "medium", "companies": ["Google", "Amazon"], "description": "给你一个字符串 s,找到 s 中最长的回文子串。", "solution_python": "def longestPalindrome(s):\n def expand(l, r):\n while l >= 0 and r < len(s) and s[l] == s[r]: l -= 1; r += 1\n return l + 1, r - 1\n start = end = 0\n for i in range(len(s)):\n l1, r1 = expand(i, i)\n l2, r2 = expand(i, i + 1)\n if r1 - l1 > end - start: start, end = l1, r1\n if r2 - l2 > end - start: start, end = l2, r2\n return s[start:end+1]", "solution_java": "public String longestPalindrome(String s) {\n int start = 0, end = 0;\n for (int i = 0; i < s.length(); i++) {\n int len1 = expand(s, i, i), len2 = expand(s, i, i+1);\n int len = Math.max(len1, len2);\n if (len > end - start) { start = i - (len-1)/2; end = i + len/2; }\n }\n return s.substring(start, end + 1);\n}\nprivate int expand(String s, int l, int r) {\n while (l >= 0 && r < s.length() && s.charAt(l) == s.charAt(r)) { l--; r++; }\n return r - l - 1;\n}", "solution_cpp": "string longestPalindrome(string s) {\n int start = 0, end = 0;\n for (int i = 0; i < s.size(); i++) {\n int len1 = expand(s, i, i), len2 = expand(s, i, i+1);\n if (max(len1, len2) > end - start) { start = i - (max(len1,len2)-1)/2; end = i + max(len1,len2)/2; }\n }\n return s.substr(start, end - start + 1);\n}", "test_cases": ["s=\"babad\" -> bab或aba", "s=\"cbbd\" -> bb"], "key_points": ["中心扩展法", "处理奇偶长度"], "tags": ["string", "medium", "Google", "Amazon"]} {"problem_id": "algo_00246", "original_id": "reverse-list", "title": "反转链表", "category": "linkedlist", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "给你单链表的头节点 head,请你反转链表,并返回反转后的链表。", "solution_python": "def reverseList(head):\n prev = None\n curr = head\n while curr:\n nxt = curr.next\n curr.next = prev\n prev = curr\n curr = nxt\n return prev", "solution_java": "public ListNode reverseList(ListNode head) {\n ListNode prev = null, curr = head;\n while (curr != null) {\n ListNode next = curr.next;\n curr.next = prev;\n prev = curr;\n curr = next;\n }\n return prev;\n}", "solution_cpp": "ListNode* reverseList(ListNode* head) {\n ListNode* prev = nullptr, *curr = head;\n while (curr) {\n ListNode* next = curr->next;\n curr->next = prev;\n prev = curr;\n curr = next;\n }\n return prev;\n}", "test_cases": ["head=[1,2,3,4,5] -> [5,4,3,2,1]", "head=[1,2] -> [2,1]"], "key_points": ["迭代法 O(1)空间", "递归法 O(n)空间"], "tags": ["linkedlist", "medium", "Google", "Microsoft"]} {"problem_id": "algo_00247", "original_id": "middle-node", "title": "链表的中间结点", "category": "linkedlist", "difficulty": "easy", "companies": ["Amazon", "Facebook"], "description": "给你单链表的头节点 head,请你找出并返回链表的中间结点。如果有两个中间结点,则返回第二个中间结点。", "solution_python": "def middleNode(head):\n slow = fast = head\n while fast and fast.next:\n slow = slow.next\n fast = fast.next.next\n return slow", "solution_java": "public ListNode middleNode(ListNode head) {\n ListNode slow = head, fast = head;\n while (fast != null && fast.next != null) {\n slow = slow.next;\n fast = fast.next.next;\n }\n return slow;\n}", "solution_cpp": "ListNode* middleNode(ListNode* head) {\n ListNode* slow = head, *fast = head;\n while (fast && fast->next) { slow = slow->next; fast = fast->next->next; }\n return slow;\n}", "test_cases": ["head=[1,2,3,4,5] -> 3", "head=[1,2,3,4,5,6] -> 4"], "key_points": ["快慢指针", "O(n)时间O(1)空间"], "tags": ["linkedlist", "easy", "Amazon", "Facebook"]} {"problem_id": "algo_00248", "original_id": "max-depth", "title": "二叉树的最大深度", "category": "tree", "difficulty": "easy", "companies": ["Microsoft", "Apple"], "description": "给定一个二叉树 root,返回其最大深度。", "solution_python": "def maxDepth(root):\n if not root: return 0\n return max(maxDepth(root.left), maxDepth(root.right)) + 1", "solution_java": "public int maxDepth(TreeNode root) {\n if (root == null) return 0;\n return Math.max(maxDepth(root.left), maxDepth(root.right)) + 1;\n}", "solution_cpp": "int maxDepth(TreeNode* root) {\n if (!root) return 0;\n return max(maxDepth(root->left), maxDepth(root->right)) + 1;\n}", "test_cases": ["root=[3,9,20,null,null,15,7] -> 3", "root=[1,null,2] -> 2"], "key_points": ["DFS递归", "层序遍历也可"], "tags": ["tree", "easy", "Microsoft", "Apple"]} {"problem_id": "algo_00249", "original_id": "inorder-traversal", "title": "二叉树的中序遍历", "category": "tree", "difficulty": "easy", "companies": ["Google", "Microsoft"], "description": "给定一个二叉树的根节点 root,返回它的中序遍历结果。", "solution_python": "def inorderTraversal(root):\n result = []\n def dfs(node):\n if node:\n dfs(node.left)\n result.append(node.val)\n dfs(node.right)\n dfs(root)\n return result", "solution_java": "public List inorderTraversal(TreeNode root) {\n List res = new ArrayList<>();\n dfs(root, res);\n return res;\n}\nprivate void dfs(TreeNode node, List res) {\n if (node == null) return;\n dfs(node.left, res); res.add(node.val); dfs(node.right, res);\n}", "solution_cpp": "vector inorderTraversal(TreeNode* root) {\n vector res;\n dfs(root, res);\n return res;\n}\nvoid dfs(TreeNode* node, vector& res) {\n if (!node) return;\n dfs(node->left, res); res.push_back(node->val); dfs(node->right, res);\n}", "test_cases": ["root=[1,null,2,3] -> [1,3,2]", "root=[] -> []"], "key_points": ["左-根-右顺序", "递归最简洁"], "tags": ["tree", "easy", "Google", "Microsoft"]} {"problem_id": "algo_00250", "original_id": "binary-search", "title": "二分查找", "category": "binarysearch", "difficulty": "easy", "companies": ["Google", "Amazon"], "description": "给定一个 n 个元素有序的(升序)整型数组 nums 和一个目标值 target,写一个函数搜索 nums 中的 target,如果目标值存在返回下标,否则返回 -1。", "solution_python": "def search(nums, target):\n left, right = 0, len(nums) - 1\n while left <= right:\n mid = (left + right) // 2\n if nums[mid] == target: return mid\n elif nums[mid] < target: left = mid + 1\n else: right = mid - 1\n return -1", "solution_java": "public int search(int[] nums, int target) {\n int left = 0, right = nums.length - 1;\n while (left <= right) {\n int mid = left + (right - left) / 2;\n if (nums[mid] == target) return mid;\n else if (nums[mid] < target) left = mid + 1;\n else right = mid - 1;\n }\n return -1;\n}", "solution_cpp": "int search(vector& nums, int target) {\n int left = 0, right = nums.size() - 1;\n while (left <= right) {\n int mid = left + (right - left) / 2;\n if (nums[mid] == target) return mid;\n else if (nums[mid] < target) left = mid + 1;\n else right = mid - 1;\n }\n return -1;\n}", "test_cases": ["nums=[-1,0,3,5,9,12], target=9 -> 4", "nums=[-1,0,3,5,9,12], target=2 -> -1"], "key_points": ["标准模板", "注意防溢出写法"], "tags": ["binarysearch", "easy", "Google", "Amazon"]} {"problem_id": "algo_00251", "original_id": "climbing-stairs", "title": "爬楼梯", "category": "dp", "difficulty": "easy", "companies": ["Amazon", "Google"], "description": "假设你正在爬楼梯。需要 n 阶你才能到达楼顶。每次你可以爬 1 或 2 个台阶。你有多少种不同的方法可以爬到楼顶?", "solution_python": "def climbStairs(n):\n if n <= 2: return n\n a, b = 1, 2\n for _ in range(3, n+1):\n a, b = b, a + b\n return b", "solution_java": "public int climbStairs(int n) {\n if (n <= 2) return n;\n int a = 1, b = 2;\n for (int i = 3; i <= n; i++) { int temp = a + b; a = b; b = temp; }\n return b;\n}", "solution_cpp": "int climbStairs(int n) {\n if (n <= 2) return n;\n int a = 1, b = 2;\n for (int i = 3; i <= n; i++) { int temp = a + b; a = b; b = temp; }\n return b;\n}", "test_cases": ["n=2 -> 2", "n=3 -> 3", "n=5 -> 8"], "key_points": ["斐波那契数列", "滚动数组优化空间"], "tags": ["dp", "easy", "Amazon", "Google"]} {"problem_id": "algo_00252", "original_id": "coin-change", "title": "零钱兑换", "category": "dp", "difficulty": "medium", "companies": ["Google", "Amazon"], "description": "给你一个整数数组 coins 表示不同面额的硬币,以及一个整数 amount 表示总金额。计算并返回可以凑成总金额所需的最少的硬币个数。如果没有任何一种硬币组合能组成总金额,返回 -1。", "solution_python": "def coinChange(coins, amount):\n dp = [float('inf')] * (amount + 1)\n dp[0] = 0\n for coin in coins:\n for x in range(coin, amount + 1):\n dp[x] = min(dp[x], dp[x - coin] + 1)\n return dp[amount] if dp[amount] != float('inf') else -1", "solution_java": "public int coinChange(int[] coins, int amount) {\n int[] dp = new int[amount + 1];\n Arrays.fill(dp, amount + 1);\n dp[0] = 0;\n for (int coin : coins) {\n for (int x = coin; x <= amount; x++) {\n dp[x] = Math.min(dp[x], dp[x - coin] + 1);\n }\n }\n return dp[amount] > amount ? -1 : dp[amount];\n}", "solution_cpp": "int coinChange(vector& coins, int amount) {\n vector dp(amount + 1, amount + 1);\n dp[0] = 0;\n for (int coin : coins) {\n for (int x = coin; x <= amount; x++) {\n dp[x] = min(dp[x], dp[x - coin] + 1);\n }\n }\n return dp[amount] > amount ? -1 : dp[amount];\n}", "test_cases": ["coins=[1,2,5], amount=11 -> 3", "coins=[2], amount=3 -> -1"], "key_points": ["完全背包问题", "dp[x] = min(dp[x-coin]+1)"], "tags": ["dp", "medium", "Google", "Amazon"]} {"problem_id": "algo_00253", "original_id": "subsets", "title": "子集", "category": "backtracking", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "给你一个整数数组 nums ,数组中的元素 互不相同 。返回该数组所有可能的子集(幂集)。", "solution_python": "def subsets(nums):\n result = []\n def backtrack(start, path):\n result.append(path[:])\n for i in range(start, len(nums)):\n path.append(nums[i])\n backtrack(i + 1, path)\n path.pop()\n backtrack(0, [])\n return result", "solution_java": "public List> subsets(int[] nums) {\n List> result = new ArrayList<>();\n backtrack(nums, 0, new ArrayList<>(), result);\n return result;\n}\nprivate void backtrack(int[] nums, int start, List path, List> result) {\n result.add(new ArrayList<>(path));\n for (int i = start; i < nums.length; i++) {\n path.add(nums[i]);\n backtrack(nums, i + 1, path, result);\n path.remove(path.size() - 1);\n }\n}", "solution_cpp": "vector> subsets(vector& nums) {\n vector> result;\n vector path;\n backtrack(nums, 0, path, result);\n return result;\n}\nvoid backtrack(vector& nums, int start, vector& path, vector>& result) {\n result.push_back(path);\n for (int i = start; i < nums.size(); i++) {\n path.push_back(nums[i]);\n backtrack(nums, i + 1, path, result);\n path.pop_back();\n }\n}", "test_cases": ["nums=[1,2,3] -> [[],[1],[2],[1,2],[3],[1,3],[2,3],[1,2,3]]"], "key_points": ["选或不选", "DFS遍历子集树"], "tags": ["backtracking", "medium", "Google", "Microsoft"]} {"problem_id": "algo_00254", "original_id": "permutations", "title": "全排列", "category": "backtracking", "difficulty": "medium", "companies": ["Google", "Facebook"], "description": "给定一个不含重复数字的数组 nums,返回其所有可能的全排列。", "solution_python": "def permute(nums):\n result = []\n def backtrack(path, used):\n if len(path) == len(nums):\n result.append(path[:])\n return\n for i in range(len(nums)):\n if used[i]: continue\n used[i] = True\n path.append(nums[i])\n backtrack(path, used)\n path.pop()\n used[i] = False\n backtrack([], [False]*len(nums))\n return result", "solution_java": "public List> permute(int[] nums) {\n List> result = new ArrayList<>();\n boolean[] used = new boolean[nums.length];\n backtrack(nums, used, new ArrayList<>(), result);\n return result;\n}\nprivate void backtrack(int[] nums, boolean[] used, List path, List> result) {\n if (path.size() == nums.length) { result.add(new ArrayList<>(path)); return; }\n for (int i = 0; i < nums.length; i++) {\n if (used[i]) continue;\n used[i] = true;\n path.add(nums[i]);\n backtrack(nums, used, path, result);\n path.remove(path.size() - 1);\n used[i] = false;\n }\n}", "solution_cpp": "vector> permute(vector& nums) {\n vector> result;\n vector used(nums.size(), false);\n vector path;\n backtrack(nums, used, path, result);\n return result;\n}\nvoid backtrack(vector& nums, vector& used, vector& path, vector>& result) {\n if (path.size() == nums.size()) { result.push_back(path); return; }\n for (int i = 0; i < nums.size(); i++) {\n if (used[i]) continue;\n used[i] = true;\n path.push_back(nums[i]);\n backtrack(nums, used, path, result);\n path.pop_back();\n used[i] = false;\n }\n}", "test_cases": ["nums=[1,2,3] -> [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]"], "key_points": ["标记已使用元素", "回溯经典模板"], "tags": ["backtracking", "medium", "Google", "Facebook"]} {"problem_id": "algo_00255", "original_id": "top-k-frequent", "title": "前K个高频元素", "category": "heap", "difficulty": "medium", "companies": ["Amazon", "Facebook"], "description": "给你一个整数数组 nums 和一个整数 k,请你返回其中出现频率前 k 高的元素。", "solution_python": "import heapq\nfrom collections import Counter\ndef topKFrequent(nums, k):\n count = Counter(nums)\n heap = []\n for num, freq in count.items():\n heapq.heappush(heap, (freq, num))\n if len(heap) > k: heapq.heappop(heap)\n return [num for freq, num in heap]", "solution_java": "public int[] topKFrequent(int[] nums, int k) {\n Map count = new HashMap<>();\n for (int n : nums) count.put(n, count.getOrDefault(n, 0) + 1);\n PriorityQueue> heap = \n new PriorityQueue<>((a, b) -> a.getValue() - b.getValue());\n for (Map.Entry e : count.entrySet()) {\n heap.offer(e);\n if (heap.size() > k) heap.poll();\n }\n int[] res = new int[k];\n for (int i = k - 1; i >= 0; i--) res[i] = heap.poll().getKey();\n return res;\n}", "solution_cpp": "vector topKFrequent(vector& nums, int k) {\n unordered_map count;\n for (int n : nums) count[n]++;\n priority_queue, vector>, greater>> heap;\n for (auto& [num, freq] : count) {\n heap.push({freq, num});\n if (heap.size() > k) heap.pop();\n }\n vector res;\n while (!heap.empty()) { res.push_back(heap.top().second); heap.pop(); }\n reverse(res.begin(), res.end());\n return res;\n}", "test_cases": ["nums=[1,1,1,2,2,3], k=2 -> [1,2]", "nums=[1], k=1 -> [1]"], "key_points": ["小顶堆保持大小k", "时间复杂度O(nlogk)"], "tags": ["heap", "medium", "Amazon", "Facebook"]} {"problem_id": "algo_00256", "original_id": "3sum", "title": "三数之和", "category": "two-pointers", "difficulty": "medium", "companies": ["Google", "Amazon"], "description": "给你一个整数数组 nums,判断是否存在三元组满足和为0,返回所有不重复的三元组。", "solution_python": "def threeSum(nums):\n nums.sort()\n result = []\n for i in range(len(nums) - 2):\n if i > 0 and nums[i] == nums[i-1]: continue\n left, right = i + 1, len(nums) - 1\n while left < right:\n total = nums[i] + nums[left] + nums[right]\n if total < 0: left += 1\n elif total > 0: right -= 1\n else:\n result.append([nums[i], nums[left], nums[right]])\n while left < right and nums[left] == nums[left+1]: left += 1\n while left < right and nums[right] == nums[right-1]: right -= 1\n left += 1; right -= 1\n return result", "solution_java": "public List> threeSum(int[] nums) {\n Arrays.sort(nums);\n List> result = new ArrayList<>();\n for (int i = 0; i < nums.length - 2; i++) {\n if (i > 0 && nums[i] == nums[i-1]) continue;\n int left = i + 1, right = nums.length - 1;\n while (left < right) {\n int total = nums[i] + nums[left] + nums[right];\n if (total < 0) left++;\n else if (total > 0) right--;\n else {\n result.add(Arrays.asList(nums[i], nums[left], nums[right]));\n while (left < right && nums[left] == nums[left+1]) left++;\n while (left < right && nums[right] == nums[right-1]) right--;\n left++; right--;\n }\n }\n }\n return result;\n}", "solution_cpp": "vector> threeSum(vector& nums) {\n sort(nums.begin(), nums.end());\n vector> result;\n for (int i = 0; i < nums.size() - 2; i++) {\n if (i > 0 && nums[i] == nums[i-1]) continue;\n int left = i + 1, right = nums.size() - 1;\n while (left < right) {\n int total = nums[i] + nums[left] + nums[right];\n if (total < 0) left++;\n else if (total > 0) right--;\n else {\n result.push_back({nums[i], nums[left], nums[right]});\n while (left < right && nums[left] == nums[left+1]) left++;\n while (left < right && nums[right] == nums[right-1]) right--;\n left++; right--;\n }\n }\n }\n return result;\n}", "test_cases": ["nums=[-1,0,1,2,-1,-4] -> [[-1,-1,2],[-1,0,1]]"], "key_points": ["排序+双指针", "去重是关键"], "tags": ["two-pointers", "medium", "Google", "Amazon"]} {"problem_id": "algo_00257", "original_id": "container-water", "title": "盛最多水的容器", "category": "two-pointers", "difficulty": "medium", "companies": ["Google", "Uber"], "description": "给定一个长度为 n 的整数数组 height,找出其中的两条线,使得它们与 x 轴共同构成的容器可以容纳最多的水。", "solution_python": "def maxArea(height):\n left, right = 0, len(height) - 1\n max_area = 0\n while left < right:\n h = min(height[left], height[right])\n max_area = max(max_area, h * (right - left))\n if height[left] < height[right]: left += 1\n else: right -= 1\n return max_area", "solution_java": "public int maxArea(int[] height) {\n int left = 0, right = height.length - 1, maxArea = 0;\n while (left < right) {\n int h = Math.min(height[left], height[right]);\n maxArea = Math.max(maxArea, h * (right - left));\n if (height[left] < height[right]) left++;\n else right--;\n }\n return maxArea;\n}", "solution_cpp": "int maxArea(vector& height) {\n int left = 0, right = height.size() - 1, maxArea = 0;\n while (left < right) {\n int h = min(height[left], height[right]);\n maxArea = max(maxArea, h * (right - left));\n if (height[left] < height[right]) left++;\n else right--;\n }\n return maxArea;\n}", "test_cases": ["height=[1,8,6,2,5,4,8,3,7] -> 49"], "key_points": ["移动短边指针", "面积=min(h1,h2)*width"], "tags": ["two-pointers", "medium", "Google", "Uber"]} {"problem_id": "algo_00258", "original_id": "min-stack", "title": "最小栈", "category": "stack", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "设计一个支持 push,pop,top 操作,并能在常数时间内检索到最小元素的栈。", "solution_python": "class MinStack:\n def __init__(self):\n self.stack = []\n self.min_stack = []\n def push(self, val):\n self.stack.append(val)\n self.min_stack.append(min(val, self.min_stack[-1] if self.min_stack else val))\n def pop(self):\n self.stack.pop(); self.min_stack.pop()\n def top(self): return self.stack[-1]\n def getMin(self): return self.min_stack[-1]", "solution_java": "class MinStack {\n Stack stack = new Stack<>();\n Stack minStack = new Stack<>();\n public void push(int val) { stack.push(val); minStack.push(Math.min(val, minStack.isEmpty() ? val : minStack.peek())); }\n public void pop() { stack.pop(); minStack.pop(); }\n public int top() { return stack.peek(); }\n public int getMin() { return minStack.peek(); }\n}", "solution_cpp": "class MinStack {\n stack st, minSt;\npublic:\n void push(int val) { st.push(val); minSt.push(min(val, minSt.empty() ? val : minSt.top())); }\n void pop() { st.pop(); minSt.pop(); }\n int top() { return st.top(); }\n int getMin() { return minSt.top(); }\n};", "test_cases": ["push(-2), push(0), push(-3) -> getMin() returns -3"], "key_points": ["辅助栈记录最小值", "O(1)时间获取最小值"], "tags": ["stack", "medium", "Google", "Microsoft"]} {"problem_id": "algo_00259", "original_id": "lru-cache", "title": "LRU缓存", "category": "design", "difficulty": "hard", "companies": ["Google", "Amazon"], "description": "设计和实现一个 LRU(最近最少使用)缓存机制。", "solution_python": "class LRUCache:\n def __init__(self, capacity):\n self.capacity = capacity\n self.cache = {}\n self.order = []\n def get(self, key):\n if key not in self.cache: return -1\n self.order.remove(key); self.order.append(key)\n return self.cache[key]\n def put(self, key, value):\n if key in self.cache:\n self.order.remove(key)\n elif len(self.cache) >= self.capacity:\n del self.cache[self.order.pop(0)]\n self.cache[key] = value; self.order.append(key)", "solution_java": "class LRUCache {\n int capacity;\n LinkedHashMap cache = new LinkedHashMap<>();\n public LRUCache(int cap) { capacity = cap; }\n public int get(int key) { return cache.containsKey(key) ? cache.remove(key) : -1; }\n public void put(int key, int val) {\n if (cache.containsKey(key)) cache.remove(key);\n else if (cache.size() >= capacity) cache.remove(cache.keySet().iterator().next());\n cache.put(key, val);\n }\n}", "solution_cpp": "class LRUCache {\n int cap;\n list> dll;\n unordered_map>::iterator> cache;\npublic:\n LRUCache(int capacity) : cap(capacity) {}\n int get(int key) {\n auto it = cache.find(key);\n if (it == cache.end()) return -1;\n dll.splice(dll.end(), dll, it->second);\n return it->second->second;\n }\n void put(int key, int value) {\n auto it = cache.find(key);\n if (it != cache.end()) dll.erase(it->second);\n else if (cache.size() >= cap) { cache.erase(dll.front().first); dll.pop_front(); }\n dll.push_back({key, value});\n cache[key] = --dll.end();\n }\n};", "test_cases": ["put(1,1), put(2,2), get(1) -> 1"], "key_points": ["HashMap + 双向链表", "O(1)时间操作"], "tags": ["design", "hard", "Google", "Amazon"]} {"problem_id": "algo_00260", "original_id": "num-islands", "title": "岛屿数量", "category": "graph", "difficulty": "medium", "companies": ["Google", "Facebook"], "description": "给你一个由 '1'(陆地)和 '0'(水)组成的二维网格,请你计算网格中岛屿的数量。岛屿总是被水包围,且只能由水平或垂直方向相邻的陆地连接形成。", "solution_python": "def numIslands(grid):\n if not grid: return 0\n rows, cols = len(grid), len(grid[0])\n count = 0\n def dfs(r, c):\n if r < 0 or r >= rows or c < 0 or c >= cols or grid[r][c] != '1': return\n grid[r][c] = '0'\n dfs(r+1, c); dfs(r-1, c); dfs(r, c+1); dfs(r, c-1)\n for r in range(rows):\n for c in range(cols):\n if grid[r][c] == '1': count += 1; dfs(r, c)\n return count", "solution_java": "public int numIslands(char[][] grid) {\n if (grid.length == 0) return 0;\n int count = 0;\n for (int i = 0; i < grid.length; i++)\n for (int j = 0; j < grid[0].length; j++)\n if (grid[i][j] == '1') { count++; dfs(grid, i, j); }\n return count;\n}\nprivate void dfs(char[][] grid, int r, int c) {\n if (r < 0 || r >= grid.length || c < 0 || c >= grid[0].length || grid[r][c] != '1') return;\n grid[r][c] = '0';\n dfs(grid, r+1, c); dfs(grid, r-1, c); dfs(grid, r, c+1); dfs(grid, r, c-1);\n}", "solution_cpp": "int numIslands(vector>& grid) {\n if (grid.empty()) return 0;\n int count = 0;\n for (int i = 0; i < grid.size(); i++)\n for (int j = 0; j < grid[0].size(); j++)\n if (grid[i][j] == '1') { count++; dfs(grid, i, j); }\n return count;\n}\nvoid dfs(vector>& grid, int r, int c) {\n if (r < 0 || r >= grid.size() || c < 0 || c >= grid[0].size() || grid[r][c] != '1') return;\n grid[r][c] = '0';\n dfs(grid, r+1, c); dfs(grid, r-1, c); dfs(grid, r, c+1); dfs(grid, r, c-1);\n}", "test_cases": ["grid=[[1,1,1,1,0],[1,1,0,1,0],[1,1,0,0,0],[0,0,0,0,0]] -> 1"], "key_points": ["DFS/BFS遍历", "访问后标记为0避免重复"], "tags": ["graph", "medium", "Google", "Facebook"]} {"problem_id": "algo_00261", "original_id": "two-sum", "title": "两数之和", "category": "array", "difficulty": "easy", "companies": ["Amazon", "Google"], "description": "给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那两个整数,并返回他们的数组下标。", "solution_python": "def twoSum(nums, target):\n hashmap = {}\n for i, num in enumerate(nums):\n complement = target - num\n if complement in hashmap:\n return [hashmap[complement], i]\n hashmap[num] = i\n return []", "solution_java": "public int[] twoSum(int[] nums, int target) {\n Map map = new HashMap<>();\n for (int i = 0; i < nums.length; i++) {\n int complement = target - nums[i];\n if (map.containsKey(complement)) return new int[]{map.get(complement), i};\n map.put(nums[i], i);\n }\n return new int[]{};\n}", "solution_cpp": "vector twoSum(vector& nums, int target) {\n unordered_map m;\n for (int i = 0; i < nums.size(); i++) {\n if (m.count(target - nums[i])) return {m[target - nums[i]], i};\n m[nums[i]] = i;\n }\n return {};\n}", "test_cases": ["nums=[2,7,11,15], target=9 -> [0,1]", "nums=[3,2,4], target=6 -> [1,2]"], "key_points": ["哈希表一次遍历", "空间换时间"], "tags": ["array", "easy", "Amazon", "Google"]} {"problem_id": "algo_00262", "original_id": "merge-sorted", "title": "合并两个有序数组", "category": "array", "difficulty": "easy", "companies": ["Microsoft", "Uber"], "description": "给你两个按非递减顺序排列的整数数组 nums1 和 nums2,另有两个整数 m 和 n,分别表示 nums1 和 nums2 中的元素数目。请你合并 nums2 到 nums1 中。", "solution_python": "def merge(nums1, m, nums2, n):\n p1, p2, p = m-1, n-1, m+n-1\n while p1 >= 0 and p2 >= 0:\n if nums1[p1] > nums2[p2]: nums1[p] = nums1[p1]; p1 -= 1\n else: nums1[p] = nums2[p2]; p2 -= 1\n p -= 1\n while p2 >= 0: nums1[p] = nums2[p2]; p2 -= 1; p -= 1", "solution_java": "public void merge(int[] nums1, int m, int[] nums2, int n) {\n int p1 = m-1, p2 = n-1, p = m+n-1;\n while (p1 >= 0 && p2 >= 0) {\n nums1[p--] = nums1[p1] > nums2[p2] ? nums1[p1--] : nums2[p2--];\n }\n while (p2 >= 0) nums1[p--] = nums2[p2--];\n}", "solution_cpp": "void merge(vector& nums1, int m, vector& nums2, int n) {\n int p1 = m-1, p2 = n-1, p = m+n-1;\n while (p1 >= 0 && p2 >= 0) nums1[p--] = nums1[p1] > nums2[p2] ? nums1[p1--] : nums2[p2--];\n while (p2 >= 0) nums1[p--] = nums2[p2--];\n}", "test_cases": ["nums1=[1,2,3], m=3, nums2=[2,5,6], n=3 -> [1,2,2,3,5,6]", "nums1=[], m=0, nums2=[1], n=1 -> [1]"], "key_points": ["从后往前合并", "三指针技巧"], "tags": ["array", "easy", "Microsoft", "Uber"]} {"problem_id": "algo_00263", "original_id": "max-subarray", "title": "最大子数组和", "category": "array", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "给你一个整数数组 nums ,请你找出一个具有最大和的连续子数组,返回其最大和。", "solution_python": "def maxSubArray(nums):\n max_sum = current = nums[0]\n for num in nums[1:]:\n current = max(num, current + num)\n max_sum = max(max_sum, current)\n return max_sum", "solution_java": "public int maxSubArray(int[] nums) {\n int maxSum = nums[0], curr = nums[0];\n for (int i = 1; i < nums.length; i++) {\n curr = Math.max(nums[i], curr + nums[i]);\n maxSum = Math.max(maxSum, curr);\n }\n return maxSum;\n}", "solution_cpp": "int maxSubArray(vector& nums) {\n int maxSum = nums[0], curr = nums[0];\n for (int i = 1; i < nums.size(); i++) {\n curr = max(nums[i], curr + nums[i]);\n maxSum = max(maxSum, curr);\n }\n return maxSum;\n}", "test_cases": ["nums=[-2,1,-3,4,-1,2,1,-5,4] -> 6", "nums=[1] -> 1"], "key_points": ["Kadane算法", "动态规划基础题"], "tags": ["array", "medium", "Google", "Microsoft"]} {"problem_id": "algo_00264", "original_id": "valid-parentheses", "title": "有效的括号", "category": "string", "difficulty": "easy", "companies": ["Google", "Uber"], "description": "给定一个只包括 '(',')','{','}','[',']' 的字符串 s,判断字符串是否有效。", "solution_python": "def isValid(s):\n stack = []\n mapping = {')': '(', ']': '[', '}': '{'}\n for c in s:\n if c in mapping:\n if not stack or stack[-1] != mapping[c]: return False\n stack.pop()\n else: stack.append(c)\n return not stack", "solution_java": "public boolean isValid(String s) {\n Stack stack = new Stack<>();\n Map map = Map.of(')', '(', ']', '[', '}', '{');\n for (char c : s.toCharArray()) {\n if (map.containsValue(c)) stack.push(c);\n else if (!stack.isEmpty() && stack.pop() != map.get(c)) return false;\n }\n return stack.isEmpty();\n}", "solution_cpp": "bool isValid(string s) {\n stack st;\n unordered_map m = {{')','('},{']','['},{'}','{'}};\n for (char c : s) {\n if (m.find(c) == m.end()) st.push(c);\n else if (st.empty() || st.top() != m[c]) return false;\n else st.pop();\n }\n return st.empty();\n}", "test_cases": ["s=\"()\" -> true", "s=\"()[]{}\" -> true", "s=\"(]\" -> false"], "key_points": ["栈匹配法", "注意空栈边界"], "tags": ["string", "easy", "Google", "Uber"]} {"problem_id": "algo_00265", "original_id": "longest-palindrome", "title": "最长回文子串", "category": "string", "difficulty": "medium", "companies": ["Google", "Amazon"], "description": "给你一个字符串 s,找到 s 中最长的回文子串。", "solution_python": "def longestPalindrome(s):\n def expand(l, r):\n while l >= 0 and r < len(s) and s[l] == s[r]: l -= 1; r += 1\n return l + 1, r - 1\n start = end = 0\n for i in range(len(s)):\n l1, r1 = expand(i, i)\n l2, r2 = expand(i, i + 1)\n if r1 - l1 > end - start: start, end = l1, r1\n if r2 - l2 > end - start: start, end = l2, r2\n return s[start:end+1]", "solution_java": "public String longestPalindrome(String s) {\n int start = 0, end = 0;\n for (int i = 0; i < s.length(); i++) {\n int len1 = expand(s, i, i), len2 = expand(s, i, i+1);\n int len = Math.max(len1, len2);\n if (len > end - start) { start = i - (len-1)/2; end = i + len/2; }\n }\n return s.substring(start, end + 1);\n}\nprivate int expand(String s, int l, int r) {\n while (l >= 0 && r < s.length() && s.charAt(l) == s.charAt(r)) { l--; r++; }\n return r - l - 1;\n}", "solution_cpp": "string longestPalindrome(string s) {\n int start = 0, end = 0;\n for (int i = 0; i < s.size(); i++) {\n int len1 = expand(s, i, i), len2 = expand(s, i, i+1);\n if (max(len1, len2) > end - start) { start = i - (max(len1,len2)-1)/2; end = i + max(len1,len2)/2; }\n }\n return s.substr(start, end - start + 1);\n}", "test_cases": ["s=\"babad\" -> bab或aba", "s=\"cbbd\" -> bb"], "key_points": ["中心扩展法", "处理奇偶长度"], "tags": ["string", "medium", "Google", "Amazon"]} {"problem_id": "algo_00266", "original_id": "reverse-list", "title": "反转链表", "category": "linkedlist", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "给你单链表的头节点 head,请你反转链表,并返回反转后的链表。", "solution_python": "def reverseList(head):\n prev = None\n curr = head\n while curr:\n nxt = curr.next\n curr.next = prev\n prev = curr\n curr = nxt\n return prev", "solution_java": "public ListNode reverseList(ListNode head) {\n ListNode prev = null, curr = head;\n while (curr != null) {\n ListNode next = curr.next;\n curr.next = prev;\n prev = curr;\n curr = next;\n }\n return prev;\n}", "solution_cpp": "ListNode* reverseList(ListNode* head) {\n ListNode* prev = nullptr, *curr = head;\n while (curr) {\n ListNode* next = curr->next;\n curr->next = prev;\n prev = curr;\n curr = next;\n }\n return prev;\n}", "test_cases": ["head=[1,2,3,4,5] -> [5,4,3,2,1]", "head=[1,2] -> [2,1]"], "key_points": ["迭代法 O(1)空间", "递归法 O(n)空间"], "tags": ["linkedlist", "medium", "Google", "Microsoft"]} {"problem_id": "algo_00267", "original_id": "middle-node", "title": "链表的中间结点", "category": "linkedlist", "difficulty": "easy", "companies": ["Amazon", "Facebook"], "description": "给你单链表的头节点 head,请你找出并返回链表的中间结点。如果有两个中间结点,则返回第二个中间结点。", "solution_python": "def middleNode(head):\n slow = fast = head\n while fast and fast.next:\n slow = slow.next\n fast = fast.next.next\n return slow", "solution_java": "public ListNode middleNode(ListNode head) {\n ListNode slow = head, fast = head;\n while (fast != null && fast.next != null) {\n slow = slow.next;\n fast = fast.next.next;\n }\n return slow;\n}", "solution_cpp": "ListNode* middleNode(ListNode* head) {\n ListNode* slow = head, *fast = head;\n while (fast && fast->next) { slow = slow->next; fast = fast->next->next; }\n return slow;\n}", "test_cases": ["head=[1,2,3,4,5] -> 3", "head=[1,2,3,4,5,6] -> 4"], "key_points": ["快慢指针", "O(n)时间O(1)空间"], "tags": ["linkedlist", "easy", "Amazon", "Facebook"]} {"problem_id": "algo_00268", "original_id": "max-depth", "title": "二叉树的最大深度", "category": "tree", "difficulty": "easy", "companies": ["Microsoft", "Apple"], "description": "给定一个二叉树 root,返回其最大深度。", "solution_python": "def maxDepth(root):\n if not root: return 0\n return max(maxDepth(root.left), maxDepth(root.right)) + 1", "solution_java": "public int maxDepth(TreeNode root) {\n if (root == null) return 0;\n return Math.max(maxDepth(root.left), maxDepth(root.right)) + 1;\n}", "solution_cpp": "int maxDepth(TreeNode* root) {\n if (!root) return 0;\n return max(maxDepth(root->left), maxDepth(root->right)) + 1;\n}", "test_cases": ["root=[3,9,20,null,null,15,7] -> 3", "root=[1,null,2] -> 2"], "key_points": ["DFS递归", "层序遍历也可"], "tags": ["tree", "easy", "Microsoft", "Apple"]} {"problem_id": "algo_00269", "original_id": "inorder-traversal", "title": "二叉树的中序遍历", "category": "tree", "difficulty": "easy", "companies": ["Google", "Microsoft"], "description": "给定一个二叉树的根节点 root,返回它的中序遍历结果。", "solution_python": "def inorderTraversal(root):\n result = []\n def dfs(node):\n if node:\n dfs(node.left)\n result.append(node.val)\n dfs(node.right)\n dfs(root)\n return result", "solution_java": "public List inorderTraversal(TreeNode root) {\n List res = new ArrayList<>();\n dfs(root, res);\n return res;\n}\nprivate void dfs(TreeNode node, List res) {\n if (node == null) return;\n dfs(node.left, res); res.add(node.val); dfs(node.right, res);\n}", "solution_cpp": "vector inorderTraversal(TreeNode* root) {\n vector res;\n dfs(root, res);\n return res;\n}\nvoid dfs(TreeNode* node, vector& res) {\n if (!node) return;\n dfs(node->left, res); res.push_back(node->val); dfs(node->right, res);\n}", "test_cases": ["root=[1,null,2,3] -> [1,3,2]", "root=[] -> []"], "key_points": ["左-根-右顺序", "递归最简洁"], "tags": ["tree", "easy", "Google", "Microsoft"]} {"problem_id": "algo_00270", "original_id": "binary-search", "title": "二分查找", "category": "binarysearch", "difficulty": "easy", "companies": ["Google", "Amazon"], "description": "给定一个 n 个元素有序的(升序)整型数组 nums 和一个目标值 target,写一个函数搜索 nums 中的 target,如果目标值存在返回下标,否则返回 -1。", "solution_python": "def search(nums, target):\n left, right = 0, len(nums) - 1\n while left <= right:\n mid = (left + right) // 2\n if nums[mid] == target: return mid\n elif nums[mid] < target: left = mid + 1\n else: right = mid - 1\n return -1", "solution_java": "public int search(int[] nums, int target) {\n int left = 0, right = nums.length - 1;\n while (left <= right) {\n int mid = left + (right - left) / 2;\n if (nums[mid] == target) return mid;\n else if (nums[mid] < target) left = mid + 1;\n else right = mid - 1;\n }\n return -1;\n}", "solution_cpp": "int search(vector& nums, int target) {\n int left = 0, right = nums.size() - 1;\n while (left <= right) {\n int mid = left + (right - left) / 2;\n if (nums[mid] == target) return mid;\n else if (nums[mid] < target) left = mid + 1;\n else right = mid - 1;\n }\n return -1;\n}", "test_cases": ["nums=[-1,0,3,5,9,12], target=9 -> 4", "nums=[-1,0,3,5,9,12], target=2 -> -1"], "key_points": ["标准模板", "注意防溢出写法"], "tags": ["binarysearch", "easy", "Google", "Amazon"]} {"problem_id": "algo_00271", "original_id": "climbing-stairs", "title": "爬楼梯", "category": "dp", "difficulty": "easy", "companies": ["Amazon", "Google"], "description": "假设你正在爬楼梯。需要 n 阶你才能到达楼顶。每次你可以爬 1 或 2 个台阶。你有多少种不同的方法可以爬到楼顶?", "solution_python": "def climbStairs(n):\n if n <= 2: return n\n a, b = 1, 2\n for _ in range(3, n+1):\n a, b = b, a + b\n return b", "solution_java": "public int climbStairs(int n) {\n if (n <= 2) return n;\n int a = 1, b = 2;\n for (int i = 3; i <= n; i++) { int temp = a + b; a = b; b = temp; }\n return b;\n}", "solution_cpp": "int climbStairs(int n) {\n if (n <= 2) return n;\n int a = 1, b = 2;\n for (int i = 3; i <= n; i++) { int temp = a + b; a = b; b = temp; }\n return b;\n}", "test_cases": ["n=2 -> 2", "n=3 -> 3", "n=5 -> 8"], "key_points": ["斐波那契数列", "滚动数组优化空间"], "tags": ["dp", "easy", "Amazon", "Google"]} {"problem_id": "algo_00272", "original_id": "coin-change", "title": "零钱兑换", "category": "dp", "difficulty": "medium", "companies": ["Google", "Amazon"], "description": "给你一个整数数组 coins 表示不同面额的硬币,以及一个整数 amount 表示总金额。计算并返回可以凑成总金额所需的最少的硬币个数。如果没有任何一种硬币组合能组成总金额,返回 -1。", "solution_python": "def coinChange(coins, amount):\n dp = [float('inf')] * (amount + 1)\n dp[0] = 0\n for coin in coins:\n for x in range(coin, amount + 1):\n dp[x] = min(dp[x], dp[x - coin] + 1)\n return dp[amount] if dp[amount] != float('inf') else -1", "solution_java": "public int coinChange(int[] coins, int amount) {\n int[] dp = new int[amount + 1];\n Arrays.fill(dp, amount + 1);\n dp[0] = 0;\n for (int coin : coins) {\n for (int x = coin; x <= amount; x++) {\n dp[x] = Math.min(dp[x], dp[x - coin] + 1);\n }\n }\n return dp[amount] > amount ? -1 : dp[amount];\n}", "solution_cpp": "int coinChange(vector& coins, int amount) {\n vector dp(amount + 1, amount + 1);\n dp[0] = 0;\n for (int coin : coins) {\n for (int x = coin; x <= amount; x++) {\n dp[x] = min(dp[x], dp[x - coin] + 1);\n }\n }\n return dp[amount] > amount ? -1 : dp[amount];\n}", "test_cases": ["coins=[1,2,5], amount=11 -> 3", "coins=[2], amount=3 -> -1"], "key_points": ["完全背包问题", "dp[x] = min(dp[x-coin]+1)"], "tags": ["dp", "medium", "Google", "Amazon"]} {"problem_id": "algo_00273", "original_id": "subsets", "title": "子集", "category": "backtracking", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "给你一个整数数组 nums ,数组中的元素 互不相同 。返回该数组所有可能的子集(幂集)。", "solution_python": "def subsets(nums):\n result = []\n def backtrack(start, path):\n result.append(path[:])\n for i in range(start, len(nums)):\n path.append(nums[i])\n backtrack(i + 1, path)\n path.pop()\n backtrack(0, [])\n return result", "solution_java": "public List> subsets(int[] nums) {\n List> result = new ArrayList<>();\n backtrack(nums, 0, new ArrayList<>(), result);\n return result;\n}\nprivate void backtrack(int[] nums, int start, List path, List> result) {\n result.add(new ArrayList<>(path));\n for (int i = start; i < nums.length; i++) {\n path.add(nums[i]);\n backtrack(nums, i + 1, path, result);\n path.remove(path.size() - 1);\n }\n}", "solution_cpp": "vector> subsets(vector& nums) {\n vector> result;\n vector path;\n backtrack(nums, 0, path, result);\n return result;\n}\nvoid backtrack(vector& nums, int start, vector& path, vector>& result) {\n result.push_back(path);\n for (int i = start; i < nums.size(); i++) {\n path.push_back(nums[i]);\n backtrack(nums, i + 1, path, result);\n path.pop_back();\n }\n}", "test_cases": ["nums=[1,2,3] -> [[],[1],[2],[1,2],[3],[1,3],[2,3],[1,2,3]]"], "key_points": ["选或不选", "DFS遍历子集树"], "tags": ["backtracking", "medium", "Google", "Microsoft"]} {"problem_id": "algo_00274", "original_id": "permutations", "title": "全排列", "category": "backtracking", "difficulty": "medium", "companies": ["Google", "Facebook"], "description": "给定一个不含重复数字的数组 nums,返回其所有可能的全排列。", "solution_python": "def permute(nums):\n result = []\n def backtrack(path, used):\n if len(path) == len(nums):\n result.append(path[:])\n return\n for i in range(len(nums)):\n if used[i]: continue\n used[i] = True\n path.append(nums[i])\n backtrack(path, used)\n path.pop()\n used[i] = False\n backtrack([], [False]*len(nums))\n return result", "solution_java": "public List> permute(int[] nums) {\n List> result = new ArrayList<>();\n boolean[] used = new boolean[nums.length];\n backtrack(nums, used, new ArrayList<>(), result);\n return result;\n}\nprivate void backtrack(int[] nums, boolean[] used, List path, List> result) {\n if (path.size() == nums.length) { result.add(new ArrayList<>(path)); return; }\n for (int i = 0; i < nums.length; i++) {\n if (used[i]) continue;\n used[i] = true;\n path.add(nums[i]);\n backtrack(nums, used, path, result);\n path.remove(path.size() - 1);\n used[i] = false;\n }\n}", "solution_cpp": "vector> permute(vector& nums) {\n vector> result;\n vector used(nums.size(), false);\n vector path;\n backtrack(nums, used, path, result);\n return result;\n}\nvoid backtrack(vector& nums, vector& used, vector& path, vector>& result) {\n if (path.size() == nums.size()) { result.push_back(path); return; }\n for (int i = 0; i < nums.size(); i++) {\n if (used[i]) continue;\n used[i] = true;\n path.push_back(nums[i]);\n backtrack(nums, used, path, result);\n path.pop_back();\n used[i] = false;\n }\n}", "test_cases": ["nums=[1,2,3] -> [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]"], "key_points": ["标记已使用元素", "回溯经典模板"], "tags": ["backtracking", "medium", "Google", "Facebook"]} {"problem_id": "algo_00275", "original_id": "top-k-frequent", "title": "前K个高频元素", "category": "heap", "difficulty": "medium", "companies": ["Amazon", "Facebook"], "description": "给你一个整数数组 nums 和一个整数 k,请你返回其中出现频率前 k 高的元素。", "solution_python": "import heapq\nfrom collections import Counter\ndef topKFrequent(nums, k):\n count = Counter(nums)\n heap = []\n for num, freq in count.items():\n heapq.heappush(heap, (freq, num))\n if len(heap) > k: heapq.heappop(heap)\n return [num for freq, num in heap]", "solution_java": "public int[] topKFrequent(int[] nums, int k) {\n Map count = new HashMap<>();\n for (int n : nums) count.put(n, count.getOrDefault(n, 0) + 1);\n PriorityQueue> heap = \n new PriorityQueue<>((a, b) -> a.getValue() - b.getValue());\n for (Map.Entry e : count.entrySet()) {\n heap.offer(e);\n if (heap.size() > k) heap.poll();\n }\n int[] res = new int[k];\n for (int i = k - 1; i >= 0; i--) res[i] = heap.poll().getKey();\n return res;\n}", "solution_cpp": "vector topKFrequent(vector& nums, int k) {\n unordered_map count;\n for (int n : nums) count[n]++;\n priority_queue, vector>, greater>> heap;\n for (auto& [num, freq] : count) {\n heap.push({freq, num});\n if (heap.size() > k) heap.pop();\n }\n vector res;\n while (!heap.empty()) { res.push_back(heap.top().second); heap.pop(); }\n reverse(res.begin(), res.end());\n return res;\n}", "test_cases": ["nums=[1,1,1,2,2,3], k=2 -> [1,2]", "nums=[1], k=1 -> [1]"], "key_points": ["小顶堆保持大小k", "时间复杂度O(nlogk)"], "tags": ["heap", "medium", "Amazon", "Facebook"]} {"problem_id": "algo_00276", "original_id": "3sum", "title": "三数之和", "category": "two-pointers", "difficulty": "medium", "companies": ["Google", "Amazon"], "description": "给你一个整数数组 nums,判断是否存在三元组满足和为0,返回所有不重复的三元组。", "solution_python": "def threeSum(nums):\n nums.sort()\n result = []\n for i in range(len(nums) - 2):\n if i > 0 and nums[i] == nums[i-1]: continue\n left, right = i + 1, len(nums) - 1\n while left < right:\n total = nums[i] + nums[left] + nums[right]\n if total < 0: left += 1\n elif total > 0: right -= 1\n else:\n result.append([nums[i], nums[left], nums[right]])\n while left < right and nums[left] == nums[left+1]: left += 1\n while left < right and nums[right] == nums[right-1]: right -= 1\n left += 1; right -= 1\n return result", "solution_java": "public List> threeSum(int[] nums) {\n Arrays.sort(nums);\n List> result = new ArrayList<>();\n for (int i = 0; i < nums.length - 2; i++) {\n if (i > 0 && nums[i] == nums[i-1]) continue;\n int left = i + 1, right = nums.length - 1;\n while (left < right) {\n int total = nums[i] + nums[left] + nums[right];\n if (total < 0) left++;\n else if (total > 0) right--;\n else {\n result.add(Arrays.asList(nums[i], nums[left], nums[right]));\n while (left < right && nums[left] == nums[left+1]) left++;\n while (left < right && nums[right] == nums[right-1]) right--;\n left++; right--;\n }\n }\n }\n return result;\n}", "solution_cpp": "vector> threeSum(vector& nums) {\n sort(nums.begin(), nums.end());\n vector> result;\n for (int i = 0; i < nums.size() - 2; i++) {\n if (i > 0 && nums[i] == nums[i-1]) continue;\n int left = i + 1, right = nums.size() - 1;\n while (left < right) {\n int total = nums[i] + nums[left] + nums[right];\n if (total < 0) left++;\n else if (total > 0) right--;\n else {\n result.push_back({nums[i], nums[left], nums[right]});\n while (left < right && nums[left] == nums[left+1]) left++;\n while (left < right && nums[right] == nums[right-1]) right--;\n left++; right--;\n }\n }\n }\n return result;\n}", "test_cases": ["nums=[-1,0,1,2,-1,-4] -> [[-1,-1,2],[-1,0,1]]"], "key_points": ["排序+双指针", "去重是关键"], "tags": ["two-pointers", "medium", "Google", "Amazon"]} {"problem_id": "algo_00277", "original_id": "container-water", "title": "盛最多水的容器", "category": "two-pointers", "difficulty": "medium", "companies": ["Google", "Uber"], "description": "给定一个长度为 n 的整数数组 height,找出其中的两条线,使得它们与 x 轴共同构成的容器可以容纳最多的水。", "solution_python": "def maxArea(height):\n left, right = 0, len(height) - 1\n max_area = 0\n while left < right:\n h = min(height[left], height[right])\n max_area = max(max_area, h * (right - left))\n if height[left] < height[right]: left += 1\n else: right -= 1\n return max_area", "solution_java": "public int maxArea(int[] height) {\n int left = 0, right = height.length - 1, maxArea = 0;\n while (left < right) {\n int h = Math.min(height[left], height[right]);\n maxArea = Math.max(maxArea, h * (right - left));\n if (height[left] < height[right]) left++;\n else right--;\n }\n return maxArea;\n}", "solution_cpp": "int maxArea(vector& height) {\n int left = 0, right = height.size() - 1, maxArea = 0;\n while (left < right) {\n int h = min(height[left], height[right]);\n maxArea = max(maxArea, h * (right - left));\n if (height[left] < height[right]) left++;\n else right--;\n }\n return maxArea;\n}", "test_cases": ["height=[1,8,6,2,5,4,8,3,7] -> 49"], "key_points": ["移动短边指针", "面积=min(h1,h2)*width"], "tags": ["two-pointers", "medium", "Google", "Uber"]} {"problem_id": "algo_00278", "original_id": "min-stack", "title": "最小栈", "category": "stack", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "设计一个支持 push,pop,top 操作,并能在常数时间内检索到最小元素的栈。", "solution_python": "class MinStack:\n def __init__(self):\n self.stack = []\n self.min_stack = []\n def push(self, val):\n self.stack.append(val)\n self.min_stack.append(min(val, self.min_stack[-1] if self.min_stack else val))\n def pop(self):\n self.stack.pop(); self.min_stack.pop()\n def top(self): return self.stack[-1]\n def getMin(self): return self.min_stack[-1]", "solution_java": "class MinStack {\n Stack stack = new Stack<>();\n Stack minStack = new Stack<>();\n public void push(int val) { stack.push(val); minStack.push(Math.min(val, minStack.isEmpty() ? val : minStack.peek())); }\n public void pop() { stack.pop(); minStack.pop(); }\n public int top() { return stack.peek(); }\n public int getMin() { return minStack.peek(); }\n}", "solution_cpp": "class MinStack {\n stack st, minSt;\npublic:\n void push(int val) { st.push(val); minSt.push(min(val, minSt.empty() ? val : minSt.top())); }\n void pop() { st.pop(); minSt.pop(); }\n int top() { return st.top(); }\n int getMin() { return minSt.top(); }\n};", "test_cases": ["push(-2), push(0), push(-3) -> getMin() returns -3"], "key_points": ["辅助栈记录最小值", "O(1)时间获取最小值"], "tags": ["stack", "medium", "Google", "Microsoft"]} {"problem_id": "algo_00279", "original_id": "lru-cache", "title": "LRU缓存", "category": "design", "difficulty": "hard", "companies": ["Google", "Amazon"], "description": "设计和实现一个 LRU(最近最少使用)缓存机制。", "solution_python": "class LRUCache:\n def __init__(self, capacity):\n self.capacity = capacity\n self.cache = {}\n self.order = []\n def get(self, key):\n if key not in self.cache: return -1\n self.order.remove(key); self.order.append(key)\n return self.cache[key]\n def put(self, key, value):\n if key in self.cache:\n self.order.remove(key)\n elif len(self.cache) >= self.capacity:\n del self.cache[self.order.pop(0)]\n self.cache[key] = value; self.order.append(key)", "solution_java": "class LRUCache {\n int capacity;\n LinkedHashMap cache = new LinkedHashMap<>();\n public LRUCache(int cap) { capacity = cap; }\n public int get(int key) { return cache.containsKey(key) ? cache.remove(key) : -1; }\n public void put(int key, int val) {\n if (cache.containsKey(key)) cache.remove(key);\n else if (cache.size() >= capacity) cache.remove(cache.keySet().iterator().next());\n cache.put(key, val);\n }\n}", "solution_cpp": "class LRUCache {\n int cap;\n list> dll;\n unordered_map>::iterator> cache;\npublic:\n LRUCache(int capacity) : cap(capacity) {}\n int get(int key) {\n auto it = cache.find(key);\n if (it == cache.end()) return -1;\n dll.splice(dll.end(), dll, it->second);\n return it->second->second;\n }\n void put(int key, int value) {\n auto it = cache.find(key);\n if (it != cache.end()) dll.erase(it->second);\n else if (cache.size() >= cap) { cache.erase(dll.front().first); dll.pop_front(); }\n dll.push_back({key, value});\n cache[key] = --dll.end();\n }\n};", "test_cases": ["put(1,1), put(2,2), get(1) -> 1"], "key_points": ["HashMap + 双向链表", "O(1)时间操作"], "tags": ["design", "hard", "Google", "Amazon"]} {"problem_id": "algo_00280", "original_id": "num-islands", "title": "岛屿数量", "category": "graph", "difficulty": "medium", "companies": ["Google", "Facebook"], "description": "给你一个由 '1'(陆地)和 '0'(水)组成的二维网格,请你计算网格中岛屿的数量。岛屿总是被水包围,且只能由水平或垂直方向相邻的陆地连接形成。", "solution_python": "def numIslands(grid):\n if not grid: return 0\n rows, cols = len(grid), len(grid[0])\n count = 0\n def dfs(r, c):\n if r < 0 or r >= rows or c < 0 or c >= cols or grid[r][c] != '1': return\n grid[r][c] = '0'\n dfs(r+1, c); dfs(r-1, c); dfs(r, c+1); dfs(r, c-1)\n for r in range(rows):\n for c in range(cols):\n if grid[r][c] == '1': count += 1; dfs(r, c)\n return count", "solution_java": "public int numIslands(char[][] grid) {\n if (grid.length == 0) return 0;\n int count = 0;\n for (int i = 0; i < grid.length; i++)\n for (int j = 0; j < grid[0].length; j++)\n if (grid[i][j] == '1') { count++; dfs(grid, i, j); }\n return count;\n}\nprivate void dfs(char[][] grid, int r, int c) {\n if (r < 0 || r >= grid.length || c < 0 || c >= grid[0].length || grid[r][c] != '1') return;\n grid[r][c] = '0';\n dfs(grid, r+1, c); dfs(grid, r-1, c); dfs(grid, r, c+1); dfs(grid, r, c-1);\n}", "solution_cpp": "int numIslands(vector>& grid) {\n if (grid.empty()) return 0;\n int count = 0;\n for (int i = 0; i < grid.size(); i++)\n for (int j = 0; j < grid[0].size(); j++)\n if (grid[i][j] == '1') { count++; dfs(grid, i, j); }\n return count;\n}\nvoid dfs(vector>& grid, int r, int c) {\n if (r < 0 || r >= grid.size() || c < 0 || c >= grid[0].size() || grid[r][c] != '1') return;\n grid[r][c] = '0';\n dfs(grid, r+1, c); dfs(grid, r-1, c); dfs(grid, r, c+1); dfs(grid, r, c-1);\n}", "test_cases": ["grid=[[1,1,1,1,0],[1,1,0,1,0],[1,1,0,0,0],[0,0,0,0,0]] -> 1"], "key_points": ["DFS/BFS遍历", "访问后标记为0避免重复"], "tags": ["graph", "medium", "Google", "Facebook"]} {"problem_id": "algo_00281", "original_id": "two-sum", "title": "两数之和", "category": "array", "difficulty": "easy", "companies": ["Amazon", "Google"], "description": "给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那两个整数,并返回他们的数组下标。", "solution_python": "def twoSum(nums, target):\n hashmap = {}\n for i, num in enumerate(nums):\n complement = target - num\n if complement in hashmap:\n return [hashmap[complement], i]\n hashmap[num] = i\n return []", "solution_java": "public int[] twoSum(int[] nums, int target) {\n Map map = new HashMap<>();\n for (int i = 0; i < nums.length; i++) {\n int complement = target - nums[i];\n if (map.containsKey(complement)) return new int[]{map.get(complement), i};\n map.put(nums[i], i);\n }\n return new int[]{};\n}", "solution_cpp": "vector twoSum(vector& nums, int target) {\n unordered_map m;\n for (int i = 0; i < nums.size(); i++) {\n if (m.count(target - nums[i])) return {m[target - nums[i]], i};\n m[nums[i]] = i;\n }\n return {};\n}", "test_cases": ["nums=[2,7,11,15], target=9 -> [0,1]", "nums=[3,2,4], target=6 -> [1,2]"], "key_points": ["哈希表一次遍历", "空间换时间"], "tags": ["array", "easy", "Amazon", "Google"]} {"problem_id": "algo_00282", "original_id": "merge-sorted", "title": "合并两个有序数组", "category": "array", "difficulty": "easy", "companies": ["Microsoft", "Uber"], "description": "给你两个按非递减顺序排列的整数数组 nums1 和 nums2,另有两个整数 m 和 n,分别表示 nums1 和 nums2 中的元素数目。请你合并 nums2 到 nums1 中。", "solution_python": "def merge(nums1, m, nums2, n):\n p1, p2, p = m-1, n-1, m+n-1\n while p1 >= 0 and p2 >= 0:\n if nums1[p1] > nums2[p2]: nums1[p] = nums1[p1]; p1 -= 1\n else: nums1[p] = nums2[p2]; p2 -= 1\n p -= 1\n while p2 >= 0: nums1[p] = nums2[p2]; p2 -= 1; p -= 1", "solution_java": "public void merge(int[] nums1, int m, int[] nums2, int n) {\n int p1 = m-1, p2 = n-1, p = m+n-1;\n while (p1 >= 0 && p2 >= 0) {\n nums1[p--] = nums1[p1] > nums2[p2] ? nums1[p1--] : nums2[p2--];\n }\n while (p2 >= 0) nums1[p--] = nums2[p2--];\n}", "solution_cpp": "void merge(vector& nums1, int m, vector& nums2, int n) {\n int p1 = m-1, p2 = n-1, p = m+n-1;\n while (p1 >= 0 && p2 >= 0) nums1[p--] = nums1[p1] > nums2[p2] ? nums1[p1--] : nums2[p2--];\n while (p2 >= 0) nums1[p--] = nums2[p2--];\n}", "test_cases": ["nums1=[1,2,3], m=3, nums2=[2,5,6], n=3 -> [1,2,2,3,5,6]", "nums1=[], m=0, nums2=[1], n=1 -> [1]"], "key_points": ["从后往前合并", "三指针技巧"], "tags": ["array", "easy", "Microsoft", "Uber"]} {"problem_id": "algo_00283", "original_id": "max-subarray", "title": "最大子数组和", "category": "array", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "给你一个整数数组 nums ,请你找出一个具有最大和的连续子数组,返回其最大和。", "solution_python": "def maxSubArray(nums):\n max_sum = current = nums[0]\n for num in nums[1:]:\n current = max(num, current + num)\n max_sum = max(max_sum, current)\n return max_sum", "solution_java": "public int maxSubArray(int[] nums) {\n int maxSum = nums[0], curr = nums[0];\n for (int i = 1; i < nums.length; i++) {\n curr = Math.max(nums[i], curr + nums[i]);\n maxSum = Math.max(maxSum, curr);\n }\n return maxSum;\n}", "solution_cpp": "int maxSubArray(vector& nums) {\n int maxSum = nums[0], curr = nums[0];\n for (int i = 1; i < nums.size(); i++) {\n curr = max(nums[i], curr + nums[i]);\n maxSum = max(maxSum, curr);\n }\n return maxSum;\n}", "test_cases": ["nums=[-2,1,-3,4,-1,2,1,-5,4] -> 6", "nums=[1] -> 1"], "key_points": ["Kadane算法", "动态规划基础题"], "tags": ["array", "medium", "Google", "Microsoft"]} {"problem_id": "algo_00284", "original_id": "valid-parentheses", "title": "有效的括号", "category": "string", "difficulty": "easy", "companies": ["Google", "Uber"], "description": "给定一个只包括 '(',')','{','}','[',']' 的字符串 s,判断字符串是否有效。", "solution_python": "def isValid(s):\n stack = []\n mapping = {')': '(', ']': '[', '}': '{'}\n for c in s:\n if c in mapping:\n if not stack or stack[-1] != mapping[c]: return False\n stack.pop()\n else: stack.append(c)\n return not stack", "solution_java": "public boolean isValid(String s) {\n Stack stack = new Stack<>();\n Map map = Map.of(')', '(', ']', '[', '}', '{');\n for (char c : s.toCharArray()) {\n if (map.containsValue(c)) stack.push(c);\n else if (!stack.isEmpty() && stack.pop() != map.get(c)) return false;\n }\n return stack.isEmpty();\n}", "solution_cpp": "bool isValid(string s) {\n stack st;\n unordered_map m = {{')','('},{']','['},{'}','{'}};\n for (char c : s) {\n if (m.find(c) == m.end()) st.push(c);\n else if (st.empty() || st.top() != m[c]) return false;\n else st.pop();\n }\n return st.empty();\n}", "test_cases": ["s=\"()\" -> true", "s=\"()[]{}\" -> true", "s=\"(]\" -> false"], "key_points": ["栈匹配法", "注意空栈边界"], "tags": ["string", "easy", "Google", "Uber"]} {"problem_id": "algo_00285", "original_id": "longest-palindrome", "title": "最长回文子串", "category": "string", "difficulty": "medium", "companies": ["Google", "Amazon"], "description": "给你一个字符串 s,找到 s 中最长的回文子串。", "solution_python": "def longestPalindrome(s):\n def expand(l, r):\n while l >= 0 and r < len(s) and s[l] == s[r]: l -= 1; r += 1\n return l + 1, r - 1\n start = end = 0\n for i in range(len(s)):\n l1, r1 = expand(i, i)\n l2, r2 = expand(i, i + 1)\n if r1 - l1 > end - start: start, end = l1, r1\n if r2 - l2 > end - start: start, end = l2, r2\n return s[start:end+1]", "solution_java": "public String longestPalindrome(String s) {\n int start = 0, end = 0;\n for (int i = 0; i < s.length(); i++) {\n int len1 = expand(s, i, i), len2 = expand(s, i, i+1);\n int len = Math.max(len1, len2);\n if (len > end - start) { start = i - (len-1)/2; end = i + len/2; }\n }\n return s.substring(start, end + 1);\n}\nprivate int expand(String s, int l, int r) {\n while (l >= 0 && r < s.length() && s.charAt(l) == s.charAt(r)) { l--; r++; }\n return r - l - 1;\n}", "solution_cpp": "string longestPalindrome(string s) {\n int start = 0, end = 0;\n for (int i = 0; i < s.size(); i++) {\n int len1 = expand(s, i, i), len2 = expand(s, i, i+1);\n if (max(len1, len2) > end - start) { start = i - (max(len1,len2)-1)/2; end = i + max(len1,len2)/2; }\n }\n return s.substr(start, end - start + 1);\n}", "test_cases": ["s=\"babad\" -> bab或aba", "s=\"cbbd\" -> bb"], "key_points": ["中心扩展法", "处理奇偶长度"], "tags": ["string", "medium", "Google", "Amazon"]} {"problem_id": "algo_00286", "original_id": "reverse-list", "title": "反转链表", "category": "linkedlist", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "给你单链表的头节点 head,请你反转链表,并返回反转后的链表。", "solution_python": "def reverseList(head):\n prev = None\n curr = head\n while curr:\n nxt = curr.next\n curr.next = prev\n prev = curr\n curr = nxt\n return prev", "solution_java": "public ListNode reverseList(ListNode head) {\n ListNode prev = null, curr = head;\n while (curr != null) {\n ListNode next = curr.next;\n curr.next = prev;\n prev = curr;\n curr = next;\n }\n return prev;\n}", "solution_cpp": "ListNode* reverseList(ListNode* head) {\n ListNode* prev = nullptr, *curr = head;\n while (curr) {\n ListNode* next = curr->next;\n curr->next = prev;\n prev = curr;\n curr = next;\n }\n return prev;\n}", "test_cases": ["head=[1,2,3,4,5] -> [5,4,3,2,1]", "head=[1,2] -> [2,1]"], "key_points": ["迭代法 O(1)空间", "递归法 O(n)空间"], "tags": ["linkedlist", "medium", "Google", "Microsoft"]} {"problem_id": "algo_00287", "original_id": "middle-node", "title": "链表的中间结点", "category": "linkedlist", "difficulty": "easy", "companies": ["Amazon", "Facebook"], "description": "给你单链表的头节点 head,请你找出并返回链表的中间结点。如果有两个中间结点,则返回第二个中间结点。", "solution_python": "def middleNode(head):\n slow = fast = head\n while fast and fast.next:\n slow = slow.next\n fast = fast.next.next\n return slow", "solution_java": "public ListNode middleNode(ListNode head) {\n ListNode slow = head, fast = head;\n while (fast != null && fast.next != null) {\n slow = slow.next;\n fast = fast.next.next;\n }\n return slow;\n}", "solution_cpp": "ListNode* middleNode(ListNode* head) {\n ListNode* slow = head, *fast = head;\n while (fast && fast->next) { slow = slow->next; fast = fast->next->next; }\n return slow;\n}", "test_cases": ["head=[1,2,3,4,5] -> 3", "head=[1,2,3,4,5,6] -> 4"], "key_points": ["快慢指针", "O(n)时间O(1)空间"], "tags": ["linkedlist", "easy", "Amazon", "Facebook"]} {"problem_id": "algo_00288", "original_id": "max-depth", "title": "二叉树的最大深度", "category": "tree", "difficulty": "easy", "companies": ["Microsoft", "Apple"], "description": "给定一个二叉树 root,返回其最大深度。", "solution_python": "def maxDepth(root):\n if not root: return 0\n return max(maxDepth(root.left), maxDepth(root.right)) + 1", "solution_java": "public int maxDepth(TreeNode root) {\n if (root == null) return 0;\n return Math.max(maxDepth(root.left), maxDepth(root.right)) + 1;\n}", "solution_cpp": "int maxDepth(TreeNode* root) {\n if (!root) return 0;\n return max(maxDepth(root->left), maxDepth(root->right)) + 1;\n}", "test_cases": ["root=[3,9,20,null,null,15,7] -> 3", "root=[1,null,2] -> 2"], "key_points": ["DFS递归", "层序遍历也可"], "tags": ["tree", "easy", "Microsoft", "Apple"]} {"problem_id": "algo_00289", "original_id": "inorder-traversal", "title": "二叉树的中序遍历", "category": "tree", "difficulty": "easy", "companies": ["Google", "Microsoft"], "description": "给定一个二叉树的根节点 root,返回它的中序遍历结果。", "solution_python": "def inorderTraversal(root):\n result = []\n def dfs(node):\n if node:\n dfs(node.left)\n result.append(node.val)\n dfs(node.right)\n dfs(root)\n return result", "solution_java": "public List inorderTraversal(TreeNode root) {\n List res = new ArrayList<>();\n dfs(root, res);\n return res;\n}\nprivate void dfs(TreeNode node, List res) {\n if (node == null) return;\n dfs(node.left, res); res.add(node.val); dfs(node.right, res);\n}", "solution_cpp": "vector inorderTraversal(TreeNode* root) {\n vector res;\n dfs(root, res);\n return res;\n}\nvoid dfs(TreeNode* node, vector& res) {\n if (!node) return;\n dfs(node->left, res); res.push_back(node->val); dfs(node->right, res);\n}", "test_cases": ["root=[1,null,2,3] -> [1,3,2]", "root=[] -> []"], "key_points": ["左-根-右顺序", "递归最简洁"], "tags": ["tree", "easy", "Google", "Microsoft"]} {"problem_id": "algo_00290", "original_id": "binary-search", "title": "二分查找", "category": "binarysearch", "difficulty": "easy", "companies": ["Google", "Amazon"], "description": "给定一个 n 个元素有序的(升序)整型数组 nums 和一个目标值 target,写一个函数搜索 nums 中的 target,如果目标值存在返回下标,否则返回 -1。", "solution_python": "def search(nums, target):\n left, right = 0, len(nums) - 1\n while left <= right:\n mid = (left + right) // 2\n if nums[mid] == target: return mid\n elif nums[mid] < target: left = mid + 1\n else: right = mid - 1\n return -1", "solution_java": "public int search(int[] nums, int target) {\n int left = 0, right = nums.length - 1;\n while (left <= right) {\n int mid = left + (right - left) / 2;\n if (nums[mid] == target) return mid;\n else if (nums[mid] < target) left = mid + 1;\n else right = mid - 1;\n }\n return -1;\n}", "solution_cpp": "int search(vector& nums, int target) {\n int left = 0, right = nums.size() - 1;\n while (left <= right) {\n int mid = left + (right - left) / 2;\n if (nums[mid] == target) return mid;\n else if (nums[mid] < target) left = mid + 1;\n else right = mid - 1;\n }\n return -1;\n}", "test_cases": ["nums=[-1,0,3,5,9,12], target=9 -> 4", "nums=[-1,0,3,5,9,12], target=2 -> -1"], "key_points": ["标准模板", "注意防溢出写法"], "tags": ["binarysearch", "easy", "Google", "Amazon"]} {"problem_id": "algo_00291", "original_id": "climbing-stairs", "title": "爬楼梯", "category": "dp", "difficulty": "easy", "companies": ["Amazon", "Google"], "description": "假设你正在爬楼梯。需要 n 阶你才能到达楼顶。每次你可以爬 1 或 2 个台阶。你有多少种不同的方法可以爬到楼顶?", "solution_python": "def climbStairs(n):\n if n <= 2: return n\n a, b = 1, 2\n for _ in range(3, n+1):\n a, b = b, a + b\n return b", "solution_java": "public int climbStairs(int n) {\n if (n <= 2) return n;\n int a = 1, b = 2;\n for (int i = 3; i <= n; i++) { int temp = a + b; a = b; b = temp; }\n return b;\n}", "solution_cpp": "int climbStairs(int n) {\n if (n <= 2) return n;\n int a = 1, b = 2;\n for (int i = 3; i <= n; i++) { int temp = a + b; a = b; b = temp; }\n return b;\n}", "test_cases": ["n=2 -> 2", "n=3 -> 3", "n=5 -> 8"], "key_points": ["斐波那契数列", "滚动数组优化空间"], "tags": ["dp", "easy", "Amazon", "Google"]} {"problem_id": "algo_00292", "original_id": "coin-change", "title": "零钱兑换", "category": "dp", "difficulty": "medium", "companies": ["Google", "Amazon"], "description": "给你一个整数数组 coins 表示不同面额的硬币,以及一个整数 amount 表示总金额。计算并返回可以凑成总金额所需的最少的硬币个数。如果没有任何一种硬币组合能组成总金额,返回 -1。", "solution_python": "def coinChange(coins, amount):\n dp = [float('inf')] * (amount + 1)\n dp[0] = 0\n for coin in coins:\n for x in range(coin, amount + 1):\n dp[x] = min(dp[x], dp[x - coin] + 1)\n return dp[amount] if dp[amount] != float('inf') else -1", "solution_java": "public int coinChange(int[] coins, int amount) {\n int[] dp = new int[amount + 1];\n Arrays.fill(dp, amount + 1);\n dp[0] = 0;\n for (int coin : coins) {\n for (int x = coin; x <= amount; x++) {\n dp[x] = Math.min(dp[x], dp[x - coin] + 1);\n }\n }\n return dp[amount] > amount ? -1 : dp[amount];\n}", "solution_cpp": "int coinChange(vector& coins, int amount) {\n vector dp(amount + 1, amount + 1);\n dp[0] = 0;\n for (int coin : coins) {\n for (int x = coin; x <= amount; x++) {\n dp[x] = min(dp[x], dp[x - coin] + 1);\n }\n }\n return dp[amount] > amount ? -1 : dp[amount];\n}", "test_cases": ["coins=[1,2,5], amount=11 -> 3", "coins=[2], amount=3 -> -1"], "key_points": ["完全背包问题", "dp[x] = min(dp[x-coin]+1)"], "tags": ["dp", "medium", "Google", "Amazon"]} {"problem_id": "algo_00293", "original_id": "subsets", "title": "子集", "category": "backtracking", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "给你一个整数数组 nums ,数组中的元素 互不相同 。返回该数组所有可能的子集(幂集)。", "solution_python": "def subsets(nums):\n result = []\n def backtrack(start, path):\n result.append(path[:])\n for i in range(start, len(nums)):\n path.append(nums[i])\n backtrack(i + 1, path)\n path.pop()\n backtrack(0, [])\n return result", "solution_java": "public List> subsets(int[] nums) {\n List> result = new ArrayList<>();\n backtrack(nums, 0, new ArrayList<>(), result);\n return result;\n}\nprivate void backtrack(int[] nums, int start, List path, List> result) {\n result.add(new ArrayList<>(path));\n for (int i = start; i < nums.length; i++) {\n path.add(nums[i]);\n backtrack(nums, i + 1, path, result);\n path.remove(path.size() - 1);\n }\n}", "solution_cpp": "vector> subsets(vector& nums) {\n vector> result;\n vector path;\n backtrack(nums, 0, path, result);\n return result;\n}\nvoid backtrack(vector& nums, int start, vector& path, vector>& result) {\n result.push_back(path);\n for (int i = start; i < nums.size(); i++) {\n path.push_back(nums[i]);\n backtrack(nums, i + 1, path, result);\n path.pop_back();\n }\n}", "test_cases": ["nums=[1,2,3] -> [[],[1],[2],[1,2],[3],[1,3],[2,3],[1,2,3]]"], "key_points": ["选或不选", "DFS遍历子集树"], "tags": ["backtracking", "medium", "Google", "Microsoft"]} {"problem_id": "algo_00294", "original_id": "permutations", "title": "全排列", "category": "backtracking", "difficulty": "medium", "companies": ["Google", "Facebook"], "description": "给定一个不含重复数字的数组 nums,返回其所有可能的全排列。", "solution_python": "def permute(nums):\n result = []\n def backtrack(path, used):\n if len(path) == len(nums):\n result.append(path[:])\n return\n for i in range(len(nums)):\n if used[i]: continue\n used[i] = True\n path.append(nums[i])\n backtrack(path, used)\n path.pop()\n used[i] = False\n backtrack([], [False]*len(nums))\n return result", "solution_java": "public List> permute(int[] nums) {\n List> result = new ArrayList<>();\n boolean[] used = new boolean[nums.length];\n backtrack(nums, used, new ArrayList<>(), result);\n return result;\n}\nprivate void backtrack(int[] nums, boolean[] used, List path, List> result) {\n if (path.size() == nums.length) { result.add(new ArrayList<>(path)); return; }\n for (int i = 0; i < nums.length; i++) {\n if (used[i]) continue;\n used[i] = true;\n path.add(nums[i]);\n backtrack(nums, used, path, result);\n path.remove(path.size() - 1);\n used[i] = false;\n }\n}", "solution_cpp": "vector> permute(vector& nums) {\n vector> result;\n vector used(nums.size(), false);\n vector path;\n backtrack(nums, used, path, result);\n return result;\n}\nvoid backtrack(vector& nums, vector& used, vector& path, vector>& result) {\n if (path.size() == nums.size()) { result.push_back(path); return; }\n for (int i = 0; i < nums.size(); i++) {\n if (used[i]) continue;\n used[i] = true;\n path.push_back(nums[i]);\n backtrack(nums, used, path, result);\n path.pop_back();\n used[i] = false;\n }\n}", "test_cases": ["nums=[1,2,3] -> [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]"], "key_points": ["标记已使用元素", "回溯经典模板"], "tags": ["backtracking", "medium", "Google", "Facebook"]} {"problem_id": "algo_00295", "original_id": "top-k-frequent", "title": "前K个高频元素", "category": "heap", "difficulty": "medium", "companies": ["Amazon", "Facebook"], "description": "给你一个整数数组 nums 和一个整数 k,请你返回其中出现频率前 k 高的元素。", "solution_python": "import heapq\nfrom collections import Counter\ndef topKFrequent(nums, k):\n count = Counter(nums)\n heap = []\n for num, freq in count.items():\n heapq.heappush(heap, (freq, num))\n if len(heap) > k: heapq.heappop(heap)\n return [num for freq, num in heap]", "solution_java": "public int[] topKFrequent(int[] nums, int k) {\n Map count = new HashMap<>();\n for (int n : nums) count.put(n, count.getOrDefault(n, 0) + 1);\n PriorityQueue> heap = \n new PriorityQueue<>((a, b) -> a.getValue() - b.getValue());\n for (Map.Entry e : count.entrySet()) {\n heap.offer(e);\n if (heap.size() > k) heap.poll();\n }\n int[] res = new int[k];\n for (int i = k - 1; i >= 0; i--) res[i] = heap.poll().getKey();\n return res;\n}", "solution_cpp": "vector topKFrequent(vector& nums, int k) {\n unordered_map count;\n for (int n : nums) count[n]++;\n priority_queue, vector>, greater>> heap;\n for (auto& [num, freq] : count) {\n heap.push({freq, num});\n if (heap.size() > k) heap.pop();\n }\n vector res;\n while (!heap.empty()) { res.push_back(heap.top().second); heap.pop(); }\n reverse(res.begin(), res.end());\n return res;\n}", "test_cases": ["nums=[1,1,1,2,2,3], k=2 -> [1,2]", "nums=[1], k=1 -> [1]"], "key_points": ["小顶堆保持大小k", "时间复杂度O(nlogk)"], "tags": ["heap", "medium", "Amazon", "Facebook"]} {"problem_id": "algo_00296", "original_id": "3sum", "title": "三数之和", "category": "two-pointers", "difficulty": "medium", "companies": ["Google", "Amazon"], "description": "给你一个整数数组 nums,判断是否存在三元组满足和为0,返回所有不重复的三元组。", "solution_python": "def threeSum(nums):\n nums.sort()\n result = []\n for i in range(len(nums) - 2):\n if i > 0 and nums[i] == nums[i-1]: continue\n left, right = i + 1, len(nums) - 1\n while left < right:\n total = nums[i] + nums[left] + nums[right]\n if total < 0: left += 1\n elif total > 0: right -= 1\n else:\n result.append([nums[i], nums[left], nums[right]])\n while left < right and nums[left] == nums[left+1]: left += 1\n while left < right and nums[right] == nums[right-1]: right -= 1\n left += 1; right -= 1\n return result", "solution_java": "public List> threeSum(int[] nums) {\n Arrays.sort(nums);\n List> result = new ArrayList<>();\n for (int i = 0; i < nums.length - 2; i++) {\n if (i > 0 && nums[i] == nums[i-1]) continue;\n int left = i + 1, right = nums.length - 1;\n while (left < right) {\n int total = nums[i] + nums[left] + nums[right];\n if (total < 0) left++;\n else if (total > 0) right--;\n else {\n result.add(Arrays.asList(nums[i], nums[left], nums[right]));\n while (left < right && nums[left] == nums[left+1]) left++;\n while (left < right && nums[right] == nums[right-1]) right--;\n left++; right--;\n }\n }\n }\n return result;\n}", "solution_cpp": "vector> threeSum(vector& nums) {\n sort(nums.begin(), nums.end());\n vector> result;\n for (int i = 0; i < nums.size() - 2; i++) {\n if (i > 0 && nums[i] == nums[i-1]) continue;\n int left = i + 1, right = nums.size() - 1;\n while (left < right) {\n int total = nums[i] + nums[left] + nums[right];\n if (total < 0) left++;\n else if (total > 0) right--;\n else {\n result.push_back({nums[i], nums[left], nums[right]});\n while (left < right && nums[left] == nums[left+1]) left++;\n while (left < right && nums[right] == nums[right-1]) right--;\n left++; right--;\n }\n }\n }\n return result;\n}", "test_cases": ["nums=[-1,0,1,2,-1,-4] -> [[-1,-1,2],[-1,0,1]]"], "key_points": ["排序+双指针", "去重是关键"], "tags": ["two-pointers", "medium", "Google", "Amazon"]} {"problem_id": "algo_00297", "original_id": "container-water", "title": "盛最多水的容器", "category": "two-pointers", "difficulty": "medium", "companies": ["Google", "Uber"], "description": "给定一个长度为 n 的整数数组 height,找出其中的两条线,使得它们与 x 轴共同构成的容器可以容纳最多的水。", "solution_python": "def maxArea(height):\n left, right = 0, len(height) - 1\n max_area = 0\n while left < right:\n h = min(height[left], height[right])\n max_area = max(max_area, h * (right - left))\n if height[left] < height[right]: left += 1\n else: right -= 1\n return max_area", "solution_java": "public int maxArea(int[] height) {\n int left = 0, right = height.length - 1, maxArea = 0;\n while (left < right) {\n int h = Math.min(height[left], height[right]);\n maxArea = Math.max(maxArea, h * (right - left));\n if (height[left] < height[right]) left++;\n else right--;\n }\n return maxArea;\n}", "solution_cpp": "int maxArea(vector& height) {\n int left = 0, right = height.size() - 1, maxArea = 0;\n while (left < right) {\n int h = min(height[left], height[right]);\n maxArea = max(maxArea, h * (right - left));\n if (height[left] < height[right]) left++;\n else right--;\n }\n return maxArea;\n}", "test_cases": ["height=[1,8,6,2,5,4,8,3,7] -> 49"], "key_points": ["移动短边指针", "面积=min(h1,h2)*width"], "tags": ["two-pointers", "medium", "Google", "Uber"]} {"problem_id": "algo_00298", "original_id": "min-stack", "title": "最小栈", "category": "stack", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "设计一个支持 push,pop,top 操作,并能在常数时间内检索到最小元素的栈。", "solution_python": "class MinStack:\n def __init__(self):\n self.stack = []\n self.min_stack = []\n def push(self, val):\n self.stack.append(val)\n self.min_stack.append(min(val, self.min_stack[-1] if self.min_stack else val))\n def pop(self):\n self.stack.pop(); self.min_stack.pop()\n def top(self): return self.stack[-1]\n def getMin(self): return self.min_stack[-1]", "solution_java": "class MinStack {\n Stack stack = new Stack<>();\n Stack minStack = new Stack<>();\n public void push(int val) { stack.push(val); minStack.push(Math.min(val, minStack.isEmpty() ? val : minStack.peek())); }\n public void pop() { stack.pop(); minStack.pop(); }\n public int top() { return stack.peek(); }\n public int getMin() { return minStack.peek(); }\n}", "solution_cpp": "class MinStack {\n stack st, minSt;\npublic:\n void push(int val) { st.push(val); minSt.push(min(val, minSt.empty() ? val : minSt.top())); }\n void pop() { st.pop(); minSt.pop(); }\n int top() { return st.top(); }\n int getMin() { return minSt.top(); }\n};", "test_cases": ["push(-2), push(0), push(-3) -> getMin() returns -3"], "key_points": ["辅助栈记录最小值", "O(1)时间获取最小值"], "tags": ["stack", "medium", "Google", "Microsoft"]} {"problem_id": "algo_00299", "original_id": "lru-cache", "title": "LRU缓存", "category": "design", "difficulty": "hard", "companies": ["Google", "Amazon"], "description": "设计和实现一个 LRU(最近最少使用)缓存机制。", "solution_python": "class LRUCache:\n def __init__(self, capacity):\n self.capacity = capacity\n self.cache = {}\n self.order = []\n def get(self, key):\n if key not in self.cache: return -1\n self.order.remove(key); self.order.append(key)\n return self.cache[key]\n def put(self, key, value):\n if key in self.cache:\n self.order.remove(key)\n elif len(self.cache) >= self.capacity:\n del self.cache[self.order.pop(0)]\n self.cache[key] = value; self.order.append(key)", "solution_java": "class LRUCache {\n int capacity;\n LinkedHashMap cache = new LinkedHashMap<>();\n public LRUCache(int cap) { capacity = cap; }\n public int get(int key) { return cache.containsKey(key) ? cache.remove(key) : -1; }\n public void put(int key, int val) {\n if (cache.containsKey(key)) cache.remove(key);\n else if (cache.size() >= capacity) cache.remove(cache.keySet().iterator().next());\n cache.put(key, val);\n }\n}", "solution_cpp": "class LRUCache {\n int cap;\n list> dll;\n unordered_map>::iterator> cache;\npublic:\n LRUCache(int capacity) : cap(capacity) {}\n int get(int key) {\n auto it = cache.find(key);\n if (it == cache.end()) return -1;\n dll.splice(dll.end(), dll, it->second);\n return it->second->second;\n }\n void put(int key, int value) {\n auto it = cache.find(key);\n if (it != cache.end()) dll.erase(it->second);\n else if (cache.size() >= cap) { cache.erase(dll.front().first); dll.pop_front(); }\n dll.push_back({key, value});\n cache[key] = --dll.end();\n }\n};", "test_cases": ["put(1,1), put(2,2), get(1) -> 1"], "key_points": ["HashMap + 双向链表", "O(1)时间操作"], "tags": ["design", "hard", "Google", "Amazon"]} {"problem_id": "algo_00300", "original_id": "num-islands", "title": "岛屿数量", "category": "graph", "difficulty": "medium", "companies": ["Google", "Facebook"], "description": "给你一个由 '1'(陆地)和 '0'(水)组成的二维网格,请你计算网格中岛屿的数量。岛屿总是被水包围,且只能由水平或垂直方向相邻的陆地连接形成。", "solution_python": "def numIslands(grid):\n if not grid: return 0\n rows, cols = len(grid), len(grid[0])\n count = 0\n def dfs(r, c):\n if r < 0 or r >= rows or c < 0 or c >= cols or grid[r][c] != '1': return\n grid[r][c] = '0'\n dfs(r+1, c); dfs(r-1, c); dfs(r, c+1); dfs(r, c-1)\n for r in range(rows):\n for c in range(cols):\n if grid[r][c] == '1': count += 1; dfs(r, c)\n return count", "solution_java": "public int numIslands(char[][] grid) {\n if (grid.length == 0) return 0;\n int count = 0;\n for (int i = 0; i < grid.length; i++)\n for (int j = 0; j < grid[0].length; j++)\n if (grid[i][j] == '1') { count++; dfs(grid, i, j); }\n return count;\n}\nprivate void dfs(char[][] grid, int r, int c) {\n if (r < 0 || r >= grid.length || c < 0 || c >= grid[0].length || grid[r][c] != '1') return;\n grid[r][c] = '0';\n dfs(grid, r+1, c); dfs(grid, r-1, c); dfs(grid, r, c+1); dfs(grid, r, c-1);\n}", "solution_cpp": "int numIslands(vector>& grid) {\n if (grid.empty()) return 0;\n int count = 0;\n for (int i = 0; i < grid.size(); i++)\n for (int j = 0; j < grid[0].size(); j++)\n if (grid[i][j] == '1') { count++; dfs(grid, i, j); }\n return count;\n}\nvoid dfs(vector>& grid, int r, int c) {\n if (r < 0 || r >= grid.size() || c < 0 || c >= grid[0].size() || grid[r][c] != '1') return;\n grid[r][c] = '0';\n dfs(grid, r+1, c); dfs(grid, r-1, c); dfs(grid, r, c+1); dfs(grid, r, c-1);\n}", "test_cases": ["grid=[[1,1,1,1,0],[1,1,0,1,0],[1,1,0,0,0],[0,0,0,0,0]] -> 1"], "key_points": ["DFS/BFS遍历", "访问后标记为0避免重复"], "tags": ["graph", "medium", "Google", "Facebook"]} {"problem_id": "algo_00301", "original_id": "two-sum", "title": "两数之和", "category": "array", "difficulty": "easy", "companies": ["Amazon", "Google"], "description": "给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那两个整数,并返回他们的数组下标。", "solution_python": "def twoSum(nums, target):\n hashmap = {}\n for i, num in enumerate(nums):\n complement = target - num\n if complement in hashmap:\n return [hashmap[complement], i]\n hashmap[num] = i\n return []", "solution_java": "public int[] twoSum(int[] nums, int target) {\n Map map = new HashMap<>();\n for (int i = 0; i < nums.length; i++) {\n int complement = target - nums[i];\n if (map.containsKey(complement)) return new int[]{map.get(complement), i};\n map.put(nums[i], i);\n }\n return new int[]{};\n}", "solution_cpp": "vector twoSum(vector& nums, int target) {\n unordered_map m;\n for (int i = 0; i < nums.size(); i++) {\n if (m.count(target - nums[i])) return {m[target - nums[i]], i};\n m[nums[i]] = i;\n }\n return {};\n}", "test_cases": ["nums=[2,7,11,15], target=9 -> [0,1]", "nums=[3,2,4], target=6 -> [1,2]"], "key_points": ["哈希表一次遍历", "空间换时间"], "tags": ["array", "easy", "Amazon", "Google"]} {"problem_id": "algo_00302", "original_id": "merge-sorted", "title": "合并两个有序数组", "category": "array", "difficulty": "easy", "companies": ["Microsoft", "Uber"], "description": "给你两个按非递减顺序排列的整数数组 nums1 和 nums2,另有两个整数 m 和 n,分别表示 nums1 和 nums2 中的元素数目。请你合并 nums2 到 nums1 中。", "solution_python": "def merge(nums1, m, nums2, n):\n p1, p2, p = m-1, n-1, m+n-1\n while p1 >= 0 and p2 >= 0:\n if nums1[p1] > nums2[p2]: nums1[p] = nums1[p1]; p1 -= 1\n else: nums1[p] = nums2[p2]; p2 -= 1\n p -= 1\n while p2 >= 0: nums1[p] = nums2[p2]; p2 -= 1; p -= 1", "solution_java": "public void merge(int[] nums1, int m, int[] nums2, int n) {\n int p1 = m-1, p2 = n-1, p = m+n-1;\n while (p1 >= 0 && p2 >= 0) {\n nums1[p--] = nums1[p1] > nums2[p2] ? nums1[p1--] : nums2[p2--];\n }\n while (p2 >= 0) nums1[p--] = nums2[p2--];\n}", "solution_cpp": "void merge(vector& nums1, int m, vector& nums2, int n) {\n int p1 = m-1, p2 = n-1, p = m+n-1;\n while (p1 >= 0 && p2 >= 0) nums1[p--] = nums1[p1] > nums2[p2] ? nums1[p1--] : nums2[p2--];\n while (p2 >= 0) nums1[p--] = nums2[p2--];\n}", "test_cases": ["nums1=[1,2,3], m=3, nums2=[2,5,6], n=3 -> [1,2,2,3,5,6]", "nums1=[], m=0, nums2=[1], n=1 -> [1]"], "key_points": ["从后往前合并", "三指针技巧"], "tags": ["array", "easy", "Microsoft", "Uber"]} {"problem_id": "algo_00303", "original_id": "max-subarray", "title": "最大子数组和", "category": "array", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "给你一个整数数组 nums ,请你找出一个具有最大和的连续子数组,返回其最大和。", "solution_python": "def maxSubArray(nums):\n max_sum = current = nums[0]\n for num in nums[1:]:\n current = max(num, current + num)\n max_sum = max(max_sum, current)\n return max_sum", "solution_java": "public int maxSubArray(int[] nums) {\n int maxSum = nums[0], curr = nums[0];\n for (int i = 1; i < nums.length; i++) {\n curr = Math.max(nums[i], curr + nums[i]);\n maxSum = Math.max(maxSum, curr);\n }\n return maxSum;\n}", "solution_cpp": "int maxSubArray(vector& nums) {\n int maxSum = nums[0], curr = nums[0];\n for (int i = 1; i < nums.size(); i++) {\n curr = max(nums[i], curr + nums[i]);\n maxSum = max(maxSum, curr);\n }\n return maxSum;\n}", "test_cases": ["nums=[-2,1,-3,4,-1,2,1,-5,4] -> 6", "nums=[1] -> 1"], "key_points": ["Kadane算法", "动态规划基础题"], "tags": ["array", "medium", "Google", "Microsoft"]} {"problem_id": "algo_00304", "original_id": "valid-parentheses", "title": "有效的括号", "category": "string", "difficulty": "easy", "companies": ["Google", "Uber"], "description": "给定一个只包括 '(',')','{','}','[',']' 的字符串 s,判断字符串是否有效。", "solution_python": "def isValid(s):\n stack = []\n mapping = {')': '(', ']': '[', '}': '{'}\n for c in s:\n if c in mapping:\n if not stack or stack[-1] != mapping[c]: return False\n stack.pop()\n else: stack.append(c)\n return not stack", "solution_java": "public boolean isValid(String s) {\n Stack stack = new Stack<>();\n Map map = Map.of(')', '(', ']', '[', '}', '{');\n for (char c : s.toCharArray()) {\n if (map.containsValue(c)) stack.push(c);\n else if (!stack.isEmpty() && stack.pop() != map.get(c)) return false;\n }\n return stack.isEmpty();\n}", "solution_cpp": "bool isValid(string s) {\n stack st;\n unordered_map m = {{')','('},{']','['},{'}','{'}};\n for (char c : s) {\n if (m.find(c) == m.end()) st.push(c);\n else if (st.empty() || st.top() != m[c]) return false;\n else st.pop();\n }\n return st.empty();\n}", "test_cases": ["s=\"()\" -> true", "s=\"()[]{}\" -> true", "s=\"(]\" -> false"], "key_points": ["栈匹配法", "注意空栈边界"], "tags": ["string", "easy", "Google", "Uber"]} {"problem_id": "algo_00305", "original_id": "longest-palindrome", "title": "最长回文子串", "category": "string", "difficulty": "medium", "companies": ["Google", "Amazon"], "description": "给你一个字符串 s,找到 s 中最长的回文子串。", "solution_python": "def longestPalindrome(s):\n def expand(l, r):\n while l >= 0 and r < len(s) and s[l] == s[r]: l -= 1; r += 1\n return l + 1, r - 1\n start = end = 0\n for i in range(len(s)):\n l1, r1 = expand(i, i)\n l2, r2 = expand(i, i + 1)\n if r1 - l1 > end - start: start, end = l1, r1\n if r2 - l2 > end - start: start, end = l2, r2\n return s[start:end+1]", "solution_java": "public String longestPalindrome(String s) {\n int start = 0, end = 0;\n for (int i = 0; i < s.length(); i++) {\n int len1 = expand(s, i, i), len2 = expand(s, i, i+1);\n int len = Math.max(len1, len2);\n if (len > end - start) { start = i - (len-1)/2; end = i + len/2; }\n }\n return s.substring(start, end + 1);\n}\nprivate int expand(String s, int l, int r) {\n while (l >= 0 && r < s.length() && s.charAt(l) == s.charAt(r)) { l--; r++; }\n return r - l - 1;\n}", "solution_cpp": "string longestPalindrome(string s) {\n int start = 0, end = 0;\n for (int i = 0; i < s.size(); i++) {\n int len1 = expand(s, i, i), len2 = expand(s, i, i+1);\n if (max(len1, len2) > end - start) { start = i - (max(len1,len2)-1)/2; end = i + max(len1,len2)/2; }\n }\n return s.substr(start, end - start + 1);\n}", "test_cases": ["s=\"babad\" -> bab或aba", "s=\"cbbd\" -> bb"], "key_points": ["中心扩展法", "处理奇偶长度"], "tags": ["string", "medium", "Google", "Amazon"]} {"problem_id": "algo_00306", "original_id": "reverse-list", "title": "反转链表", "category": "linkedlist", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "给你单链表的头节点 head,请你反转链表,并返回反转后的链表。", "solution_python": "def reverseList(head):\n prev = None\n curr = head\n while curr:\n nxt = curr.next\n curr.next = prev\n prev = curr\n curr = nxt\n return prev", "solution_java": "public ListNode reverseList(ListNode head) {\n ListNode prev = null, curr = head;\n while (curr != null) {\n ListNode next = curr.next;\n curr.next = prev;\n prev = curr;\n curr = next;\n }\n return prev;\n}", "solution_cpp": "ListNode* reverseList(ListNode* head) {\n ListNode* prev = nullptr, *curr = head;\n while (curr) {\n ListNode* next = curr->next;\n curr->next = prev;\n prev = curr;\n curr = next;\n }\n return prev;\n}", "test_cases": ["head=[1,2,3,4,5] -> [5,4,3,2,1]", "head=[1,2] -> [2,1]"], "key_points": ["迭代法 O(1)空间", "递归法 O(n)空间"], "tags": ["linkedlist", "medium", "Google", "Microsoft"]} {"problem_id": "algo_00307", "original_id": "middle-node", "title": "链表的中间结点", "category": "linkedlist", "difficulty": "easy", "companies": ["Amazon", "Facebook"], "description": "给你单链表的头节点 head,请你找出并返回链表的中间结点。如果有两个中间结点,则返回第二个中间结点。", "solution_python": "def middleNode(head):\n slow = fast = head\n while fast and fast.next:\n slow = slow.next\n fast = fast.next.next\n return slow", "solution_java": "public ListNode middleNode(ListNode head) {\n ListNode slow = head, fast = head;\n while (fast != null && fast.next != null) {\n slow = slow.next;\n fast = fast.next.next;\n }\n return slow;\n}", "solution_cpp": "ListNode* middleNode(ListNode* head) {\n ListNode* slow = head, *fast = head;\n while (fast && fast->next) { slow = slow->next; fast = fast->next->next; }\n return slow;\n}", "test_cases": ["head=[1,2,3,4,5] -> 3", "head=[1,2,3,4,5,6] -> 4"], "key_points": ["快慢指针", "O(n)时间O(1)空间"], "tags": ["linkedlist", "easy", "Amazon", "Facebook"]} {"problem_id": "algo_00308", "original_id": "max-depth", "title": "二叉树的最大深度", "category": "tree", "difficulty": "easy", "companies": ["Microsoft", "Apple"], "description": "给定一个二叉树 root,返回其最大深度。", "solution_python": "def maxDepth(root):\n if not root: return 0\n return max(maxDepth(root.left), maxDepth(root.right)) + 1", "solution_java": "public int maxDepth(TreeNode root) {\n if (root == null) return 0;\n return Math.max(maxDepth(root.left), maxDepth(root.right)) + 1;\n}", "solution_cpp": "int maxDepth(TreeNode* root) {\n if (!root) return 0;\n return max(maxDepth(root->left), maxDepth(root->right)) + 1;\n}", "test_cases": ["root=[3,9,20,null,null,15,7] -> 3", "root=[1,null,2] -> 2"], "key_points": ["DFS递归", "层序遍历也可"], "tags": ["tree", "easy", "Microsoft", "Apple"]} {"problem_id": "algo_00309", "original_id": "inorder-traversal", "title": "二叉树的中序遍历", "category": "tree", "difficulty": "easy", "companies": ["Google", "Microsoft"], "description": "给定一个二叉树的根节点 root,返回它的中序遍历结果。", "solution_python": "def inorderTraversal(root):\n result = []\n def dfs(node):\n if node:\n dfs(node.left)\n result.append(node.val)\n dfs(node.right)\n dfs(root)\n return result", "solution_java": "public List inorderTraversal(TreeNode root) {\n List res = new ArrayList<>();\n dfs(root, res);\n return res;\n}\nprivate void dfs(TreeNode node, List res) {\n if (node == null) return;\n dfs(node.left, res); res.add(node.val); dfs(node.right, res);\n}", "solution_cpp": "vector inorderTraversal(TreeNode* root) {\n vector res;\n dfs(root, res);\n return res;\n}\nvoid dfs(TreeNode* node, vector& res) {\n if (!node) return;\n dfs(node->left, res); res.push_back(node->val); dfs(node->right, res);\n}", "test_cases": ["root=[1,null,2,3] -> [1,3,2]", "root=[] -> []"], "key_points": ["左-根-右顺序", "递归最简洁"], "tags": ["tree", "easy", "Google", "Microsoft"]} {"problem_id": "algo_00310", "original_id": "binary-search", "title": "二分查找", "category": "binarysearch", "difficulty": "easy", "companies": ["Google", "Amazon"], "description": "给定一个 n 个元素有序的(升序)整型数组 nums 和一个目标值 target,写一个函数搜索 nums 中的 target,如果目标值存在返回下标,否则返回 -1。", "solution_python": "def search(nums, target):\n left, right = 0, len(nums) - 1\n while left <= right:\n mid = (left + right) // 2\n if nums[mid] == target: return mid\n elif nums[mid] < target: left = mid + 1\n else: right = mid - 1\n return -1", "solution_java": "public int search(int[] nums, int target) {\n int left = 0, right = nums.length - 1;\n while (left <= right) {\n int mid = left + (right - left) / 2;\n if (nums[mid] == target) return mid;\n else if (nums[mid] < target) left = mid + 1;\n else right = mid - 1;\n }\n return -1;\n}", "solution_cpp": "int search(vector& nums, int target) {\n int left = 0, right = nums.size() - 1;\n while (left <= right) {\n int mid = left + (right - left) / 2;\n if (nums[mid] == target) return mid;\n else if (nums[mid] < target) left = mid + 1;\n else right = mid - 1;\n }\n return -1;\n}", "test_cases": ["nums=[-1,0,3,5,9,12], target=9 -> 4", "nums=[-1,0,3,5,9,12], target=2 -> -1"], "key_points": ["标准模板", "注意防溢出写法"], "tags": ["binarysearch", "easy", "Google", "Amazon"]} {"problem_id": "algo_00311", "original_id": "climbing-stairs", "title": "爬楼梯", "category": "dp", "difficulty": "easy", "companies": ["Amazon", "Google"], "description": "假设你正在爬楼梯。需要 n 阶你才能到达楼顶。每次你可以爬 1 或 2 个台阶。你有多少种不同的方法可以爬到楼顶?", "solution_python": "def climbStairs(n):\n if n <= 2: return n\n a, b = 1, 2\n for _ in range(3, n+1):\n a, b = b, a + b\n return b", "solution_java": "public int climbStairs(int n) {\n if (n <= 2) return n;\n int a = 1, b = 2;\n for (int i = 3; i <= n; i++) { int temp = a + b; a = b; b = temp; }\n return b;\n}", "solution_cpp": "int climbStairs(int n) {\n if (n <= 2) return n;\n int a = 1, b = 2;\n for (int i = 3; i <= n; i++) { int temp = a + b; a = b; b = temp; }\n return b;\n}", "test_cases": ["n=2 -> 2", "n=3 -> 3", "n=5 -> 8"], "key_points": ["斐波那契数列", "滚动数组优化空间"], "tags": ["dp", "easy", "Amazon", "Google"]} {"problem_id": "algo_00312", "original_id": "coin-change", "title": "零钱兑换", "category": "dp", "difficulty": "medium", "companies": ["Google", "Amazon"], "description": "给你一个整数数组 coins 表示不同面额的硬币,以及一个整数 amount 表示总金额。计算并返回可以凑成总金额所需的最少的硬币个数。如果没有任何一种硬币组合能组成总金额,返回 -1。", "solution_python": "def coinChange(coins, amount):\n dp = [float('inf')] * (amount + 1)\n dp[0] = 0\n for coin in coins:\n for x in range(coin, amount + 1):\n dp[x] = min(dp[x], dp[x - coin] + 1)\n return dp[amount] if dp[amount] != float('inf') else -1", "solution_java": "public int coinChange(int[] coins, int amount) {\n int[] dp = new int[amount + 1];\n Arrays.fill(dp, amount + 1);\n dp[0] = 0;\n for (int coin : coins) {\n for (int x = coin; x <= amount; x++) {\n dp[x] = Math.min(dp[x], dp[x - coin] + 1);\n }\n }\n return dp[amount] > amount ? -1 : dp[amount];\n}", "solution_cpp": "int coinChange(vector& coins, int amount) {\n vector dp(amount + 1, amount + 1);\n dp[0] = 0;\n for (int coin : coins) {\n for (int x = coin; x <= amount; x++) {\n dp[x] = min(dp[x], dp[x - coin] + 1);\n }\n }\n return dp[amount] > amount ? -1 : dp[amount];\n}", "test_cases": ["coins=[1,2,5], amount=11 -> 3", "coins=[2], amount=3 -> -1"], "key_points": ["完全背包问题", "dp[x] = min(dp[x-coin]+1)"], "tags": ["dp", "medium", "Google", "Amazon"]} {"problem_id": "algo_00313", "original_id": "subsets", "title": "子集", "category": "backtracking", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "给你一个整数数组 nums ,数组中的元素 互不相同 。返回该数组所有可能的子集(幂集)。", "solution_python": "def subsets(nums):\n result = []\n def backtrack(start, path):\n result.append(path[:])\n for i in range(start, len(nums)):\n path.append(nums[i])\n backtrack(i + 1, path)\n path.pop()\n backtrack(0, [])\n return result", "solution_java": "public List> subsets(int[] nums) {\n List> result = new ArrayList<>();\n backtrack(nums, 0, new ArrayList<>(), result);\n return result;\n}\nprivate void backtrack(int[] nums, int start, List path, List> result) {\n result.add(new ArrayList<>(path));\n for (int i = start; i < nums.length; i++) {\n path.add(nums[i]);\n backtrack(nums, i + 1, path, result);\n path.remove(path.size() - 1);\n }\n}", "solution_cpp": "vector> subsets(vector& nums) {\n vector> result;\n vector path;\n backtrack(nums, 0, path, result);\n return result;\n}\nvoid backtrack(vector& nums, int start, vector& path, vector>& result) {\n result.push_back(path);\n for (int i = start; i < nums.size(); i++) {\n path.push_back(nums[i]);\n backtrack(nums, i + 1, path, result);\n path.pop_back();\n }\n}", "test_cases": ["nums=[1,2,3] -> [[],[1],[2],[1,2],[3],[1,3],[2,3],[1,2,3]]"], "key_points": ["选或不选", "DFS遍历子集树"], "tags": ["backtracking", "medium", "Google", "Microsoft"]} {"problem_id": "algo_00314", "original_id": "permutations", "title": "全排列", "category": "backtracking", "difficulty": "medium", "companies": ["Google", "Facebook"], "description": "给定一个不含重复数字的数组 nums,返回其所有可能的全排列。", "solution_python": "def permute(nums):\n result = []\n def backtrack(path, used):\n if len(path) == len(nums):\n result.append(path[:])\n return\n for i in range(len(nums)):\n if used[i]: continue\n used[i] = True\n path.append(nums[i])\n backtrack(path, used)\n path.pop()\n used[i] = False\n backtrack([], [False]*len(nums))\n return result", "solution_java": "public List> permute(int[] nums) {\n List> result = new ArrayList<>();\n boolean[] used = new boolean[nums.length];\n backtrack(nums, used, new ArrayList<>(), result);\n return result;\n}\nprivate void backtrack(int[] nums, boolean[] used, List path, List> result) {\n if (path.size() == nums.length) { result.add(new ArrayList<>(path)); return; }\n for (int i = 0; i < nums.length; i++) {\n if (used[i]) continue;\n used[i] = true;\n path.add(nums[i]);\n backtrack(nums, used, path, result);\n path.remove(path.size() - 1);\n used[i] = false;\n }\n}", "solution_cpp": "vector> permute(vector& nums) {\n vector> result;\n vector used(nums.size(), false);\n vector path;\n backtrack(nums, used, path, result);\n return result;\n}\nvoid backtrack(vector& nums, vector& used, vector& path, vector>& result) {\n if (path.size() == nums.size()) { result.push_back(path); return; }\n for (int i = 0; i < nums.size(); i++) {\n if (used[i]) continue;\n used[i] = true;\n path.push_back(nums[i]);\n backtrack(nums, used, path, result);\n path.pop_back();\n used[i] = false;\n }\n}", "test_cases": ["nums=[1,2,3] -> [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]"], "key_points": ["标记已使用元素", "回溯经典模板"], "tags": ["backtracking", "medium", "Google", "Facebook"]} {"problem_id": "algo_00315", "original_id": "top-k-frequent", "title": "前K个高频元素", "category": "heap", "difficulty": "medium", "companies": ["Amazon", "Facebook"], "description": "给你一个整数数组 nums 和一个整数 k,请你返回其中出现频率前 k 高的元素。", "solution_python": "import heapq\nfrom collections import Counter\ndef topKFrequent(nums, k):\n count = Counter(nums)\n heap = []\n for num, freq in count.items():\n heapq.heappush(heap, (freq, num))\n if len(heap) > k: heapq.heappop(heap)\n return [num for freq, num in heap]", "solution_java": "public int[] topKFrequent(int[] nums, int k) {\n Map count = new HashMap<>();\n for (int n : nums) count.put(n, count.getOrDefault(n, 0) + 1);\n PriorityQueue> heap = \n new PriorityQueue<>((a, b) -> a.getValue() - b.getValue());\n for (Map.Entry e : count.entrySet()) {\n heap.offer(e);\n if (heap.size() > k) heap.poll();\n }\n int[] res = new int[k];\n for (int i = k - 1; i >= 0; i--) res[i] = heap.poll().getKey();\n return res;\n}", "solution_cpp": "vector topKFrequent(vector& nums, int k) {\n unordered_map count;\n for (int n : nums) count[n]++;\n priority_queue, vector>, greater>> heap;\n for (auto& [num, freq] : count) {\n heap.push({freq, num});\n if (heap.size() > k) heap.pop();\n }\n vector res;\n while (!heap.empty()) { res.push_back(heap.top().second); heap.pop(); }\n reverse(res.begin(), res.end());\n return res;\n}", "test_cases": ["nums=[1,1,1,2,2,3], k=2 -> [1,2]", "nums=[1], k=1 -> [1]"], "key_points": ["小顶堆保持大小k", "时间复杂度O(nlogk)"], "tags": ["heap", "medium", "Amazon", "Facebook"]} {"problem_id": "algo_00316", "original_id": "3sum", "title": "三数之和", "category": "two-pointers", "difficulty": "medium", "companies": ["Google", "Amazon"], "description": "给你一个整数数组 nums,判断是否存在三元组满足和为0,返回所有不重复的三元组。", "solution_python": "def threeSum(nums):\n nums.sort()\n result = []\n for i in range(len(nums) - 2):\n if i > 0 and nums[i] == nums[i-1]: continue\n left, right = i + 1, len(nums) - 1\n while left < right:\n total = nums[i] + nums[left] + nums[right]\n if total < 0: left += 1\n elif total > 0: right -= 1\n else:\n result.append([nums[i], nums[left], nums[right]])\n while left < right and nums[left] == nums[left+1]: left += 1\n while left < right and nums[right] == nums[right-1]: right -= 1\n left += 1; right -= 1\n return result", "solution_java": "public List> threeSum(int[] nums) {\n Arrays.sort(nums);\n List> result = new ArrayList<>();\n for (int i = 0; i < nums.length - 2; i++) {\n if (i > 0 && nums[i] == nums[i-1]) continue;\n int left = i + 1, right = nums.length - 1;\n while (left < right) {\n int total = nums[i] + nums[left] + nums[right];\n if (total < 0) left++;\n else if (total > 0) right--;\n else {\n result.add(Arrays.asList(nums[i], nums[left], nums[right]));\n while (left < right && nums[left] == nums[left+1]) left++;\n while (left < right && nums[right] == nums[right-1]) right--;\n left++; right--;\n }\n }\n }\n return result;\n}", "solution_cpp": "vector> threeSum(vector& nums) {\n sort(nums.begin(), nums.end());\n vector> result;\n for (int i = 0; i < nums.size() - 2; i++) {\n if (i > 0 && nums[i] == nums[i-1]) continue;\n int left = i + 1, right = nums.size() - 1;\n while (left < right) {\n int total = nums[i] + nums[left] + nums[right];\n if (total < 0) left++;\n else if (total > 0) right--;\n else {\n result.push_back({nums[i], nums[left], nums[right]});\n while (left < right && nums[left] == nums[left+1]) left++;\n while (left < right && nums[right] == nums[right-1]) right--;\n left++; right--;\n }\n }\n }\n return result;\n}", "test_cases": ["nums=[-1,0,1,2,-1,-4] -> [[-1,-1,2],[-1,0,1]]"], "key_points": ["排序+双指针", "去重是关键"], "tags": ["two-pointers", "medium", "Google", "Amazon"]} {"problem_id": "algo_00317", "original_id": "container-water", "title": "盛最多水的容器", "category": "two-pointers", "difficulty": "medium", "companies": ["Google", "Uber"], "description": "给定一个长度为 n 的整数数组 height,找出其中的两条线,使得它们与 x 轴共同构成的容器可以容纳最多的水。", "solution_python": "def maxArea(height):\n left, right = 0, len(height) - 1\n max_area = 0\n while left < right:\n h = min(height[left], height[right])\n max_area = max(max_area, h * (right - left))\n if height[left] < height[right]: left += 1\n else: right -= 1\n return max_area", "solution_java": "public int maxArea(int[] height) {\n int left = 0, right = height.length - 1, maxArea = 0;\n while (left < right) {\n int h = Math.min(height[left], height[right]);\n maxArea = Math.max(maxArea, h * (right - left));\n if (height[left] < height[right]) left++;\n else right--;\n }\n return maxArea;\n}", "solution_cpp": "int maxArea(vector& height) {\n int left = 0, right = height.size() - 1, maxArea = 0;\n while (left < right) {\n int h = min(height[left], height[right]);\n maxArea = max(maxArea, h * (right - left));\n if (height[left] < height[right]) left++;\n else right--;\n }\n return maxArea;\n}", "test_cases": ["height=[1,8,6,2,5,4,8,3,7] -> 49"], "key_points": ["移动短边指针", "面积=min(h1,h2)*width"], "tags": ["two-pointers", "medium", "Google", "Uber"]} {"problem_id": "algo_00318", "original_id": "min-stack", "title": "最小栈", "category": "stack", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "设计一个支持 push,pop,top 操作,并能在常数时间内检索到最小元素的栈。", "solution_python": "class MinStack:\n def __init__(self):\n self.stack = []\n self.min_stack = []\n def push(self, val):\n self.stack.append(val)\n self.min_stack.append(min(val, self.min_stack[-1] if self.min_stack else val))\n def pop(self):\n self.stack.pop(); self.min_stack.pop()\n def top(self): return self.stack[-1]\n def getMin(self): return self.min_stack[-1]", "solution_java": "class MinStack {\n Stack stack = new Stack<>();\n Stack minStack = new Stack<>();\n public void push(int val) { stack.push(val); minStack.push(Math.min(val, minStack.isEmpty() ? val : minStack.peek())); }\n public void pop() { stack.pop(); minStack.pop(); }\n public int top() { return stack.peek(); }\n public int getMin() { return minStack.peek(); }\n}", "solution_cpp": "class MinStack {\n stack st, minSt;\npublic:\n void push(int val) { st.push(val); minSt.push(min(val, minSt.empty() ? val : minSt.top())); }\n void pop() { st.pop(); minSt.pop(); }\n int top() { return st.top(); }\n int getMin() { return minSt.top(); }\n};", "test_cases": ["push(-2), push(0), push(-3) -> getMin() returns -3"], "key_points": ["辅助栈记录最小值", "O(1)时间获取最小值"], "tags": ["stack", "medium", "Google", "Microsoft"]} {"problem_id": "algo_00319", "original_id": "lru-cache", "title": "LRU缓存", "category": "design", "difficulty": "hard", "companies": ["Google", "Amazon"], "description": "设计和实现一个 LRU(最近最少使用)缓存机制。", "solution_python": "class LRUCache:\n def __init__(self, capacity):\n self.capacity = capacity\n self.cache = {}\n self.order = []\n def get(self, key):\n if key not in self.cache: return -1\n self.order.remove(key); self.order.append(key)\n return self.cache[key]\n def put(self, key, value):\n if key in self.cache:\n self.order.remove(key)\n elif len(self.cache) >= self.capacity:\n del self.cache[self.order.pop(0)]\n self.cache[key] = value; self.order.append(key)", "solution_java": "class LRUCache {\n int capacity;\n LinkedHashMap cache = new LinkedHashMap<>();\n public LRUCache(int cap) { capacity = cap; }\n public int get(int key) { return cache.containsKey(key) ? cache.remove(key) : -1; }\n public void put(int key, int val) {\n if (cache.containsKey(key)) cache.remove(key);\n else if (cache.size() >= capacity) cache.remove(cache.keySet().iterator().next());\n cache.put(key, val);\n }\n}", "solution_cpp": "class LRUCache {\n int cap;\n list> dll;\n unordered_map>::iterator> cache;\npublic:\n LRUCache(int capacity) : cap(capacity) {}\n int get(int key) {\n auto it = cache.find(key);\n if (it == cache.end()) return -1;\n dll.splice(dll.end(), dll, it->second);\n return it->second->second;\n }\n void put(int key, int value) {\n auto it = cache.find(key);\n if (it != cache.end()) dll.erase(it->second);\n else if (cache.size() >= cap) { cache.erase(dll.front().first); dll.pop_front(); }\n dll.push_back({key, value});\n cache[key] = --dll.end();\n }\n};", "test_cases": ["put(1,1), put(2,2), get(1) -> 1"], "key_points": ["HashMap + 双向链表", "O(1)时间操作"], "tags": ["design", "hard", "Google", "Amazon"]} {"problem_id": "algo_00320", "original_id": "num-islands", "title": "岛屿数量", "category": "graph", "difficulty": "medium", "companies": ["Google", "Facebook"], "description": "给你一个由 '1'(陆地)和 '0'(水)组成的二维网格,请你计算网格中岛屿的数量。岛屿总是被水包围,且只能由水平或垂直方向相邻的陆地连接形成。", "solution_python": "def numIslands(grid):\n if not grid: return 0\n rows, cols = len(grid), len(grid[0])\n count = 0\n def dfs(r, c):\n if r < 0 or r >= rows or c < 0 or c >= cols or grid[r][c] != '1': return\n grid[r][c] = '0'\n dfs(r+1, c); dfs(r-1, c); dfs(r, c+1); dfs(r, c-1)\n for r in range(rows):\n for c in range(cols):\n if grid[r][c] == '1': count += 1; dfs(r, c)\n return count", "solution_java": "public int numIslands(char[][] grid) {\n if (grid.length == 0) return 0;\n int count = 0;\n for (int i = 0; i < grid.length; i++)\n for (int j = 0; j < grid[0].length; j++)\n if (grid[i][j] == '1') { count++; dfs(grid, i, j); }\n return count;\n}\nprivate void dfs(char[][] grid, int r, int c) {\n if (r < 0 || r >= grid.length || c < 0 || c >= grid[0].length || grid[r][c] != '1') return;\n grid[r][c] = '0';\n dfs(grid, r+1, c); dfs(grid, r-1, c); dfs(grid, r, c+1); dfs(grid, r, c-1);\n}", "solution_cpp": "int numIslands(vector>& grid) {\n if (grid.empty()) return 0;\n int count = 0;\n for (int i = 0; i < grid.size(); i++)\n for (int j = 0; j < grid[0].size(); j++)\n if (grid[i][j] == '1') { count++; dfs(grid, i, j); }\n return count;\n}\nvoid dfs(vector>& grid, int r, int c) {\n if (r < 0 || r >= grid.size() || c < 0 || c >= grid[0].size() || grid[r][c] != '1') return;\n grid[r][c] = '0';\n dfs(grid, r+1, c); dfs(grid, r-1, c); dfs(grid, r, c+1); dfs(grid, r, c-1);\n}", "test_cases": ["grid=[[1,1,1,1,0],[1,1,0,1,0],[1,1,0,0,0],[0,0,0,0,0]] -> 1"], "key_points": ["DFS/BFS遍历", "访问后标记为0避免重复"], "tags": ["graph", "medium", "Google", "Facebook"]} {"problem_id": "algo_00321", "original_id": "two-sum", "title": "两数之和", "category": "array", "difficulty": "easy", "companies": ["Amazon", "Google"], "description": "给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那两个整数,并返回他们的数组下标。", "solution_python": "def twoSum(nums, target):\n hashmap = {}\n for i, num in enumerate(nums):\n complement = target - num\n if complement in hashmap:\n return [hashmap[complement], i]\n hashmap[num] = i\n return []", "solution_java": "public int[] twoSum(int[] nums, int target) {\n Map map = new HashMap<>();\n for (int i = 0; i < nums.length; i++) {\n int complement = target - nums[i];\n if (map.containsKey(complement)) return new int[]{map.get(complement), i};\n map.put(nums[i], i);\n }\n return new int[]{};\n}", "solution_cpp": "vector twoSum(vector& nums, int target) {\n unordered_map m;\n for (int i = 0; i < nums.size(); i++) {\n if (m.count(target - nums[i])) return {m[target - nums[i]], i};\n m[nums[i]] = i;\n }\n return {};\n}", "test_cases": ["nums=[2,7,11,15], target=9 -> [0,1]", "nums=[3,2,4], target=6 -> [1,2]"], "key_points": ["哈希表一次遍历", "空间换时间"], "tags": ["array", "easy", "Amazon", "Google"]} {"problem_id": "algo_00322", "original_id": "merge-sorted", "title": "合并两个有序数组", "category": "array", "difficulty": "easy", "companies": ["Microsoft", "Uber"], "description": "给你两个按非递减顺序排列的整数数组 nums1 和 nums2,另有两个整数 m 和 n,分别表示 nums1 和 nums2 中的元素数目。请你合并 nums2 到 nums1 中。", "solution_python": "def merge(nums1, m, nums2, n):\n p1, p2, p = m-1, n-1, m+n-1\n while p1 >= 0 and p2 >= 0:\n if nums1[p1] > nums2[p2]: nums1[p] = nums1[p1]; p1 -= 1\n else: nums1[p] = nums2[p2]; p2 -= 1\n p -= 1\n while p2 >= 0: nums1[p] = nums2[p2]; p2 -= 1; p -= 1", "solution_java": "public void merge(int[] nums1, int m, int[] nums2, int n) {\n int p1 = m-1, p2 = n-1, p = m+n-1;\n while (p1 >= 0 && p2 >= 0) {\n nums1[p--] = nums1[p1] > nums2[p2] ? nums1[p1--] : nums2[p2--];\n }\n while (p2 >= 0) nums1[p--] = nums2[p2--];\n}", "solution_cpp": "void merge(vector& nums1, int m, vector& nums2, int n) {\n int p1 = m-1, p2 = n-1, p = m+n-1;\n while (p1 >= 0 && p2 >= 0) nums1[p--] = nums1[p1] > nums2[p2] ? nums1[p1--] : nums2[p2--];\n while (p2 >= 0) nums1[p--] = nums2[p2--];\n}", "test_cases": ["nums1=[1,2,3], m=3, nums2=[2,5,6], n=3 -> [1,2,2,3,5,6]", "nums1=[], m=0, nums2=[1], n=1 -> [1]"], "key_points": ["从后往前合并", "三指针技巧"], "tags": ["array", "easy", "Microsoft", "Uber"]} {"problem_id": "algo_00323", "original_id": "max-subarray", "title": "最大子数组和", "category": "array", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "给你一个整数数组 nums ,请你找出一个具有最大和的连续子数组,返回其最大和。", "solution_python": "def maxSubArray(nums):\n max_sum = current = nums[0]\n for num in nums[1:]:\n current = max(num, current + num)\n max_sum = max(max_sum, current)\n return max_sum", "solution_java": "public int maxSubArray(int[] nums) {\n int maxSum = nums[0], curr = nums[0];\n for (int i = 1; i < nums.length; i++) {\n curr = Math.max(nums[i], curr + nums[i]);\n maxSum = Math.max(maxSum, curr);\n }\n return maxSum;\n}", "solution_cpp": "int maxSubArray(vector& nums) {\n int maxSum = nums[0], curr = nums[0];\n for (int i = 1; i < nums.size(); i++) {\n curr = max(nums[i], curr + nums[i]);\n maxSum = max(maxSum, curr);\n }\n return maxSum;\n}", "test_cases": ["nums=[-2,1,-3,4,-1,2,1,-5,4] -> 6", "nums=[1] -> 1"], "key_points": ["Kadane算法", "动态规划基础题"], "tags": ["array", "medium", "Google", "Microsoft"]} {"problem_id": "algo_00324", "original_id": "valid-parentheses", "title": "有效的括号", "category": "string", "difficulty": "easy", "companies": ["Google", "Uber"], "description": "给定一个只包括 '(',')','{','}','[',']' 的字符串 s,判断字符串是否有效。", "solution_python": "def isValid(s):\n stack = []\n mapping = {')': '(', ']': '[', '}': '{'}\n for c in s:\n if c in mapping:\n if not stack or stack[-1] != mapping[c]: return False\n stack.pop()\n else: stack.append(c)\n return not stack", "solution_java": "public boolean isValid(String s) {\n Stack stack = new Stack<>();\n Map map = Map.of(')', '(', ']', '[', '}', '{');\n for (char c : s.toCharArray()) {\n if (map.containsValue(c)) stack.push(c);\n else if (!stack.isEmpty() && stack.pop() != map.get(c)) return false;\n }\n return stack.isEmpty();\n}", "solution_cpp": "bool isValid(string s) {\n stack st;\n unordered_map m = {{')','('},{']','['},{'}','{'}};\n for (char c : s) {\n if (m.find(c) == m.end()) st.push(c);\n else if (st.empty() || st.top() != m[c]) return false;\n else st.pop();\n }\n return st.empty();\n}", "test_cases": ["s=\"()\" -> true", "s=\"()[]{}\" -> true", "s=\"(]\" -> false"], "key_points": ["栈匹配法", "注意空栈边界"], "tags": ["string", "easy", "Google", "Uber"]} {"problem_id": "algo_00325", "original_id": "longest-palindrome", "title": "最长回文子串", "category": "string", "difficulty": "medium", "companies": ["Google", "Amazon"], "description": "给你一个字符串 s,找到 s 中最长的回文子串。", "solution_python": "def longestPalindrome(s):\n def expand(l, r):\n while l >= 0 and r < len(s) and s[l] == s[r]: l -= 1; r += 1\n return l + 1, r - 1\n start = end = 0\n for i in range(len(s)):\n l1, r1 = expand(i, i)\n l2, r2 = expand(i, i + 1)\n if r1 - l1 > end - start: start, end = l1, r1\n if r2 - l2 > end - start: start, end = l2, r2\n return s[start:end+1]", "solution_java": "public String longestPalindrome(String s) {\n int start = 0, end = 0;\n for (int i = 0; i < s.length(); i++) {\n int len1 = expand(s, i, i), len2 = expand(s, i, i+1);\n int len = Math.max(len1, len2);\n if (len > end - start) { start = i - (len-1)/2; end = i + len/2; }\n }\n return s.substring(start, end + 1);\n}\nprivate int expand(String s, int l, int r) {\n while (l >= 0 && r < s.length() && s.charAt(l) == s.charAt(r)) { l--; r++; }\n return r - l - 1;\n}", "solution_cpp": "string longestPalindrome(string s) {\n int start = 0, end = 0;\n for (int i = 0; i < s.size(); i++) {\n int len1 = expand(s, i, i), len2 = expand(s, i, i+1);\n if (max(len1, len2) > end - start) { start = i - (max(len1,len2)-1)/2; end = i + max(len1,len2)/2; }\n }\n return s.substr(start, end - start + 1);\n}", "test_cases": ["s=\"babad\" -> bab或aba", "s=\"cbbd\" -> bb"], "key_points": ["中心扩展法", "处理奇偶长度"], "tags": ["string", "medium", "Google", "Amazon"]} {"problem_id": "algo_00326", "original_id": "reverse-list", "title": "反转链表", "category": "linkedlist", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "给你单链表的头节点 head,请你反转链表,并返回反转后的链表。", "solution_python": "def reverseList(head):\n prev = None\n curr = head\n while curr:\n nxt = curr.next\n curr.next = prev\n prev = curr\n curr = nxt\n return prev", "solution_java": "public ListNode reverseList(ListNode head) {\n ListNode prev = null, curr = head;\n while (curr != null) {\n ListNode next = curr.next;\n curr.next = prev;\n prev = curr;\n curr = next;\n }\n return prev;\n}", "solution_cpp": "ListNode* reverseList(ListNode* head) {\n ListNode* prev = nullptr, *curr = head;\n while (curr) {\n ListNode* next = curr->next;\n curr->next = prev;\n prev = curr;\n curr = next;\n }\n return prev;\n}", "test_cases": ["head=[1,2,3,4,5] -> [5,4,3,2,1]", "head=[1,2] -> [2,1]"], "key_points": ["迭代法 O(1)空间", "递归法 O(n)空间"], "tags": ["linkedlist", "medium", "Google", "Microsoft"]} {"problem_id": "algo_00327", "original_id": "middle-node", "title": "链表的中间结点", "category": "linkedlist", "difficulty": "easy", "companies": ["Amazon", "Facebook"], "description": "给你单链表的头节点 head,请你找出并返回链表的中间结点。如果有两个中间结点,则返回第二个中间结点。", "solution_python": "def middleNode(head):\n slow = fast = head\n while fast and fast.next:\n slow = slow.next\n fast = fast.next.next\n return slow", "solution_java": "public ListNode middleNode(ListNode head) {\n ListNode slow = head, fast = head;\n while (fast != null && fast.next != null) {\n slow = slow.next;\n fast = fast.next.next;\n }\n return slow;\n}", "solution_cpp": "ListNode* middleNode(ListNode* head) {\n ListNode* slow = head, *fast = head;\n while (fast && fast->next) { slow = slow->next; fast = fast->next->next; }\n return slow;\n}", "test_cases": ["head=[1,2,3,4,5] -> 3", "head=[1,2,3,4,5,6] -> 4"], "key_points": ["快慢指针", "O(n)时间O(1)空间"], "tags": ["linkedlist", "easy", "Amazon", "Facebook"]} {"problem_id": "algo_00328", "original_id": "max-depth", "title": "二叉树的最大深度", "category": "tree", "difficulty": "easy", "companies": ["Microsoft", "Apple"], "description": "给定一个二叉树 root,返回其最大深度。", "solution_python": "def maxDepth(root):\n if not root: return 0\n return max(maxDepth(root.left), maxDepth(root.right)) + 1", "solution_java": "public int maxDepth(TreeNode root) {\n if (root == null) return 0;\n return Math.max(maxDepth(root.left), maxDepth(root.right)) + 1;\n}", "solution_cpp": "int maxDepth(TreeNode* root) {\n if (!root) return 0;\n return max(maxDepth(root->left), maxDepth(root->right)) + 1;\n}", "test_cases": ["root=[3,9,20,null,null,15,7] -> 3", "root=[1,null,2] -> 2"], "key_points": ["DFS递归", "层序遍历也可"], "tags": ["tree", "easy", "Microsoft", "Apple"]} {"problem_id": "algo_00329", "original_id": "inorder-traversal", "title": "二叉树的中序遍历", "category": "tree", "difficulty": "easy", "companies": ["Google", "Microsoft"], "description": "给定一个二叉树的根节点 root,返回它的中序遍历结果。", "solution_python": "def inorderTraversal(root):\n result = []\n def dfs(node):\n if node:\n dfs(node.left)\n result.append(node.val)\n dfs(node.right)\n dfs(root)\n return result", "solution_java": "public List inorderTraversal(TreeNode root) {\n List res = new ArrayList<>();\n dfs(root, res);\n return res;\n}\nprivate void dfs(TreeNode node, List res) {\n if (node == null) return;\n dfs(node.left, res); res.add(node.val); dfs(node.right, res);\n}", "solution_cpp": "vector inorderTraversal(TreeNode* root) {\n vector res;\n dfs(root, res);\n return res;\n}\nvoid dfs(TreeNode* node, vector& res) {\n if (!node) return;\n dfs(node->left, res); res.push_back(node->val); dfs(node->right, res);\n}", "test_cases": ["root=[1,null,2,3] -> [1,3,2]", "root=[] -> []"], "key_points": ["左-根-右顺序", "递归最简洁"], "tags": ["tree", "easy", "Google", "Microsoft"]} {"problem_id": "algo_00330", "original_id": "binary-search", "title": "二分查找", "category": "binarysearch", "difficulty": "easy", "companies": ["Google", "Amazon"], "description": "给定一个 n 个元素有序的(升序)整型数组 nums 和一个目标值 target,写一个函数搜索 nums 中的 target,如果目标值存在返回下标,否则返回 -1。", "solution_python": "def search(nums, target):\n left, right = 0, len(nums) - 1\n while left <= right:\n mid = (left + right) // 2\n if nums[mid] == target: return mid\n elif nums[mid] < target: left = mid + 1\n else: right = mid - 1\n return -1", "solution_java": "public int search(int[] nums, int target) {\n int left = 0, right = nums.length - 1;\n while (left <= right) {\n int mid = left + (right - left) / 2;\n if (nums[mid] == target) return mid;\n else if (nums[mid] < target) left = mid + 1;\n else right = mid - 1;\n }\n return -1;\n}", "solution_cpp": "int search(vector& nums, int target) {\n int left = 0, right = nums.size() - 1;\n while (left <= right) {\n int mid = left + (right - left) / 2;\n if (nums[mid] == target) return mid;\n else if (nums[mid] < target) left = mid + 1;\n else right = mid - 1;\n }\n return -1;\n}", "test_cases": ["nums=[-1,0,3,5,9,12], target=9 -> 4", "nums=[-1,0,3,5,9,12], target=2 -> -1"], "key_points": ["标准模板", "注意防溢出写法"], "tags": ["binarysearch", "easy", "Google", "Amazon"]} {"problem_id": "algo_00331", "original_id": "climbing-stairs", "title": "爬楼梯", "category": "dp", "difficulty": "easy", "companies": ["Amazon", "Google"], "description": "假设你正在爬楼梯。需要 n 阶你才能到达楼顶。每次你可以爬 1 或 2 个台阶。你有多少种不同的方法可以爬到楼顶?", "solution_python": "def climbStairs(n):\n if n <= 2: return n\n a, b = 1, 2\n for _ in range(3, n+1):\n a, b = b, a + b\n return b", "solution_java": "public int climbStairs(int n) {\n if (n <= 2) return n;\n int a = 1, b = 2;\n for (int i = 3; i <= n; i++) { int temp = a + b; a = b; b = temp; }\n return b;\n}", "solution_cpp": "int climbStairs(int n) {\n if (n <= 2) return n;\n int a = 1, b = 2;\n for (int i = 3; i <= n; i++) { int temp = a + b; a = b; b = temp; }\n return b;\n}", "test_cases": ["n=2 -> 2", "n=3 -> 3", "n=5 -> 8"], "key_points": ["斐波那契数列", "滚动数组优化空间"], "tags": ["dp", "easy", "Amazon", "Google"]} {"problem_id": "algo_00332", "original_id": "coin-change", "title": "零钱兑换", "category": "dp", "difficulty": "medium", "companies": ["Google", "Amazon"], "description": "给你一个整数数组 coins 表示不同面额的硬币,以及一个整数 amount 表示总金额。计算并返回可以凑成总金额所需的最少的硬币个数。如果没有任何一种硬币组合能组成总金额,返回 -1。", "solution_python": "def coinChange(coins, amount):\n dp = [float('inf')] * (amount + 1)\n dp[0] = 0\n for coin in coins:\n for x in range(coin, amount + 1):\n dp[x] = min(dp[x], dp[x - coin] + 1)\n return dp[amount] if dp[amount] != float('inf') else -1", "solution_java": "public int coinChange(int[] coins, int amount) {\n int[] dp = new int[amount + 1];\n Arrays.fill(dp, amount + 1);\n dp[0] = 0;\n for (int coin : coins) {\n for (int x = coin; x <= amount; x++) {\n dp[x] = Math.min(dp[x], dp[x - coin] + 1);\n }\n }\n return dp[amount] > amount ? -1 : dp[amount];\n}", "solution_cpp": "int coinChange(vector& coins, int amount) {\n vector dp(amount + 1, amount + 1);\n dp[0] = 0;\n for (int coin : coins) {\n for (int x = coin; x <= amount; x++) {\n dp[x] = min(dp[x], dp[x - coin] + 1);\n }\n }\n return dp[amount] > amount ? -1 : dp[amount];\n}", "test_cases": ["coins=[1,2,5], amount=11 -> 3", "coins=[2], amount=3 -> -1"], "key_points": ["完全背包问题", "dp[x] = min(dp[x-coin]+1)"], "tags": ["dp", "medium", "Google", "Amazon"]} {"problem_id": "algo_00333", "original_id": "subsets", "title": "子集", "category": "backtracking", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "给你一个整数数组 nums ,数组中的元素 互不相同 。返回该数组所有可能的子集(幂集)。", "solution_python": "def subsets(nums):\n result = []\n def backtrack(start, path):\n result.append(path[:])\n for i in range(start, len(nums)):\n path.append(nums[i])\n backtrack(i + 1, path)\n path.pop()\n backtrack(0, [])\n return result", "solution_java": "public List> subsets(int[] nums) {\n List> result = new ArrayList<>();\n backtrack(nums, 0, new ArrayList<>(), result);\n return result;\n}\nprivate void backtrack(int[] nums, int start, List path, List> result) {\n result.add(new ArrayList<>(path));\n for (int i = start; i < nums.length; i++) {\n path.add(nums[i]);\n backtrack(nums, i + 1, path, result);\n path.remove(path.size() - 1);\n }\n}", "solution_cpp": "vector> subsets(vector& nums) {\n vector> result;\n vector path;\n backtrack(nums, 0, path, result);\n return result;\n}\nvoid backtrack(vector& nums, int start, vector& path, vector>& result) {\n result.push_back(path);\n for (int i = start; i < nums.size(); i++) {\n path.push_back(nums[i]);\n backtrack(nums, i + 1, path, result);\n path.pop_back();\n }\n}", "test_cases": ["nums=[1,2,3] -> [[],[1],[2],[1,2],[3],[1,3],[2,3],[1,2,3]]"], "key_points": ["选或不选", "DFS遍历子集树"], "tags": ["backtracking", "medium", "Google", "Microsoft"]} {"problem_id": "algo_00334", "original_id": "permutations", "title": "全排列", "category": "backtracking", "difficulty": "medium", "companies": ["Google", "Facebook"], "description": "给定一个不含重复数字的数组 nums,返回其所有可能的全排列。", "solution_python": "def permute(nums):\n result = []\n def backtrack(path, used):\n if len(path) == len(nums):\n result.append(path[:])\n return\n for i in range(len(nums)):\n if used[i]: continue\n used[i] = True\n path.append(nums[i])\n backtrack(path, used)\n path.pop()\n used[i] = False\n backtrack([], [False]*len(nums))\n return result", "solution_java": "public List> permute(int[] nums) {\n List> result = new ArrayList<>();\n boolean[] used = new boolean[nums.length];\n backtrack(nums, used, new ArrayList<>(), result);\n return result;\n}\nprivate void backtrack(int[] nums, boolean[] used, List path, List> result) {\n if (path.size() == nums.length) { result.add(new ArrayList<>(path)); return; }\n for (int i = 0; i < nums.length; i++) {\n if (used[i]) continue;\n used[i] = true;\n path.add(nums[i]);\n backtrack(nums, used, path, result);\n path.remove(path.size() - 1);\n used[i] = false;\n }\n}", "solution_cpp": "vector> permute(vector& nums) {\n vector> result;\n vector used(nums.size(), false);\n vector path;\n backtrack(nums, used, path, result);\n return result;\n}\nvoid backtrack(vector& nums, vector& used, vector& path, vector>& result) {\n if (path.size() == nums.size()) { result.push_back(path); return; }\n for (int i = 0; i < nums.size(); i++) {\n if (used[i]) continue;\n used[i] = true;\n path.push_back(nums[i]);\n backtrack(nums, used, path, result);\n path.pop_back();\n used[i] = false;\n }\n}", "test_cases": ["nums=[1,2,3] -> [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]"], "key_points": ["标记已使用元素", "回溯经典模板"], "tags": ["backtracking", "medium", "Google", "Facebook"]} {"problem_id": "algo_00335", "original_id": "top-k-frequent", "title": "前K个高频元素", "category": "heap", "difficulty": "medium", "companies": ["Amazon", "Facebook"], "description": "给你一个整数数组 nums 和一个整数 k,请你返回其中出现频率前 k 高的元素。", "solution_python": "import heapq\nfrom collections import Counter\ndef topKFrequent(nums, k):\n count = Counter(nums)\n heap = []\n for num, freq in count.items():\n heapq.heappush(heap, (freq, num))\n if len(heap) > k: heapq.heappop(heap)\n return [num for freq, num in heap]", "solution_java": "public int[] topKFrequent(int[] nums, int k) {\n Map count = new HashMap<>();\n for (int n : nums) count.put(n, count.getOrDefault(n, 0) + 1);\n PriorityQueue> heap = \n new PriorityQueue<>((a, b) -> a.getValue() - b.getValue());\n for (Map.Entry e : count.entrySet()) {\n heap.offer(e);\n if (heap.size() > k) heap.poll();\n }\n int[] res = new int[k];\n for (int i = k - 1; i >= 0; i--) res[i] = heap.poll().getKey();\n return res;\n}", "solution_cpp": "vector topKFrequent(vector& nums, int k) {\n unordered_map count;\n for (int n : nums) count[n]++;\n priority_queue, vector>, greater>> heap;\n for (auto& [num, freq] : count) {\n heap.push({freq, num});\n if (heap.size() > k) heap.pop();\n }\n vector res;\n while (!heap.empty()) { res.push_back(heap.top().second); heap.pop(); }\n reverse(res.begin(), res.end());\n return res;\n}", "test_cases": ["nums=[1,1,1,2,2,3], k=2 -> [1,2]", "nums=[1], k=1 -> [1]"], "key_points": ["小顶堆保持大小k", "时间复杂度O(nlogk)"], "tags": ["heap", "medium", "Amazon", "Facebook"]} {"problem_id": "algo_00336", "original_id": "3sum", "title": "三数之和", "category": "two-pointers", "difficulty": "medium", "companies": ["Google", "Amazon"], "description": "给你一个整数数组 nums,判断是否存在三元组满足和为0,返回所有不重复的三元组。", "solution_python": "def threeSum(nums):\n nums.sort()\n result = []\n for i in range(len(nums) - 2):\n if i > 0 and nums[i] == nums[i-1]: continue\n left, right = i + 1, len(nums) - 1\n while left < right:\n total = nums[i] + nums[left] + nums[right]\n if total < 0: left += 1\n elif total > 0: right -= 1\n else:\n result.append([nums[i], nums[left], nums[right]])\n while left < right and nums[left] == nums[left+1]: left += 1\n while left < right and nums[right] == nums[right-1]: right -= 1\n left += 1; right -= 1\n return result", "solution_java": "public List> threeSum(int[] nums) {\n Arrays.sort(nums);\n List> result = new ArrayList<>();\n for (int i = 0; i < nums.length - 2; i++) {\n if (i > 0 && nums[i] == nums[i-1]) continue;\n int left = i + 1, right = nums.length - 1;\n while (left < right) {\n int total = nums[i] + nums[left] + nums[right];\n if (total < 0) left++;\n else if (total > 0) right--;\n else {\n result.add(Arrays.asList(nums[i], nums[left], nums[right]));\n while (left < right && nums[left] == nums[left+1]) left++;\n while (left < right && nums[right] == nums[right-1]) right--;\n left++; right--;\n }\n }\n }\n return result;\n}", "solution_cpp": "vector> threeSum(vector& nums) {\n sort(nums.begin(), nums.end());\n vector> result;\n for (int i = 0; i < nums.size() - 2; i++) {\n if (i > 0 && nums[i] == nums[i-1]) continue;\n int left = i + 1, right = nums.size() - 1;\n while (left < right) {\n int total = nums[i] + nums[left] + nums[right];\n if (total < 0) left++;\n else if (total > 0) right--;\n else {\n result.push_back({nums[i], nums[left], nums[right]});\n while (left < right && nums[left] == nums[left+1]) left++;\n while (left < right && nums[right] == nums[right-1]) right--;\n left++; right--;\n }\n }\n }\n return result;\n}", "test_cases": ["nums=[-1,0,1,2,-1,-4] -> [[-1,-1,2],[-1,0,1]]"], "key_points": ["排序+双指针", "去重是关键"], "tags": ["two-pointers", "medium", "Google", "Amazon"]} {"problem_id": "algo_00337", "original_id": "container-water", "title": "盛最多水的容器", "category": "two-pointers", "difficulty": "medium", "companies": ["Google", "Uber"], "description": "给定一个长度为 n 的整数数组 height,找出其中的两条线,使得它们与 x 轴共同构成的容器可以容纳最多的水。", "solution_python": "def maxArea(height):\n left, right = 0, len(height) - 1\n max_area = 0\n while left < right:\n h = min(height[left], height[right])\n max_area = max(max_area, h * (right - left))\n if height[left] < height[right]: left += 1\n else: right -= 1\n return max_area", "solution_java": "public int maxArea(int[] height) {\n int left = 0, right = height.length - 1, maxArea = 0;\n while (left < right) {\n int h = Math.min(height[left], height[right]);\n maxArea = Math.max(maxArea, h * (right - left));\n if (height[left] < height[right]) left++;\n else right--;\n }\n return maxArea;\n}", "solution_cpp": "int maxArea(vector& height) {\n int left = 0, right = height.size() - 1, maxArea = 0;\n while (left < right) {\n int h = min(height[left], height[right]);\n maxArea = max(maxArea, h * (right - left));\n if (height[left] < height[right]) left++;\n else right--;\n }\n return maxArea;\n}", "test_cases": ["height=[1,8,6,2,5,4,8,3,7] -> 49"], "key_points": ["移动短边指针", "面积=min(h1,h2)*width"], "tags": ["two-pointers", "medium", "Google", "Uber"]} {"problem_id": "algo_00338", "original_id": "min-stack", "title": "最小栈", "category": "stack", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "设计一个支持 push,pop,top 操作,并能在常数时间内检索到最小元素的栈。", "solution_python": "class MinStack:\n def __init__(self):\n self.stack = []\n self.min_stack = []\n def push(self, val):\n self.stack.append(val)\n self.min_stack.append(min(val, self.min_stack[-1] if self.min_stack else val))\n def pop(self):\n self.stack.pop(); self.min_stack.pop()\n def top(self): return self.stack[-1]\n def getMin(self): return self.min_stack[-1]", "solution_java": "class MinStack {\n Stack stack = new Stack<>();\n Stack minStack = new Stack<>();\n public void push(int val) { stack.push(val); minStack.push(Math.min(val, minStack.isEmpty() ? val : minStack.peek())); }\n public void pop() { stack.pop(); minStack.pop(); }\n public int top() { return stack.peek(); }\n public int getMin() { return minStack.peek(); }\n}", "solution_cpp": "class MinStack {\n stack st, minSt;\npublic:\n void push(int val) { st.push(val); minSt.push(min(val, minSt.empty() ? val : minSt.top())); }\n void pop() { st.pop(); minSt.pop(); }\n int top() { return st.top(); }\n int getMin() { return minSt.top(); }\n};", "test_cases": ["push(-2), push(0), push(-3) -> getMin() returns -3"], "key_points": ["辅助栈记录最小值", "O(1)时间获取最小值"], "tags": ["stack", "medium", "Google", "Microsoft"]} {"problem_id": "algo_00339", "original_id": "lru-cache", "title": "LRU缓存", "category": "design", "difficulty": "hard", "companies": ["Google", "Amazon"], "description": "设计和实现一个 LRU(最近最少使用)缓存机制。", "solution_python": "class LRUCache:\n def __init__(self, capacity):\n self.capacity = capacity\n self.cache = {}\n self.order = []\n def get(self, key):\n if key not in self.cache: return -1\n self.order.remove(key); self.order.append(key)\n return self.cache[key]\n def put(self, key, value):\n if key in self.cache:\n self.order.remove(key)\n elif len(self.cache) >= self.capacity:\n del self.cache[self.order.pop(0)]\n self.cache[key] = value; self.order.append(key)", "solution_java": "class LRUCache {\n int capacity;\n LinkedHashMap cache = new LinkedHashMap<>();\n public LRUCache(int cap) { capacity = cap; }\n public int get(int key) { return cache.containsKey(key) ? cache.remove(key) : -1; }\n public void put(int key, int val) {\n if (cache.containsKey(key)) cache.remove(key);\n else if (cache.size() >= capacity) cache.remove(cache.keySet().iterator().next());\n cache.put(key, val);\n }\n}", "solution_cpp": "class LRUCache {\n int cap;\n list> dll;\n unordered_map>::iterator> cache;\npublic:\n LRUCache(int capacity) : cap(capacity) {}\n int get(int key) {\n auto it = cache.find(key);\n if (it == cache.end()) return -1;\n dll.splice(dll.end(), dll, it->second);\n return it->second->second;\n }\n void put(int key, int value) {\n auto it = cache.find(key);\n if (it != cache.end()) dll.erase(it->second);\n else if (cache.size() >= cap) { cache.erase(dll.front().first); dll.pop_front(); }\n dll.push_back({key, value});\n cache[key] = --dll.end();\n }\n};", "test_cases": ["put(1,1), put(2,2), get(1) -> 1"], "key_points": ["HashMap + 双向链表", "O(1)时间操作"], "tags": ["design", "hard", "Google", "Amazon"]} {"problem_id": "algo_00340", "original_id": "num-islands", "title": "岛屿数量", "category": "graph", "difficulty": "medium", "companies": ["Google", "Facebook"], "description": "给你一个由 '1'(陆地)和 '0'(水)组成的二维网格,请你计算网格中岛屿的数量。岛屿总是被水包围,且只能由水平或垂直方向相邻的陆地连接形成。", "solution_python": "def numIslands(grid):\n if not grid: return 0\n rows, cols = len(grid), len(grid[0])\n count = 0\n def dfs(r, c):\n if r < 0 or r >= rows or c < 0 or c >= cols or grid[r][c] != '1': return\n grid[r][c] = '0'\n dfs(r+1, c); dfs(r-1, c); dfs(r, c+1); dfs(r, c-1)\n for r in range(rows):\n for c in range(cols):\n if grid[r][c] == '1': count += 1; dfs(r, c)\n return count", "solution_java": "public int numIslands(char[][] grid) {\n if (grid.length == 0) return 0;\n int count = 0;\n for (int i = 0; i < grid.length; i++)\n for (int j = 0; j < grid[0].length; j++)\n if (grid[i][j] == '1') { count++; dfs(grid, i, j); }\n return count;\n}\nprivate void dfs(char[][] grid, int r, int c) {\n if (r < 0 || r >= grid.length || c < 0 || c >= grid[0].length || grid[r][c] != '1') return;\n grid[r][c] = '0';\n dfs(grid, r+1, c); dfs(grid, r-1, c); dfs(grid, r, c+1); dfs(grid, r, c-1);\n}", "solution_cpp": "int numIslands(vector>& grid) {\n if (grid.empty()) return 0;\n int count = 0;\n for (int i = 0; i < grid.size(); i++)\n for (int j = 0; j < grid[0].size(); j++)\n if (grid[i][j] == '1') { count++; dfs(grid, i, j); }\n return count;\n}\nvoid dfs(vector>& grid, int r, int c) {\n if (r < 0 || r >= grid.size() || c < 0 || c >= grid[0].size() || grid[r][c] != '1') return;\n grid[r][c] = '0';\n dfs(grid, r+1, c); dfs(grid, r-1, c); dfs(grid, r, c+1); dfs(grid, r, c-1);\n}", "test_cases": ["grid=[[1,1,1,1,0],[1,1,0,1,0],[1,1,0,0,0],[0,0,0,0,0]] -> 1"], "key_points": ["DFS/BFS遍历", "访问后标记为0避免重复"], "tags": ["graph", "medium", "Google", "Facebook"]} {"problem_id": "algo_00341", "original_id": "two-sum", "title": "两数之和", "category": "array", "difficulty": "easy", "companies": ["Amazon", "Google"], "description": "给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那两个整数,并返回他们的数组下标。", "solution_python": "def twoSum(nums, target):\n hashmap = {}\n for i, num in enumerate(nums):\n complement = target - num\n if complement in hashmap:\n return [hashmap[complement], i]\n hashmap[num] = i\n return []", "solution_java": "public int[] twoSum(int[] nums, int target) {\n Map map = new HashMap<>();\n for (int i = 0; i < nums.length; i++) {\n int complement = target - nums[i];\n if (map.containsKey(complement)) return new int[]{map.get(complement), i};\n map.put(nums[i], i);\n }\n return new int[]{};\n}", "solution_cpp": "vector twoSum(vector& nums, int target) {\n unordered_map m;\n for (int i = 0; i < nums.size(); i++) {\n if (m.count(target - nums[i])) return {m[target - nums[i]], i};\n m[nums[i]] = i;\n }\n return {};\n}", "test_cases": ["nums=[2,7,11,15], target=9 -> [0,1]", "nums=[3,2,4], target=6 -> [1,2]"], "key_points": ["哈希表一次遍历", "空间换时间"], "tags": ["array", "easy", "Amazon", "Google"]} {"problem_id": "algo_00342", "original_id": "merge-sorted", "title": "合并两个有序数组", "category": "array", "difficulty": "easy", "companies": ["Microsoft", "Uber"], "description": "给你两个按非递减顺序排列的整数数组 nums1 和 nums2,另有两个整数 m 和 n,分别表示 nums1 和 nums2 中的元素数目。请你合并 nums2 到 nums1 中。", "solution_python": "def merge(nums1, m, nums2, n):\n p1, p2, p = m-1, n-1, m+n-1\n while p1 >= 0 and p2 >= 0:\n if nums1[p1] > nums2[p2]: nums1[p] = nums1[p1]; p1 -= 1\n else: nums1[p] = nums2[p2]; p2 -= 1\n p -= 1\n while p2 >= 0: nums1[p] = nums2[p2]; p2 -= 1; p -= 1", "solution_java": "public void merge(int[] nums1, int m, int[] nums2, int n) {\n int p1 = m-1, p2 = n-1, p = m+n-1;\n while (p1 >= 0 && p2 >= 0) {\n nums1[p--] = nums1[p1] > nums2[p2] ? nums1[p1--] : nums2[p2--];\n }\n while (p2 >= 0) nums1[p--] = nums2[p2--];\n}", "solution_cpp": "void merge(vector& nums1, int m, vector& nums2, int n) {\n int p1 = m-1, p2 = n-1, p = m+n-1;\n while (p1 >= 0 && p2 >= 0) nums1[p--] = nums1[p1] > nums2[p2] ? nums1[p1--] : nums2[p2--];\n while (p2 >= 0) nums1[p--] = nums2[p2--];\n}", "test_cases": ["nums1=[1,2,3], m=3, nums2=[2,5,6], n=3 -> [1,2,2,3,5,6]", "nums1=[], m=0, nums2=[1], n=1 -> [1]"], "key_points": ["从后往前合并", "三指针技巧"], "tags": ["array", "easy", "Microsoft", "Uber"]} {"problem_id": "algo_00343", "original_id": "max-subarray", "title": "最大子数组和", "category": "array", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "给你一个整数数组 nums ,请你找出一个具有最大和的连续子数组,返回其最大和。", "solution_python": "def maxSubArray(nums):\n max_sum = current = nums[0]\n for num in nums[1:]:\n current = max(num, current + num)\n max_sum = max(max_sum, current)\n return max_sum", "solution_java": "public int maxSubArray(int[] nums) {\n int maxSum = nums[0], curr = nums[0];\n for (int i = 1; i < nums.length; i++) {\n curr = Math.max(nums[i], curr + nums[i]);\n maxSum = Math.max(maxSum, curr);\n }\n return maxSum;\n}", "solution_cpp": "int maxSubArray(vector& nums) {\n int maxSum = nums[0], curr = nums[0];\n for (int i = 1; i < nums.size(); i++) {\n curr = max(nums[i], curr + nums[i]);\n maxSum = max(maxSum, curr);\n }\n return maxSum;\n}", "test_cases": ["nums=[-2,1,-3,4,-1,2,1,-5,4] -> 6", "nums=[1] -> 1"], "key_points": ["Kadane算法", "动态规划基础题"], "tags": ["array", "medium", "Google", "Microsoft"]} {"problem_id": "algo_00344", "original_id": "valid-parentheses", "title": "有效的括号", "category": "string", "difficulty": "easy", "companies": ["Google", "Uber"], "description": "给定一个只包括 '(',')','{','}','[',']' 的字符串 s,判断字符串是否有效。", "solution_python": "def isValid(s):\n stack = []\n mapping = {')': '(', ']': '[', '}': '{'}\n for c in s:\n if c in mapping:\n if not stack or stack[-1] != mapping[c]: return False\n stack.pop()\n else: stack.append(c)\n return not stack", "solution_java": "public boolean isValid(String s) {\n Stack stack = new Stack<>();\n Map map = Map.of(')', '(', ']', '[', '}', '{');\n for (char c : s.toCharArray()) {\n if (map.containsValue(c)) stack.push(c);\n else if (!stack.isEmpty() && stack.pop() != map.get(c)) return false;\n }\n return stack.isEmpty();\n}", "solution_cpp": "bool isValid(string s) {\n stack st;\n unordered_map m = {{')','('},{']','['},{'}','{'}};\n for (char c : s) {\n if (m.find(c) == m.end()) st.push(c);\n else if (st.empty() || st.top() != m[c]) return false;\n else st.pop();\n }\n return st.empty();\n}", "test_cases": ["s=\"()\" -> true", "s=\"()[]{}\" -> true", "s=\"(]\" -> false"], "key_points": ["栈匹配法", "注意空栈边界"], "tags": ["string", "easy", "Google", "Uber"]} {"problem_id": "algo_00345", "original_id": "longest-palindrome", "title": "最长回文子串", "category": "string", "difficulty": "medium", "companies": ["Google", "Amazon"], "description": "给你一个字符串 s,找到 s 中最长的回文子串。", "solution_python": "def longestPalindrome(s):\n def expand(l, r):\n while l >= 0 and r < len(s) and s[l] == s[r]: l -= 1; r += 1\n return l + 1, r - 1\n start = end = 0\n for i in range(len(s)):\n l1, r1 = expand(i, i)\n l2, r2 = expand(i, i + 1)\n if r1 - l1 > end - start: start, end = l1, r1\n if r2 - l2 > end - start: start, end = l2, r2\n return s[start:end+1]", "solution_java": "public String longestPalindrome(String s) {\n int start = 0, end = 0;\n for (int i = 0; i < s.length(); i++) {\n int len1 = expand(s, i, i), len2 = expand(s, i, i+1);\n int len = Math.max(len1, len2);\n if (len > end - start) { start = i - (len-1)/2; end = i + len/2; }\n }\n return s.substring(start, end + 1);\n}\nprivate int expand(String s, int l, int r) {\n while (l >= 0 && r < s.length() && s.charAt(l) == s.charAt(r)) { l--; r++; }\n return r - l - 1;\n}", "solution_cpp": "string longestPalindrome(string s) {\n int start = 0, end = 0;\n for (int i = 0; i < s.size(); i++) {\n int len1 = expand(s, i, i), len2 = expand(s, i, i+1);\n if (max(len1, len2) > end - start) { start = i - (max(len1,len2)-1)/2; end = i + max(len1,len2)/2; }\n }\n return s.substr(start, end - start + 1);\n}", "test_cases": ["s=\"babad\" -> bab或aba", "s=\"cbbd\" -> bb"], "key_points": ["中心扩展法", "处理奇偶长度"], "tags": ["string", "medium", "Google", "Amazon"]} {"problem_id": "algo_00346", "original_id": "reverse-list", "title": "反转链表", "category": "linkedlist", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "给你单链表的头节点 head,请你反转链表,并返回反转后的链表。", "solution_python": "def reverseList(head):\n prev = None\n curr = head\n while curr:\n nxt = curr.next\n curr.next = prev\n prev = curr\n curr = nxt\n return prev", "solution_java": "public ListNode reverseList(ListNode head) {\n ListNode prev = null, curr = head;\n while (curr != null) {\n ListNode next = curr.next;\n curr.next = prev;\n prev = curr;\n curr = next;\n }\n return prev;\n}", "solution_cpp": "ListNode* reverseList(ListNode* head) {\n ListNode* prev = nullptr, *curr = head;\n while (curr) {\n ListNode* next = curr->next;\n curr->next = prev;\n prev = curr;\n curr = next;\n }\n return prev;\n}", "test_cases": ["head=[1,2,3,4,5] -> [5,4,3,2,1]", "head=[1,2] -> [2,1]"], "key_points": ["迭代法 O(1)空间", "递归法 O(n)空间"], "tags": ["linkedlist", "medium", "Google", "Microsoft"]} {"problem_id": "algo_00347", "original_id": "middle-node", "title": "链表的中间结点", "category": "linkedlist", "difficulty": "easy", "companies": ["Amazon", "Facebook"], "description": "给你单链表的头节点 head,请你找出并返回链表的中间结点。如果有两个中间结点,则返回第二个中间结点。", "solution_python": "def middleNode(head):\n slow = fast = head\n while fast and fast.next:\n slow = slow.next\n fast = fast.next.next\n return slow", "solution_java": "public ListNode middleNode(ListNode head) {\n ListNode slow = head, fast = head;\n while (fast != null && fast.next != null) {\n slow = slow.next;\n fast = fast.next.next;\n }\n return slow;\n}", "solution_cpp": "ListNode* middleNode(ListNode* head) {\n ListNode* slow = head, *fast = head;\n while (fast && fast->next) { slow = slow->next; fast = fast->next->next; }\n return slow;\n}", "test_cases": ["head=[1,2,3,4,5] -> 3", "head=[1,2,3,4,5,6] -> 4"], "key_points": ["快慢指针", "O(n)时间O(1)空间"], "tags": ["linkedlist", "easy", "Amazon", "Facebook"]} {"problem_id": "algo_00348", "original_id": "max-depth", "title": "二叉树的最大深度", "category": "tree", "difficulty": "easy", "companies": ["Microsoft", "Apple"], "description": "给定一个二叉树 root,返回其最大深度。", "solution_python": "def maxDepth(root):\n if not root: return 0\n return max(maxDepth(root.left), maxDepth(root.right)) + 1", "solution_java": "public int maxDepth(TreeNode root) {\n if (root == null) return 0;\n return Math.max(maxDepth(root.left), maxDepth(root.right)) + 1;\n}", "solution_cpp": "int maxDepth(TreeNode* root) {\n if (!root) return 0;\n return max(maxDepth(root->left), maxDepth(root->right)) + 1;\n}", "test_cases": ["root=[3,9,20,null,null,15,7] -> 3", "root=[1,null,2] -> 2"], "key_points": ["DFS递归", "层序遍历也可"], "tags": ["tree", "easy", "Microsoft", "Apple"]} {"problem_id": "algo_00349", "original_id": "inorder-traversal", "title": "二叉树的中序遍历", "category": "tree", "difficulty": "easy", "companies": ["Google", "Microsoft"], "description": "给定一个二叉树的根节点 root,返回它的中序遍历结果。", "solution_python": "def inorderTraversal(root):\n result = []\n def dfs(node):\n if node:\n dfs(node.left)\n result.append(node.val)\n dfs(node.right)\n dfs(root)\n return result", "solution_java": "public List inorderTraversal(TreeNode root) {\n List res = new ArrayList<>();\n dfs(root, res);\n return res;\n}\nprivate void dfs(TreeNode node, List res) {\n if (node == null) return;\n dfs(node.left, res); res.add(node.val); dfs(node.right, res);\n}", "solution_cpp": "vector inorderTraversal(TreeNode* root) {\n vector res;\n dfs(root, res);\n return res;\n}\nvoid dfs(TreeNode* node, vector& res) {\n if (!node) return;\n dfs(node->left, res); res.push_back(node->val); dfs(node->right, res);\n}", "test_cases": ["root=[1,null,2,3] -> [1,3,2]", "root=[] -> []"], "key_points": ["左-根-右顺序", "递归最简洁"], "tags": ["tree", "easy", "Google", "Microsoft"]} {"problem_id": "algo_00350", "original_id": "binary-search", "title": "二分查找", "category": "binarysearch", "difficulty": "easy", "companies": ["Google", "Amazon"], "description": "给定一个 n 个元素有序的(升序)整型数组 nums 和一个目标值 target,写一个函数搜索 nums 中的 target,如果目标值存在返回下标,否则返回 -1。", "solution_python": "def search(nums, target):\n left, right = 0, len(nums) - 1\n while left <= right:\n mid = (left + right) // 2\n if nums[mid] == target: return mid\n elif nums[mid] < target: left = mid + 1\n else: right = mid - 1\n return -1", "solution_java": "public int search(int[] nums, int target) {\n int left = 0, right = nums.length - 1;\n while (left <= right) {\n int mid = left + (right - left) / 2;\n if (nums[mid] == target) return mid;\n else if (nums[mid] < target) left = mid + 1;\n else right = mid - 1;\n }\n return -1;\n}", "solution_cpp": "int search(vector& nums, int target) {\n int left = 0, right = nums.size() - 1;\n while (left <= right) {\n int mid = left + (right - left) / 2;\n if (nums[mid] == target) return mid;\n else if (nums[mid] < target) left = mid + 1;\n else right = mid - 1;\n }\n return -1;\n}", "test_cases": ["nums=[-1,0,3,5,9,12], target=9 -> 4", "nums=[-1,0,3,5,9,12], target=2 -> -1"], "key_points": ["标准模板", "注意防溢出写法"], "tags": ["binarysearch", "easy", "Google", "Amazon"]} {"problem_id": "algo_00351", "original_id": "climbing-stairs", "title": "爬楼梯", "category": "dp", "difficulty": "easy", "companies": ["Amazon", "Google"], "description": "假设你正在爬楼梯。需要 n 阶你才能到达楼顶。每次你可以爬 1 或 2 个台阶。你有多少种不同的方法可以爬到楼顶?", "solution_python": "def climbStairs(n):\n if n <= 2: return n\n a, b = 1, 2\n for _ in range(3, n+1):\n a, b = b, a + b\n return b", "solution_java": "public int climbStairs(int n) {\n if (n <= 2) return n;\n int a = 1, b = 2;\n for (int i = 3; i <= n; i++) { int temp = a + b; a = b; b = temp; }\n return b;\n}", "solution_cpp": "int climbStairs(int n) {\n if (n <= 2) return n;\n int a = 1, b = 2;\n for (int i = 3; i <= n; i++) { int temp = a + b; a = b; b = temp; }\n return b;\n}", "test_cases": ["n=2 -> 2", "n=3 -> 3", "n=5 -> 8"], "key_points": ["斐波那契数列", "滚动数组优化空间"], "tags": ["dp", "easy", "Amazon", "Google"]} {"problem_id": "algo_00352", "original_id": "coin-change", "title": "零钱兑换", "category": "dp", "difficulty": "medium", "companies": ["Google", "Amazon"], "description": "给你一个整数数组 coins 表示不同面额的硬币,以及一个整数 amount 表示总金额。计算并返回可以凑成总金额所需的最少的硬币个数。如果没有任何一种硬币组合能组成总金额,返回 -1。", "solution_python": "def coinChange(coins, amount):\n dp = [float('inf')] * (amount + 1)\n dp[0] = 0\n for coin in coins:\n for x in range(coin, amount + 1):\n dp[x] = min(dp[x], dp[x - coin] + 1)\n return dp[amount] if dp[amount] != float('inf') else -1", "solution_java": "public int coinChange(int[] coins, int amount) {\n int[] dp = new int[amount + 1];\n Arrays.fill(dp, amount + 1);\n dp[0] = 0;\n for (int coin : coins) {\n for (int x = coin; x <= amount; x++) {\n dp[x] = Math.min(dp[x], dp[x - coin] + 1);\n }\n }\n return dp[amount] > amount ? -1 : dp[amount];\n}", "solution_cpp": "int coinChange(vector& coins, int amount) {\n vector dp(amount + 1, amount + 1);\n dp[0] = 0;\n for (int coin : coins) {\n for (int x = coin; x <= amount; x++) {\n dp[x] = min(dp[x], dp[x - coin] + 1);\n }\n }\n return dp[amount] > amount ? -1 : dp[amount];\n}", "test_cases": ["coins=[1,2,5], amount=11 -> 3", "coins=[2], amount=3 -> -1"], "key_points": ["完全背包问题", "dp[x] = min(dp[x-coin]+1)"], "tags": ["dp", "medium", "Google", "Amazon"]} {"problem_id": "algo_00353", "original_id": "subsets", "title": "子集", "category": "backtracking", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "给你一个整数数组 nums ,数组中的元素 互不相同 。返回该数组所有可能的子集(幂集)。", "solution_python": "def subsets(nums):\n result = []\n def backtrack(start, path):\n result.append(path[:])\n for i in range(start, len(nums)):\n path.append(nums[i])\n backtrack(i + 1, path)\n path.pop()\n backtrack(0, [])\n return result", "solution_java": "public List> subsets(int[] nums) {\n List> result = new ArrayList<>();\n backtrack(nums, 0, new ArrayList<>(), result);\n return result;\n}\nprivate void backtrack(int[] nums, int start, List path, List> result) {\n result.add(new ArrayList<>(path));\n for (int i = start; i < nums.length; i++) {\n path.add(nums[i]);\n backtrack(nums, i + 1, path, result);\n path.remove(path.size() - 1);\n }\n}", "solution_cpp": "vector> subsets(vector& nums) {\n vector> result;\n vector path;\n backtrack(nums, 0, path, result);\n return result;\n}\nvoid backtrack(vector& nums, int start, vector& path, vector>& result) {\n result.push_back(path);\n for (int i = start; i < nums.size(); i++) {\n path.push_back(nums[i]);\n backtrack(nums, i + 1, path, result);\n path.pop_back();\n }\n}", "test_cases": ["nums=[1,2,3] -> [[],[1],[2],[1,2],[3],[1,3],[2,3],[1,2,3]]"], "key_points": ["选或不选", "DFS遍历子集树"], "tags": ["backtracking", "medium", "Google", "Microsoft"]} {"problem_id": "algo_00354", "original_id": "permutations", "title": "全排列", "category": "backtracking", "difficulty": "medium", "companies": ["Google", "Facebook"], "description": "给定一个不含重复数字的数组 nums,返回其所有可能的全排列。", "solution_python": "def permute(nums):\n result = []\n def backtrack(path, used):\n if len(path) == len(nums):\n result.append(path[:])\n return\n for i in range(len(nums)):\n if used[i]: continue\n used[i] = True\n path.append(nums[i])\n backtrack(path, used)\n path.pop()\n used[i] = False\n backtrack([], [False]*len(nums))\n return result", "solution_java": "public List> permute(int[] nums) {\n List> result = new ArrayList<>();\n boolean[] used = new boolean[nums.length];\n backtrack(nums, used, new ArrayList<>(), result);\n return result;\n}\nprivate void backtrack(int[] nums, boolean[] used, List path, List> result) {\n if (path.size() == nums.length) { result.add(new ArrayList<>(path)); return; }\n for (int i = 0; i < nums.length; i++) {\n if (used[i]) continue;\n used[i] = true;\n path.add(nums[i]);\n backtrack(nums, used, path, result);\n path.remove(path.size() - 1);\n used[i] = false;\n }\n}", "solution_cpp": "vector> permute(vector& nums) {\n vector> result;\n vector used(nums.size(), false);\n vector path;\n backtrack(nums, used, path, result);\n return result;\n}\nvoid backtrack(vector& nums, vector& used, vector& path, vector>& result) {\n if (path.size() == nums.size()) { result.push_back(path); return; }\n for (int i = 0; i < nums.size(); i++) {\n if (used[i]) continue;\n used[i] = true;\n path.push_back(nums[i]);\n backtrack(nums, used, path, result);\n path.pop_back();\n used[i] = false;\n }\n}", "test_cases": ["nums=[1,2,3] -> [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]"], "key_points": ["标记已使用元素", "回溯经典模板"], "tags": ["backtracking", "medium", "Google", "Facebook"]} {"problem_id": "algo_00355", "original_id": "top-k-frequent", "title": "前K个高频元素", "category": "heap", "difficulty": "medium", "companies": ["Amazon", "Facebook"], "description": "给你一个整数数组 nums 和一个整数 k,请你返回其中出现频率前 k 高的元素。", "solution_python": "import heapq\nfrom collections import Counter\ndef topKFrequent(nums, k):\n count = Counter(nums)\n heap = []\n for num, freq in count.items():\n heapq.heappush(heap, (freq, num))\n if len(heap) > k: heapq.heappop(heap)\n return [num for freq, num in heap]", "solution_java": "public int[] topKFrequent(int[] nums, int k) {\n Map count = new HashMap<>();\n for (int n : nums) count.put(n, count.getOrDefault(n, 0) + 1);\n PriorityQueue> heap = \n new PriorityQueue<>((a, b) -> a.getValue() - b.getValue());\n for (Map.Entry e : count.entrySet()) {\n heap.offer(e);\n if (heap.size() > k) heap.poll();\n }\n int[] res = new int[k];\n for (int i = k - 1; i >= 0; i--) res[i] = heap.poll().getKey();\n return res;\n}", "solution_cpp": "vector topKFrequent(vector& nums, int k) {\n unordered_map count;\n for (int n : nums) count[n]++;\n priority_queue, vector>, greater>> heap;\n for (auto& [num, freq] : count) {\n heap.push({freq, num});\n if (heap.size() > k) heap.pop();\n }\n vector res;\n while (!heap.empty()) { res.push_back(heap.top().second); heap.pop(); }\n reverse(res.begin(), res.end());\n return res;\n}", "test_cases": ["nums=[1,1,1,2,2,3], k=2 -> [1,2]", "nums=[1], k=1 -> [1]"], "key_points": ["小顶堆保持大小k", "时间复杂度O(nlogk)"], "tags": ["heap", "medium", "Amazon", "Facebook"]} {"problem_id": "algo_00356", "original_id": "3sum", "title": "三数之和", "category": "two-pointers", "difficulty": "medium", "companies": ["Google", "Amazon"], "description": "给你一个整数数组 nums,判断是否存在三元组满足和为0,返回所有不重复的三元组。", "solution_python": "def threeSum(nums):\n nums.sort()\n result = []\n for i in range(len(nums) - 2):\n if i > 0 and nums[i] == nums[i-1]: continue\n left, right = i + 1, len(nums) - 1\n while left < right:\n total = nums[i] + nums[left] + nums[right]\n if total < 0: left += 1\n elif total > 0: right -= 1\n else:\n result.append([nums[i], nums[left], nums[right]])\n while left < right and nums[left] == nums[left+1]: left += 1\n while left < right and nums[right] == nums[right-1]: right -= 1\n left += 1; right -= 1\n return result", "solution_java": "public List> threeSum(int[] nums) {\n Arrays.sort(nums);\n List> result = new ArrayList<>();\n for (int i = 0; i < nums.length - 2; i++) {\n if (i > 0 && nums[i] == nums[i-1]) continue;\n int left = i + 1, right = nums.length - 1;\n while (left < right) {\n int total = nums[i] + nums[left] + nums[right];\n if (total < 0) left++;\n else if (total > 0) right--;\n else {\n result.add(Arrays.asList(nums[i], nums[left], nums[right]));\n while (left < right && nums[left] == nums[left+1]) left++;\n while (left < right && nums[right] == nums[right-1]) right--;\n left++; right--;\n }\n }\n }\n return result;\n}", "solution_cpp": "vector> threeSum(vector& nums) {\n sort(nums.begin(), nums.end());\n vector> result;\n for (int i = 0; i < nums.size() - 2; i++) {\n if (i > 0 && nums[i] == nums[i-1]) continue;\n int left = i + 1, right = nums.size() - 1;\n while (left < right) {\n int total = nums[i] + nums[left] + nums[right];\n if (total < 0) left++;\n else if (total > 0) right--;\n else {\n result.push_back({nums[i], nums[left], nums[right]});\n while (left < right && nums[left] == nums[left+1]) left++;\n while (left < right && nums[right] == nums[right-1]) right--;\n left++; right--;\n }\n }\n }\n return result;\n}", "test_cases": ["nums=[-1,0,1,2,-1,-4] -> [[-1,-1,2],[-1,0,1]]"], "key_points": ["排序+双指针", "去重是关键"], "tags": ["two-pointers", "medium", "Google", "Amazon"]} {"problem_id": "algo_00357", "original_id": "container-water", "title": "盛最多水的容器", "category": "two-pointers", "difficulty": "medium", "companies": ["Google", "Uber"], "description": "给定一个长度为 n 的整数数组 height,找出其中的两条线,使得它们与 x 轴共同构成的容器可以容纳最多的水。", "solution_python": "def maxArea(height):\n left, right = 0, len(height) - 1\n max_area = 0\n while left < right:\n h = min(height[left], height[right])\n max_area = max(max_area, h * (right - left))\n if height[left] < height[right]: left += 1\n else: right -= 1\n return max_area", "solution_java": "public int maxArea(int[] height) {\n int left = 0, right = height.length - 1, maxArea = 0;\n while (left < right) {\n int h = Math.min(height[left], height[right]);\n maxArea = Math.max(maxArea, h * (right - left));\n if (height[left] < height[right]) left++;\n else right--;\n }\n return maxArea;\n}", "solution_cpp": "int maxArea(vector& height) {\n int left = 0, right = height.size() - 1, maxArea = 0;\n while (left < right) {\n int h = min(height[left], height[right]);\n maxArea = max(maxArea, h * (right - left));\n if (height[left] < height[right]) left++;\n else right--;\n }\n return maxArea;\n}", "test_cases": ["height=[1,8,6,2,5,4,8,3,7] -> 49"], "key_points": ["移动短边指针", "面积=min(h1,h2)*width"], "tags": ["two-pointers", "medium", "Google", "Uber"]} {"problem_id": "algo_00358", "original_id": "min-stack", "title": "最小栈", "category": "stack", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "设计一个支持 push,pop,top 操作,并能在常数时间内检索到最小元素的栈。", "solution_python": "class MinStack:\n def __init__(self):\n self.stack = []\n self.min_stack = []\n def push(self, val):\n self.stack.append(val)\n self.min_stack.append(min(val, self.min_stack[-1] if self.min_stack else val))\n def pop(self):\n self.stack.pop(); self.min_stack.pop()\n def top(self): return self.stack[-1]\n def getMin(self): return self.min_stack[-1]", "solution_java": "class MinStack {\n Stack stack = new Stack<>();\n Stack minStack = new Stack<>();\n public void push(int val) { stack.push(val); minStack.push(Math.min(val, minStack.isEmpty() ? val : minStack.peek())); }\n public void pop() { stack.pop(); minStack.pop(); }\n public int top() { return stack.peek(); }\n public int getMin() { return minStack.peek(); }\n}", "solution_cpp": "class MinStack {\n stack st, minSt;\npublic:\n void push(int val) { st.push(val); minSt.push(min(val, minSt.empty() ? val : minSt.top())); }\n void pop() { st.pop(); minSt.pop(); }\n int top() { return st.top(); }\n int getMin() { return minSt.top(); }\n};", "test_cases": ["push(-2), push(0), push(-3) -> getMin() returns -3"], "key_points": ["辅助栈记录最小值", "O(1)时间获取最小值"], "tags": ["stack", "medium", "Google", "Microsoft"]} {"problem_id": "algo_00359", "original_id": "lru-cache", "title": "LRU缓存", "category": "design", "difficulty": "hard", "companies": ["Google", "Amazon"], "description": "设计和实现一个 LRU(最近最少使用)缓存机制。", "solution_python": "class LRUCache:\n def __init__(self, capacity):\n self.capacity = capacity\n self.cache = {}\n self.order = []\n def get(self, key):\n if key not in self.cache: return -1\n self.order.remove(key); self.order.append(key)\n return self.cache[key]\n def put(self, key, value):\n if key in self.cache:\n self.order.remove(key)\n elif len(self.cache) >= self.capacity:\n del self.cache[self.order.pop(0)]\n self.cache[key] = value; self.order.append(key)", "solution_java": "class LRUCache {\n int capacity;\n LinkedHashMap cache = new LinkedHashMap<>();\n public LRUCache(int cap) { capacity = cap; }\n public int get(int key) { return cache.containsKey(key) ? cache.remove(key) : -1; }\n public void put(int key, int val) {\n if (cache.containsKey(key)) cache.remove(key);\n else if (cache.size() >= capacity) cache.remove(cache.keySet().iterator().next());\n cache.put(key, val);\n }\n}", "solution_cpp": "class LRUCache {\n int cap;\n list> dll;\n unordered_map>::iterator> cache;\npublic:\n LRUCache(int capacity) : cap(capacity) {}\n int get(int key) {\n auto it = cache.find(key);\n if (it == cache.end()) return -1;\n dll.splice(dll.end(), dll, it->second);\n return it->second->second;\n }\n void put(int key, int value) {\n auto it = cache.find(key);\n if (it != cache.end()) dll.erase(it->second);\n else if (cache.size() >= cap) { cache.erase(dll.front().first); dll.pop_front(); }\n dll.push_back({key, value});\n cache[key] = --dll.end();\n }\n};", "test_cases": ["put(1,1), put(2,2), get(1) -> 1"], "key_points": ["HashMap + 双向链表", "O(1)时间操作"], "tags": ["design", "hard", "Google", "Amazon"]} {"problem_id": "algo_00360", "original_id": "num-islands", "title": "岛屿数量", "category": "graph", "difficulty": "medium", "companies": ["Google", "Facebook"], "description": "给你一个由 '1'(陆地)和 '0'(水)组成的二维网格,请你计算网格中岛屿的数量。岛屿总是被水包围,且只能由水平或垂直方向相邻的陆地连接形成。", "solution_python": "def numIslands(grid):\n if not grid: return 0\n rows, cols = len(grid), len(grid[0])\n count = 0\n def dfs(r, c):\n if r < 0 or r >= rows or c < 0 or c >= cols or grid[r][c] != '1': return\n grid[r][c] = '0'\n dfs(r+1, c); dfs(r-1, c); dfs(r, c+1); dfs(r, c-1)\n for r in range(rows):\n for c in range(cols):\n if grid[r][c] == '1': count += 1; dfs(r, c)\n return count", "solution_java": "public int numIslands(char[][] grid) {\n if (grid.length == 0) return 0;\n int count = 0;\n for (int i = 0; i < grid.length; i++)\n for (int j = 0; j < grid[0].length; j++)\n if (grid[i][j] == '1') { count++; dfs(grid, i, j); }\n return count;\n}\nprivate void dfs(char[][] grid, int r, int c) {\n if (r < 0 || r >= grid.length || c < 0 || c >= grid[0].length || grid[r][c] != '1') return;\n grid[r][c] = '0';\n dfs(grid, r+1, c); dfs(grid, r-1, c); dfs(grid, r, c+1); dfs(grid, r, c-1);\n}", "solution_cpp": "int numIslands(vector>& grid) {\n if (grid.empty()) return 0;\n int count = 0;\n for (int i = 0; i < grid.size(); i++)\n for (int j = 0; j < grid[0].size(); j++)\n if (grid[i][j] == '1') { count++; dfs(grid, i, j); }\n return count;\n}\nvoid dfs(vector>& grid, int r, int c) {\n if (r < 0 || r >= grid.size() || c < 0 || c >= grid[0].size() || grid[r][c] != '1') return;\n grid[r][c] = '0';\n dfs(grid, r+1, c); dfs(grid, r-1, c); dfs(grid, r, c+1); dfs(grid, r, c-1);\n}", "test_cases": ["grid=[[1,1,1,1,0],[1,1,0,1,0],[1,1,0,0,0],[0,0,0,0,0]] -> 1"], "key_points": ["DFS/BFS遍历", "访问后标记为0避免重复"], "tags": ["graph", "medium", "Google", "Facebook"]} {"problem_id": "algo_00361", "original_id": "two-sum", "title": "两数之和", "category": "array", "difficulty": "easy", "companies": ["Amazon", "Google"], "description": "给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那两个整数,并返回他们的数组下标。", "solution_python": "def twoSum(nums, target):\n hashmap = {}\n for i, num in enumerate(nums):\n complement = target - num\n if complement in hashmap:\n return [hashmap[complement], i]\n hashmap[num] = i\n return []", "solution_java": "public int[] twoSum(int[] nums, int target) {\n Map map = new HashMap<>();\n for (int i = 0; i < nums.length; i++) {\n int complement = target - nums[i];\n if (map.containsKey(complement)) return new int[]{map.get(complement), i};\n map.put(nums[i], i);\n }\n return new int[]{};\n}", "solution_cpp": "vector twoSum(vector& nums, int target) {\n unordered_map m;\n for (int i = 0; i < nums.size(); i++) {\n if (m.count(target - nums[i])) return {m[target - nums[i]], i};\n m[nums[i]] = i;\n }\n return {};\n}", "test_cases": ["nums=[2,7,11,15], target=9 -> [0,1]", "nums=[3,2,4], target=6 -> [1,2]"], "key_points": ["哈希表一次遍历", "空间换时间"], "tags": ["array", "easy", "Amazon", "Google"]} {"problem_id": "algo_00362", "original_id": "merge-sorted", "title": "合并两个有序数组", "category": "array", "difficulty": "easy", "companies": ["Microsoft", "Uber"], "description": "给你两个按非递减顺序排列的整数数组 nums1 和 nums2,另有两个整数 m 和 n,分别表示 nums1 和 nums2 中的元素数目。请你合并 nums2 到 nums1 中。", "solution_python": "def merge(nums1, m, nums2, n):\n p1, p2, p = m-1, n-1, m+n-1\n while p1 >= 0 and p2 >= 0:\n if nums1[p1] > nums2[p2]: nums1[p] = nums1[p1]; p1 -= 1\n else: nums1[p] = nums2[p2]; p2 -= 1\n p -= 1\n while p2 >= 0: nums1[p] = nums2[p2]; p2 -= 1; p -= 1", "solution_java": "public void merge(int[] nums1, int m, int[] nums2, int n) {\n int p1 = m-1, p2 = n-1, p = m+n-1;\n while (p1 >= 0 && p2 >= 0) {\n nums1[p--] = nums1[p1] > nums2[p2] ? nums1[p1--] : nums2[p2--];\n }\n while (p2 >= 0) nums1[p--] = nums2[p2--];\n}", "solution_cpp": "void merge(vector& nums1, int m, vector& nums2, int n) {\n int p1 = m-1, p2 = n-1, p = m+n-1;\n while (p1 >= 0 && p2 >= 0) nums1[p--] = nums1[p1] > nums2[p2] ? nums1[p1--] : nums2[p2--];\n while (p2 >= 0) nums1[p--] = nums2[p2--];\n}", "test_cases": ["nums1=[1,2,3], m=3, nums2=[2,5,6], n=3 -> [1,2,2,3,5,6]", "nums1=[], m=0, nums2=[1], n=1 -> [1]"], "key_points": ["从后往前合并", "三指针技巧"], "tags": ["array", "easy", "Microsoft", "Uber"]} {"problem_id": "algo_00363", "original_id": "max-subarray", "title": "最大子数组和", "category": "array", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "给你一个整数数组 nums ,请你找出一个具有最大和的连续子数组,返回其最大和。", "solution_python": "def maxSubArray(nums):\n max_sum = current = nums[0]\n for num in nums[1:]:\n current = max(num, current + num)\n max_sum = max(max_sum, current)\n return max_sum", "solution_java": "public int maxSubArray(int[] nums) {\n int maxSum = nums[0], curr = nums[0];\n for (int i = 1; i < nums.length; i++) {\n curr = Math.max(nums[i], curr + nums[i]);\n maxSum = Math.max(maxSum, curr);\n }\n return maxSum;\n}", "solution_cpp": "int maxSubArray(vector& nums) {\n int maxSum = nums[0], curr = nums[0];\n for (int i = 1; i < nums.size(); i++) {\n curr = max(nums[i], curr + nums[i]);\n maxSum = max(maxSum, curr);\n }\n return maxSum;\n}", "test_cases": ["nums=[-2,1,-3,4,-1,2,1,-5,4] -> 6", "nums=[1] -> 1"], "key_points": ["Kadane算法", "动态规划基础题"], "tags": ["array", "medium", "Google", "Microsoft"]} {"problem_id": "algo_00364", "original_id": "valid-parentheses", "title": "有效的括号", "category": "string", "difficulty": "easy", "companies": ["Google", "Uber"], "description": "给定一个只包括 '(',')','{','}','[',']' 的字符串 s,判断字符串是否有效。", "solution_python": "def isValid(s):\n stack = []\n mapping = {')': '(', ']': '[', '}': '{'}\n for c in s:\n if c in mapping:\n if not stack or stack[-1] != mapping[c]: return False\n stack.pop()\n else: stack.append(c)\n return not stack", "solution_java": "public boolean isValid(String s) {\n Stack stack = new Stack<>();\n Map map = Map.of(')', '(', ']', '[', '}', '{');\n for (char c : s.toCharArray()) {\n if (map.containsValue(c)) stack.push(c);\n else if (!stack.isEmpty() && stack.pop() != map.get(c)) return false;\n }\n return stack.isEmpty();\n}", "solution_cpp": "bool isValid(string s) {\n stack st;\n unordered_map m = {{')','('},{']','['},{'}','{'}};\n for (char c : s) {\n if (m.find(c) == m.end()) st.push(c);\n else if (st.empty() || st.top() != m[c]) return false;\n else st.pop();\n }\n return st.empty();\n}", "test_cases": ["s=\"()\" -> true", "s=\"()[]{}\" -> true", "s=\"(]\" -> false"], "key_points": ["栈匹配法", "注意空栈边界"], "tags": ["string", "easy", "Google", "Uber"]} {"problem_id": "algo_00365", "original_id": "longest-palindrome", "title": "最长回文子串", "category": "string", "difficulty": "medium", "companies": ["Google", "Amazon"], "description": "给你一个字符串 s,找到 s 中最长的回文子串。", "solution_python": "def longestPalindrome(s):\n def expand(l, r):\n while l >= 0 and r < len(s) and s[l] == s[r]: l -= 1; r += 1\n return l + 1, r - 1\n start = end = 0\n for i in range(len(s)):\n l1, r1 = expand(i, i)\n l2, r2 = expand(i, i + 1)\n if r1 - l1 > end - start: start, end = l1, r1\n if r2 - l2 > end - start: start, end = l2, r2\n return s[start:end+1]", "solution_java": "public String longestPalindrome(String s) {\n int start = 0, end = 0;\n for (int i = 0; i < s.length(); i++) {\n int len1 = expand(s, i, i), len2 = expand(s, i, i+1);\n int len = Math.max(len1, len2);\n if (len > end - start) { start = i - (len-1)/2; end = i + len/2; }\n }\n return s.substring(start, end + 1);\n}\nprivate int expand(String s, int l, int r) {\n while (l >= 0 && r < s.length() && s.charAt(l) == s.charAt(r)) { l--; r++; }\n return r - l - 1;\n}", "solution_cpp": "string longestPalindrome(string s) {\n int start = 0, end = 0;\n for (int i = 0; i < s.size(); i++) {\n int len1 = expand(s, i, i), len2 = expand(s, i, i+1);\n if (max(len1, len2) > end - start) { start = i - (max(len1,len2)-1)/2; end = i + max(len1,len2)/2; }\n }\n return s.substr(start, end - start + 1);\n}", "test_cases": ["s=\"babad\" -> bab或aba", "s=\"cbbd\" -> bb"], "key_points": ["中心扩展法", "处理奇偶长度"], "tags": ["string", "medium", "Google", "Amazon"]} {"problem_id": "algo_00366", "original_id": "reverse-list", "title": "反转链表", "category": "linkedlist", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "给你单链表的头节点 head,请你反转链表,并返回反转后的链表。", "solution_python": "def reverseList(head):\n prev = None\n curr = head\n while curr:\n nxt = curr.next\n curr.next = prev\n prev = curr\n curr = nxt\n return prev", "solution_java": "public ListNode reverseList(ListNode head) {\n ListNode prev = null, curr = head;\n while (curr != null) {\n ListNode next = curr.next;\n curr.next = prev;\n prev = curr;\n curr = next;\n }\n return prev;\n}", "solution_cpp": "ListNode* reverseList(ListNode* head) {\n ListNode* prev = nullptr, *curr = head;\n while (curr) {\n ListNode* next = curr->next;\n curr->next = prev;\n prev = curr;\n curr = next;\n }\n return prev;\n}", "test_cases": ["head=[1,2,3,4,5] -> [5,4,3,2,1]", "head=[1,2] -> [2,1]"], "key_points": ["迭代法 O(1)空间", "递归法 O(n)空间"], "tags": ["linkedlist", "medium", "Google", "Microsoft"]} {"problem_id": "algo_00367", "original_id": "middle-node", "title": "链表的中间结点", "category": "linkedlist", "difficulty": "easy", "companies": ["Amazon", "Facebook"], "description": "给你单链表的头节点 head,请你找出并返回链表的中间结点。如果有两个中间结点,则返回第二个中间结点。", "solution_python": "def middleNode(head):\n slow = fast = head\n while fast and fast.next:\n slow = slow.next\n fast = fast.next.next\n return slow", "solution_java": "public ListNode middleNode(ListNode head) {\n ListNode slow = head, fast = head;\n while (fast != null && fast.next != null) {\n slow = slow.next;\n fast = fast.next.next;\n }\n return slow;\n}", "solution_cpp": "ListNode* middleNode(ListNode* head) {\n ListNode* slow = head, *fast = head;\n while (fast && fast->next) { slow = slow->next; fast = fast->next->next; }\n return slow;\n}", "test_cases": ["head=[1,2,3,4,5] -> 3", "head=[1,2,3,4,5,6] -> 4"], "key_points": ["快慢指针", "O(n)时间O(1)空间"], "tags": ["linkedlist", "easy", "Amazon", "Facebook"]} {"problem_id": "algo_00368", "original_id": "max-depth", "title": "二叉树的最大深度", "category": "tree", "difficulty": "easy", "companies": ["Microsoft", "Apple"], "description": "给定一个二叉树 root,返回其最大深度。", "solution_python": "def maxDepth(root):\n if not root: return 0\n return max(maxDepth(root.left), maxDepth(root.right)) + 1", "solution_java": "public int maxDepth(TreeNode root) {\n if (root == null) return 0;\n return Math.max(maxDepth(root.left), maxDepth(root.right)) + 1;\n}", "solution_cpp": "int maxDepth(TreeNode* root) {\n if (!root) return 0;\n return max(maxDepth(root->left), maxDepth(root->right)) + 1;\n}", "test_cases": ["root=[3,9,20,null,null,15,7] -> 3", "root=[1,null,2] -> 2"], "key_points": ["DFS递归", "层序遍历也可"], "tags": ["tree", "easy", "Microsoft", "Apple"]} {"problem_id": "algo_00369", "original_id": "inorder-traversal", "title": "二叉树的中序遍历", "category": "tree", "difficulty": "easy", "companies": ["Google", "Microsoft"], "description": "给定一个二叉树的根节点 root,返回它的中序遍历结果。", "solution_python": "def inorderTraversal(root):\n result = []\n def dfs(node):\n if node:\n dfs(node.left)\n result.append(node.val)\n dfs(node.right)\n dfs(root)\n return result", "solution_java": "public List inorderTraversal(TreeNode root) {\n List res = new ArrayList<>();\n dfs(root, res);\n return res;\n}\nprivate void dfs(TreeNode node, List res) {\n if (node == null) return;\n dfs(node.left, res); res.add(node.val); dfs(node.right, res);\n}", "solution_cpp": "vector inorderTraversal(TreeNode* root) {\n vector res;\n dfs(root, res);\n return res;\n}\nvoid dfs(TreeNode* node, vector& res) {\n if (!node) return;\n dfs(node->left, res); res.push_back(node->val); dfs(node->right, res);\n}", "test_cases": ["root=[1,null,2,3] -> [1,3,2]", "root=[] -> []"], "key_points": ["左-根-右顺序", "递归最简洁"], "tags": ["tree", "easy", "Google", "Microsoft"]} {"problem_id": "algo_00370", "original_id": "binary-search", "title": "二分查找", "category": "binarysearch", "difficulty": "easy", "companies": ["Google", "Amazon"], "description": "给定一个 n 个元素有序的(升序)整型数组 nums 和一个目标值 target,写一个函数搜索 nums 中的 target,如果目标值存在返回下标,否则返回 -1。", "solution_python": "def search(nums, target):\n left, right = 0, len(nums) - 1\n while left <= right:\n mid = (left + right) // 2\n if nums[mid] == target: return mid\n elif nums[mid] < target: left = mid + 1\n else: right = mid - 1\n return -1", "solution_java": "public int search(int[] nums, int target) {\n int left = 0, right = nums.length - 1;\n while (left <= right) {\n int mid = left + (right - left) / 2;\n if (nums[mid] == target) return mid;\n else if (nums[mid] < target) left = mid + 1;\n else right = mid - 1;\n }\n return -1;\n}", "solution_cpp": "int search(vector& nums, int target) {\n int left = 0, right = nums.size() - 1;\n while (left <= right) {\n int mid = left + (right - left) / 2;\n if (nums[mid] == target) return mid;\n else if (nums[mid] < target) left = mid + 1;\n else right = mid - 1;\n }\n return -1;\n}", "test_cases": ["nums=[-1,0,3,5,9,12], target=9 -> 4", "nums=[-1,0,3,5,9,12], target=2 -> -1"], "key_points": ["标准模板", "注意防溢出写法"], "tags": ["binarysearch", "easy", "Google", "Amazon"]} {"problem_id": "algo_00371", "original_id": "climbing-stairs", "title": "爬楼梯", "category": "dp", "difficulty": "easy", "companies": ["Amazon", "Google"], "description": "假设你正在爬楼梯。需要 n 阶你才能到达楼顶。每次你可以爬 1 或 2 个台阶。你有多少种不同的方法可以爬到楼顶?", "solution_python": "def climbStairs(n):\n if n <= 2: return n\n a, b = 1, 2\n for _ in range(3, n+1):\n a, b = b, a + b\n return b", "solution_java": "public int climbStairs(int n) {\n if (n <= 2) return n;\n int a = 1, b = 2;\n for (int i = 3; i <= n; i++) { int temp = a + b; a = b; b = temp; }\n return b;\n}", "solution_cpp": "int climbStairs(int n) {\n if (n <= 2) return n;\n int a = 1, b = 2;\n for (int i = 3; i <= n; i++) { int temp = a + b; a = b; b = temp; }\n return b;\n}", "test_cases": ["n=2 -> 2", "n=3 -> 3", "n=5 -> 8"], "key_points": ["斐波那契数列", "滚动数组优化空间"], "tags": ["dp", "easy", "Amazon", "Google"]} {"problem_id": "algo_00372", "original_id": "coin-change", "title": "零钱兑换", "category": "dp", "difficulty": "medium", "companies": ["Google", "Amazon"], "description": "给你一个整数数组 coins 表示不同面额的硬币,以及一个整数 amount 表示总金额。计算并返回可以凑成总金额所需的最少的硬币个数。如果没有任何一种硬币组合能组成总金额,返回 -1。", "solution_python": "def coinChange(coins, amount):\n dp = [float('inf')] * (amount + 1)\n dp[0] = 0\n for coin in coins:\n for x in range(coin, amount + 1):\n dp[x] = min(dp[x], dp[x - coin] + 1)\n return dp[amount] if dp[amount] != float('inf') else -1", "solution_java": "public int coinChange(int[] coins, int amount) {\n int[] dp = new int[amount + 1];\n Arrays.fill(dp, amount + 1);\n dp[0] = 0;\n for (int coin : coins) {\n for (int x = coin; x <= amount; x++) {\n dp[x] = Math.min(dp[x], dp[x - coin] + 1);\n }\n }\n return dp[amount] > amount ? -1 : dp[amount];\n}", "solution_cpp": "int coinChange(vector& coins, int amount) {\n vector dp(amount + 1, amount + 1);\n dp[0] = 0;\n for (int coin : coins) {\n for (int x = coin; x <= amount; x++) {\n dp[x] = min(dp[x], dp[x - coin] + 1);\n }\n }\n return dp[amount] > amount ? -1 : dp[amount];\n}", "test_cases": ["coins=[1,2,5], amount=11 -> 3", "coins=[2], amount=3 -> -1"], "key_points": ["完全背包问题", "dp[x] = min(dp[x-coin]+1)"], "tags": ["dp", "medium", "Google", "Amazon"]} {"problem_id": "algo_00373", "original_id": "subsets", "title": "子集", "category": "backtracking", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "给你一个整数数组 nums ,数组中的元素 互不相同 。返回该数组所有可能的子集(幂集)。", "solution_python": "def subsets(nums):\n result = []\n def backtrack(start, path):\n result.append(path[:])\n for i in range(start, len(nums)):\n path.append(nums[i])\n backtrack(i + 1, path)\n path.pop()\n backtrack(0, [])\n return result", "solution_java": "public List> subsets(int[] nums) {\n List> result = new ArrayList<>();\n backtrack(nums, 0, new ArrayList<>(), result);\n return result;\n}\nprivate void backtrack(int[] nums, int start, List path, List> result) {\n result.add(new ArrayList<>(path));\n for (int i = start; i < nums.length; i++) {\n path.add(nums[i]);\n backtrack(nums, i + 1, path, result);\n path.remove(path.size() - 1);\n }\n}", "solution_cpp": "vector> subsets(vector& nums) {\n vector> result;\n vector path;\n backtrack(nums, 0, path, result);\n return result;\n}\nvoid backtrack(vector& nums, int start, vector& path, vector>& result) {\n result.push_back(path);\n for (int i = start; i < nums.size(); i++) {\n path.push_back(nums[i]);\n backtrack(nums, i + 1, path, result);\n path.pop_back();\n }\n}", "test_cases": ["nums=[1,2,3] -> [[],[1],[2],[1,2],[3],[1,3],[2,3],[1,2,3]]"], "key_points": ["选或不选", "DFS遍历子集树"], "tags": ["backtracking", "medium", "Google", "Microsoft"]} {"problem_id": "algo_00374", "original_id": "permutations", "title": "全排列", "category": "backtracking", "difficulty": "medium", "companies": ["Google", "Facebook"], "description": "给定一个不含重复数字的数组 nums,返回其所有可能的全排列。", "solution_python": "def permute(nums):\n result = []\n def backtrack(path, used):\n if len(path) == len(nums):\n result.append(path[:])\n return\n for i in range(len(nums)):\n if used[i]: continue\n used[i] = True\n path.append(nums[i])\n backtrack(path, used)\n path.pop()\n used[i] = False\n backtrack([], [False]*len(nums))\n return result", "solution_java": "public List> permute(int[] nums) {\n List> result = new ArrayList<>();\n boolean[] used = new boolean[nums.length];\n backtrack(nums, used, new ArrayList<>(), result);\n return result;\n}\nprivate void backtrack(int[] nums, boolean[] used, List path, List> result) {\n if (path.size() == nums.length) { result.add(new ArrayList<>(path)); return; }\n for (int i = 0; i < nums.length; i++) {\n if (used[i]) continue;\n used[i] = true;\n path.add(nums[i]);\n backtrack(nums, used, path, result);\n path.remove(path.size() - 1);\n used[i] = false;\n }\n}", "solution_cpp": "vector> permute(vector& nums) {\n vector> result;\n vector used(nums.size(), false);\n vector path;\n backtrack(nums, used, path, result);\n return result;\n}\nvoid backtrack(vector& nums, vector& used, vector& path, vector>& result) {\n if (path.size() == nums.size()) { result.push_back(path); return; }\n for (int i = 0; i < nums.size(); i++) {\n if (used[i]) continue;\n used[i] = true;\n path.push_back(nums[i]);\n backtrack(nums, used, path, result);\n path.pop_back();\n used[i] = false;\n }\n}", "test_cases": ["nums=[1,2,3] -> [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]"], "key_points": ["标记已使用元素", "回溯经典模板"], "tags": ["backtracking", "medium", "Google", "Facebook"]} {"problem_id": "algo_00375", "original_id": "top-k-frequent", "title": "前K个高频元素", "category": "heap", "difficulty": "medium", "companies": ["Amazon", "Facebook"], "description": "给你一个整数数组 nums 和一个整数 k,请你返回其中出现频率前 k 高的元素。", "solution_python": "import heapq\nfrom collections import Counter\ndef topKFrequent(nums, k):\n count = Counter(nums)\n heap = []\n for num, freq in count.items():\n heapq.heappush(heap, (freq, num))\n if len(heap) > k: heapq.heappop(heap)\n return [num for freq, num in heap]", "solution_java": "public int[] topKFrequent(int[] nums, int k) {\n Map count = new HashMap<>();\n for (int n : nums) count.put(n, count.getOrDefault(n, 0) + 1);\n PriorityQueue> heap = \n new PriorityQueue<>((a, b) -> a.getValue() - b.getValue());\n for (Map.Entry e : count.entrySet()) {\n heap.offer(e);\n if (heap.size() > k) heap.poll();\n }\n int[] res = new int[k];\n for (int i = k - 1; i >= 0; i--) res[i] = heap.poll().getKey();\n return res;\n}", "solution_cpp": "vector topKFrequent(vector& nums, int k) {\n unordered_map count;\n for (int n : nums) count[n]++;\n priority_queue, vector>, greater>> heap;\n for (auto& [num, freq] : count) {\n heap.push({freq, num});\n if (heap.size() > k) heap.pop();\n }\n vector res;\n while (!heap.empty()) { res.push_back(heap.top().second); heap.pop(); }\n reverse(res.begin(), res.end());\n return res;\n}", "test_cases": ["nums=[1,1,1,2,2,3], k=2 -> [1,2]", "nums=[1], k=1 -> [1]"], "key_points": ["小顶堆保持大小k", "时间复杂度O(nlogk)"], "tags": ["heap", "medium", "Amazon", "Facebook"]} {"problem_id": "algo_00376", "original_id": "3sum", "title": "三数之和", "category": "two-pointers", "difficulty": "medium", "companies": ["Google", "Amazon"], "description": "给你一个整数数组 nums,判断是否存在三元组满足和为0,返回所有不重复的三元组。", "solution_python": "def threeSum(nums):\n nums.sort()\n result = []\n for i in range(len(nums) - 2):\n if i > 0 and nums[i] == nums[i-1]: continue\n left, right = i + 1, len(nums) - 1\n while left < right:\n total = nums[i] + nums[left] + nums[right]\n if total < 0: left += 1\n elif total > 0: right -= 1\n else:\n result.append([nums[i], nums[left], nums[right]])\n while left < right and nums[left] == nums[left+1]: left += 1\n while left < right and nums[right] == nums[right-1]: right -= 1\n left += 1; right -= 1\n return result", "solution_java": "public List> threeSum(int[] nums) {\n Arrays.sort(nums);\n List> result = new ArrayList<>();\n for (int i = 0; i < nums.length - 2; i++) {\n if (i > 0 && nums[i] == nums[i-1]) continue;\n int left = i + 1, right = nums.length - 1;\n while (left < right) {\n int total = nums[i] + nums[left] + nums[right];\n if (total < 0) left++;\n else if (total > 0) right--;\n else {\n result.add(Arrays.asList(nums[i], nums[left], nums[right]));\n while (left < right && nums[left] == nums[left+1]) left++;\n while (left < right && nums[right] == nums[right-1]) right--;\n left++; right--;\n }\n }\n }\n return result;\n}", "solution_cpp": "vector> threeSum(vector& nums) {\n sort(nums.begin(), nums.end());\n vector> result;\n for (int i = 0; i < nums.size() - 2; i++) {\n if (i > 0 && nums[i] == nums[i-1]) continue;\n int left = i + 1, right = nums.size() - 1;\n while (left < right) {\n int total = nums[i] + nums[left] + nums[right];\n if (total < 0) left++;\n else if (total > 0) right--;\n else {\n result.push_back({nums[i], nums[left], nums[right]});\n while (left < right && nums[left] == nums[left+1]) left++;\n while (left < right && nums[right] == nums[right-1]) right--;\n left++; right--;\n }\n }\n }\n return result;\n}", "test_cases": ["nums=[-1,0,1,2,-1,-4] -> [[-1,-1,2],[-1,0,1]]"], "key_points": ["排序+双指针", "去重是关键"], "tags": ["two-pointers", "medium", "Google", "Amazon"]} {"problem_id": "algo_00377", "original_id": "container-water", "title": "盛最多水的容器", "category": "two-pointers", "difficulty": "medium", "companies": ["Google", "Uber"], "description": "给定一个长度为 n 的整数数组 height,找出其中的两条线,使得它们与 x 轴共同构成的容器可以容纳最多的水。", "solution_python": "def maxArea(height):\n left, right = 0, len(height) - 1\n max_area = 0\n while left < right:\n h = min(height[left], height[right])\n max_area = max(max_area, h * (right - left))\n if height[left] < height[right]: left += 1\n else: right -= 1\n return max_area", "solution_java": "public int maxArea(int[] height) {\n int left = 0, right = height.length - 1, maxArea = 0;\n while (left < right) {\n int h = Math.min(height[left], height[right]);\n maxArea = Math.max(maxArea, h * (right - left));\n if (height[left] < height[right]) left++;\n else right--;\n }\n return maxArea;\n}", "solution_cpp": "int maxArea(vector& height) {\n int left = 0, right = height.size() - 1, maxArea = 0;\n while (left < right) {\n int h = min(height[left], height[right]);\n maxArea = max(maxArea, h * (right - left));\n if (height[left] < height[right]) left++;\n else right--;\n }\n return maxArea;\n}", "test_cases": ["height=[1,8,6,2,5,4,8,3,7] -> 49"], "key_points": ["移动短边指针", "面积=min(h1,h2)*width"], "tags": ["two-pointers", "medium", "Google", "Uber"]} {"problem_id": "algo_00378", "original_id": "min-stack", "title": "最小栈", "category": "stack", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "设计一个支持 push,pop,top 操作,并能在常数时间内检索到最小元素的栈。", "solution_python": "class MinStack:\n def __init__(self):\n self.stack = []\n self.min_stack = []\n def push(self, val):\n self.stack.append(val)\n self.min_stack.append(min(val, self.min_stack[-1] if self.min_stack else val))\n def pop(self):\n self.stack.pop(); self.min_stack.pop()\n def top(self): return self.stack[-1]\n def getMin(self): return self.min_stack[-1]", "solution_java": "class MinStack {\n Stack stack = new Stack<>();\n Stack minStack = new Stack<>();\n public void push(int val) { stack.push(val); minStack.push(Math.min(val, minStack.isEmpty() ? val : minStack.peek())); }\n public void pop() { stack.pop(); minStack.pop(); }\n public int top() { return stack.peek(); }\n public int getMin() { return minStack.peek(); }\n}", "solution_cpp": "class MinStack {\n stack st, minSt;\npublic:\n void push(int val) { st.push(val); minSt.push(min(val, minSt.empty() ? val : minSt.top())); }\n void pop() { st.pop(); minSt.pop(); }\n int top() { return st.top(); }\n int getMin() { return minSt.top(); }\n};", "test_cases": ["push(-2), push(0), push(-3) -> getMin() returns -3"], "key_points": ["辅助栈记录最小值", "O(1)时间获取最小值"], "tags": ["stack", "medium", "Google", "Microsoft"]} {"problem_id": "algo_00379", "original_id": "lru-cache", "title": "LRU缓存", "category": "design", "difficulty": "hard", "companies": ["Google", "Amazon"], "description": "设计和实现一个 LRU(最近最少使用)缓存机制。", "solution_python": "class LRUCache:\n def __init__(self, capacity):\n self.capacity = capacity\n self.cache = {}\n self.order = []\n def get(self, key):\n if key not in self.cache: return -1\n self.order.remove(key); self.order.append(key)\n return self.cache[key]\n def put(self, key, value):\n if key in self.cache:\n self.order.remove(key)\n elif len(self.cache) >= self.capacity:\n del self.cache[self.order.pop(0)]\n self.cache[key] = value; self.order.append(key)", "solution_java": "class LRUCache {\n int capacity;\n LinkedHashMap cache = new LinkedHashMap<>();\n public LRUCache(int cap) { capacity = cap; }\n public int get(int key) { return cache.containsKey(key) ? cache.remove(key) : -1; }\n public void put(int key, int val) {\n if (cache.containsKey(key)) cache.remove(key);\n else if (cache.size() >= capacity) cache.remove(cache.keySet().iterator().next());\n cache.put(key, val);\n }\n}", "solution_cpp": "class LRUCache {\n int cap;\n list> dll;\n unordered_map>::iterator> cache;\npublic:\n LRUCache(int capacity) : cap(capacity) {}\n int get(int key) {\n auto it = cache.find(key);\n if (it == cache.end()) return -1;\n dll.splice(dll.end(), dll, it->second);\n return it->second->second;\n }\n void put(int key, int value) {\n auto it = cache.find(key);\n if (it != cache.end()) dll.erase(it->second);\n else if (cache.size() >= cap) { cache.erase(dll.front().first); dll.pop_front(); }\n dll.push_back({key, value});\n cache[key] = --dll.end();\n }\n};", "test_cases": ["put(1,1), put(2,2), get(1) -> 1"], "key_points": ["HashMap + 双向链表", "O(1)时间操作"], "tags": ["design", "hard", "Google", "Amazon"]} {"problem_id": "algo_00380", "original_id": "num-islands", "title": "岛屿数量", "category": "graph", "difficulty": "medium", "companies": ["Google", "Facebook"], "description": "给你一个由 '1'(陆地)和 '0'(水)组成的二维网格,请你计算网格中岛屿的数量。岛屿总是被水包围,且只能由水平或垂直方向相邻的陆地连接形成。", "solution_python": "def numIslands(grid):\n if not grid: return 0\n rows, cols = len(grid), len(grid[0])\n count = 0\n def dfs(r, c):\n if r < 0 or r >= rows or c < 0 or c >= cols or grid[r][c] != '1': return\n grid[r][c] = '0'\n dfs(r+1, c); dfs(r-1, c); dfs(r, c+1); dfs(r, c-1)\n for r in range(rows):\n for c in range(cols):\n if grid[r][c] == '1': count += 1; dfs(r, c)\n return count", "solution_java": "public int numIslands(char[][] grid) {\n if (grid.length == 0) return 0;\n int count = 0;\n for (int i = 0; i < grid.length; i++)\n for (int j = 0; j < grid[0].length; j++)\n if (grid[i][j] == '1') { count++; dfs(grid, i, j); }\n return count;\n}\nprivate void dfs(char[][] grid, int r, int c) {\n if (r < 0 || r >= grid.length || c < 0 || c >= grid[0].length || grid[r][c] != '1') return;\n grid[r][c] = '0';\n dfs(grid, r+1, c); dfs(grid, r-1, c); dfs(grid, r, c+1); dfs(grid, r, c-1);\n}", "solution_cpp": "int numIslands(vector>& grid) {\n if (grid.empty()) return 0;\n int count = 0;\n for (int i = 0; i < grid.size(); i++)\n for (int j = 0; j < grid[0].size(); j++)\n if (grid[i][j] == '1') { count++; dfs(grid, i, j); }\n return count;\n}\nvoid dfs(vector>& grid, int r, int c) {\n if (r < 0 || r >= grid.size() || c < 0 || c >= grid[0].size() || grid[r][c] != '1') return;\n grid[r][c] = '0';\n dfs(grid, r+1, c); dfs(grid, r-1, c); dfs(grid, r, c+1); dfs(grid, r, c-1);\n}", "test_cases": ["grid=[[1,1,1,1,0],[1,1,0,1,0],[1,1,0,0,0],[0,0,0,0,0]] -> 1"], "key_points": ["DFS/BFS遍历", "访问后标记为0避免重复"], "tags": ["graph", "medium", "Google", "Facebook"]} {"problem_id": "algo_00381", "original_id": "two-sum", "title": "两数之和", "category": "array", "difficulty": "easy", "companies": ["Amazon", "Google"], "description": "给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那两个整数,并返回他们的数组下标。", "solution_python": "def twoSum(nums, target):\n hashmap = {}\n for i, num in enumerate(nums):\n complement = target - num\n if complement in hashmap:\n return [hashmap[complement], i]\n hashmap[num] = i\n return []", "solution_java": "public int[] twoSum(int[] nums, int target) {\n Map map = new HashMap<>();\n for (int i = 0; i < nums.length; i++) {\n int complement = target - nums[i];\n if (map.containsKey(complement)) return new int[]{map.get(complement), i};\n map.put(nums[i], i);\n }\n return new int[]{};\n}", "solution_cpp": "vector twoSum(vector& nums, int target) {\n unordered_map m;\n for (int i = 0; i < nums.size(); i++) {\n if (m.count(target - nums[i])) return {m[target - nums[i]], i};\n m[nums[i]] = i;\n }\n return {};\n}", "test_cases": ["nums=[2,7,11,15], target=9 -> [0,1]", "nums=[3,2,4], target=6 -> [1,2]"], "key_points": ["哈希表一次遍历", "空间换时间"], "tags": ["array", "easy", "Amazon", "Google"]} {"problem_id": "algo_00382", "original_id": "merge-sorted", "title": "合并两个有序数组", "category": "array", "difficulty": "easy", "companies": ["Microsoft", "Uber"], "description": "给你两个按非递减顺序排列的整数数组 nums1 和 nums2,另有两个整数 m 和 n,分别表示 nums1 和 nums2 中的元素数目。请你合并 nums2 到 nums1 中。", "solution_python": "def merge(nums1, m, nums2, n):\n p1, p2, p = m-1, n-1, m+n-1\n while p1 >= 0 and p2 >= 0:\n if nums1[p1] > nums2[p2]: nums1[p] = nums1[p1]; p1 -= 1\n else: nums1[p] = nums2[p2]; p2 -= 1\n p -= 1\n while p2 >= 0: nums1[p] = nums2[p2]; p2 -= 1; p -= 1", "solution_java": "public void merge(int[] nums1, int m, int[] nums2, int n) {\n int p1 = m-1, p2 = n-1, p = m+n-1;\n while (p1 >= 0 && p2 >= 0) {\n nums1[p--] = nums1[p1] > nums2[p2] ? nums1[p1--] : nums2[p2--];\n }\n while (p2 >= 0) nums1[p--] = nums2[p2--];\n}", "solution_cpp": "void merge(vector& nums1, int m, vector& nums2, int n) {\n int p1 = m-1, p2 = n-1, p = m+n-1;\n while (p1 >= 0 && p2 >= 0) nums1[p--] = nums1[p1] > nums2[p2] ? nums1[p1--] : nums2[p2--];\n while (p2 >= 0) nums1[p--] = nums2[p2--];\n}", "test_cases": ["nums1=[1,2,3], m=3, nums2=[2,5,6], n=3 -> [1,2,2,3,5,6]", "nums1=[], m=0, nums2=[1], n=1 -> [1]"], "key_points": ["从后往前合并", "三指针技巧"], "tags": ["array", "easy", "Microsoft", "Uber"]} {"problem_id": "algo_00383", "original_id": "max-subarray", "title": "最大子数组和", "category": "array", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "给你一个整数数组 nums ,请你找出一个具有最大和的连续子数组,返回其最大和。", "solution_python": "def maxSubArray(nums):\n max_sum = current = nums[0]\n for num in nums[1:]:\n current = max(num, current + num)\n max_sum = max(max_sum, current)\n return max_sum", "solution_java": "public int maxSubArray(int[] nums) {\n int maxSum = nums[0], curr = nums[0];\n for (int i = 1; i < nums.length; i++) {\n curr = Math.max(nums[i], curr + nums[i]);\n maxSum = Math.max(maxSum, curr);\n }\n return maxSum;\n}", "solution_cpp": "int maxSubArray(vector& nums) {\n int maxSum = nums[0], curr = nums[0];\n for (int i = 1; i < nums.size(); i++) {\n curr = max(nums[i], curr + nums[i]);\n maxSum = max(maxSum, curr);\n }\n return maxSum;\n}", "test_cases": ["nums=[-2,1,-3,4,-1,2,1,-5,4] -> 6", "nums=[1] -> 1"], "key_points": ["Kadane算法", "动态规划基础题"], "tags": ["array", "medium", "Google", "Microsoft"]} {"problem_id": "algo_00384", "original_id": "valid-parentheses", "title": "有效的括号", "category": "string", "difficulty": "easy", "companies": ["Google", "Uber"], "description": "给定一个只包括 '(',')','{','}','[',']' 的字符串 s,判断字符串是否有效。", "solution_python": "def isValid(s):\n stack = []\n mapping = {')': '(', ']': '[', '}': '{'}\n for c in s:\n if c in mapping:\n if not stack or stack[-1] != mapping[c]: return False\n stack.pop()\n else: stack.append(c)\n return not stack", "solution_java": "public boolean isValid(String s) {\n Stack stack = new Stack<>();\n Map map = Map.of(')', '(', ']', '[', '}', '{');\n for (char c : s.toCharArray()) {\n if (map.containsValue(c)) stack.push(c);\n else if (!stack.isEmpty() && stack.pop() != map.get(c)) return false;\n }\n return stack.isEmpty();\n}", "solution_cpp": "bool isValid(string s) {\n stack st;\n unordered_map m = {{')','('},{']','['},{'}','{'}};\n for (char c : s) {\n if (m.find(c) == m.end()) st.push(c);\n else if (st.empty() || st.top() != m[c]) return false;\n else st.pop();\n }\n return st.empty();\n}", "test_cases": ["s=\"()\" -> true", "s=\"()[]{}\" -> true", "s=\"(]\" -> false"], "key_points": ["栈匹配法", "注意空栈边界"], "tags": ["string", "easy", "Google", "Uber"]} {"problem_id": "algo_00385", "original_id": "longest-palindrome", "title": "最长回文子串", "category": "string", "difficulty": "medium", "companies": ["Google", "Amazon"], "description": "给你一个字符串 s,找到 s 中最长的回文子串。", "solution_python": "def longestPalindrome(s):\n def expand(l, r):\n while l >= 0 and r < len(s) and s[l] == s[r]: l -= 1; r += 1\n return l + 1, r - 1\n start = end = 0\n for i in range(len(s)):\n l1, r1 = expand(i, i)\n l2, r2 = expand(i, i + 1)\n if r1 - l1 > end - start: start, end = l1, r1\n if r2 - l2 > end - start: start, end = l2, r2\n return s[start:end+1]", "solution_java": "public String longestPalindrome(String s) {\n int start = 0, end = 0;\n for (int i = 0; i < s.length(); i++) {\n int len1 = expand(s, i, i), len2 = expand(s, i, i+1);\n int len = Math.max(len1, len2);\n if (len > end - start) { start = i - (len-1)/2; end = i + len/2; }\n }\n return s.substring(start, end + 1);\n}\nprivate int expand(String s, int l, int r) {\n while (l >= 0 && r < s.length() && s.charAt(l) == s.charAt(r)) { l--; r++; }\n return r - l - 1;\n}", "solution_cpp": "string longestPalindrome(string s) {\n int start = 0, end = 0;\n for (int i = 0; i < s.size(); i++) {\n int len1 = expand(s, i, i), len2 = expand(s, i, i+1);\n if (max(len1, len2) > end - start) { start = i - (max(len1,len2)-1)/2; end = i + max(len1,len2)/2; }\n }\n return s.substr(start, end - start + 1);\n}", "test_cases": ["s=\"babad\" -> bab或aba", "s=\"cbbd\" -> bb"], "key_points": ["中心扩展法", "处理奇偶长度"], "tags": ["string", "medium", "Google", "Amazon"]} {"problem_id": "algo_00386", "original_id": "reverse-list", "title": "反转链表", "category": "linkedlist", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "给你单链表的头节点 head,请你反转链表,并返回反转后的链表。", "solution_python": "def reverseList(head):\n prev = None\n curr = head\n while curr:\n nxt = curr.next\n curr.next = prev\n prev = curr\n curr = nxt\n return prev", "solution_java": "public ListNode reverseList(ListNode head) {\n ListNode prev = null, curr = head;\n while (curr != null) {\n ListNode next = curr.next;\n curr.next = prev;\n prev = curr;\n curr = next;\n }\n return prev;\n}", "solution_cpp": "ListNode* reverseList(ListNode* head) {\n ListNode* prev = nullptr, *curr = head;\n while (curr) {\n ListNode* next = curr->next;\n curr->next = prev;\n prev = curr;\n curr = next;\n }\n return prev;\n}", "test_cases": ["head=[1,2,3,4,5] -> [5,4,3,2,1]", "head=[1,2] -> [2,1]"], "key_points": ["迭代法 O(1)空间", "递归法 O(n)空间"], "tags": ["linkedlist", "medium", "Google", "Microsoft"]} {"problem_id": "algo_00387", "original_id": "middle-node", "title": "链表的中间结点", "category": "linkedlist", "difficulty": "easy", "companies": ["Amazon", "Facebook"], "description": "给你单链表的头节点 head,请你找出并返回链表的中间结点。如果有两个中间结点,则返回第二个中间结点。", "solution_python": "def middleNode(head):\n slow = fast = head\n while fast and fast.next:\n slow = slow.next\n fast = fast.next.next\n return slow", "solution_java": "public ListNode middleNode(ListNode head) {\n ListNode slow = head, fast = head;\n while (fast != null && fast.next != null) {\n slow = slow.next;\n fast = fast.next.next;\n }\n return slow;\n}", "solution_cpp": "ListNode* middleNode(ListNode* head) {\n ListNode* slow = head, *fast = head;\n while (fast && fast->next) { slow = slow->next; fast = fast->next->next; }\n return slow;\n}", "test_cases": ["head=[1,2,3,4,5] -> 3", "head=[1,2,3,4,5,6] -> 4"], "key_points": ["快慢指针", "O(n)时间O(1)空间"], "tags": ["linkedlist", "easy", "Amazon", "Facebook"]} {"problem_id": "algo_00388", "original_id": "max-depth", "title": "二叉树的最大深度", "category": "tree", "difficulty": "easy", "companies": ["Microsoft", "Apple"], "description": "给定一个二叉树 root,返回其最大深度。", "solution_python": "def maxDepth(root):\n if not root: return 0\n return max(maxDepth(root.left), maxDepth(root.right)) + 1", "solution_java": "public int maxDepth(TreeNode root) {\n if (root == null) return 0;\n return Math.max(maxDepth(root.left), maxDepth(root.right)) + 1;\n}", "solution_cpp": "int maxDepth(TreeNode* root) {\n if (!root) return 0;\n return max(maxDepth(root->left), maxDepth(root->right)) + 1;\n}", "test_cases": ["root=[3,9,20,null,null,15,7] -> 3", "root=[1,null,2] -> 2"], "key_points": ["DFS递归", "层序遍历也可"], "tags": ["tree", "easy", "Microsoft", "Apple"]} {"problem_id": "algo_00389", "original_id": "inorder-traversal", "title": "二叉树的中序遍历", "category": "tree", "difficulty": "easy", "companies": ["Google", "Microsoft"], "description": "给定一个二叉树的根节点 root,返回它的中序遍历结果。", "solution_python": "def inorderTraversal(root):\n result = []\n def dfs(node):\n if node:\n dfs(node.left)\n result.append(node.val)\n dfs(node.right)\n dfs(root)\n return result", "solution_java": "public List inorderTraversal(TreeNode root) {\n List res = new ArrayList<>();\n dfs(root, res);\n return res;\n}\nprivate void dfs(TreeNode node, List res) {\n if (node == null) return;\n dfs(node.left, res); res.add(node.val); dfs(node.right, res);\n}", "solution_cpp": "vector inorderTraversal(TreeNode* root) {\n vector res;\n dfs(root, res);\n return res;\n}\nvoid dfs(TreeNode* node, vector& res) {\n if (!node) return;\n dfs(node->left, res); res.push_back(node->val); dfs(node->right, res);\n}", "test_cases": ["root=[1,null,2,3] -> [1,3,2]", "root=[] -> []"], "key_points": ["左-根-右顺序", "递归最简洁"], "tags": ["tree", "easy", "Google", "Microsoft"]} {"problem_id": "algo_00390", "original_id": "binary-search", "title": "二分查找", "category": "binarysearch", "difficulty": "easy", "companies": ["Google", "Amazon"], "description": "给定一个 n 个元素有序的(升序)整型数组 nums 和一个目标值 target,写一个函数搜索 nums 中的 target,如果目标值存在返回下标,否则返回 -1。", "solution_python": "def search(nums, target):\n left, right = 0, len(nums) - 1\n while left <= right:\n mid = (left + right) // 2\n if nums[mid] == target: return mid\n elif nums[mid] < target: left = mid + 1\n else: right = mid - 1\n return -1", "solution_java": "public int search(int[] nums, int target) {\n int left = 0, right = nums.length - 1;\n while (left <= right) {\n int mid = left + (right - left) / 2;\n if (nums[mid] == target) return mid;\n else if (nums[mid] < target) left = mid + 1;\n else right = mid - 1;\n }\n return -1;\n}", "solution_cpp": "int search(vector& nums, int target) {\n int left = 0, right = nums.size() - 1;\n while (left <= right) {\n int mid = left + (right - left) / 2;\n if (nums[mid] == target) return mid;\n else if (nums[mid] < target) left = mid + 1;\n else right = mid - 1;\n }\n return -1;\n}", "test_cases": ["nums=[-1,0,3,5,9,12], target=9 -> 4", "nums=[-1,0,3,5,9,12], target=2 -> -1"], "key_points": ["标准模板", "注意防溢出写法"], "tags": ["binarysearch", "easy", "Google", "Amazon"]} {"problem_id": "algo_00391", "original_id": "climbing-stairs", "title": "爬楼梯", "category": "dp", "difficulty": "easy", "companies": ["Amazon", "Google"], "description": "假设你正在爬楼梯。需要 n 阶你才能到达楼顶。每次你可以爬 1 或 2 个台阶。你有多少种不同的方法可以爬到楼顶?", "solution_python": "def climbStairs(n):\n if n <= 2: return n\n a, b = 1, 2\n for _ in range(3, n+1):\n a, b = b, a + b\n return b", "solution_java": "public int climbStairs(int n) {\n if (n <= 2) return n;\n int a = 1, b = 2;\n for (int i = 3; i <= n; i++) { int temp = a + b; a = b; b = temp; }\n return b;\n}", "solution_cpp": "int climbStairs(int n) {\n if (n <= 2) return n;\n int a = 1, b = 2;\n for (int i = 3; i <= n; i++) { int temp = a + b; a = b; b = temp; }\n return b;\n}", "test_cases": ["n=2 -> 2", "n=3 -> 3", "n=5 -> 8"], "key_points": ["斐波那契数列", "滚动数组优化空间"], "tags": ["dp", "easy", "Amazon", "Google"]} {"problem_id": "algo_00392", "original_id": "coin-change", "title": "零钱兑换", "category": "dp", "difficulty": "medium", "companies": ["Google", "Amazon"], "description": "给你一个整数数组 coins 表示不同面额的硬币,以及一个整数 amount 表示总金额。计算并返回可以凑成总金额所需的最少的硬币个数。如果没有任何一种硬币组合能组成总金额,返回 -1。", "solution_python": "def coinChange(coins, amount):\n dp = [float('inf')] * (amount + 1)\n dp[0] = 0\n for coin in coins:\n for x in range(coin, amount + 1):\n dp[x] = min(dp[x], dp[x - coin] + 1)\n return dp[amount] if dp[amount] != float('inf') else -1", "solution_java": "public int coinChange(int[] coins, int amount) {\n int[] dp = new int[amount + 1];\n Arrays.fill(dp, amount + 1);\n dp[0] = 0;\n for (int coin : coins) {\n for (int x = coin; x <= amount; x++) {\n dp[x] = Math.min(dp[x], dp[x - coin] + 1);\n }\n }\n return dp[amount] > amount ? -1 : dp[amount];\n}", "solution_cpp": "int coinChange(vector& coins, int amount) {\n vector dp(amount + 1, amount + 1);\n dp[0] = 0;\n for (int coin : coins) {\n for (int x = coin; x <= amount; x++) {\n dp[x] = min(dp[x], dp[x - coin] + 1);\n }\n }\n return dp[amount] > amount ? -1 : dp[amount];\n}", "test_cases": ["coins=[1,2,5], amount=11 -> 3", "coins=[2], amount=3 -> -1"], "key_points": ["完全背包问题", "dp[x] = min(dp[x-coin]+1)"], "tags": ["dp", "medium", "Google", "Amazon"]} {"problem_id": "algo_00393", "original_id": "subsets", "title": "子集", "category": "backtracking", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "给你一个整数数组 nums ,数组中的元素 互不相同 。返回该数组所有可能的子集(幂集)。", "solution_python": "def subsets(nums):\n result = []\n def backtrack(start, path):\n result.append(path[:])\n for i in range(start, len(nums)):\n path.append(nums[i])\n backtrack(i + 1, path)\n path.pop()\n backtrack(0, [])\n return result", "solution_java": "public List> subsets(int[] nums) {\n List> result = new ArrayList<>();\n backtrack(nums, 0, new ArrayList<>(), result);\n return result;\n}\nprivate void backtrack(int[] nums, int start, List path, List> result) {\n result.add(new ArrayList<>(path));\n for (int i = start; i < nums.length; i++) {\n path.add(nums[i]);\n backtrack(nums, i + 1, path, result);\n path.remove(path.size() - 1);\n }\n}", "solution_cpp": "vector> subsets(vector& nums) {\n vector> result;\n vector path;\n backtrack(nums, 0, path, result);\n return result;\n}\nvoid backtrack(vector& nums, int start, vector& path, vector>& result) {\n result.push_back(path);\n for (int i = start; i < nums.size(); i++) {\n path.push_back(nums[i]);\n backtrack(nums, i + 1, path, result);\n path.pop_back();\n }\n}", "test_cases": ["nums=[1,2,3] -> [[],[1],[2],[1,2],[3],[1,3],[2,3],[1,2,3]]"], "key_points": ["选或不选", "DFS遍历子集树"], "tags": ["backtracking", "medium", "Google", "Microsoft"]} {"problem_id": "algo_00394", "original_id": "permutations", "title": "全排列", "category": "backtracking", "difficulty": "medium", "companies": ["Google", "Facebook"], "description": "给定一个不含重复数字的数组 nums,返回其所有可能的全排列。", "solution_python": "def permute(nums):\n result = []\n def backtrack(path, used):\n if len(path) == len(nums):\n result.append(path[:])\n return\n for i in range(len(nums)):\n if used[i]: continue\n used[i] = True\n path.append(nums[i])\n backtrack(path, used)\n path.pop()\n used[i] = False\n backtrack([], [False]*len(nums))\n return result", "solution_java": "public List> permute(int[] nums) {\n List> result = new ArrayList<>();\n boolean[] used = new boolean[nums.length];\n backtrack(nums, used, new ArrayList<>(), result);\n return result;\n}\nprivate void backtrack(int[] nums, boolean[] used, List path, List> result) {\n if (path.size() == nums.length) { result.add(new ArrayList<>(path)); return; }\n for (int i = 0; i < nums.length; i++) {\n if (used[i]) continue;\n used[i] = true;\n path.add(nums[i]);\n backtrack(nums, used, path, result);\n path.remove(path.size() - 1);\n used[i] = false;\n }\n}", "solution_cpp": "vector> permute(vector& nums) {\n vector> result;\n vector used(nums.size(), false);\n vector path;\n backtrack(nums, used, path, result);\n return result;\n}\nvoid backtrack(vector& nums, vector& used, vector& path, vector>& result) {\n if (path.size() == nums.size()) { result.push_back(path); return; }\n for (int i = 0; i < nums.size(); i++) {\n if (used[i]) continue;\n used[i] = true;\n path.push_back(nums[i]);\n backtrack(nums, used, path, result);\n path.pop_back();\n used[i] = false;\n }\n}", "test_cases": ["nums=[1,2,3] -> [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]"], "key_points": ["标记已使用元素", "回溯经典模板"], "tags": ["backtracking", "medium", "Google", "Facebook"]} {"problem_id": "algo_00395", "original_id": "top-k-frequent", "title": "前K个高频元素", "category": "heap", "difficulty": "medium", "companies": ["Amazon", "Facebook"], "description": "给你一个整数数组 nums 和一个整数 k,请你返回其中出现频率前 k 高的元素。", "solution_python": "import heapq\nfrom collections import Counter\ndef topKFrequent(nums, k):\n count = Counter(nums)\n heap = []\n for num, freq in count.items():\n heapq.heappush(heap, (freq, num))\n if len(heap) > k: heapq.heappop(heap)\n return [num for freq, num in heap]", "solution_java": "public int[] topKFrequent(int[] nums, int k) {\n Map count = new HashMap<>();\n for (int n : nums) count.put(n, count.getOrDefault(n, 0) + 1);\n PriorityQueue> heap = \n new PriorityQueue<>((a, b) -> a.getValue() - b.getValue());\n for (Map.Entry e : count.entrySet()) {\n heap.offer(e);\n if (heap.size() > k) heap.poll();\n }\n int[] res = new int[k];\n for (int i = k - 1; i >= 0; i--) res[i] = heap.poll().getKey();\n return res;\n}", "solution_cpp": "vector topKFrequent(vector& nums, int k) {\n unordered_map count;\n for (int n : nums) count[n]++;\n priority_queue, vector>, greater>> heap;\n for (auto& [num, freq] : count) {\n heap.push({freq, num});\n if (heap.size() > k) heap.pop();\n }\n vector res;\n while (!heap.empty()) { res.push_back(heap.top().second); heap.pop(); }\n reverse(res.begin(), res.end());\n return res;\n}", "test_cases": ["nums=[1,1,1,2,2,3], k=2 -> [1,2]", "nums=[1], k=1 -> [1]"], "key_points": ["小顶堆保持大小k", "时间复杂度O(nlogk)"], "tags": ["heap", "medium", "Amazon", "Facebook"]} {"problem_id": "algo_00396", "original_id": "3sum", "title": "三数之和", "category": "two-pointers", "difficulty": "medium", "companies": ["Google", "Amazon"], "description": "给你一个整数数组 nums,判断是否存在三元组满足和为0,返回所有不重复的三元组。", "solution_python": "def threeSum(nums):\n nums.sort()\n result = []\n for i in range(len(nums) - 2):\n if i > 0 and nums[i] == nums[i-1]: continue\n left, right = i + 1, len(nums) - 1\n while left < right:\n total = nums[i] + nums[left] + nums[right]\n if total < 0: left += 1\n elif total > 0: right -= 1\n else:\n result.append([nums[i], nums[left], nums[right]])\n while left < right and nums[left] == nums[left+1]: left += 1\n while left < right and nums[right] == nums[right-1]: right -= 1\n left += 1; right -= 1\n return result", "solution_java": "public List> threeSum(int[] nums) {\n Arrays.sort(nums);\n List> result = new ArrayList<>();\n for (int i = 0; i < nums.length - 2; i++) {\n if (i > 0 && nums[i] == nums[i-1]) continue;\n int left = i + 1, right = nums.length - 1;\n while (left < right) {\n int total = nums[i] + nums[left] + nums[right];\n if (total < 0) left++;\n else if (total > 0) right--;\n else {\n result.add(Arrays.asList(nums[i], nums[left], nums[right]));\n while (left < right && nums[left] == nums[left+1]) left++;\n while (left < right && nums[right] == nums[right-1]) right--;\n left++; right--;\n }\n }\n }\n return result;\n}", "solution_cpp": "vector> threeSum(vector& nums) {\n sort(nums.begin(), nums.end());\n vector> result;\n for (int i = 0; i < nums.size() - 2; i++) {\n if (i > 0 && nums[i] == nums[i-1]) continue;\n int left = i + 1, right = nums.size() - 1;\n while (left < right) {\n int total = nums[i] + nums[left] + nums[right];\n if (total < 0) left++;\n else if (total > 0) right--;\n else {\n result.push_back({nums[i], nums[left], nums[right]});\n while (left < right && nums[left] == nums[left+1]) left++;\n while (left < right && nums[right] == nums[right-1]) right--;\n left++; right--;\n }\n }\n }\n return result;\n}", "test_cases": ["nums=[-1,0,1,2,-1,-4] -> [[-1,-1,2],[-1,0,1]]"], "key_points": ["排序+双指针", "去重是关键"], "tags": ["two-pointers", "medium", "Google", "Amazon"]} {"problem_id": "algo_00397", "original_id": "container-water", "title": "盛最多水的容器", "category": "two-pointers", "difficulty": "medium", "companies": ["Google", "Uber"], "description": "给定一个长度为 n 的整数数组 height,找出其中的两条线,使得它们与 x 轴共同构成的容器可以容纳最多的水。", "solution_python": "def maxArea(height):\n left, right = 0, len(height) - 1\n max_area = 0\n while left < right:\n h = min(height[left], height[right])\n max_area = max(max_area, h * (right - left))\n if height[left] < height[right]: left += 1\n else: right -= 1\n return max_area", "solution_java": "public int maxArea(int[] height) {\n int left = 0, right = height.length - 1, maxArea = 0;\n while (left < right) {\n int h = Math.min(height[left], height[right]);\n maxArea = Math.max(maxArea, h * (right - left));\n if (height[left] < height[right]) left++;\n else right--;\n }\n return maxArea;\n}", "solution_cpp": "int maxArea(vector& height) {\n int left = 0, right = height.size() - 1, maxArea = 0;\n while (left < right) {\n int h = min(height[left], height[right]);\n maxArea = max(maxArea, h * (right - left));\n if (height[left] < height[right]) left++;\n else right--;\n }\n return maxArea;\n}", "test_cases": ["height=[1,8,6,2,5,4,8,3,7] -> 49"], "key_points": ["移动短边指针", "面积=min(h1,h2)*width"], "tags": ["two-pointers", "medium", "Google", "Uber"]} {"problem_id": "algo_00398", "original_id": "min-stack", "title": "最小栈", "category": "stack", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "设计一个支持 push,pop,top 操作,并能在常数时间内检索到最小元素的栈。", "solution_python": "class MinStack:\n def __init__(self):\n self.stack = []\n self.min_stack = []\n def push(self, val):\n self.stack.append(val)\n self.min_stack.append(min(val, self.min_stack[-1] if self.min_stack else val))\n def pop(self):\n self.stack.pop(); self.min_stack.pop()\n def top(self): return self.stack[-1]\n def getMin(self): return self.min_stack[-1]", "solution_java": "class MinStack {\n Stack stack = new Stack<>();\n Stack minStack = new Stack<>();\n public void push(int val) { stack.push(val); minStack.push(Math.min(val, minStack.isEmpty() ? val : minStack.peek())); }\n public void pop() { stack.pop(); minStack.pop(); }\n public int top() { return stack.peek(); }\n public int getMin() { return minStack.peek(); }\n}", "solution_cpp": "class MinStack {\n stack st, minSt;\npublic:\n void push(int val) { st.push(val); minSt.push(min(val, minSt.empty() ? val : minSt.top())); }\n void pop() { st.pop(); minSt.pop(); }\n int top() { return st.top(); }\n int getMin() { return minSt.top(); }\n};", "test_cases": ["push(-2), push(0), push(-3) -> getMin() returns -3"], "key_points": ["辅助栈记录最小值", "O(1)时间获取最小值"], "tags": ["stack", "medium", "Google", "Microsoft"]} {"problem_id": "algo_00399", "original_id": "lru-cache", "title": "LRU缓存", "category": "design", "difficulty": "hard", "companies": ["Google", "Amazon"], "description": "设计和实现一个 LRU(最近最少使用)缓存机制。", "solution_python": "class LRUCache:\n def __init__(self, capacity):\n self.capacity = capacity\n self.cache = {}\n self.order = []\n def get(self, key):\n if key not in self.cache: return -1\n self.order.remove(key); self.order.append(key)\n return self.cache[key]\n def put(self, key, value):\n if key in self.cache:\n self.order.remove(key)\n elif len(self.cache) >= self.capacity:\n del self.cache[self.order.pop(0)]\n self.cache[key] = value; self.order.append(key)", "solution_java": "class LRUCache {\n int capacity;\n LinkedHashMap cache = new LinkedHashMap<>();\n public LRUCache(int cap) { capacity = cap; }\n public int get(int key) { return cache.containsKey(key) ? cache.remove(key) : -1; }\n public void put(int key, int val) {\n if (cache.containsKey(key)) cache.remove(key);\n else if (cache.size() >= capacity) cache.remove(cache.keySet().iterator().next());\n cache.put(key, val);\n }\n}", "solution_cpp": "class LRUCache {\n int cap;\n list> dll;\n unordered_map>::iterator> cache;\npublic:\n LRUCache(int capacity) : cap(capacity) {}\n int get(int key) {\n auto it = cache.find(key);\n if (it == cache.end()) return -1;\n dll.splice(dll.end(), dll, it->second);\n return it->second->second;\n }\n void put(int key, int value) {\n auto it = cache.find(key);\n if (it != cache.end()) dll.erase(it->second);\n else if (cache.size() >= cap) { cache.erase(dll.front().first); dll.pop_front(); }\n dll.push_back({key, value});\n cache[key] = --dll.end();\n }\n};", "test_cases": ["put(1,1), put(2,2), get(1) -> 1"], "key_points": ["HashMap + 双向链表", "O(1)时间操作"], "tags": ["design", "hard", "Google", "Amazon"]} {"problem_id": "algo_00400", "original_id": "num-islands", "title": "岛屿数量", "category": "graph", "difficulty": "medium", "companies": ["Google", "Facebook"], "description": "给你一个由 '1'(陆地)和 '0'(水)组成的二维网格,请你计算网格中岛屿的数量。岛屿总是被水包围,且只能由水平或垂直方向相邻的陆地连接形成。", "solution_python": "def numIslands(grid):\n if not grid: return 0\n rows, cols = len(grid), len(grid[0])\n count = 0\n def dfs(r, c):\n if r < 0 or r >= rows or c < 0 or c >= cols or grid[r][c] != '1': return\n grid[r][c] = '0'\n dfs(r+1, c); dfs(r-1, c); dfs(r, c+1); dfs(r, c-1)\n for r in range(rows):\n for c in range(cols):\n if grid[r][c] == '1': count += 1; dfs(r, c)\n return count", "solution_java": "public int numIslands(char[][] grid) {\n if (grid.length == 0) return 0;\n int count = 0;\n for (int i = 0; i < grid.length; i++)\n for (int j = 0; j < grid[0].length; j++)\n if (grid[i][j] == '1') { count++; dfs(grid, i, j); }\n return count;\n}\nprivate void dfs(char[][] grid, int r, int c) {\n if (r < 0 || r >= grid.length || c < 0 || c >= grid[0].length || grid[r][c] != '1') return;\n grid[r][c] = '0';\n dfs(grid, r+1, c); dfs(grid, r-1, c); dfs(grid, r, c+1); dfs(grid, r, c-1);\n}", "solution_cpp": "int numIslands(vector>& grid) {\n if (grid.empty()) return 0;\n int count = 0;\n for (int i = 0; i < grid.size(); i++)\n for (int j = 0; j < grid[0].size(); j++)\n if (grid[i][j] == '1') { count++; dfs(grid, i, j); }\n return count;\n}\nvoid dfs(vector>& grid, int r, int c) {\n if (r < 0 || r >= grid.size() || c < 0 || c >= grid[0].size() || grid[r][c] != '1') return;\n grid[r][c] = '0';\n dfs(grid, r+1, c); dfs(grid, r-1, c); dfs(grid, r, c+1); dfs(grid, r, c-1);\n}", "test_cases": ["grid=[[1,1,1,1,0],[1,1,0,1,0],[1,1,0,0,0],[0,0,0,0,0]] -> 1"], "key_points": ["DFS/BFS遍历", "访问后标记为0避免重复"], "tags": ["graph", "medium", "Google", "Facebook"]} {"problem_id": "algo_00401", "original_id": "two-sum", "title": "两数之和", "category": "array", "difficulty": "easy", "companies": ["Amazon", "Google"], "description": "给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那两个整数,并返回他们的数组下标。", "solution_python": "def twoSum(nums, target):\n hashmap = {}\n for i, num in enumerate(nums):\n complement = target - num\n if complement in hashmap:\n return [hashmap[complement], i]\n hashmap[num] = i\n return []", "solution_java": "public int[] twoSum(int[] nums, int target) {\n Map map = new HashMap<>();\n for (int i = 0; i < nums.length; i++) {\n int complement = target - nums[i];\n if (map.containsKey(complement)) return new int[]{map.get(complement), i};\n map.put(nums[i], i);\n }\n return new int[]{};\n}", "solution_cpp": "vector twoSum(vector& nums, int target) {\n unordered_map m;\n for (int i = 0; i < nums.size(); i++) {\n if (m.count(target - nums[i])) return {m[target - nums[i]], i};\n m[nums[i]] = i;\n }\n return {};\n}", "test_cases": ["nums=[2,7,11,15], target=9 -> [0,1]", "nums=[3,2,4], target=6 -> [1,2]"], "key_points": ["哈希表一次遍历", "空间换时间"], "tags": ["array", "easy", "Amazon", "Google"]} {"problem_id": "algo_00402", "original_id": "merge-sorted", "title": "合并两个有序数组", "category": "array", "difficulty": "easy", "companies": ["Microsoft", "Uber"], "description": "给你两个按非递减顺序排列的整数数组 nums1 和 nums2,另有两个整数 m 和 n,分别表示 nums1 和 nums2 中的元素数目。请你合并 nums2 到 nums1 中。", "solution_python": "def merge(nums1, m, nums2, n):\n p1, p2, p = m-1, n-1, m+n-1\n while p1 >= 0 and p2 >= 0:\n if nums1[p1] > nums2[p2]: nums1[p] = nums1[p1]; p1 -= 1\n else: nums1[p] = nums2[p2]; p2 -= 1\n p -= 1\n while p2 >= 0: nums1[p] = nums2[p2]; p2 -= 1; p -= 1", "solution_java": "public void merge(int[] nums1, int m, int[] nums2, int n) {\n int p1 = m-1, p2 = n-1, p = m+n-1;\n while (p1 >= 0 && p2 >= 0) {\n nums1[p--] = nums1[p1] > nums2[p2] ? nums1[p1--] : nums2[p2--];\n }\n while (p2 >= 0) nums1[p--] = nums2[p2--];\n}", "solution_cpp": "void merge(vector& nums1, int m, vector& nums2, int n) {\n int p1 = m-1, p2 = n-1, p = m+n-1;\n while (p1 >= 0 && p2 >= 0) nums1[p--] = nums1[p1] > nums2[p2] ? nums1[p1--] : nums2[p2--];\n while (p2 >= 0) nums1[p--] = nums2[p2--];\n}", "test_cases": ["nums1=[1,2,3], m=3, nums2=[2,5,6], n=3 -> [1,2,2,3,5,6]", "nums1=[], m=0, nums2=[1], n=1 -> [1]"], "key_points": ["从后往前合并", "三指针技巧"], "tags": ["array", "easy", "Microsoft", "Uber"]} {"problem_id": "algo_00403", "original_id": "max-subarray", "title": "最大子数组和", "category": "array", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "给你一个整数数组 nums ,请你找出一个具有最大和的连续子数组,返回其最大和。", "solution_python": "def maxSubArray(nums):\n max_sum = current = nums[0]\n for num in nums[1:]:\n current = max(num, current + num)\n max_sum = max(max_sum, current)\n return max_sum", "solution_java": "public int maxSubArray(int[] nums) {\n int maxSum = nums[0], curr = nums[0];\n for (int i = 1; i < nums.length; i++) {\n curr = Math.max(nums[i], curr + nums[i]);\n maxSum = Math.max(maxSum, curr);\n }\n return maxSum;\n}", "solution_cpp": "int maxSubArray(vector& nums) {\n int maxSum = nums[0], curr = nums[0];\n for (int i = 1; i < nums.size(); i++) {\n curr = max(nums[i], curr + nums[i]);\n maxSum = max(maxSum, curr);\n }\n return maxSum;\n}", "test_cases": ["nums=[-2,1,-3,4,-1,2,1,-5,4] -> 6", "nums=[1] -> 1"], "key_points": ["Kadane算法", "动态规划基础题"], "tags": ["array", "medium", "Google", "Microsoft"]} {"problem_id": "algo_00404", "original_id": "valid-parentheses", "title": "有效的括号", "category": "string", "difficulty": "easy", "companies": ["Google", "Uber"], "description": "给定一个只包括 '(',')','{','}','[',']' 的字符串 s,判断字符串是否有效。", "solution_python": "def isValid(s):\n stack = []\n mapping = {')': '(', ']': '[', '}': '{'}\n for c in s:\n if c in mapping:\n if not stack or stack[-1] != mapping[c]: return False\n stack.pop()\n else: stack.append(c)\n return not stack", "solution_java": "public boolean isValid(String s) {\n Stack stack = new Stack<>();\n Map map = Map.of(')', '(', ']', '[', '}', '{');\n for (char c : s.toCharArray()) {\n if (map.containsValue(c)) stack.push(c);\n else if (!stack.isEmpty() && stack.pop() != map.get(c)) return false;\n }\n return stack.isEmpty();\n}", "solution_cpp": "bool isValid(string s) {\n stack st;\n unordered_map m = {{')','('},{']','['},{'}','{'}};\n for (char c : s) {\n if (m.find(c) == m.end()) st.push(c);\n else if (st.empty() || st.top() != m[c]) return false;\n else st.pop();\n }\n return st.empty();\n}", "test_cases": ["s=\"()\" -> true", "s=\"()[]{}\" -> true", "s=\"(]\" -> false"], "key_points": ["栈匹配法", "注意空栈边界"], "tags": ["string", "easy", "Google", "Uber"]} {"problem_id": "algo_00405", "original_id": "longest-palindrome", "title": "最长回文子串", "category": "string", "difficulty": "medium", "companies": ["Google", "Amazon"], "description": "给你一个字符串 s,找到 s 中最长的回文子串。", "solution_python": "def longestPalindrome(s):\n def expand(l, r):\n while l >= 0 and r < len(s) and s[l] == s[r]: l -= 1; r += 1\n return l + 1, r - 1\n start = end = 0\n for i in range(len(s)):\n l1, r1 = expand(i, i)\n l2, r2 = expand(i, i + 1)\n if r1 - l1 > end - start: start, end = l1, r1\n if r2 - l2 > end - start: start, end = l2, r2\n return s[start:end+1]", "solution_java": "public String longestPalindrome(String s) {\n int start = 0, end = 0;\n for (int i = 0; i < s.length(); i++) {\n int len1 = expand(s, i, i), len2 = expand(s, i, i+1);\n int len = Math.max(len1, len2);\n if (len > end - start) { start = i - (len-1)/2; end = i + len/2; }\n }\n return s.substring(start, end + 1);\n}\nprivate int expand(String s, int l, int r) {\n while (l >= 0 && r < s.length() && s.charAt(l) == s.charAt(r)) { l--; r++; }\n return r - l - 1;\n}", "solution_cpp": "string longestPalindrome(string s) {\n int start = 0, end = 0;\n for (int i = 0; i < s.size(); i++) {\n int len1 = expand(s, i, i), len2 = expand(s, i, i+1);\n if (max(len1, len2) > end - start) { start = i - (max(len1,len2)-1)/2; end = i + max(len1,len2)/2; }\n }\n return s.substr(start, end - start + 1);\n}", "test_cases": ["s=\"babad\" -> bab或aba", "s=\"cbbd\" -> bb"], "key_points": ["中心扩展法", "处理奇偶长度"], "tags": ["string", "medium", "Google", "Amazon"]} {"problem_id": "algo_00406", "original_id": "reverse-list", "title": "反转链表", "category": "linkedlist", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "给你单链表的头节点 head,请你反转链表,并返回反转后的链表。", "solution_python": "def reverseList(head):\n prev = None\n curr = head\n while curr:\n nxt = curr.next\n curr.next = prev\n prev = curr\n curr = nxt\n return prev", "solution_java": "public ListNode reverseList(ListNode head) {\n ListNode prev = null, curr = head;\n while (curr != null) {\n ListNode next = curr.next;\n curr.next = prev;\n prev = curr;\n curr = next;\n }\n return prev;\n}", "solution_cpp": "ListNode* reverseList(ListNode* head) {\n ListNode* prev = nullptr, *curr = head;\n while (curr) {\n ListNode* next = curr->next;\n curr->next = prev;\n prev = curr;\n curr = next;\n }\n return prev;\n}", "test_cases": ["head=[1,2,3,4,5] -> [5,4,3,2,1]", "head=[1,2] -> [2,1]"], "key_points": ["迭代法 O(1)空间", "递归法 O(n)空间"], "tags": ["linkedlist", "medium", "Google", "Microsoft"]} {"problem_id": "algo_00407", "original_id": "middle-node", "title": "链表的中间结点", "category": "linkedlist", "difficulty": "easy", "companies": ["Amazon", "Facebook"], "description": "给你单链表的头节点 head,请你找出并返回链表的中间结点。如果有两个中间结点,则返回第二个中间结点。", "solution_python": "def middleNode(head):\n slow = fast = head\n while fast and fast.next:\n slow = slow.next\n fast = fast.next.next\n return slow", "solution_java": "public ListNode middleNode(ListNode head) {\n ListNode slow = head, fast = head;\n while (fast != null && fast.next != null) {\n slow = slow.next;\n fast = fast.next.next;\n }\n return slow;\n}", "solution_cpp": "ListNode* middleNode(ListNode* head) {\n ListNode* slow = head, *fast = head;\n while (fast && fast->next) { slow = slow->next; fast = fast->next->next; }\n return slow;\n}", "test_cases": ["head=[1,2,3,4,5] -> 3", "head=[1,2,3,4,5,6] -> 4"], "key_points": ["快慢指针", "O(n)时间O(1)空间"], "tags": ["linkedlist", "easy", "Amazon", "Facebook"]} {"problem_id": "algo_00408", "original_id": "max-depth", "title": "二叉树的最大深度", "category": "tree", "difficulty": "easy", "companies": ["Microsoft", "Apple"], "description": "给定一个二叉树 root,返回其最大深度。", "solution_python": "def maxDepth(root):\n if not root: return 0\n return max(maxDepth(root.left), maxDepth(root.right)) + 1", "solution_java": "public int maxDepth(TreeNode root) {\n if (root == null) return 0;\n return Math.max(maxDepth(root.left), maxDepth(root.right)) + 1;\n}", "solution_cpp": "int maxDepth(TreeNode* root) {\n if (!root) return 0;\n return max(maxDepth(root->left), maxDepth(root->right)) + 1;\n}", "test_cases": ["root=[3,9,20,null,null,15,7] -> 3", "root=[1,null,2] -> 2"], "key_points": ["DFS递归", "层序遍历也可"], "tags": ["tree", "easy", "Microsoft", "Apple"]} {"problem_id": "algo_00409", "original_id": "inorder-traversal", "title": "二叉树的中序遍历", "category": "tree", "difficulty": "easy", "companies": ["Google", "Microsoft"], "description": "给定一个二叉树的根节点 root,返回它的中序遍历结果。", "solution_python": "def inorderTraversal(root):\n result = []\n def dfs(node):\n if node:\n dfs(node.left)\n result.append(node.val)\n dfs(node.right)\n dfs(root)\n return result", "solution_java": "public List inorderTraversal(TreeNode root) {\n List res = new ArrayList<>();\n dfs(root, res);\n return res;\n}\nprivate void dfs(TreeNode node, List res) {\n if (node == null) return;\n dfs(node.left, res); res.add(node.val); dfs(node.right, res);\n}", "solution_cpp": "vector inorderTraversal(TreeNode* root) {\n vector res;\n dfs(root, res);\n return res;\n}\nvoid dfs(TreeNode* node, vector& res) {\n if (!node) return;\n dfs(node->left, res); res.push_back(node->val); dfs(node->right, res);\n}", "test_cases": ["root=[1,null,2,3] -> [1,3,2]", "root=[] -> []"], "key_points": ["左-根-右顺序", "递归最简洁"], "tags": ["tree", "easy", "Google", "Microsoft"]} {"problem_id": "algo_00410", "original_id": "binary-search", "title": "二分查找", "category": "binarysearch", "difficulty": "easy", "companies": ["Google", "Amazon"], "description": "给定一个 n 个元素有序的(升序)整型数组 nums 和一个目标值 target,写一个函数搜索 nums 中的 target,如果目标值存在返回下标,否则返回 -1。", "solution_python": "def search(nums, target):\n left, right = 0, len(nums) - 1\n while left <= right:\n mid = (left + right) // 2\n if nums[mid] == target: return mid\n elif nums[mid] < target: left = mid + 1\n else: right = mid - 1\n return -1", "solution_java": "public int search(int[] nums, int target) {\n int left = 0, right = nums.length - 1;\n while (left <= right) {\n int mid = left + (right - left) / 2;\n if (nums[mid] == target) return mid;\n else if (nums[mid] < target) left = mid + 1;\n else right = mid - 1;\n }\n return -1;\n}", "solution_cpp": "int search(vector& nums, int target) {\n int left = 0, right = nums.size() - 1;\n while (left <= right) {\n int mid = left + (right - left) / 2;\n if (nums[mid] == target) return mid;\n else if (nums[mid] < target) left = mid + 1;\n else right = mid - 1;\n }\n return -1;\n}", "test_cases": ["nums=[-1,0,3,5,9,12], target=9 -> 4", "nums=[-1,0,3,5,9,12], target=2 -> -1"], "key_points": ["标准模板", "注意防溢出写法"], "tags": ["binarysearch", "easy", "Google", "Amazon"]} {"problem_id": "algo_00411", "original_id": "climbing-stairs", "title": "爬楼梯", "category": "dp", "difficulty": "easy", "companies": ["Amazon", "Google"], "description": "假设你正在爬楼梯。需要 n 阶你才能到达楼顶。每次你可以爬 1 或 2 个台阶。你有多少种不同的方法可以爬到楼顶?", "solution_python": "def climbStairs(n):\n if n <= 2: return n\n a, b = 1, 2\n for _ in range(3, n+1):\n a, b = b, a + b\n return b", "solution_java": "public int climbStairs(int n) {\n if (n <= 2) return n;\n int a = 1, b = 2;\n for (int i = 3; i <= n; i++) { int temp = a + b; a = b; b = temp; }\n return b;\n}", "solution_cpp": "int climbStairs(int n) {\n if (n <= 2) return n;\n int a = 1, b = 2;\n for (int i = 3; i <= n; i++) { int temp = a + b; a = b; b = temp; }\n return b;\n}", "test_cases": ["n=2 -> 2", "n=3 -> 3", "n=5 -> 8"], "key_points": ["斐波那契数列", "滚动数组优化空间"], "tags": ["dp", "easy", "Amazon", "Google"]} {"problem_id": "algo_00412", "original_id": "coin-change", "title": "零钱兑换", "category": "dp", "difficulty": "medium", "companies": ["Google", "Amazon"], "description": "给你一个整数数组 coins 表示不同面额的硬币,以及一个整数 amount 表示总金额。计算并返回可以凑成总金额所需的最少的硬币个数。如果没有任何一种硬币组合能组成总金额,返回 -1。", "solution_python": "def coinChange(coins, amount):\n dp = [float('inf')] * (amount + 1)\n dp[0] = 0\n for coin in coins:\n for x in range(coin, amount + 1):\n dp[x] = min(dp[x], dp[x - coin] + 1)\n return dp[amount] if dp[amount] != float('inf') else -1", "solution_java": "public int coinChange(int[] coins, int amount) {\n int[] dp = new int[amount + 1];\n Arrays.fill(dp, amount + 1);\n dp[0] = 0;\n for (int coin : coins) {\n for (int x = coin; x <= amount; x++) {\n dp[x] = Math.min(dp[x], dp[x - coin] + 1);\n }\n }\n return dp[amount] > amount ? -1 : dp[amount];\n}", "solution_cpp": "int coinChange(vector& coins, int amount) {\n vector dp(amount + 1, amount + 1);\n dp[0] = 0;\n for (int coin : coins) {\n for (int x = coin; x <= amount; x++) {\n dp[x] = min(dp[x], dp[x - coin] + 1);\n }\n }\n return dp[amount] > amount ? -1 : dp[amount];\n}", "test_cases": ["coins=[1,2,5], amount=11 -> 3", "coins=[2], amount=3 -> -1"], "key_points": ["完全背包问题", "dp[x] = min(dp[x-coin]+1)"], "tags": ["dp", "medium", "Google", "Amazon"]} {"problem_id": "algo_00413", "original_id": "subsets", "title": "子集", "category": "backtracking", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "给你一个整数数组 nums ,数组中的元素 互不相同 。返回该数组所有可能的子集(幂集)。", "solution_python": "def subsets(nums):\n result = []\n def backtrack(start, path):\n result.append(path[:])\n for i in range(start, len(nums)):\n path.append(nums[i])\n backtrack(i + 1, path)\n path.pop()\n backtrack(0, [])\n return result", "solution_java": "public List> subsets(int[] nums) {\n List> result = new ArrayList<>();\n backtrack(nums, 0, new ArrayList<>(), result);\n return result;\n}\nprivate void backtrack(int[] nums, int start, List path, List> result) {\n result.add(new ArrayList<>(path));\n for (int i = start; i < nums.length; i++) {\n path.add(nums[i]);\n backtrack(nums, i + 1, path, result);\n path.remove(path.size() - 1);\n }\n}", "solution_cpp": "vector> subsets(vector& nums) {\n vector> result;\n vector path;\n backtrack(nums, 0, path, result);\n return result;\n}\nvoid backtrack(vector& nums, int start, vector& path, vector>& result) {\n result.push_back(path);\n for (int i = start; i < nums.size(); i++) {\n path.push_back(nums[i]);\n backtrack(nums, i + 1, path, result);\n path.pop_back();\n }\n}", "test_cases": ["nums=[1,2,3] -> [[],[1],[2],[1,2],[3],[1,3],[2,3],[1,2,3]]"], "key_points": ["选或不选", "DFS遍历子集树"], "tags": ["backtracking", "medium", "Google", "Microsoft"]} {"problem_id": "algo_00414", "original_id": "permutations", "title": "全排列", "category": "backtracking", "difficulty": "medium", "companies": ["Google", "Facebook"], "description": "给定一个不含重复数字的数组 nums,返回其所有可能的全排列。", "solution_python": "def permute(nums):\n result = []\n def backtrack(path, used):\n if len(path) == len(nums):\n result.append(path[:])\n return\n for i in range(len(nums)):\n if used[i]: continue\n used[i] = True\n path.append(nums[i])\n backtrack(path, used)\n path.pop()\n used[i] = False\n backtrack([], [False]*len(nums))\n return result", "solution_java": "public List> permute(int[] nums) {\n List> result = new ArrayList<>();\n boolean[] used = new boolean[nums.length];\n backtrack(nums, used, new ArrayList<>(), result);\n return result;\n}\nprivate void backtrack(int[] nums, boolean[] used, List path, List> result) {\n if (path.size() == nums.length) { result.add(new ArrayList<>(path)); return; }\n for (int i = 0; i < nums.length; i++) {\n if (used[i]) continue;\n used[i] = true;\n path.add(nums[i]);\n backtrack(nums, used, path, result);\n path.remove(path.size() - 1);\n used[i] = false;\n }\n}", "solution_cpp": "vector> permute(vector& nums) {\n vector> result;\n vector used(nums.size(), false);\n vector path;\n backtrack(nums, used, path, result);\n return result;\n}\nvoid backtrack(vector& nums, vector& used, vector& path, vector>& result) {\n if (path.size() == nums.size()) { result.push_back(path); return; }\n for (int i = 0; i < nums.size(); i++) {\n if (used[i]) continue;\n used[i] = true;\n path.push_back(nums[i]);\n backtrack(nums, used, path, result);\n path.pop_back();\n used[i] = false;\n }\n}", "test_cases": ["nums=[1,2,3] -> [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]"], "key_points": ["标记已使用元素", "回溯经典模板"], "tags": ["backtracking", "medium", "Google", "Facebook"]} {"problem_id": "algo_00415", "original_id": "top-k-frequent", "title": "前K个高频元素", "category": "heap", "difficulty": "medium", "companies": ["Amazon", "Facebook"], "description": "给你一个整数数组 nums 和一个整数 k,请你返回其中出现频率前 k 高的元素。", "solution_python": "import heapq\nfrom collections import Counter\ndef topKFrequent(nums, k):\n count = Counter(nums)\n heap = []\n for num, freq in count.items():\n heapq.heappush(heap, (freq, num))\n if len(heap) > k: heapq.heappop(heap)\n return [num for freq, num in heap]", "solution_java": "public int[] topKFrequent(int[] nums, int k) {\n Map count = new HashMap<>();\n for (int n : nums) count.put(n, count.getOrDefault(n, 0) + 1);\n PriorityQueue> heap = \n new PriorityQueue<>((a, b) -> a.getValue() - b.getValue());\n for (Map.Entry e : count.entrySet()) {\n heap.offer(e);\n if (heap.size() > k) heap.poll();\n }\n int[] res = new int[k];\n for (int i = k - 1; i >= 0; i--) res[i] = heap.poll().getKey();\n return res;\n}", "solution_cpp": "vector topKFrequent(vector& nums, int k) {\n unordered_map count;\n for (int n : nums) count[n]++;\n priority_queue, vector>, greater>> heap;\n for (auto& [num, freq] : count) {\n heap.push({freq, num});\n if (heap.size() > k) heap.pop();\n }\n vector res;\n while (!heap.empty()) { res.push_back(heap.top().second); heap.pop(); }\n reverse(res.begin(), res.end());\n return res;\n}", "test_cases": ["nums=[1,1,1,2,2,3], k=2 -> [1,2]", "nums=[1], k=1 -> [1]"], "key_points": ["小顶堆保持大小k", "时间复杂度O(nlogk)"], "tags": ["heap", "medium", "Amazon", "Facebook"]} {"problem_id": "algo_00416", "original_id": "3sum", "title": "三数之和", "category": "two-pointers", "difficulty": "medium", "companies": ["Google", "Amazon"], "description": "给你一个整数数组 nums,判断是否存在三元组满足和为0,返回所有不重复的三元组。", "solution_python": "def threeSum(nums):\n nums.sort()\n result = []\n for i in range(len(nums) - 2):\n if i > 0 and nums[i] == nums[i-1]: continue\n left, right = i + 1, len(nums) - 1\n while left < right:\n total = nums[i] + nums[left] + nums[right]\n if total < 0: left += 1\n elif total > 0: right -= 1\n else:\n result.append([nums[i], nums[left], nums[right]])\n while left < right and nums[left] == nums[left+1]: left += 1\n while left < right and nums[right] == nums[right-1]: right -= 1\n left += 1; right -= 1\n return result", "solution_java": "public List> threeSum(int[] nums) {\n Arrays.sort(nums);\n List> result = new ArrayList<>();\n for (int i = 0; i < nums.length - 2; i++) {\n if (i > 0 && nums[i] == nums[i-1]) continue;\n int left = i + 1, right = nums.length - 1;\n while (left < right) {\n int total = nums[i] + nums[left] + nums[right];\n if (total < 0) left++;\n else if (total > 0) right--;\n else {\n result.add(Arrays.asList(nums[i], nums[left], nums[right]));\n while (left < right && nums[left] == nums[left+1]) left++;\n while (left < right && nums[right] == nums[right-1]) right--;\n left++; right--;\n }\n }\n }\n return result;\n}", "solution_cpp": "vector> threeSum(vector& nums) {\n sort(nums.begin(), nums.end());\n vector> result;\n for (int i = 0; i < nums.size() - 2; i++) {\n if (i > 0 && nums[i] == nums[i-1]) continue;\n int left = i + 1, right = nums.size() - 1;\n while (left < right) {\n int total = nums[i] + nums[left] + nums[right];\n if (total < 0) left++;\n else if (total > 0) right--;\n else {\n result.push_back({nums[i], nums[left], nums[right]});\n while (left < right && nums[left] == nums[left+1]) left++;\n while (left < right && nums[right] == nums[right-1]) right--;\n left++; right--;\n }\n }\n }\n return result;\n}", "test_cases": ["nums=[-1,0,1,2,-1,-4] -> [[-1,-1,2],[-1,0,1]]"], "key_points": ["排序+双指针", "去重是关键"], "tags": ["two-pointers", "medium", "Google", "Amazon"]} {"problem_id": "algo_00417", "original_id": "container-water", "title": "盛最多水的容器", "category": "two-pointers", "difficulty": "medium", "companies": ["Google", "Uber"], "description": "给定一个长度为 n 的整数数组 height,找出其中的两条线,使得它们与 x 轴共同构成的容器可以容纳最多的水。", "solution_python": "def maxArea(height):\n left, right = 0, len(height) - 1\n max_area = 0\n while left < right:\n h = min(height[left], height[right])\n max_area = max(max_area, h * (right - left))\n if height[left] < height[right]: left += 1\n else: right -= 1\n return max_area", "solution_java": "public int maxArea(int[] height) {\n int left = 0, right = height.length - 1, maxArea = 0;\n while (left < right) {\n int h = Math.min(height[left], height[right]);\n maxArea = Math.max(maxArea, h * (right - left));\n if (height[left] < height[right]) left++;\n else right--;\n }\n return maxArea;\n}", "solution_cpp": "int maxArea(vector& height) {\n int left = 0, right = height.size() - 1, maxArea = 0;\n while (left < right) {\n int h = min(height[left], height[right]);\n maxArea = max(maxArea, h * (right - left));\n if (height[left] < height[right]) left++;\n else right--;\n }\n return maxArea;\n}", "test_cases": ["height=[1,8,6,2,5,4,8,3,7] -> 49"], "key_points": ["移动短边指针", "面积=min(h1,h2)*width"], "tags": ["two-pointers", "medium", "Google", "Uber"]} {"problem_id": "algo_00418", "original_id": "min-stack", "title": "最小栈", "category": "stack", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "设计一个支持 push,pop,top 操作,并能在常数时间内检索到最小元素的栈。", "solution_python": "class MinStack:\n def __init__(self):\n self.stack = []\n self.min_stack = []\n def push(self, val):\n self.stack.append(val)\n self.min_stack.append(min(val, self.min_stack[-1] if self.min_stack else val))\n def pop(self):\n self.stack.pop(); self.min_stack.pop()\n def top(self): return self.stack[-1]\n def getMin(self): return self.min_stack[-1]", "solution_java": "class MinStack {\n Stack stack = new Stack<>();\n Stack minStack = new Stack<>();\n public void push(int val) { stack.push(val); minStack.push(Math.min(val, minStack.isEmpty() ? val : minStack.peek())); }\n public void pop() { stack.pop(); minStack.pop(); }\n public int top() { return stack.peek(); }\n public int getMin() { return minStack.peek(); }\n}", "solution_cpp": "class MinStack {\n stack st, minSt;\npublic:\n void push(int val) { st.push(val); minSt.push(min(val, minSt.empty() ? val : minSt.top())); }\n void pop() { st.pop(); minSt.pop(); }\n int top() { return st.top(); }\n int getMin() { return minSt.top(); }\n};", "test_cases": ["push(-2), push(0), push(-3) -> getMin() returns -3"], "key_points": ["辅助栈记录最小值", "O(1)时间获取最小值"], "tags": ["stack", "medium", "Google", "Microsoft"]} {"problem_id": "algo_00419", "original_id": "lru-cache", "title": "LRU缓存", "category": "design", "difficulty": "hard", "companies": ["Google", "Amazon"], "description": "设计和实现一个 LRU(最近最少使用)缓存机制。", "solution_python": "class LRUCache:\n def __init__(self, capacity):\n self.capacity = capacity\n self.cache = {}\n self.order = []\n def get(self, key):\n if key not in self.cache: return -1\n self.order.remove(key); self.order.append(key)\n return self.cache[key]\n def put(self, key, value):\n if key in self.cache:\n self.order.remove(key)\n elif len(self.cache) >= self.capacity:\n del self.cache[self.order.pop(0)]\n self.cache[key] = value; self.order.append(key)", "solution_java": "class LRUCache {\n int capacity;\n LinkedHashMap cache = new LinkedHashMap<>();\n public LRUCache(int cap) { capacity = cap; }\n public int get(int key) { return cache.containsKey(key) ? cache.remove(key) : -1; }\n public void put(int key, int val) {\n if (cache.containsKey(key)) cache.remove(key);\n else if (cache.size() >= capacity) cache.remove(cache.keySet().iterator().next());\n cache.put(key, val);\n }\n}", "solution_cpp": "class LRUCache {\n int cap;\n list> dll;\n unordered_map>::iterator> cache;\npublic:\n LRUCache(int capacity) : cap(capacity) {}\n int get(int key) {\n auto it = cache.find(key);\n if (it == cache.end()) return -1;\n dll.splice(dll.end(), dll, it->second);\n return it->second->second;\n }\n void put(int key, int value) {\n auto it = cache.find(key);\n if (it != cache.end()) dll.erase(it->second);\n else if (cache.size() >= cap) { cache.erase(dll.front().first); dll.pop_front(); }\n dll.push_back({key, value});\n cache[key] = --dll.end();\n }\n};", "test_cases": ["put(1,1), put(2,2), get(1) -> 1"], "key_points": ["HashMap + 双向链表", "O(1)时间操作"], "tags": ["design", "hard", "Google", "Amazon"]} {"problem_id": "algo_00420", "original_id": "num-islands", "title": "岛屿数量", "category": "graph", "difficulty": "medium", "companies": ["Google", "Facebook"], "description": "给你一个由 '1'(陆地)和 '0'(水)组成的二维网格,请你计算网格中岛屿的数量。岛屿总是被水包围,且只能由水平或垂直方向相邻的陆地连接形成。", "solution_python": "def numIslands(grid):\n if not grid: return 0\n rows, cols = len(grid), len(grid[0])\n count = 0\n def dfs(r, c):\n if r < 0 or r >= rows or c < 0 or c >= cols or grid[r][c] != '1': return\n grid[r][c] = '0'\n dfs(r+1, c); dfs(r-1, c); dfs(r, c+1); dfs(r, c-1)\n for r in range(rows):\n for c in range(cols):\n if grid[r][c] == '1': count += 1; dfs(r, c)\n return count", "solution_java": "public int numIslands(char[][] grid) {\n if (grid.length == 0) return 0;\n int count = 0;\n for (int i = 0; i < grid.length; i++)\n for (int j = 0; j < grid[0].length; j++)\n if (grid[i][j] == '1') { count++; dfs(grid, i, j); }\n return count;\n}\nprivate void dfs(char[][] grid, int r, int c) {\n if (r < 0 || r >= grid.length || c < 0 || c >= grid[0].length || grid[r][c] != '1') return;\n grid[r][c] = '0';\n dfs(grid, r+1, c); dfs(grid, r-1, c); dfs(grid, r, c+1); dfs(grid, r, c-1);\n}", "solution_cpp": "int numIslands(vector>& grid) {\n if (grid.empty()) return 0;\n int count = 0;\n for (int i = 0; i < grid.size(); i++)\n for (int j = 0; j < grid[0].size(); j++)\n if (grid[i][j] == '1') { count++; dfs(grid, i, j); }\n return count;\n}\nvoid dfs(vector>& grid, int r, int c) {\n if (r < 0 || r >= grid.size() || c < 0 || c >= grid[0].size() || grid[r][c] != '1') return;\n grid[r][c] = '0';\n dfs(grid, r+1, c); dfs(grid, r-1, c); dfs(grid, r, c+1); dfs(grid, r, c-1);\n}", "test_cases": ["grid=[[1,1,1,1,0],[1,1,0,1,0],[1,1,0,0,0],[0,0,0,0,0]] -> 1"], "key_points": ["DFS/BFS遍历", "访问后标记为0避免重复"], "tags": ["graph", "medium", "Google", "Facebook"]} {"problem_id": "algo_00421", "original_id": "two-sum", "title": "两数之和", "category": "array", "difficulty": "easy", "companies": ["Amazon", "Google"], "description": "给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那两个整数,并返回他们的数组下标。", "solution_python": "def twoSum(nums, target):\n hashmap = {}\n for i, num in enumerate(nums):\n complement = target - num\n if complement in hashmap:\n return [hashmap[complement], i]\n hashmap[num] = i\n return []", "solution_java": "public int[] twoSum(int[] nums, int target) {\n Map map = new HashMap<>();\n for (int i = 0; i < nums.length; i++) {\n int complement = target - nums[i];\n if (map.containsKey(complement)) return new int[]{map.get(complement), i};\n map.put(nums[i], i);\n }\n return new int[]{};\n}", "solution_cpp": "vector twoSum(vector& nums, int target) {\n unordered_map m;\n for (int i = 0; i < nums.size(); i++) {\n if (m.count(target - nums[i])) return {m[target - nums[i]], i};\n m[nums[i]] = i;\n }\n return {};\n}", "test_cases": ["nums=[2,7,11,15], target=9 -> [0,1]", "nums=[3,2,4], target=6 -> [1,2]"], "key_points": ["哈希表一次遍历", "空间换时间"], "tags": ["array", "easy", "Amazon", "Google"]} {"problem_id": "algo_00422", "original_id": "merge-sorted", "title": "合并两个有序数组", "category": "array", "difficulty": "easy", "companies": ["Microsoft", "Uber"], "description": "给你两个按非递减顺序排列的整数数组 nums1 和 nums2,另有两个整数 m 和 n,分别表示 nums1 和 nums2 中的元素数目。请你合并 nums2 到 nums1 中。", "solution_python": "def merge(nums1, m, nums2, n):\n p1, p2, p = m-1, n-1, m+n-1\n while p1 >= 0 and p2 >= 0:\n if nums1[p1] > nums2[p2]: nums1[p] = nums1[p1]; p1 -= 1\n else: nums1[p] = nums2[p2]; p2 -= 1\n p -= 1\n while p2 >= 0: nums1[p] = nums2[p2]; p2 -= 1; p -= 1", "solution_java": "public void merge(int[] nums1, int m, int[] nums2, int n) {\n int p1 = m-1, p2 = n-1, p = m+n-1;\n while (p1 >= 0 && p2 >= 0) {\n nums1[p--] = nums1[p1] > nums2[p2] ? nums1[p1--] : nums2[p2--];\n }\n while (p2 >= 0) nums1[p--] = nums2[p2--];\n}", "solution_cpp": "void merge(vector& nums1, int m, vector& nums2, int n) {\n int p1 = m-1, p2 = n-1, p = m+n-1;\n while (p1 >= 0 && p2 >= 0) nums1[p--] = nums1[p1] > nums2[p2] ? nums1[p1--] : nums2[p2--];\n while (p2 >= 0) nums1[p--] = nums2[p2--];\n}", "test_cases": ["nums1=[1,2,3], m=3, nums2=[2,5,6], n=3 -> [1,2,2,3,5,6]", "nums1=[], m=0, nums2=[1], n=1 -> [1]"], "key_points": ["从后往前合并", "三指针技巧"], "tags": ["array", "easy", "Microsoft", "Uber"]} {"problem_id": "algo_00423", "original_id": "max-subarray", "title": "最大子数组和", "category": "array", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "给你一个整数数组 nums ,请你找出一个具有最大和的连续子数组,返回其最大和。", "solution_python": "def maxSubArray(nums):\n max_sum = current = nums[0]\n for num in nums[1:]:\n current = max(num, current + num)\n max_sum = max(max_sum, current)\n return max_sum", "solution_java": "public int maxSubArray(int[] nums) {\n int maxSum = nums[0], curr = nums[0];\n for (int i = 1; i < nums.length; i++) {\n curr = Math.max(nums[i], curr + nums[i]);\n maxSum = Math.max(maxSum, curr);\n }\n return maxSum;\n}", "solution_cpp": "int maxSubArray(vector& nums) {\n int maxSum = nums[0], curr = nums[0];\n for (int i = 1; i < nums.size(); i++) {\n curr = max(nums[i], curr + nums[i]);\n maxSum = max(maxSum, curr);\n }\n return maxSum;\n}", "test_cases": ["nums=[-2,1,-3,4,-1,2,1,-5,4] -> 6", "nums=[1] -> 1"], "key_points": ["Kadane算法", "动态规划基础题"], "tags": ["array", "medium", "Google", "Microsoft"]} {"problem_id": "algo_00424", "original_id": "valid-parentheses", "title": "有效的括号", "category": "string", "difficulty": "easy", "companies": ["Google", "Uber"], "description": "给定一个只包括 '(',')','{','}','[',']' 的字符串 s,判断字符串是否有效。", "solution_python": "def isValid(s):\n stack = []\n mapping = {')': '(', ']': '[', '}': '{'}\n for c in s:\n if c in mapping:\n if not stack or stack[-1] != mapping[c]: return False\n stack.pop()\n else: stack.append(c)\n return not stack", "solution_java": "public boolean isValid(String s) {\n Stack stack = new Stack<>();\n Map map = Map.of(')', '(', ']', '[', '}', '{');\n for (char c : s.toCharArray()) {\n if (map.containsValue(c)) stack.push(c);\n else if (!stack.isEmpty() && stack.pop() != map.get(c)) return false;\n }\n return stack.isEmpty();\n}", "solution_cpp": "bool isValid(string s) {\n stack st;\n unordered_map m = {{')','('},{']','['},{'}','{'}};\n for (char c : s) {\n if (m.find(c) == m.end()) st.push(c);\n else if (st.empty() || st.top() != m[c]) return false;\n else st.pop();\n }\n return st.empty();\n}", "test_cases": ["s=\"()\" -> true", "s=\"()[]{}\" -> true", "s=\"(]\" -> false"], "key_points": ["栈匹配法", "注意空栈边界"], "tags": ["string", "easy", "Google", "Uber"]} {"problem_id": "algo_00425", "original_id": "longest-palindrome", "title": "最长回文子串", "category": "string", "difficulty": "medium", "companies": ["Google", "Amazon"], "description": "给你一个字符串 s,找到 s 中最长的回文子串。", "solution_python": "def longestPalindrome(s):\n def expand(l, r):\n while l >= 0 and r < len(s) and s[l] == s[r]: l -= 1; r += 1\n return l + 1, r - 1\n start = end = 0\n for i in range(len(s)):\n l1, r1 = expand(i, i)\n l2, r2 = expand(i, i + 1)\n if r1 - l1 > end - start: start, end = l1, r1\n if r2 - l2 > end - start: start, end = l2, r2\n return s[start:end+1]", "solution_java": "public String longestPalindrome(String s) {\n int start = 0, end = 0;\n for (int i = 0; i < s.length(); i++) {\n int len1 = expand(s, i, i), len2 = expand(s, i, i+1);\n int len = Math.max(len1, len2);\n if (len > end - start) { start = i - (len-1)/2; end = i + len/2; }\n }\n return s.substring(start, end + 1);\n}\nprivate int expand(String s, int l, int r) {\n while (l >= 0 && r < s.length() && s.charAt(l) == s.charAt(r)) { l--; r++; }\n return r - l - 1;\n}", "solution_cpp": "string longestPalindrome(string s) {\n int start = 0, end = 0;\n for (int i = 0; i < s.size(); i++) {\n int len1 = expand(s, i, i), len2 = expand(s, i, i+1);\n if (max(len1, len2) > end - start) { start = i - (max(len1,len2)-1)/2; end = i + max(len1,len2)/2; }\n }\n return s.substr(start, end - start + 1);\n}", "test_cases": ["s=\"babad\" -> bab或aba", "s=\"cbbd\" -> bb"], "key_points": ["中心扩展法", "处理奇偶长度"], "tags": ["string", "medium", "Google", "Amazon"]} {"problem_id": "algo_00426", "original_id": "reverse-list", "title": "反转链表", "category": "linkedlist", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "给你单链表的头节点 head,请你反转链表,并返回反转后的链表。", "solution_python": "def reverseList(head):\n prev = None\n curr = head\n while curr:\n nxt = curr.next\n curr.next = prev\n prev = curr\n curr = nxt\n return prev", "solution_java": "public ListNode reverseList(ListNode head) {\n ListNode prev = null, curr = head;\n while (curr != null) {\n ListNode next = curr.next;\n curr.next = prev;\n prev = curr;\n curr = next;\n }\n return prev;\n}", "solution_cpp": "ListNode* reverseList(ListNode* head) {\n ListNode* prev = nullptr, *curr = head;\n while (curr) {\n ListNode* next = curr->next;\n curr->next = prev;\n prev = curr;\n curr = next;\n }\n return prev;\n}", "test_cases": ["head=[1,2,3,4,5] -> [5,4,3,2,1]", "head=[1,2] -> [2,1]"], "key_points": ["迭代法 O(1)空间", "递归法 O(n)空间"], "tags": ["linkedlist", "medium", "Google", "Microsoft"]} {"problem_id": "algo_00427", "original_id": "middle-node", "title": "链表的中间结点", "category": "linkedlist", "difficulty": "easy", "companies": ["Amazon", "Facebook"], "description": "给你单链表的头节点 head,请你找出并返回链表的中间结点。如果有两个中间结点,则返回第二个中间结点。", "solution_python": "def middleNode(head):\n slow = fast = head\n while fast and fast.next:\n slow = slow.next\n fast = fast.next.next\n return slow", "solution_java": "public ListNode middleNode(ListNode head) {\n ListNode slow = head, fast = head;\n while (fast != null && fast.next != null) {\n slow = slow.next;\n fast = fast.next.next;\n }\n return slow;\n}", "solution_cpp": "ListNode* middleNode(ListNode* head) {\n ListNode* slow = head, *fast = head;\n while (fast && fast->next) { slow = slow->next; fast = fast->next->next; }\n return slow;\n}", "test_cases": ["head=[1,2,3,4,5] -> 3", "head=[1,2,3,4,5,6] -> 4"], "key_points": ["快慢指针", "O(n)时间O(1)空间"], "tags": ["linkedlist", "easy", "Amazon", "Facebook"]} {"problem_id": "algo_00428", "original_id": "max-depth", "title": "二叉树的最大深度", "category": "tree", "difficulty": "easy", "companies": ["Microsoft", "Apple"], "description": "给定一个二叉树 root,返回其最大深度。", "solution_python": "def maxDepth(root):\n if not root: return 0\n return max(maxDepth(root.left), maxDepth(root.right)) + 1", "solution_java": "public int maxDepth(TreeNode root) {\n if (root == null) return 0;\n return Math.max(maxDepth(root.left), maxDepth(root.right)) + 1;\n}", "solution_cpp": "int maxDepth(TreeNode* root) {\n if (!root) return 0;\n return max(maxDepth(root->left), maxDepth(root->right)) + 1;\n}", "test_cases": ["root=[3,9,20,null,null,15,7] -> 3", "root=[1,null,2] -> 2"], "key_points": ["DFS递归", "层序遍历也可"], "tags": ["tree", "easy", "Microsoft", "Apple"]} {"problem_id": "algo_00429", "original_id": "inorder-traversal", "title": "二叉树的中序遍历", "category": "tree", "difficulty": "easy", "companies": ["Google", "Microsoft"], "description": "给定一个二叉树的根节点 root,返回它的中序遍历结果。", "solution_python": "def inorderTraversal(root):\n result = []\n def dfs(node):\n if node:\n dfs(node.left)\n result.append(node.val)\n dfs(node.right)\n dfs(root)\n return result", "solution_java": "public List inorderTraversal(TreeNode root) {\n List res = new ArrayList<>();\n dfs(root, res);\n return res;\n}\nprivate void dfs(TreeNode node, List res) {\n if (node == null) return;\n dfs(node.left, res); res.add(node.val); dfs(node.right, res);\n}", "solution_cpp": "vector inorderTraversal(TreeNode* root) {\n vector res;\n dfs(root, res);\n return res;\n}\nvoid dfs(TreeNode* node, vector& res) {\n if (!node) return;\n dfs(node->left, res); res.push_back(node->val); dfs(node->right, res);\n}", "test_cases": ["root=[1,null,2,3] -> [1,3,2]", "root=[] -> []"], "key_points": ["左-根-右顺序", "递归最简洁"], "tags": ["tree", "easy", "Google", "Microsoft"]} {"problem_id": "algo_00430", "original_id": "binary-search", "title": "二分查找", "category": "binarysearch", "difficulty": "easy", "companies": ["Google", "Amazon"], "description": "给定一个 n 个元素有序的(升序)整型数组 nums 和一个目标值 target,写一个函数搜索 nums 中的 target,如果目标值存在返回下标,否则返回 -1。", "solution_python": "def search(nums, target):\n left, right = 0, len(nums) - 1\n while left <= right:\n mid = (left + right) // 2\n if nums[mid] == target: return mid\n elif nums[mid] < target: left = mid + 1\n else: right = mid - 1\n return -1", "solution_java": "public int search(int[] nums, int target) {\n int left = 0, right = nums.length - 1;\n while (left <= right) {\n int mid = left + (right - left) / 2;\n if (nums[mid] == target) return mid;\n else if (nums[mid] < target) left = mid + 1;\n else right = mid - 1;\n }\n return -1;\n}", "solution_cpp": "int search(vector& nums, int target) {\n int left = 0, right = nums.size() - 1;\n while (left <= right) {\n int mid = left + (right - left) / 2;\n if (nums[mid] == target) return mid;\n else if (nums[mid] < target) left = mid + 1;\n else right = mid - 1;\n }\n return -1;\n}", "test_cases": ["nums=[-1,0,3,5,9,12], target=9 -> 4", "nums=[-1,0,3,5,9,12], target=2 -> -1"], "key_points": ["标准模板", "注意防溢出写法"], "tags": ["binarysearch", "easy", "Google", "Amazon"]} {"problem_id": "algo_00431", "original_id": "climbing-stairs", "title": "爬楼梯", "category": "dp", "difficulty": "easy", "companies": ["Amazon", "Google"], "description": "假设你正在爬楼梯。需要 n 阶你才能到达楼顶。每次你可以爬 1 或 2 个台阶。你有多少种不同的方法可以爬到楼顶?", "solution_python": "def climbStairs(n):\n if n <= 2: return n\n a, b = 1, 2\n for _ in range(3, n+1):\n a, b = b, a + b\n return b", "solution_java": "public int climbStairs(int n) {\n if (n <= 2) return n;\n int a = 1, b = 2;\n for (int i = 3; i <= n; i++) { int temp = a + b; a = b; b = temp; }\n return b;\n}", "solution_cpp": "int climbStairs(int n) {\n if (n <= 2) return n;\n int a = 1, b = 2;\n for (int i = 3; i <= n; i++) { int temp = a + b; a = b; b = temp; }\n return b;\n}", "test_cases": ["n=2 -> 2", "n=3 -> 3", "n=5 -> 8"], "key_points": ["斐波那契数列", "滚动数组优化空间"], "tags": ["dp", "easy", "Amazon", "Google"]} {"problem_id": "algo_00432", "original_id": "coin-change", "title": "零钱兑换", "category": "dp", "difficulty": "medium", "companies": ["Google", "Amazon"], "description": "给你一个整数数组 coins 表示不同面额的硬币,以及一个整数 amount 表示总金额。计算并返回可以凑成总金额所需的最少的硬币个数。如果没有任何一种硬币组合能组成总金额,返回 -1。", "solution_python": "def coinChange(coins, amount):\n dp = [float('inf')] * (amount + 1)\n dp[0] = 0\n for coin in coins:\n for x in range(coin, amount + 1):\n dp[x] = min(dp[x], dp[x - coin] + 1)\n return dp[amount] if dp[amount] != float('inf') else -1", "solution_java": "public int coinChange(int[] coins, int amount) {\n int[] dp = new int[amount + 1];\n Arrays.fill(dp, amount + 1);\n dp[0] = 0;\n for (int coin : coins) {\n for (int x = coin; x <= amount; x++) {\n dp[x] = Math.min(dp[x], dp[x - coin] + 1);\n }\n }\n return dp[amount] > amount ? -1 : dp[amount];\n}", "solution_cpp": "int coinChange(vector& coins, int amount) {\n vector dp(amount + 1, amount + 1);\n dp[0] = 0;\n for (int coin : coins) {\n for (int x = coin; x <= amount; x++) {\n dp[x] = min(dp[x], dp[x - coin] + 1);\n }\n }\n return dp[amount] > amount ? -1 : dp[amount];\n}", "test_cases": ["coins=[1,2,5], amount=11 -> 3", "coins=[2], amount=3 -> -1"], "key_points": ["完全背包问题", "dp[x] = min(dp[x-coin]+1)"], "tags": ["dp", "medium", "Google", "Amazon"]} {"problem_id": "algo_00433", "original_id": "subsets", "title": "子集", "category": "backtracking", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "给你一个整数数组 nums ,数组中的元素 互不相同 。返回该数组所有可能的子集(幂集)。", "solution_python": "def subsets(nums):\n result = []\n def backtrack(start, path):\n result.append(path[:])\n for i in range(start, len(nums)):\n path.append(nums[i])\n backtrack(i + 1, path)\n path.pop()\n backtrack(0, [])\n return result", "solution_java": "public List> subsets(int[] nums) {\n List> result = new ArrayList<>();\n backtrack(nums, 0, new ArrayList<>(), result);\n return result;\n}\nprivate void backtrack(int[] nums, int start, List path, List> result) {\n result.add(new ArrayList<>(path));\n for (int i = start; i < nums.length; i++) {\n path.add(nums[i]);\n backtrack(nums, i + 1, path, result);\n path.remove(path.size() - 1);\n }\n}", "solution_cpp": "vector> subsets(vector& nums) {\n vector> result;\n vector path;\n backtrack(nums, 0, path, result);\n return result;\n}\nvoid backtrack(vector& nums, int start, vector& path, vector>& result) {\n result.push_back(path);\n for (int i = start; i < nums.size(); i++) {\n path.push_back(nums[i]);\n backtrack(nums, i + 1, path, result);\n path.pop_back();\n }\n}", "test_cases": ["nums=[1,2,3] -> [[],[1],[2],[1,2],[3],[1,3],[2,3],[1,2,3]]"], "key_points": ["选或不选", "DFS遍历子集树"], "tags": ["backtracking", "medium", "Google", "Microsoft"]} {"problem_id": "algo_00434", "original_id": "permutations", "title": "全排列", "category": "backtracking", "difficulty": "medium", "companies": ["Google", "Facebook"], "description": "给定一个不含重复数字的数组 nums,返回其所有可能的全排列。", "solution_python": "def permute(nums):\n result = []\n def backtrack(path, used):\n if len(path) == len(nums):\n result.append(path[:])\n return\n for i in range(len(nums)):\n if used[i]: continue\n used[i] = True\n path.append(nums[i])\n backtrack(path, used)\n path.pop()\n used[i] = False\n backtrack([], [False]*len(nums))\n return result", "solution_java": "public List> permute(int[] nums) {\n List> result = new ArrayList<>();\n boolean[] used = new boolean[nums.length];\n backtrack(nums, used, new ArrayList<>(), result);\n return result;\n}\nprivate void backtrack(int[] nums, boolean[] used, List path, List> result) {\n if (path.size() == nums.length) { result.add(new ArrayList<>(path)); return; }\n for (int i = 0; i < nums.length; i++) {\n if (used[i]) continue;\n used[i] = true;\n path.add(nums[i]);\n backtrack(nums, used, path, result);\n path.remove(path.size() - 1);\n used[i] = false;\n }\n}", "solution_cpp": "vector> permute(vector& nums) {\n vector> result;\n vector used(nums.size(), false);\n vector path;\n backtrack(nums, used, path, result);\n return result;\n}\nvoid backtrack(vector& nums, vector& used, vector& path, vector>& result) {\n if (path.size() == nums.size()) { result.push_back(path); return; }\n for (int i = 0; i < nums.size(); i++) {\n if (used[i]) continue;\n used[i] = true;\n path.push_back(nums[i]);\n backtrack(nums, used, path, result);\n path.pop_back();\n used[i] = false;\n }\n}", "test_cases": ["nums=[1,2,3] -> [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]"], "key_points": ["标记已使用元素", "回溯经典模板"], "tags": ["backtracking", "medium", "Google", "Facebook"]} {"problem_id": "algo_00435", "original_id": "top-k-frequent", "title": "前K个高频元素", "category": "heap", "difficulty": "medium", "companies": ["Amazon", "Facebook"], "description": "给你一个整数数组 nums 和一个整数 k,请你返回其中出现频率前 k 高的元素。", "solution_python": "import heapq\nfrom collections import Counter\ndef topKFrequent(nums, k):\n count = Counter(nums)\n heap = []\n for num, freq in count.items():\n heapq.heappush(heap, (freq, num))\n if len(heap) > k: heapq.heappop(heap)\n return [num for freq, num in heap]", "solution_java": "public int[] topKFrequent(int[] nums, int k) {\n Map count = new HashMap<>();\n for (int n : nums) count.put(n, count.getOrDefault(n, 0) + 1);\n PriorityQueue> heap = \n new PriorityQueue<>((a, b) -> a.getValue() - b.getValue());\n for (Map.Entry e : count.entrySet()) {\n heap.offer(e);\n if (heap.size() > k) heap.poll();\n }\n int[] res = new int[k];\n for (int i = k - 1; i >= 0; i--) res[i] = heap.poll().getKey();\n return res;\n}", "solution_cpp": "vector topKFrequent(vector& nums, int k) {\n unordered_map count;\n for (int n : nums) count[n]++;\n priority_queue, vector>, greater>> heap;\n for (auto& [num, freq] : count) {\n heap.push({freq, num});\n if (heap.size() > k) heap.pop();\n }\n vector res;\n while (!heap.empty()) { res.push_back(heap.top().second); heap.pop(); }\n reverse(res.begin(), res.end());\n return res;\n}", "test_cases": ["nums=[1,1,1,2,2,3], k=2 -> [1,2]", "nums=[1], k=1 -> [1]"], "key_points": ["小顶堆保持大小k", "时间复杂度O(nlogk)"], "tags": ["heap", "medium", "Amazon", "Facebook"]} {"problem_id": "algo_00436", "original_id": "3sum", "title": "三数之和", "category": "two-pointers", "difficulty": "medium", "companies": ["Google", "Amazon"], "description": "给你一个整数数组 nums,判断是否存在三元组满足和为0,返回所有不重复的三元组。", "solution_python": "def threeSum(nums):\n nums.sort()\n result = []\n for i in range(len(nums) - 2):\n if i > 0 and nums[i] == nums[i-1]: continue\n left, right = i + 1, len(nums) - 1\n while left < right:\n total = nums[i] + nums[left] + nums[right]\n if total < 0: left += 1\n elif total > 0: right -= 1\n else:\n result.append([nums[i], nums[left], nums[right]])\n while left < right and nums[left] == nums[left+1]: left += 1\n while left < right and nums[right] == nums[right-1]: right -= 1\n left += 1; right -= 1\n return result", "solution_java": "public List> threeSum(int[] nums) {\n Arrays.sort(nums);\n List> result = new ArrayList<>();\n for (int i = 0; i < nums.length - 2; i++) {\n if (i > 0 && nums[i] == nums[i-1]) continue;\n int left = i + 1, right = nums.length - 1;\n while (left < right) {\n int total = nums[i] + nums[left] + nums[right];\n if (total < 0) left++;\n else if (total > 0) right--;\n else {\n result.add(Arrays.asList(nums[i], nums[left], nums[right]));\n while (left < right && nums[left] == nums[left+1]) left++;\n while (left < right && nums[right] == nums[right-1]) right--;\n left++; right--;\n }\n }\n }\n return result;\n}", "solution_cpp": "vector> threeSum(vector& nums) {\n sort(nums.begin(), nums.end());\n vector> result;\n for (int i = 0; i < nums.size() - 2; i++) {\n if (i > 0 && nums[i] == nums[i-1]) continue;\n int left = i + 1, right = nums.size() - 1;\n while (left < right) {\n int total = nums[i] + nums[left] + nums[right];\n if (total < 0) left++;\n else if (total > 0) right--;\n else {\n result.push_back({nums[i], nums[left], nums[right]});\n while (left < right && nums[left] == nums[left+1]) left++;\n while (left < right && nums[right] == nums[right-1]) right--;\n left++; right--;\n }\n }\n }\n return result;\n}", "test_cases": ["nums=[-1,0,1,2,-1,-4] -> [[-1,-1,2],[-1,0,1]]"], "key_points": ["排序+双指针", "去重是关键"], "tags": ["two-pointers", "medium", "Google", "Amazon"]} {"problem_id": "algo_00437", "original_id": "container-water", "title": "盛最多水的容器", "category": "two-pointers", "difficulty": "medium", "companies": ["Google", "Uber"], "description": "给定一个长度为 n 的整数数组 height,找出其中的两条线,使得它们与 x 轴共同构成的容器可以容纳最多的水。", "solution_python": "def maxArea(height):\n left, right = 0, len(height) - 1\n max_area = 0\n while left < right:\n h = min(height[left], height[right])\n max_area = max(max_area, h * (right - left))\n if height[left] < height[right]: left += 1\n else: right -= 1\n return max_area", "solution_java": "public int maxArea(int[] height) {\n int left = 0, right = height.length - 1, maxArea = 0;\n while (left < right) {\n int h = Math.min(height[left], height[right]);\n maxArea = Math.max(maxArea, h * (right - left));\n if (height[left] < height[right]) left++;\n else right--;\n }\n return maxArea;\n}", "solution_cpp": "int maxArea(vector& height) {\n int left = 0, right = height.size() - 1, maxArea = 0;\n while (left < right) {\n int h = min(height[left], height[right]);\n maxArea = max(maxArea, h * (right - left));\n if (height[left] < height[right]) left++;\n else right--;\n }\n return maxArea;\n}", "test_cases": ["height=[1,8,6,2,5,4,8,3,7] -> 49"], "key_points": ["移动短边指针", "面积=min(h1,h2)*width"], "tags": ["two-pointers", "medium", "Google", "Uber"]} {"problem_id": "algo_00438", "original_id": "min-stack", "title": "最小栈", "category": "stack", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "设计一个支持 push,pop,top 操作,并能在常数时间内检索到最小元素的栈。", "solution_python": "class MinStack:\n def __init__(self):\n self.stack = []\n self.min_stack = []\n def push(self, val):\n self.stack.append(val)\n self.min_stack.append(min(val, self.min_stack[-1] if self.min_stack else val))\n def pop(self):\n self.stack.pop(); self.min_stack.pop()\n def top(self): return self.stack[-1]\n def getMin(self): return self.min_stack[-1]", "solution_java": "class MinStack {\n Stack stack = new Stack<>();\n Stack minStack = new Stack<>();\n public void push(int val) { stack.push(val); minStack.push(Math.min(val, minStack.isEmpty() ? val : minStack.peek())); }\n public void pop() { stack.pop(); minStack.pop(); }\n public int top() { return stack.peek(); }\n public int getMin() { return minStack.peek(); }\n}", "solution_cpp": "class MinStack {\n stack st, minSt;\npublic:\n void push(int val) { st.push(val); minSt.push(min(val, minSt.empty() ? val : minSt.top())); }\n void pop() { st.pop(); minSt.pop(); }\n int top() { return st.top(); }\n int getMin() { return minSt.top(); }\n};", "test_cases": ["push(-2), push(0), push(-3) -> getMin() returns -3"], "key_points": ["辅助栈记录最小值", "O(1)时间获取最小值"], "tags": ["stack", "medium", "Google", "Microsoft"]} {"problem_id": "algo_00439", "original_id": "lru-cache", "title": "LRU缓存", "category": "design", "difficulty": "hard", "companies": ["Google", "Amazon"], "description": "设计和实现一个 LRU(最近最少使用)缓存机制。", "solution_python": "class LRUCache:\n def __init__(self, capacity):\n self.capacity = capacity\n self.cache = {}\n self.order = []\n def get(self, key):\n if key not in self.cache: return -1\n self.order.remove(key); self.order.append(key)\n return self.cache[key]\n def put(self, key, value):\n if key in self.cache:\n self.order.remove(key)\n elif len(self.cache) >= self.capacity:\n del self.cache[self.order.pop(0)]\n self.cache[key] = value; self.order.append(key)", "solution_java": "class LRUCache {\n int capacity;\n LinkedHashMap cache = new LinkedHashMap<>();\n public LRUCache(int cap) { capacity = cap; }\n public int get(int key) { return cache.containsKey(key) ? cache.remove(key) : -1; }\n public void put(int key, int val) {\n if (cache.containsKey(key)) cache.remove(key);\n else if (cache.size() >= capacity) cache.remove(cache.keySet().iterator().next());\n cache.put(key, val);\n }\n}", "solution_cpp": "class LRUCache {\n int cap;\n list> dll;\n unordered_map>::iterator> cache;\npublic:\n LRUCache(int capacity) : cap(capacity) {}\n int get(int key) {\n auto it = cache.find(key);\n if (it == cache.end()) return -1;\n dll.splice(dll.end(), dll, it->second);\n return it->second->second;\n }\n void put(int key, int value) {\n auto it = cache.find(key);\n if (it != cache.end()) dll.erase(it->second);\n else if (cache.size() >= cap) { cache.erase(dll.front().first); dll.pop_front(); }\n dll.push_back({key, value});\n cache[key] = --dll.end();\n }\n};", "test_cases": ["put(1,1), put(2,2), get(1) -> 1"], "key_points": ["HashMap + 双向链表", "O(1)时间操作"], "tags": ["design", "hard", "Google", "Amazon"]} {"problem_id": "algo_00440", "original_id": "num-islands", "title": "岛屿数量", "category": "graph", "difficulty": "medium", "companies": ["Google", "Facebook"], "description": "给你一个由 '1'(陆地)和 '0'(水)组成的二维网格,请你计算网格中岛屿的数量。岛屿总是被水包围,且只能由水平或垂直方向相邻的陆地连接形成。", "solution_python": "def numIslands(grid):\n if not grid: return 0\n rows, cols = len(grid), len(grid[0])\n count = 0\n def dfs(r, c):\n if r < 0 or r >= rows or c < 0 or c >= cols or grid[r][c] != '1': return\n grid[r][c] = '0'\n dfs(r+1, c); dfs(r-1, c); dfs(r, c+1); dfs(r, c-1)\n for r in range(rows):\n for c in range(cols):\n if grid[r][c] == '1': count += 1; dfs(r, c)\n return count", "solution_java": "public int numIslands(char[][] grid) {\n if (grid.length == 0) return 0;\n int count = 0;\n for (int i = 0; i < grid.length; i++)\n for (int j = 0; j < grid[0].length; j++)\n if (grid[i][j] == '1') { count++; dfs(grid, i, j); }\n return count;\n}\nprivate void dfs(char[][] grid, int r, int c) {\n if (r < 0 || r >= grid.length || c < 0 || c >= grid[0].length || grid[r][c] != '1') return;\n grid[r][c] = '0';\n dfs(grid, r+1, c); dfs(grid, r-1, c); dfs(grid, r, c+1); dfs(grid, r, c-1);\n}", "solution_cpp": "int numIslands(vector>& grid) {\n if (grid.empty()) return 0;\n int count = 0;\n for (int i = 0; i < grid.size(); i++)\n for (int j = 0; j < grid[0].size(); j++)\n if (grid[i][j] == '1') { count++; dfs(grid, i, j); }\n return count;\n}\nvoid dfs(vector>& grid, int r, int c) {\n if (r < 0 || r >= grid.size() || c < 0 || c >= grid[0].size() || grid[r][c] != '1') return;\n grid[r][c] = '0';\n dfs(grid, r+1, c); dfs(grid, r-1, c); dfs(grid, r, c+1); dfs(grid, r, c-1);\n}", "test_cases": ["grid=[[1,1,1,1,0],[1,1,0,1,0],[1,1,0,0,0],[0,0,0,0,0]] -> 1"], "key_points": ["DFS/BFS遍历", "访问后标记为0避免重复"], "tags": ["graph", "medium", "Google", "Facebook"]} {"problem_id": "algo_00441", "original_id": "two-sum", "title": "两数之和", "category": "array", "difficulty": "easy", "companies": ["Amazon", "Google"], "description": "给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那两个整数,并返回他们的数组下标。", "solution_python": "def twoSum(nums, target):\n hashmap = {}\n for i, num in enumerate(nums):\n complement = target - num\n if complement in hashmap:\n return [hashmap[complement], i]\n hashmap[num] = i\n return []", "solution_java": "public int[] twoSum(int[] nums, int target) {\n Map map = new HashMap<>();\n for (int i = 0; i < nums.length; i++) {\n int complement = target - nums[i];\n if (map.containsKey(complement)) return new int[]{map.get(complement), i};\n map.put(nums[i], i);\n }\n return new int[]{};\n}", "solution_cpp": "vector twoSum(vector& nums, int target) {\n unordered_map m;\n for (int i = 0; i < nums.size(); i++) {\n if (m.count(target - nums[i])) return {m[target - nums[i]], i};\n m[nums[i]] = i;\n }\n return {};\n}", "test_cases": ["nums=[2,7,11,15], target=9 -> [0,1]", "nums=[3,2,4], target=6 -> [1,2]"], "key_points": ["哈希表一次遍历", "空间换时间"], "tags": ["array", "easy", "Amazon", "Google"]} {"problem_id": "algo_00442", "original_id": "merge-sorted", "title": "合并两个有序数组", "category": "array", "difficulty": "easy", "companies": ["Microsoft", "Uber"], "description": "给你两个按非递减顺序排列的整数数组 nums1 和 nums2,另有两个整数 m 和 n,分别表示 nums1 和 nums2 中的元素数目。请你合并 nums2 到 nums1 中。", "solution_python": "def merge(nums1, m, nums2, n):\n p1, p2, p = m-1, n-1, m+n-1\n while p1 >= 0 and p2 >= 0:\n if nums1[p1] > nums2[p2]: nums1[p] = nums1[p1]; p1 -= 1\n else: nums1[p] = nums2[p2]; p2 -= 1\n p -= 1\n while p2 >= 0: nums1[p] = nums2[p2]; p2 -= 1; p -= 1", "solution_java": "public void merge(int[] nums1, int m, int[] nums2, int n) {\n int p1 = m-1, p2 = n-1, p = m+n-1;\n while (p1 >= 0 && p2 >= 0) {\n nums1[p--] = nums1[p1] > nums2[p2] ? nums1[p1--] : nums2[p2--];\n }\n while (p2 >= 0) nums1[p--] = nums2[p2--];\n}", "solution_cpp": "void merge(vector& nums1, int m, vector& nums2, int n) {\n int p1 = m-1, p2 = n-1, p = m+n-1;\n while (p1 >= 0 && p2 >= 0) nums1[p--] = nums1[p1] > nums2[p2] ? nums1[p1--] : nums2[p2--];\n while (p2 >= 0) nums1[p--] = nums2[p2--];\n}", "test_cases": ["nums1=[1,2,3], m=3, nums2=[2,5,6], n=3 -> [1,2,2,3,5,6]", "nums1=[], m=0, nums2=[1], n=1 -> [1]"], "key_points": ["从后往前合并", "三指针技巧"], "tags": ["array", "easy", "Microsoft", "Uber"]} {"problem_id": "algo_00443", "original_id": "max-subarray", "title": "最大子数组和", "category": "array", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "给你一个整数数组 nums ,请你找出一个具有最大和的连续子数组,返回其最大和。", "solution_python": "def maxSubArray(nums):\n max_sum = current = nums[0]\n for num in nums[1:]:\n current = max(num, current + num)\n max_sum = max(max_sum, current)\n return max_sum", "solution_java": "public int maxSubArray(int[] nums) {\n int maxSum = nums[0], curr = nums[0];\n for (int i = 1; i < nums.length; i++) {\n curr = Math.max(nums[i], curr + nums[i]);\n maxSum = Math.max(maxSum, curr);\n }\n return maxSum;\n}", "solution_cpp": "int maxSubArray(vector& nums) {\n int maxSum = nums[0], curr = nums[0];\n for (int i = 1; i < nums.size(); i++) {\n curr = max(nums[i], curr + nums[i]);\n maxSum = max(maxSum, curr);\n }\n return maxSum;\n}", "test_cases": ["nums=[-2,1,-3,4,-1,2,1,-5,4] -> 6", "nums=[1] -> 1"], "key_points": ["Kadane算法", "动态规划基础题"], "tags": ["array", "medium", "Google", "Microsoft"]} {"problem_id": "algo_00444", "original_id": "valid-parentheses", "title": "有效的括号", "category": "string", "difficulty": "easy", "companies": ["Google", "Uber"], "description": "给定一个只包括 '(',')','{','}','[',']' 的字符串 s,判断字符串是否有效。", "solution_python": "def isValid(s):\n stack = []\n mapping = {')': '(', ']': '[', '}': '{'}\n for c in s:\n if c in mapping:\n if not stack or stack[-1] != mapping[c]: return False\n stack.pop()\n else: stack.append(c)\n return not stack", "solution_java": "public boolean isValid(String s) {\n Stack stack = new Stack<>();\n Map map = Map.of(')', '(', ']', '[', '}', '{');\n for (char c : s.toCharArray()) {\n if (map.containsValue(c)) stack.push(c);\n else if (!stack.isEmpty() && stack.pop() != map.get(c)) return false;\n }\n return stack.isEmpty();\n}", "solution_cpp": "bool isValid(string s) {\n stack st;\n unordered_map m = {{')','('},{']','['},{'}','{'}};\n for (char c : s) {\n if (m.find(c) == m.end()) st.push(c);\n else if (st.empty() || st.top() != m[c]) return false;\n else st.pop();\n }\n return st.empty();\n}", "test_cases": ["s=\"()\" -> true", "s=\"()[]{}\" -> true", "s=\"(]\" -> false"], "key_points": ["栈匹配法", "注意空栈边界"], "tags": ["string", "easy", "Google", "Uber"]} {"problem_id": "algo_00445", "original_id": "longest-palindrome", "title": "最长回文子串", "category": "string", "difficulty": "medium", "companies": ["Google", "Amazon"], "description": "给你一个字符串 s,找到 s 中最长的回文子串。", "solution_python": "def longestPalindrome(s):\n def expand(l, r):\n while l >= 0 and r < len(s) and s[l] == s[r]: l -= 1; r += 1\n return l + 1, r - 1\n start = end = 0\n for i in range(len(s)):\n l1, r1 = expand(i, i)\n l2, r2 = expand(i, i + 1)\n if r1 - l1 > end - start: start, end = l1, r1\n if r2 - l2 > end - start: start, end = l2, r2\n return s[start:end+1]", "solution_java": "public String longestPalindrome(String s) {\n int start = 0, end = 0;\n for (int i = 0; i < s.length(); i++) {\n int len1 = expand(s, i, i), len2 = expand(s, i, i+1);\n int len = Math.max(len1, len2);\n if (len > end - start) { start = i - (len-1)/2; end = i + len/2; }\n }\n return s.substring(start, end + 1);\n}\nprivate int expand(String s, int l, int r) {\n while (l >= 0 && r < s.length() && s.charAt(l) == s.charAt(r)) { l--; r++; }\n return r - l - 1;\n}", "solution_cpp": "string longestPalindrome(string s) {\n int start = 0, end = 0;\n for (int i = 0; i < s.size(); i++) {\n int len1 = expand(s, i, i), len2 = expand(s, i, i+1);\n if (max(len1, len2) > end - start) { start = i - (max(len1,len2)-1)/2; end = i + max(len1,len2)/2; }\n }\n return s.substr(start, end - start + 1);\n}", "test_cases": ["s=\"babad\" -> bab或aba", "s=\"cbbd\" -> bb"], "key_points": ["中心扩展法", "处理奇偶长度"], "tags": ["string", "medium", "Google", "Amazon"]} {"problem_id": "algo_00446", "original_id": "reverse-list", "title": "反转链表", "category": "linkedlist", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "给你单链表的头节点 head,请你反转链表,并返回反转后的链表。", "solution_python": "def reverseList(head):\n prev = None\n curr = head\n while curr:\n nxt = curr.next\n curr.next = prev\n prev = curr\n curr = nxt\n return prev", "solution_java": "public ListNode reverseList(ListNode head) {\n ListNode prev = null, curr = head;\n while (curr != null) {\n ListNode next = curr.next;\n curr.next = prev;\n prev = curr;\n curr = next;\n }\n return prev;\n}", "solution_cpp": "ListNode* reverseList(ListNode* head) {\n ListNode* prev = nullptr, *curr = head;\n while (curr) {\n ListNode* next = curr->next;\n curr->next = prev;\n prev = curr;\n curr = next;\n }\n return prev;\n}", "test_cases": ["head=[1,2,3,4,5] -> [5,4,3,2,1]", "head=[1,2] -> [2,1]"], "key_points": ["迭代法 O(1)空间", "递归法 O(n)空间"], "tags": ["linkedlist", "medium", "Google", "Microsoft"]} {"problem_id": "algo_00447", "original_id": "middle-node", "title": "链表的中间结点", "category": "linkedlist", "difficulty": "easy", "companies": ["Amazon", "Facebook"], "description": "给你单链表的头节点 head,请你找出并返回链表的中间结点。如果有两个中间结点,则返回第二个中间结点。", "solution_python": "def middleNode(head):\n slow = fast = head\n while fast and fast.next:\n slow = slow.next\n fast = fast.next.next\n return slow", "solution_java": "public ListNode middleNode(ListNode head) {\n ListNode slow = head, fast = head;\n while (fast != null && fast.next != null) {\n slow = slow.next;\n fast = fast.next.next;\n }\n return slow;\n}", "solution_cpp": "ListNode* middleNode(ListNode* head) {\n ListNode* slow = head, *fast = head;\n while (fast && fast->next) { slow = slow->next; fast = fast->next->next; }\n return slow;\n}", "test_cases": ["head=[1,2,3,4,5] -> 3", "head=[1,2,3,4,5,6] -> 4"], "key_points": ["快慢指针", "O(n)时间O(1)空间"], "tags": ["linkedlist", "easy", "Amazon", "Facebook"]} {"problem_id": "algo_00448", "original_id": "max-depth", "title": "二叉树的最大深度", "category": "tree", "difficulty": "easy", "companies": ["Microsoft", "Apple"], "description": "给定一个二叉树 root,返回其最大深度。", "solution_python": "def maxDepth(root):\n if not root: return 0\n return max(maxDepth(root.left), maxDepth(root.right)) + 1", "solution_java": "public int maxDepth(TreeNode root) {\n if (root == null) return 0;\n return Math.max(maxDepth(root.left), maxDepth(root.right)) + 1;\n}", "solution_cpp": "int maxDepth(TreeNode* root) {\n if (!root) return 0;\n return max(maxDepth(root->left), maxDepth(root->right)) + 1;\n}", "test_cases": ["root=[3,9,20,null,null,15,7] -> 3", "root=[1,null,2] -> 2"], "key_points": ["DFS递归", "层序遍历也可"], "tags": ["tree", "easy", "Microsoft", "Apple"]} {"problem_id": "algo_00449", "original_id": "inorder-traversal", "title": "二叉树的中序遍历", "category": "tree", "difficulty": "easy", "companies": ["Google", "Microsoft"], "description": "给定一个二叉树的根节点 root,返回它的中序遍历结果。", "solution_python": "def inorderTraversal(root):\n result = []\n def dfs(node):\n if node:\n dfs(node.left)\n result.append(node.val)\n dfs(node.right)\n dfs(root)\n return result", "solution_java": "public List inorderTraversal(TreeNode root) {\n List res = new ArrayList<>();\n dfs(root, res);\n return res;\n}\nprivate void dfs(TreeNode node, List res) {\n if (node == null) return;\n dfs(node.left, res); res.add(node.val); dfs(node.right, res);\n}", "solution_cpp": "vector inorderTraversal(TreeNode* root) {\n vector res;\n dfs(root, res);\n return res;\n}\nvoid dfs(TreeNode* node, vector& res) {\n if (!node) return;\n dfs(node->left, res); res.push_back(node->val); dfs(node->right, res);\n}", "test_cases": ["root=[1,null,2,3] -> [1,3,2]", "root=[] -> []"], "key_points": ["左-根-右顺序", "递归最简洁"], "tags": ["tree", "easy", "Google", "Microsoft"]} {"problem_id": "algo_00450", "original_id": "binary-search", "title": "二分查找", "category": "binarysearch", "difficulty": "easy", "companies": ["Google", "Amazon"], "description": "给定一个 n 个元素有序的(升序)整型数组 nums 和一个目标值 target,写一个函数搜索 nums 中的 target,如果目标值存在返回下标,否则返回 -1。", "solution_python": "def search(nums, target):\n left, right = 0, len(nums) - 1\n while left <= right:\n mid = (left + right) // 2\n if nums[mid] == target: return mid\n elif nums[mid] < target: left = mid + 1\n else: right = mid - 1\n return -1", "solution_java": "public int search(int[] nums, int target) {\n int left = 0, right = nums.length - 1;\n while (left <= right) {\n int mid = left + (right - left) / 2;\n if (nums[mid] == target) return mid;\n else if (nums[mid] < target) left = mid + 1;\n else right = mid - 1;\n }\n return -1;\n}", "solution_cpp": "int search(vector& nums, int target) {\n int left = 0, right = nums.size() - 1;\n while (left <= right) {\n int mid = left + (right - left) / 2;\n if (nums[mid] == target) return mid;\n else if (nums[mid] < target) left = mid + 1;\n else right = mid - 1;\n }\n return -1;\n}", "test_cases": ["nums=[-1,0,3,5,9,12], target=9 -> 4", "nums=[-1,0,3,5,9,12], target=2 -> -1"], "key_points": ["标准模板", "注意防溢出写法"], "tags": ["binarysearch", "easy", "Google", "Amazon"]} {"problem_id": "algo_00451", "original_id": "climbing-stairs", "title": "爬楼梯", "category": "dp", "difficulty": "easy", "companies": ["Amazon", "Google"], "description": "假设你正在爬楼梯。需要 n 阶你才能到达楼顶。每次你可以爬 1 或 2 个台阶。你有多少种不同的方法可以爬到楼顶?", "solution_python": "def climbStairs(n):\n if n <= 2: return n\n a, b = 1, 2\n for _ in range(3, n+1):\n a, b = b, a + b\n return b", "solution_java": "public int climbStairs(int n) {\n if (n <= 2) return n;\n int a = 1, b = 2;\n for (int i = 3; i <= n; i++) { int temp = a + b; a = b; b = temp; }\n return b;\n}", "solution_cpp": "int climbStairs(int n) {\n if (n <= 2) return n;\n int a = 1, b = 2;\n for (int i = 3; i <= n; i++) { int temp = a + b; a = b; b = temp; }\n return b;\n}", "test_cases": ["n=2 -> 2", "n=3 -> 3", "n=5 -> 8"], "key_points": ["斐波那契数列", "滚动数组优化空间"], "tags": ["dp", "easy", "Amazon", "Google"]} {"problem_id": "algo_00452", "original_id": "coin-change", "title": "零钱兑换", "category": "dp", "difficulty": "medium", "companies": ["Google", "Amazon"], "description": "给你一个整数数组 coins 表示不同面额的硬币,以及一个整数 amount 表示总金额。计算并返回可以凑成总金额所需的最少的硬币个数。如果没有任何一种硬币组合能组成总金额,返回 -1。", "solution_python": "def coinChange(coins, amount):\n dp = [float('inf')] * (amount + 1)\n dp[0] = 0\n for coin in coins:\n for x in range(coin, amount + 1):\n dp[x] = min(dp[x], dp[x - coin] + 1)\n return dp[amount] if dp[amount] != float('inf') else -1", "solution_java": "public int coinChange(int[] coins, int amount) {\n int[] dp = new int[amount + 1];\n Arrays.fill(dp, amount + 1);\n dp[0] = 0;\n for (int coin : coins) {\n for (int x = coin; x <= amount; x++) {\n dp[x] = Math.min(dp[x], dp[x - coin] + 1);\n }\n }\n return dp[amount] > amount ? -1 : dp[amount];\n}", "solution_cpp": "int coinChange(vector& coins, int amount) {\n vector dp(amount + 1, amount + 1);\n dp[0] = 0;\n for (int coin : coins) {\n for (int x = coin; x <= amount; x++) {\n dp[x] = min(dp[x], dp[x - coin] + 1);\n }\n }\n return dp[amount] > amount ? -1 : dp[amount];\n}", "test_cases": ["coins=[1,2,5], amount=11 -> 3", "coins=[2], amount=3 -> -1"], "key_points": ["完全背包问题", "dp[x] = min(dp[x-coin]+1)"], "tags": ["dp", "medium", "Google", "Amazon"]} {"problem_id": "algo_00453", "original_id": "subsets", "title": "子集", "category": "backtracking", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "给你一个整数数组 nums ,数组中的元素 互不相同 。返回该数组所有可能的子集(幂集)。", "solution_python": "def subsets(nums):\n result = []\n def backtrack(start, path):\n result.append(path[:])\n for i in range(start, len(nums)):\n path.append(nums[i])\n backtrack(i + 1, path)\n path.pop()\n backtrack(0, [])\n return result", "solution_java": "public List> subsets(int[] nums) {\n List> result = new ArrayList<>();\n backtrack(nums, 0, new ArrayList<>(), result);\n return result;\n}\nprivate void backtrack(int[] nums, int start, List path, List> result) {\n result.add(new ArrayList<>(path));\n for (int i = start; i < nums.length; i++) {\n path.add(nums[i]);\n backtrack(nums, i + 1, path, result);\n path.remove(path.size() - 1);\n }\n}", "solution_cpp": "vector> subsets(vector& nums) {\n vector> result;\n vector path;\n backtrack(nums, 0, path, result);\n return result;\n}\nvoid backtrack(vector& nums, int start, vector& path, vector>& result) {\n result.push_back(path);\n for (int i = start; i < nums.size(); i++) {\n path.push_back(nums[i]);\n backtrack(nums, i + 1, path, result);\n path.pop_back();\n }\n}", "test_cases": ["nums=[1,2,3] -> [[],[1],[2],[1,2],[3],[1,3],[2,3],[1,2,3]]"], "key_points": ["选或不选", "DFS遍历子集树"], "tags": ["backtracking", "medium", "Google", "Microsoft"]} {"problem_id": "algo_00454", "original_id": "permutations", "title": "全排列", "category": "backtracking", "difficulty": "medium", "companies": ["Google", "Facebook"], "description": "给定一个不含重复数字的数组 nums,返回其所有可能的全排列。", "solution_python": "def permute(nums):\n result = []\n def backtrack(path, used):\n if len(path) == len(nums):\n result.append(path[:])\n return\n for i in range(len(nums)):\n if used[i]: continue\n used[i] = True\n path.append(nums[i])\n backtrack(path, used)\n path.pop()\n used[i] = False\n backtrack([], [False]*len(nums))\n return result", "solution_java": "public List> permute(int[] nums) {\n List> result = new ArrayList<>();\n boolean[] used = new boolean[nums.length];\n backtrack(nums, used, new ArrayList<>(), result);\n return result;\n}\nprivate void backtrack(int[] nums, boolean[] used, List path, List> result) {\n if (path.size() == nums.length) { result.add(new ArrayList<>(path)); return; }\n for (int i = 0; i < nums.length; i++) {\n if (used[i]) continue;\n used[i] = true;\n path.add(nums[i]);\n backtrack(nums, used, path, result);\n path.remove(path.size() - 1);\n used[i] = false;\n }\n}", "solution_cpp": "vector> permute(vector& nums) {\n vector> result;\n vector used(nums.size(), false);\n vector path;\n backtrack(nums, used, path, result);\n return result;\n}\nvoid backtrack(vector& nums, vector& used, vector& path, vector>& result) {\n if (path.size() == nums.size()) { result.push_back(path); return; }\n for (int i = 0; i < nums.size(); i++) {\n if (used[i]) continue;\n used[i] = true;\n path.push_back(nums[i]);\n backtrack(nums, used, path, result);\n path.pop_back();\n used[i] = false;\n }\n}", "test_cases": ["nums=[1,2,3] -> [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]"], "key_points": ["标记已使用元素", "回溯经典模板"], "tags": ["backtracking", "medium", "Google", "Facebook"]} {"problem_id": "algo_00455", "original_id": "top-k-frequent", "title": "前K个高频元素", "category": "heap", "difficulty": "medium", "companies": ["Amazon", "Facebook"], "description": "给你一个整数数组 nums 和一个整数 k,请你返回其中出现频率前 k 高的元素。", "solution_python": "import heapq\nfrom collections import Counter\ndef topKFrequent(nums, k):\n count = Counter(nums)\n heap = []\n for num, freq in count.items():\n heapq.heappush(heap, (freq, num))\n if len(heap) > k: heapq.heappop(heap)\n return [num for freq, num in heap]", "solution_java": "public int[] topKFrequent(int[] nums, int k) {\n Map count = new HashMap<>();\n for (int n : nums) count.put(n, count.getOrDefault(n, 0) + 1);\n PriorityQueue> heap = \n new PriorityQueue<>((a, b) -> a.getValue() - b.getValue());\n for (Map.Entry e : count.entrySet()) {\n heap.offer(e);\n if (heap.size() > k) heap.poll();\n }\n int[] res = new int[k];\n for (int i = k - 1; i >= 0; i--) res[i] = heap.poll().getKey();\n return res;\n}", "solution_cpp": "vector topKFrequent(vector& nums, int k) {\n unordered_map count;\n for (int n : nums) count[n]++;\n priority_queue, vector>, greater>> heap;\n for (auto& [num, freq] : count) {\n heap.push({freq, num});\n if (heap.size() > k) heap.pop();\n }\n vector res;\n while (!heap.empty()) { res.push_back(heap.top().second); heap.pop(); }\n reverse(res.begin(), res.end());\n return res;\n}", "test_cases": ["nums=[1,1,1,2,2,3], k=2 -> [1,2]", "nums=[1], k=1 -> [1]"], "key_points": ["小顶堆保持大小k", "时间复杂度O(nlogk)"], "tags": ["heap", "medium", "Amazon", "Facebook"]} {"problem_id": "algo_00456", "original_id": "3sum", "title": "三数之和", "category": "two-pointers", "difficulty": "medium", "companies": ["Google", "Amazon"], "description": "给你一个整数数组 nums,判断是否存在三元组满足和为0,返回所有不重复的三元组。", "solution_python": "def threeSum(nums):\n nums.sort()\n result = []\n for i in range(len(nums) - 2):\n if i > 0 and nums[i] == nums[i-1]: continue\n left, right = i + 1, len(nums) - 1\n while left < right:\n total = nums[i] + nums[left] + nums[right]\n if total < 0: left += 1\n elif total > 0: right -= 1\n else:\n result.append([nums[i], nums[left], nums[right]])\n while left < right and nums[left] == nums[left+1]: left += 1\n while left < right and nums[right] == nums[right-1]: right -= 1\n left += 1; right -= 1\n return result", "solution_java": "public List> threeSum(int[] nums) {\n Arrays.sort(nums);\n List> result = new ArrayList<>();\n for (int i = 0; i < nums.length - 2; i++) {\n if (i > 0 && nums[i] == nums[i-1]) continue;\n int left = i + 1, right = nums.length - 1;\n while (left < right) {\n int total = nums[i] + nums[left] + nums[right];\n if (total < 0) left++;\n else if (total > 0) right--;\n else {\n result.add(Arrays.asList(nums[i], nums[left], nums[right]));\n while (left < right && nums[left] == nums[left+1]) left++;\n while (left < right && nums[right] == nums[right-1]) right--;\n left++; right--;\n }\n }\n }\n return result;\n}", "solution_cpp": "vector> threeSum(vector& nums) {\n sort(nums.begin(), nums.end());\n vector> result;\n for (int i = 0; i < nums.size() - 2; i++) {\n if (i > 0 && nums[i] == nums[i-1]) continue;\n int left = i + 1, right = nums.size() - 1;\n while (left < right) {\n int total = nums[i] + nums[left] + nums[right];\n if (total < 0) left++;\n else if (total > 0) right--;\n else {\n result.push_back({nums[i], nums[left], nums[right]});\n while (left < right && nums[left] == nums[left+1]) left++;\n while (left < right && nums[right] == nums[right-1]) right--;\n left++; right--;\n }\n }\n }\n return result;\n}", "test_cases": ["nums=[-1,0,1,2,-1,-4] -> [[-1,-1,2],[-1,0,1]]"], "key_points": ["排序+双指针", "去重是关键"], "tags": ["two-pointers", "medium", "Google", "Amazon"]} {"problem_id": "algo_00457", "original_id": "container-water", "title": "盛最多水的容器", "category": "two-pointers", "difficulty": "medium", "companies": ["Google", "Uber"], "description": "给定一个长度为 n 的整数数组 height,找出其中的两条线,使得它们与 x 轴共同构成的容器可以容纳最多的水。", "solution_python": "def maxArea(height):\n left, right = 0, len(height) - 1\n max_area = 0\n while left < right:\n h = min(height[left], height[right])\n max_area = max(max_area, h * (right - left))\n if height[left] < height[right]: left += 1\n else: right -= 1\n return max_area", "solution_java": "public int maxArea(int[] height) {\n int left = 0, right = height.length - 1, maxArea = 0;\n while (left < right) {\n int h = Math.min(height[left], height[right]);\n maxArea = Math.max(maxArea, h * (right - left));\n if (height[left] < height[right]) left++;\n else right--;\n }\n return maxArea;\n}", "solution_cpp": "int maxArea(vector& height) {\n int left = 0, right = height.size() - 1, maxArea = 0;\n while (left < right) {\n int h = min(height[left], height[right]);\n maxArea = max(maxArea, h * (right - left));\n if (height[left] < height[right]) left++;\n else right--;\n }\n return maxArea;\n}", "test_cases": ["height=[1,8,6,2,5,4,8,3,7] -> 49"], "key_points": ["移动短边指针", "面积=min(h1,h2)*width"], "tags": ["two-pointers", "medium", "Google", "Uber"]} {"problem_id": "algo_00458", "original_id": "min-stack", "title": "最小栈", "category": "stack", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "设计一个支持 push,pop,top 操作,并能在常数时间内检索到最小元素的栈。", "solution_python": "class MinStack:\n def __init__(self):\n self.stack = []\n self.min_stack = []\n def push(self, val):\n self.stack.append(val)\n self.min_stack.append(min(val, self.min_stack[-1] if self.min_stack else val))\n def pop(self):\n self.stack.pop(); self.min_stack.pop()\n def top(self): return self.stack[-1]\n def getMin(self): return self.min_stack[-1]", "solution_java": "class MinStack {\n Stack stack = new Stack<>();\n Stack minStack = new Stack<>();\n public void push(int val) { stack.push(val); minStack.push(Math.min(val, minStack.isEmpty() ? val : minStack.peek())); }\n public void pop() { stack.pop(); minStack.pop(); }\n public int top() { return stack.peek(); }\n public int getMin() { return minStack.peek(); }\n}", "solution_cpp": "class MinStack {\n stack st, minSt;\npublic:\n void push(int val) { st.push(val); minSt.push(min(val, minSt.empty() ? val : minSt.top())); }\n void pop() { st.pop(); minSt.pop(); }\n int top() { return st.top(); }\n int getMin() { return minSt.top(); }\n};", "test_cases": ["push(-2), push(0), push(-3) -> getMin() returns -3"], "key_points": ["辅助栈记录最小值", "O(1)时间获取最小值"], "tags": ["stack", "medium", "Google", "Microsoft"]} {"problem_id": "algo_00459", "original_id": "lru-cache", "title": "LRU缓存", "category": "design", "difficulty": "hard", "companies": ["Google", "Amazon"], "description": "设计和实现一个 LRU(最近最少使用)缓存机制。", "solution_python": "class LRUCache:\n def __init__(self, capacity):\n self.capacity = capacity\n self.cache = {}\n self.order = []\n def get(self, key):\n if key not in self.cache: return -1\n self.order.remove(key); self.order.append(key)\n return self.cache[key]\n def put(self, key, value):\n if key in self.cache:\n self.order.remove(key)\n elif len(self.cache) >= self.capacity:\n del self.cache[self.order.pop(0)]\n self.cache[key] = value; self.order.append(key)", "solution_java": "class LRUCache {\n int capacity;\n LinkedHashMap cache = new LinkedHashMap<>();\n public LRUCache(int cap) { capacity = cap; }\n public int get(int key) { return cache.containsKey(key) ? cache.remove(key) : -1; }\n public void put(int key, int val) {\n if (cache.containsKey(key)) cache.remove(key);\n else if (cache.size() >= capacity) cache.remove(cache.keySet().iterator().next());\n cache.put(key, val);\n }\n}", "solution_cpp": "class LRUCache {\n int cap;\n list> dll;\n unordered_map>::iterator> cache;\npublic:\n LRUCache(int capacity) : cap(capacity) {}\n int get(int key) {\n auto it = cache.find(key);\n if (it == cache.end()) return -1;\n dll.splice(dll.end(), dll, it->second);\n return it->second->second;\n }\n void put(int key, int value) {\n auto it = cache.find(key);\n if (it != cache.end()) dll.erase(it->second);\n else if (cache.size() >= cap) { cache.erase(dll.front().first); dll.pop_front(); }\n dll.push_back({key, value});\n cache[key] = --dll.end();\n }\n};", "test_cases": ["put(1,1), put(2,2), get(1) -> 1"], "key_points": ["HashMap + 双向链表", "O(1)时间操作"], "tags": ["design", "hard", "Google", "Amazon"]} {"problem_id": "algo_00460", "original_id": "num-islands", "title": "岛屿数量", "category": "graph", "difficulty": "medium", "companies": ["Google", "Facebook"], "description": "给你一个由 '1'(陆地)和 '0'(水)组成的二维网格,请你计算网格中岛屿的数量。岛屿总是被水包围,且只能由水平或垂直方向相邻的陆地连接形成。", "solution_python": "def numIslands(grid):\n if not grid: return 0\n rows, cols = len(grid), len(grid[0])\n count = 0\n def dfs(r, c):\n if r < 0 or r >= rows or c < 0 or c >= cols or grid[r][c] != '1': return\n grid[r][c] = '0'\n dfs(r+1, c); dfs(r-1, c); dfs(r, c+1); dfs(r, c-1)\n for r in range(rows):\n for c in range(cols):\n if grid[r][c] == '1': count += 1; dfs(r, c)\n return count", "solution_java": "public int numIslands(char[][] grid) {\n if (grid.length == 0) return 0;\n int count = 0;\n for (int i = 0; i < grid.length; i++)\n for (int j = 0; j < grid[0].length; j++)\n if (grid[i][j] == '1') { count++; dfs(grid, i, j); }\n return count;\n}\nprivate void dfs(char[][] grid, int r, int c) {\n if (r < 0 || r >= grid.length || c < 0 || c >= grid[0].length || grid[r][c] != '1') return;\n grid[r][c] = '0';\n dfs(grid, r+1, c); dfs(grid, r-1, c); dfs(grid, r, c+1); dfs(grid, r, c-1);\n}", "solution_cpp": "int numIslands(vector>& grid) {\n if (grid.empty()) return 0;\n int count = 0;\n for (int i = 0; i < grid.size(); i++)\n for (int j = 0; j < grid[0].size(); j++)\n if (grid[i][j] == '1') { count++; dfs(grid, i, j); }\n return count;\n}\nvoid dfs(vector>& grid, int r, int c) {\n if (r < 0 || r >= grid.size() || c < 0 || c >= grid[0].size() || grid[r][c] != '1') return;\n grid[r][c] = '0';\n dfs(grid, r+1, c); dfs(grid, r-1, c); dfs(grid, r, c+1); dfs(grid, r, c-1);\n}", "test_cases": ["grid=[[1,1,1,1,0],[1,1,0,1,0],[1,1,0,0,0],[0,0,0,0,0]] -> 1"], "key_points": ["DFS/BFS遍历", "访问后标记为0避免重复"], "tags": ["graph", "medium", "Google", "Facebook"]} {"problem_id": "algo_00461", "original_id": "two-sum", "title": "两数之和", "category": "array", "difficulty": "easy", "companies": ["Amazon", "Google"], "description": "给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那两个整数,并返回他们的数组下标。", "solution_python": "def twoSum(nums, target):\n hashmap = {}\n for i, num in enumerate(nums):\n complement = target - num\n if complement in hashmap:\n return [hashmap[complement], i]\n hashmap[num] = i\n return []", "solution_java": "public int[] twoSum(int[] nums, int target) {\n Map map = new HashMap<>();\n for (int i = 0; i < nums.length; i++) {\n int complement = target - nums[i];\n if (map.containsKey(complement)) return new int[]{map.get(complement), i};\n map.put(nums[i], i);\n }\n return new int[]{};\n}", "solution_cpp": "vector twoSum(vector& nums, int target) {\n unordered_map m;\n for (int i = 0; i < nums.size(); i++) {\n if (m.count(target - nums[i])) return {m[target - nums[i]], i};\n m[nums[i]] = i;\n }\n return {};\n}", "test_cases": ["nums=[2,7,11,15], target=9 -> [0,1]", "nums=[3,2,4], target=6 -> [1,2]"], "key_points": ["哈希表一次遍历", "空间换时间"], "tags": ["array", "easy", "Amazon", "Google"]} {"problem_id": "algo_00462", "original_id": "merge-sorted", "title": "合并两个有序数组", "category": "array", "difficulty": "easy", "companies": ["Microsoft", "Uber"], "description": "给你两个按非递减顺序排列的整数数组 nums1 和 nums2,另有两个整数 m 和 n,分别表示 nums1 和 nums2 中的元素数目。请你合并 nums2 到 nums1 中。", "solution_python": "def merge(nums1, m, nums2, n):\n p1, p2, p = m-1, n-1, m+n-1\n while p1 >= 0 and p2 >= 0:\n if nums1[p1] > nums2[p2]: nums1[p] = nums1[p1]; p1 -= 1\n else: nums1[p] = nums2[p2]; p2 -= 1\n p -= 1\n while p2 >= 0: nums1[p] = nums2[p2]; p2 -= 1; p -= 1", "solution_java": "public void merge(int[] nums1, int m, int[] nums2, int n) {\n int p1 = m-1, p2 = n-1, p = m+n-1;\n while (p1 >= 0 && p2 >= 0) {\n nums1[p--] = nums1[p1] > nums2[p2] ? nums1[p1--] : nums2[p2--];\n }\n while (p2 >= 0) nums1[p--] = nums2[p2--];\n}", "solution_cpp": "void merge(vector& nums1, int m, vector& nums2, int n) {\n int p1 = m-1, p2 = n-1, p = m+n-1;\n while (p1 >= 0 && p2 >= 0) nums1[p--] = nums1[p1] > nums2[p2] ? nums1[p1--] : nums2[p2--];\n while (p2 >= 0) nums1[p--] = nums2[p2--];\n}", "test_cases": ["nums1=[1,2,3], m=3, nums2=[2,5,6], n=3 -> [1,2,2,3,5,6]", "nums1=[], m=0, nums2=[1], n=1 -> [1]"], "key_points": ["从后往前合并", "三指针技巧"], "tags": ["array", "easy", "Microsoft", "Uber"]} {"problem_id": "algo_00463", "original_id": "max-subarray", "title": "最大子数组和", "category": "array", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "给你一个整数数组 nums ,请你找出一个具有最大和的连续子数组,返回其最大和。", "solution_python": "def maxSubArray(nums):\n max_sum = current = nums[0]\n for num in nums[1:]:\n current = max(num, current + num)\n max_sum = max(max_sum, current)\n return max_sum", "solution_java": "public int maxSubArray(int[] nums) {\n int maxSum = nums[0], curr = nums[0];\n for (int i = 1; i < nums.length; i++) {\n curr = Math.max(nums[i], curr + nums[i]);\n maxSum = Math.max(maxSum, curr);\n }\n return maxSum;\n}", "solution_cpp": "int maxSubArray(vector& nums) {\n int maxSum = nums[0], curr = nums[0];\n for (int i = 1; i < nums.size(); i++) {\n curr = max(nums[i], curr + nums[i]);\n maxSum = max(maxSum, curr);\n }\n return maxSum;\n}", "test_cases": ["nums=[-2,1,-3,4,-1,2,1,-5,4] -> 6", "nums=[1] -> 1"], "key_points": ["Kadane算法", "动态规划基础题"], "tags": ["array", "medium", "Google", "Microsoft"]} {"problem_id": "algo_00464", "original_id": "valid-parentheses", "title": "有效的括号", "category": "string", "difficulty": "easy", "companies": ["Google", "Uber"], "description": "给定一个只包括 '(',')','{','}','[',']' 的字符串 s,判断字符串是否有效。", "solution_python": "def isValid(s):\n stack = []\n mapping = {')': '(', ']': '[', '}': '{'}\n for c in s:\n if c in mapping:\n if not stack or stack[-1] != mapping[c]: return False\n stack.pop()\n else: stack.append(c)\n return not stack", "solution_java": "public boolean isValid(String s) {\n Stack stack = new Stack<>();\n Map map = Map.of(')', '(', ']', '[', '}', '{');\n for (char c : s.toCharArray()) {\n if (map.containsValue(c)) stack.push(c);\n else if (!stack.isEmpty() && stack.pop() != map.get(c)) return false;\n }\n return stack.isEmpty();\n}", "solution_cpp": "bool isValid(string s) {\n stack st;\n unordered_map m = {{')','('},{']','['},{'}','{'}};\n for (char c : s) {\n if (m.find(c) == m.end()) st.push(c);\n else if (st.empty() || st.top() != m[c]) return false;\n else st.pop();\n }\n return st.empty();\n}", "test_cases": ["s=\"()\" -> true", "s=\"()[]{}\" -> true", "s=\"(]\" -> false"], "key_points": ["栈匹配法", "注意空栈边界"], "tags": ["string", "easy", "Google", "Uber"]} {"problem_id": "algo_00465", "original_id": "longest-palindrome", "title": "最长回文子串", "category": "string", "difficulty": "medium", "companies": ["Google", "Amazon"], "description": "给你一个字符串 s,找到 s 中最长的回文子串。", "solution_python": "def longestPalindrome(s):\n def expand(l, r):\n while l >= 0 and r < len(s) and s[l] == s[r]: l -= 1; r += 1\n return l + 1, r - 1\n start = end = 0\n for i in range(len(s)):\n l1, r1 = expand(i, i)\n l2, r2 = expand(i, i + 1)\n if r1 - l1 > end - start: start, end = l1, r1\n if r2 - l2 > end - start: start, end = l2, r2\n return s[start:end+1]", "solution_java": "public String longestPalindrome(String s) {\n int start = 0, end = 0;\n for (int i = 0; i < s.length(); i++) {\n int len1 = expand(s, i, i), len2 = expand(s, i, i+1);\n int len = Math.max(len1, len2);\n if (len > end - start) { start = i - (len-1)/2; end = i + len/2; }\n }\n return s.substring(start, end + 1);\n}\nprivate int expand(String s, int l, int r) {\n while (l >= 0 && r < s.length() && s.charAt(l) == s.charAt(r)) { l--; r++; }\n return r - l - 1;\n}", "solution_cpp": "string longestPalindrome(string s) {\n int start = 0, end = 0;\n for (int i = 0; i < s.size(); i++) {\n int len1 = expand(s, i, i), len2 = expand(s, i, i+1);\n if (max(len1, len2) > end - start) { start = i - (max(len1,len2)-1)/2; end = i + max(len1,len2)/2; }\n }\n return s.substr(start, end - start + 1);\n}", "test_cases": ["s=\"babad\" -> bab或aba", "s=\"cbbd\" -> bb"], "key_points": ["中心扩展法", "处理奇偶长度"], "tags": ["string", "medium", "Google", "Amazon"]} {"problem_id": "algo_00466", "original_id": "reverse-list", "title": "反转链表", "category": "linkedlist", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "给你单链表的头节点 head,请你反转链表,并返回反转后的链表。", "solution_python": "def reverseList(head):\n prev = None\n curr = head\n while curr:\n nxt = curr.next\n curr.next = prev\n prev = curr\n curr = nxt\n return prev", "solution_java": "public ListNode reverseList(ListNode head) {\n ListNode prev = null, curr = head;\n while (curr != null) {\n ListNode next = curr.next;\n curr.next = prev;\n prev = curr;\n curr = next;\n }\n return prev;\n}", "solution_cpp": "ListNode* reverseList(ListNode* head) {\n ListNode* prev = nullptr, *curr = head;\n while (curr) {\n ListNode* next = curr->next;\n curr->next = prev;\n prev = curr;\n curr = next;\n }\n return prev;\n}", "test_cases": ["head=[1,2,3,4,5] -> [5,4,3,2,1]", "head=[1,2] -> [2,1]"], "key_points": ["迭代法 O(1)空间", "递归法 O(n)空间"], "tags": ["linkedlist", "medium", "Google", "Microsoft"]} {"problem_id": "algo_00467", "original_id": "middle-node", "title": "链表的中间结点", "category": "linkedlist", "difficulty": "easy", "companies": ["Amazon", "Facebook"], "description": "给你单链表的头节点 head,请你找出并返回链表的中间结点。如果有两个中间结点,则返回第二个中间结点。", "solution_python": "def middleNode(head):\n slow = fast = head\n while fast and fast.next:\n slow = slow.next\n fast = fast.next.next\n return slow", "solution_java": "public ListNode middleNode(ListNode head) {\n ListNode slow = head, fast = head;\n while (fast != null && fast.next != null) {\n slow = slow.next;\n fast = fast.next.next;\n }\n return slow;\n}", "solution_cpp": "ListNode* middleNode(ListNode* head) {\n ListNode* slow = head, *fast = head;\n while (fast && fast->next) { slow = slow->next; fast = fast->next->next; }\n return slow;\n}", "test_cases": ["head=[1,2,3,4,5] -> 3", "head=[1,2,3,4,5,6] -> 4"], "key_points": ["快慢指针", "O(n)时间O(1)空间"], "tags": ["linkedlist", "easy", "Amazon", "Facebook"]} {"problem_id": "algo_00468", "original_id": "max-depth", "title": "二叉树的最大深度", "category": "tree", "difficulty": "easy", "companies": ["Microsoft", "Apple"], "description": "给定一个二叉树 root,返回其最大深度。", "solution_python": "def maxDepth(root):\n if not root: return 0\n return max(maxDepth(root.left), maxDepth(root.right)) + 1", "solution_java": "public int maxDepth(TreeNode root) {\n if (root == null) return 0;\n return Math.max(maxDepth(root.left), maxDepth(root.right)) + 1;\n}", "solution_cpp": "int maxDepth(TreeNode* root) {\n if (!root) return 0;\n return max(maxDepth(root->left), maxDepth(root->right)) + 1;\n}", "test_cases": ["root=[3,9,20,null,null,15,7] -> 3", "root=[1,null,2] -> 2"], "key_points": ["DFS递归", "层序遍历也可"], "tags": ["tree", "easy", "Microsoft", "Apple"]} {"problem_id": "algo_00469", "original_id": "inorder-traversal", "title": "二叉树的中序遍历", "category": "tree", "difficulty": "easy", "companies": ["Google", "Microsoft"], "description": "给定一个二叉树的根节点 root,返回它的中序遍历结果。", "solution_python": "def inorderTraversal(root):\n result = []\n def dfs(node):\n if node:\n dfs(node.left)\n result.append(node.val)\n dfs(node.right)\n dfs(root)\n return result", "solution_java": "public List inorderTraversal(TreeNode root) {\n List res = new ArrayList<>();\n dfs(root, res);\n return res;\n}\nprivate void dfs(TreeNode node, List res) {\n if (node == null) return;\n dfs(node.left, res); res.add(node.val); dfs(node.right, res);\n}", "solution_cpp": "vector inorderTraversal(TreeNode* root) {\n vector res;\n dfs(root, res);\n return res;\n}\nvoid dfs(TreeNode* node, vector& res) {\n if (!node) return;\n dfs(node->left, res); res.push_back(node->val); dfs(node->right, res);\n}", "test_cases": ["root=[1,null,2,3] -> [1,3,2]", "root=[] -> []"], "key_points": ["左-根-右顺序", "递归最简洁"], "tags": ["tree", "easy", "Google", "Microsoft"]} {"problem_id": "algo_00470", "original_id": "binary-search", "title": "二分查找", "category": "binarysearch", "difficulty": "easy", "companies": ["Google", "Amazon"], "description": "给定一个 n 个元素有序的(升序)整型数组 nums 和一个目标值 target,写一个函数搜索 nums 中的 target,如果目标值存在返回下标,否则返回 -1。", "solution_python": "def search(nums, target):\n left, right = 0, len(nums) - 1\n while left <= right:\n mid = (left + right) // 2\n if nums[mid] == target: return mid\n elif nums[mid] < target: left = mid + 1\n else: right = mid - 1\n return -1", "solution_java": "public int search(int[] nums, int target) {\n int left = 0, right = nums.length - 1;\n while (left <= right) {\n int mid = left + (right - left) / 2;\n if (nums[mid] == target) return mid;\n else if (nums[mid] < target) left = mid + 1;\n else right = mid - 1;\n }\n return -1;\n}", "solution_cpp": "int search(vector& nums, int target) {\n int left = 0, right = nums.size() - 1;\n while (left <= right) {\n int mid = left + (right - left) / 2;\n if (nums[mid] == target) return mid;\n else if (nums[mid] < target) left = mid + 1;\n else right = mid - 1;\n }\n return -1;\n}", "test_cases": ["nums=[-1,0,3,5,9,12], target=9 -> 4", "nums=[-1,0,3,5,9,12], target=2 -> -1"], "key_points": ["标准模板", "注意防溢出写法"], "tags": ["binarysearch", "easy", "Google", "Amazon"]} {"problem_id": "algo_00471", "original_id": "climbing-stairs", "title": "爬楼梯", "category": "dp", "difficulty": "easy", "companies": ["Amazon", "Google"], "description": "假设你正在爬楼梯。需要 n 阶你才能到达楼顶。每次你可以爬 1 或 2 个台阶。你有多少种不同的方法可以爬到楼顶?", "solution_python": "def climbStairs(n):\n if n <= 2: return n\n a, b = 1, 2\n for _ in range(3, n+1):\n a, b = b, a + b\n return b", "solution_java": "public int climbStairs(int n) {\n if (n <= 2) return n;\n int a = 1, b = 2;\n for (int i = 3; i <= n; i++) { int temp = a + b; a = b; b = temp; }\n return b;\n}", "solution_cpp": "int climbStairs(int n) {\n if (n <= 2) return n;\n int a = 1, b = 2;\n for (int i = 3; i <= n; i++) { int temp = a + b; a = b; b = temp; }\n return b;\n}", "test_cases": ["n=2 -> 2", "n=3 -> 3", "n=5 -> 8"], "key_points": ["斐波那契数列", "滚动数组优化空间"], "tags": ["dp", "easy", "Amazon", "Google"]} {"problem_id": "algo_00472", "original_id": "coin-change", "title": "零钱兑换", "category": "dp", "difficulty": "medium", "companies": ["Google", "Amazon"], "description": "给你一个整数数组 coins 表示不同面额的硬币,以及一个整数 amount 表示总金额。计算并返回可以凑成总金额所需的最少的硬币个数。如果没有任何一种硬币组合能组成总金额,返回 -1。", "solution_python": "def coinChange(coins, amount):\n dp = [float('inf')] * (amount + 1)\n dp[0] = 0\n for coin in coins:\n for x in range(coin, amount + 1):\n dp[x] = min(dp[x], dp[x - coin] + 1)\n return dp[amount] if dp[amount] != float('inf') else -1", "solution_java": "public int coinChange(int[] coins, int amount) {\n int[] dp = new int[amount + 1];\n Arrays.fill(dp, amount + 1);\n dp[0] = 0;\n for (int coin : coins) {\n for (int x = coin; x <= amount; x++) {\n dp[x] = Math.min(dp[x], dp[x - coin] + 1);\n }\n }\n return dp[amount] > amount ? -1 : dp[amount];\n}", "solution_cpp": "int coinChange(vector& coins, int amount) {\n vector dp(amount + 1, amount + 1);\n dp[0] = 0;\n for (int coin : coins) {\n for (int x = coin; x <= amount; x++) {\n dp[x] = min(dp[x], dp[x - coin] + 1);\n }\n }\n return dp[amount] > amount ? -1 : dp[amount];\n}", "test_cases": ["coins=[1,2,5], amount=11 -> 3", "coins=[2], amount=3 -> -1"], "key_points": ["完全背包问题", "dp[x] = min(dp[x-coin]+1)"], "tags": ["dp", "medium", "Google", "Amazon"]} {"problem_id": "algo_00473", "original_id": "subsets", "title": "子集", "category": "backtracking", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "给你一个整数数组 nums ,数组中的元素 互不相同 。返回该数组所有可能的子集(幂集)。", "solution_python": "def subsets(nums):\n result = []\n def backtrack(start, path):\n result.append(path[:])\n for i in range(start, len(nums)):\n path.append(nums[i])\n backtrack(i + 1, path)\n path.pop()\n backtrack(0, [])\n return result", "solution_java": "public List> subsets(int[] nums) {\n List> result = new ArrayList<>();\n backtrack(nums, 0, new ArrayList<>(), result);\n return result;\n}\nprivate void backtrack(int[] nums, int start, List path, List> result) {\n result.add(new ArrayList<>(path));\n for (int i = start; i < nums.length; i++) {\n path.add(nums[i]);\n backtrack(nums, i + 1, path, result);\n path.remove(path.size() - 1);\n }\n}", "solution_cpp": "vector> subsets(vector& nums) {\n vector> result;\n vector path;\n backtrack(nums, 0, path, result);\n return result;\n}\nvoid backtrack(vector& nums, int start, vector& path, vector>& result) {\n result.push_back(path);\n for (int i = start; i < nums.size(); i++) {\n path.push_back(nums[i]);\n backtrack(nums, i + 1, path, result);\n path.pop_back();\n }\n}", "test_cases": ["nums=[1,2,3] -> [[],[1],[2],[1,2],[3],[1,3],[2,3],[1,2,3]]"], "key_points": ["选或不选", "DFS遍历子集树"], "tags": ["backtracking", "medium", "Google", "Microsoft"]} {"problem_id": "algo_00474", "original_id": "permutations", "title": "全排列", "category": "backtracking", "difficulty": "medium", "companies": ["Google", "Facebook"], "description": "给定一个不含重复数字的数组 nums,返回其所有可能的全排列。", "solution_python": "def permute(nums):\n result = []\n def backtrack(path, used):\n if len(path) == len(nums):\n result.append(path[:])\n return\n for i in range(len(nums)):\n if used[i]: continue\n used[i] = True\n path.append(nums[i])\n backtrack(path, used)\n path.pop()\n used[i] = False\n backtrack([], [False]*len(nums))\n return result", "solution_java": "public List> permute(int[] nums) {\n List> result = new ArrayList<>();\n boolean[] used = new boolean[nums.length];\n backtrack(nums, used, new ArrayList<>(), result);\n return result;\n}\nprivate void backtrack(int[] nums, boolean[] used, List path, List> result) {\n if (path.size() == nums.length) { result.add(new ArrayList<>(path)); return; }\n for (int i = 0; i < nums.length; i++) {\n if (used[i]) continue;\n used[i] = true;\n path.add(nums[i]);\n backtrack(nums, used, path, result);\n path.remove(path.size() - 1);\n used[i] = false;\n }\n}", "solution_cpp": "vector> permute(vector& nums) {\n vector> result;\n vector used(nums.size(), false);\n vector path;\n backtrack(nums, used, path, result);\n return result;\n}\nvoid backtrack(vector& nums, vector& used, vector& path, vector>& result) {\n if (path.size() == nums.size()) { result.push_back(path); return; }\n for (int i = 0; i < nums.size(); i++) {\n if (used[i]) continue;\n used[i] = true;\n path.push_back(nums[i]);\n backtrack(nums, used, path, result);\n path.pop_back();\n used[i] = false;\n }\n}", "test_cases": ["nums=[1,2,3] -> [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]"], "key_points": ["标记已使用元素", "回溯经典模板"], "tags": ["backtracking", "medium", "Google", "Facebook"]} {"problem_id": "algo_00475", "original_id": "top-k-frequent", "title": "前K个高频元素", "category": "heap", "difficulty": "medium", "companies": ["Amazon", "Facebook"], "description": "给你一个整数数组 nums 和一个整数 k,请你返回其中出现频率前 k 高的元素。", "solution_python": "import heapq\nfrom collections import Counter\ndef topKFrequent(nums, k):\n count = Counter(nums)\n heap = []\n for num, freq in count.items():\n heapq.heappush(heap, (freq, num))\n if len(heap) > k: heapq.heappop(heap)\n return [num for freq, num in heap]", "solution_java": "public int[] topKFrequent(int[] nums, int k) {\n Map count = new HashMap<>();\n for (int n : nums) count.put(n, count.getOrDefault(n, 0) + 1);\n PriorityQueue> heap = \n new PriorityQueue<>((a, b) -> a.getValue() - b.getValue());\n for (Map.Entry e : count.entrySet()) {\n heap.offer(e);\n if (heap.size() > k) heap.poll();\n }\n int[] res = new int[k];\n for (int i = k - 1; i >= 0; i--) res[i] = heap.poll().getKey();\n return res;\n}", "solution_cpp": "vector topKFrequent(vector& nums, int k) {\n unordered_map count;\n for (int n : nums) count[n]++;\n priority_queue, vector>, greater>> heap;\n for (auto& [num, freq] : count) {\n heap.push({freq, num});\n if (heap.size() > k) heap.pop();\n }\n vector res;\n while (!heap.empty()) { res.push_back(heap.top().second); heap.pop(); }\n reverse(res.begin(), res.end());\n return res;\n}", "test_cases": ["nums=[1,1,1,2,2,3], k=2 -> [1,2]", "nums=[1], k=1 -> [1]"], "key_points": ["小顶堆保持大小k", "时间复杂度O(nlogk)"], "tags": ["heap", "medium", "Amazon", "Facebook"]} {"problem_id": "algo_00476", "original_id": "3sum", "title": "三数之和", "category": "two-pointers", "difficulty": "medium", "companies": ["Google", "Amazon"], "description": "给你一个整数数组 nums,判断是否存在三元组满足和为0,返回所有不重复的三元组。", "solution_python": "def threeSum(nums):\n nums.sort()\n result = []\n for i in range(len(nums) - 2):\n if i > 0 and nums[i] == nums[i-1]: continue\n left, right = i + 1, len(nums) - 1\n while left < right:\n total = nums[i] + nums[left] + nums[right]\n if total < 0: left += 1\n elif total > 0: right -= 1\n else:\n result.append([nums[i], nums[left], nums[right]])\n while left < right and nums[left] == nums[left+1]: left += 1\n while left < right and nums[right] == nums[right-1]: right -= 1\n left += 1; right -= 1\n return result", "solution_java": "public List> threeSum(int[] nums) {\n Arrays.sort(nums);\n List> result = new ArrayList<>();\n for (int i = 0; i < nums.length - 2; i++) {\n if (i > 0 && nums[i] == nums[i-1]) continue;\n int left = i + 1, right = nums.length - 1;\n while (left < right) {\n int total = nums[i] + nums[left] + nums[right];\n if (total < 0) left++;\n else if (total > 0) right--;\n else {\n result.add(Arrays.asList(nums[i], nums[left], nums[right]));\n while (left < right && nums[left] == nums[left+1]) left++;\n while (left < right && nums[right] == nums[right-1]) right--;\n left++; right--;\n }\n }\n }\n return result;\n}", "solution_cpp": "vector> threeSum(vector& nums) {\n sort(nums.begin(), nums.end());\n vector> result;\n for (int i = 0; i < nums.size() - 2; i++) {\n if (i > 0 && nums[i] == nums[i-1]) continue;\n int left = i + 1, right = nums.size() - 1;\n while (left < right) {\n int total = nums[i] + nums[left] + nums[right];\n if (total < 0) left++;\n else if (total > 0) right--;\n else {\n result.push_back({nums[i], nums[left], nums[right]});\n while (left < right && nums[left] == nums[left+1]) left++;\n while (left < right && nums[right] == nums[right-1]) right--;\n left++; right--;\n }\n }\n }\n return result;\n}", "test_cases": ["nums=[-1,0,1,2,-1,-4] -> [[-1,-1,2],[-1,0,1]]"], "key_points": ["排序+双指针", "去重是关键"], "tags": ["two-pointers", "medium", "Google", "Amazon"]} {"problem_id": "algo_00477", "original_id": "container-water", "title": "盛最多水的容器", "category": "two-pointers", "difficulty": "medium", "companies": ["Google", "Uber"], "description": "给定一个长度为 n 的整数数组 height,找出其中的两条线,使得它们与 x 轴共同构成的容器可以容纳最多的水。", "solution_python": "def maxArea(height):\n left, right = 0, len(height) - 1\n max_area = 0\n while left < right:\n h = min(height[left], height[right])\n max_area = max(max_area, h * (right - left))\n if height[left] < height[right]: left += 1\n else: right -= 1\n return max_area", "solution_java": "public int maxArea(int[] height) {\n int left = 0, right = height.length - 1, maxArea = 0;\n while (left < right) {\n int h = Math.min(height[left], height[right]);\n maxArea = Math.max(maxArea, h * (right - left));\n if (height[left] < height[right]) left++;\n else right--;\n }\n return maxArea;\n}", "solution_cpp": "int maxArea(vector& height) {\n int left = 0, right = height.size() - 1, maxArea = 0;\n while (left < right) {\n int h = min(height[left], height[right]);\n maxArea = max(maxArea, h * (right - left));\n if (height[left] < height[right]) left++;\n else right--;\n }\n return maxArea;\n}", "test_cases": ["height=[1,8,6,2,5,4,8,3,7] -> 49"], "key_points": ["移动短边指针", "面积=min(h1,h2)*width"], "tags": ["two-pointers", "medium", "Google", "Uber"]} {"problem_id": "algo_00478", "original_id": "min-stack", "title": "最小栈", "category": "stack", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "设计一个支持 push,pop,top 操作,并能在常数时间内检索到最小元素的栈。", "solution_python": "class MinStack:\n def __init__(self):\n self.stack = []\n self.min_stack = []\n def push(self, val):\n self.stack.append(val)\n self.min_stack.append(min(val, self.min_stack[-1] if self.min_stack else val))\n def pop(self):\n self.stack.pop(); self.min_stack.pop()\n def top(self): return self.stack[-1]\n def getMin(self): return self.min_stack[-1]", "solution_java": "class MinStack {\n Stack stack = new Stack<>();\n Stack minStack = new Stack<>();\n public void push(int val) { stack.push(val); minStack.push(Math.min(val, minStack.isEmpty() ? val : minStack.peek())); }\n public void pop() { stack.pop(); minStack.pop(); }\n public int top() { return stack.peek(); }\n public int getMin() { return minStack.peek(); }\n}", "solution_cpp": "class MinStack {\n stack st, minSt;\npublic:\n void push(int val) { st.push(val); minSt.push(min(val, minSt.empty() ? val : minSt.top())); }\n void pop() { st.pop(); minSt.pop(); }\n int top() { return st.top(); }\n int getMin() { return minSt.top(); }\n};", "test_cases": ["push(-2), push(0), push(-3) -> getMin() returns -3"], "key_points": ["辅助栈记录最小值", "O(1)时间获取最小值"], "tags": ["stack", "medium", "Google", "Microsoft"]} {"problem_id": "algo_00479", "original_id": "lru-cache", "title": "LRU缓存", "category": "design", "difficulty": "hard", "companies": ["Google", "Amazon"], "description": "设计和实现一个 LRU(最近最少使用)缓存机制。", "solution_python": "class LRUCache:\n def __init__(self, capacity):\n self.capacity = capacity\n self.cache = {}\n self.order = []\n def get(self, key):\n if key not in self.cache: return -1\n self.order.remove(key); self.order.append(key)\n return self.cache[key]\n def put(self, key, value):\n if key in self.cache:\n self.order.remove(key)\n elif len(self.cache) >= self.capacity:\n del self.cache[self.order.pop(0)]\n self.cache[key] = value; self.order.append(key)", "solution_java": "class LRUCache {\n int capacity;\n LinkedHashMap cache = new LinkedHashMap<>();\n public LRUCache(int cap) { capacity = cap; }\n public int get(int key) { return cache.containsKey(key) ? cache.remove(key) : -1; }\n public void put(int key, int val) {\n if (cache.containsKey(key)) cache.remove(key);\n else if (cache.size() >= capacity) cache.remove(cache.keySet().iterator().next());\n cache.put(key, val);\n }\n}", "solution_cpp": "class LRUCache {\n int cap;\n list> dll;\n unordered_map>::iterator> cache;\npublic:\n LRUCache(int capacity) : cap(capacity) {}\n int get(int key) {\n auto it = cache.find(key);\n if (it == cache.end()) return -1;\n dll.splice(dll.end(), dll, it->second);\n return it->second->second;\n }\n void put(int key, int value) {\n auto it = cache.find(key);\n if (it != cache.end()) dll.erase(it->second);\n else if (cache.size() >= cap) { cache.erase(dll.front().first); dll.pop_front(); }\n dll.push_back({key, value});\n cache[key] = --dll.end();\n }\n};", "test_cases": ["put(1,1), put(2,2), get(1) -> 1"], "key_points": ["HashMap + 双向链表", "O(1)时间操作"], "tags": ["design", "hard", "Google", "Amazon"]} {"problem_id": "algo_00480", "original_id": "num-islands", "title": "岛屿数量", "category": "graph", "difficulty": "medium", "companies": ["Google", "Facebook"], "description": "给你一个由 '1'(陆地)和 '0'(水)组成的二维网格,请你计算网格中岛屿的数量。岛屿总是被水包围,且只能由水平或垂直方向相邻的陆地连接形成。", "solution_python": "def numIslands(grid):\n if not grid: return 0\n rows, cols = len(grid), len(grid[0])\n count = 0\n def dfs(r, c):\n if r < 0 or r >= rows or c < 0 or c >= cols or grid[r][c] != '1': return\n grid[r][c] = '0'\n dfs(r+1, c); dfs(r-1, c); dfs(r, c+1); dfs(r, c-1)\n for r in range(rows):\n for c in range(cols):\n if grid[r][c] == '1': count += 1; dfs(r, c)\n return count", "solution_java": "public int numIslands(char[][] grid) {\n if (grid.length == 0) return 0;\n int count = 0;\n for (int i = 0; i < grid.length; i++)\n for (int j = 0; j < grid[0].length; j++)\n if (grid[i][j] == '1') { count++; dfs(grid, i, j); }\n return count;\n}\nprivate void dfs(char[][] grid, int r, int c) {\n if (r < 0 || r >= grid.length || c < 0 || c >= grid[0].length || grid[r][c] != '1') return;\n grid[r][c] = '0';\n dfs(grid, r+1, c); dfs(grid, r-1, c); dfs(grid, r, c+1); dfs(grid, r, c-1);\n}", "solution_cpp": "int numIslands(vector>& grid) {\n if (grid.empty()) return 0;\n int count = 0;\n for (int i = 0; i < grid.size(); i++)\n for (int j = 0; j < grid[0].size(); j++)\n if (grid[i][j] == '1') { count++; dfs(grid, i, j); }\n return count;\n}\nvoid dfs(vector>& grid, int r, int c) {\n if (r < 0 || r >= grid.size() || c < 0 || c >= grid[0].size() || grid[r][c] != '1') return;\n grid[r][c] = '0';\n dfs(grid, r+1, c); dfs(grid, r-1, c); dfs(grid, r, c+1); dfs(grid, r, c-1);\n}", "test_cases": ["grid=[[1,1,1,1,0],[1,1,0,1,0],[1,1,0,0,0],[0,0,0,0,0]] -> 1"], "key_points": ["DFS/BFS遍历", "访问后标记为0避免重复"], "tags": ["graph", "medium", "Google", "Facebook"]} {"problem_id": "algo_00481", "original_id": "two-sum", "title": "两数之和", "category": "array", "difficulty": "easy", "companies": ["Amazon", "Google"], "description": "给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那两个整数,并返回他们的数组下标。", "solution_python": "def twoSum(nums, target):\n hashmap = {}\n for i, num in enumerate(nums):\n complement = target - num\n if complement in hashmap:\n return [hashmap[complement], i]\n hashmap[num] = i\n return []", "solution_java": "public int[] twoSum(int[] nums, int target) {\n Map map = new HashMap<>();\n for (int i = 0; i < nums.length; i++) {\n int complement = target - nums[i];\n if (map.containsKey(complement)) return new int[]{map.get(complement), i};\n map.put(nums[i], i);\n }\n return new int[]{};\n}", "solution_cpp": "vector twoSum(vector& nums, int target) {\n unordered_map m;\n for (int i = 0; i < nums.size(); i++) {\n if (m.count(target - nums[i])) return {m[target - nums[i]], i};\n m[nums[i]] = i;\n }\n return {};\n}", "test_cases": ["nums=[2,7,11,15], target=9 -> [0,1]", "nums=[3,2,4], target=6 -> [1,2]"], "key_points": ["哈希表一次遍历", "空间换时间"], "tags": ["array", "easy", "Amazon", "Google"]} {"problem_id": "algo_00482", "original_id": "merge-sorted", "title": "合并两个有序数组", "category": "array", "difficulty": "easy", "companies": ["Microsoft", "Uber"], "description": "给你两个按非递减顺序排列的整数数组 nums1 和 nums2,另有两个整数 m 和 n,分别表示 nums1 和 nums2 中的元素数目。请你合并 nums2 到 nums1 中。", "solution_python": "def merge(nums1, m, nums2, n):\n p1, p2, p = m-1, n-1, m+n-1\n while p1 >= 0 and p2 >= 0:\n if nums1[p1] > nums2[p2]: nums1[p] = nums1[p1]; p1 -= 1\n else: nums1[p] = nums2[p2]; p2 -= 1\n p -= 1\n while p2 >= 0: nums1[p] = nums2[p2]; p2 -= 1; p -= 1", "solution_java": "public void merge(int[] nums1, int m, int[] nums2, int n) {\n int p1 = m-1, p2 = n-1, p = m+n-1;\n while (p1 >= 0 && p2 >= 0) {\n nums1[p--] = nums1[p1] > nums2[p2] ? nums1[p1--] : nums2[p2--];\n }\n while (p2 >= 0) nums1[p--] = nums2[p2--];\n}", "solution_cpp": "void merge(vector& nums1, int m, vector& nums2, int n) {\n int p1 = m-1, p2 = n-1, p = m+n-1;\n while (p1 >= 0 && p2 >= 0) nums1[p--] = nums1[p1] > nums2[p2] ? nums1[p1--] : nums2[p2--];\n while (p2 >= 0) nums1[p--] = nums2[p2--];\n}", "test_cases": ["nums1=[1,2,3], m=3, nums2=[2,5,6], n=3 -> [1,2,2,3,5,6]", "nums1=[], m=0, nums2=[1], n=1 -> [1]"], "key_points": ["从后往前合并", "三指针技巧"], "tags": ["array", "easy", "Microsoft", "Uber"]} {"problem_id": "algo_00483", "original_id": "max-subarray", "title": "最大子数组和", "category": "array", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "给你一个整数数组 nums ,请你找出一个具有最大和的连续子数组,返回其最大和。", "solution_python": "def maxSubArray(nums):\n max_sum = current = nums[0]\n for num in nums[1:]:\n current = max(num, current + num)\n max_sum = max(max_sum, current)\n return max_sum", "solution_java": "public int maxSubArray(int[] nums) {\n int maxSum = nums[0], curr = nums[0];\n for (int i = 1; i < nums.length; i++) {\n curr = Math.max(nums[i], curr + nums[i]);\n maxSum = Math.max(maxSum, curr);\n }\n return maxSum;\n}", "solution_cpp": "int maxSubArray(vector& nums) {\n int maxSum = nums[0], curr = nums[0];\n for (int i = 1; i < nums.size(); i++) {\n curr = max(nums[i], curr + nums[i]);\n maxSum = max(maxSum, curr);\n }\n return maxSum;\n}", "test_cases": ["nums=[-2,1,-3,4,-1,2,1,-5,4] -> 6", "nums=[1] -> 1"], "key_points": ["Kadane算法", "动态规划基础题"], "tags": ["array", "medium", "Google", "Microsoft"]} {"problem_id": "algo_00484", "original_id": "valid-parentheses", "title": "有效的括号", "category": "string", "difficulty": "easy", "companies": ["Google", "Uber"], "description": "给定一个只包括 '(',')','{','}','[',']' 的字符串 s,判断字符串是否有效。", "solution_python": "def isValid(s):\n stack = []\n mapping = {')': '(', ']': '[', '}': '{'}\n for c in s:\n if c in mapping:\n if not stack or stack[-1] != mapping[c]: return False\n stack.pop()\n else: stack.append(c)\n return not stack", "solution_java": "public boolean isValid(String s) {\n Stack stack = new Stack<>();\n Map map = Map.of(')', '(', ']', '[', '}', '{');\n for (char c : s.toCharArray()) {\n if (map.containsValue(c)) stack.push(c);\n else if (!stack.isEmpty() && stack.pop() != map.get(c)) return false;\n }\n return stack.isEmpty();\n}", "solution_cpp": "bool isValid(string s) {\n stack st;\n unordered_map m = {{')','('},{']','['},{'}','{'}};\n for (char c : s) {\n if (m.find(c) == m.end()) st.push(c);\n else if (st.empty() || st.top() != m[c]) return false;\n else st.pop();\n }\n return st.empty();\n}", "test_cases": ["s=\"()\" -> true", "s=\"()[]{}\" -> true", "s=\"(]\" -> false"], "key_points": ["栈匹配法", "注意空栈边界"], "tags": ["string", "easy", "Google", "Uber"]} {"problem_id": "algo_00485", "original_id": "longest-palindrome", "title": "最长回文子串", "category": "string", "difficulty": "medium", "companies": ["Google", "Amazon"], "description": "给你一个字符串 s,找到 s 中最长的回文子串。", "solution_python": "def longestPalindrome(s):\n def expand(l, r):\n while l >= 0 and r < len(s) and s[l] == s[r]: l -= 1; r += 1\n return l + 1, r - 1\n start = end = 0\n for i in range(len(s)):\n l1, r1 = expand(i, i)\n l2, r2 = expand(i, i + 1)\n if r1 - l1 > end - start: start, end = l1, r1\n if r2 - l2 > end - start: start, end = l2, r2\n return s[start:end+1]", "solution_java": "public String longestPalindrome(String s) {\n int start = 0, end = 0;\n for (int i = 0; i < s.length(); i++) {\n int len1 = expand(s, i, i), len2 = expand(s, i, i+1);\n int len = Math.max(len1, len2);\n if (len > end - start) { start = i - (len-1)/2; end = i + len/2; }\n }\n return s.substring(start, end + 1);\n}\nprivate int expand(String s, int l, int r) {\n while (l >= 0 && r < s.length() && s.charAt(l) == s.charAt(r)) { l--; r++; }\n return r - l - 1;\n}", "solution_cpp": "string longestPalindrome(string s) {\n int start = 0, end = 0;\n for (int i = 0; i < s.size(); i++) {\n int len1 = expand(s, i, i), len2 = expand(s, i, i+1);\n if (max(len1, len2) > end - start) { start = i - (max(len1,len2)-1)/2; end = i + max(len1,len2)/2; }\n }\n return s.substr(start, end - start + 1);\n}", "test_cases": ["s=\"babad\" -> bab或aba", "s=\"cbbd\" -> bb"], "key_points": ["中心扩展法", "处理奇偶长度"], "tags": ["string", "medium", "Google", "Amazon"]} {"problem_id": "algo_00486", "original_id": "reverse-list", "title": "反转链表", "category": "linkedlist", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "给你单链表的头节点 head,请你反转链表,并返回反转后的链表。", "solution_python": "def reverseList(head):\n prev = None\n curr = head\n while curr:\n nxt = curr.next\n curr.next = prev\n prev = curr\n curr = nxt\n return prev", "solution_java": "public ListNode reverseList(ListNode head) {\n ListNode prev = null, curr = head;\n while (curr != null) {\n ListNode next = curr.next;\n curr.next = prev;\n prev = curr;\n curr = next;\n }\n return prev;\n}", "solution_cpp": "ListNode* reverseList(ListNode* head) {\n ListNode* prev = nullptr, *curr = head;\n while (curr) {\n ListNode* next = curr->next;\n curr->next = prev;\n prev = curr;\n curr = next;\n }\n return prev;\n}", "test_cases": ["head=[1,2,3,4,5] -> [5,4,3,2,1]", "head=[1,2] -> [2,1]"], "key_points": ["迭代法 O(1)空间", "递归法 O(n)空间"], "tags": ["linkedlist", "medium", "Google", "Microsoft"]} {"problem_id": "algo_00487", "original_id": "middle-node", "title": "链表的中间结点", "category": "linkedlist", "difficulty": "easy", "companies": ["Amazon", "Facebook"], "description": "给你单链表的头节点 head,请你找出并返回链表的中间结点。如果有两个中间结点,则返回第二个中间结点。", "solution_python": "def middleNode(head):\n slow = fast = head\n while fast and fast.next:\n slow = slow.next\n fast = fast.next.next\n return slow", "solution_java": "public ListNode middleNode(ListNode head) {\n ListNode slow = head, fast = head;\n while (fast != null && fast.next != null) {\n slow = slow.next;\n fast = fast.next.next;\n }\n return slow;\n}", "solution_cpp": "ListNode* middleNode(ListNode* head) {\n ListNode* slow = head, *fast = head;\n while (fast && fast->next) { slow = slow->next; fast = fast->next->next; }\n return slow;\n}", "test_cases": ["head=[1,2,3,4,5] -> 3", "head=[1,2,3,4,5,6] -> 4"], "key_points": ["快慢指针", "O(n)时间O(1)空间"], "tags": ["linkedlist", "easy", "Amazon", "Facebook"]} {"problem_id": "algo_00488", "original_id": "max-depth", "title": "二叉树的最大深度", "category": "tree", "difficulty": "easy", "companies": ["Microsoft", "Apple"], "description": "给定一个二叉树 root,返回其最大深度。", "solution_python": "def maxDepth(root):\n if not root: return 0\n return max(maxDepth(root.left), maxDepth(root.right)) + 1", "solution_java": "public int maxDepth(TreeNode root) {\n if (root == null) return 0;\n return Math.max(maxDepth(root.left), maxDepth(root.right)) + 1;\n}", "solution_cpp": "int maxDepth(TreeNode* root) {\n if (!root) return 0;\n return max(maxDepth(root->left), maxDepth(root->right)) + 1;\n}", "test_cases": ["root=[3,9,20,null,null,15,7] -> 3", "root=[1,null,2] -> 2"], "key_points": ["DFS递归", "层序遍历也可"], "tags": ["tree", "easy", "Microsoft", "Apple"]} {"problem_id": "algo_00489", "original_id": "inorder-traversal", "title": "二叉树的中序遍历", "category": "tree", "difficulty": "easy", "companies": ["Google", "Microsoft"], "description": "给定一个二叉树的根节点 root,返回它的中序遍历结果。", "solution_python": "def inorderTraversal(root):\n result = []\n def dfs(node):\n if node:\n dfs(node.left)\n result.append(node.val)\n dfs(node.right)\n dfs(root)\n return result", "solution_java": "public List inorderTraversal(TreeNode root) {\n List res = new ArrayList<>();\n dfs(root, res);\n return res;\n}\nprivate void dfs(TreeNode node, List res) {\n if (node == null) return;\n dfs(node.left, res); res.add(node.val); dfs(node.right, res);\n}", "solution_cpp": "vector inorderTraversal(TreeNode* root) {\n vector res;\n dfs(root, res);\n return res;\n}\nvoid dfs(TreeNode* node, vector& res) {\n if (!node) return;\n dfs(node->left, res); res.push_back(node->val); dfs(node->right, res);\n}", "test_cases": ["root=[1,null,2,3] -> [1,3,2]", "root=[] -> []"], "key_points": ["左-根-右顺序", "递归最简洁"], "tags": ["tree", "easy", "Google", "Microsoft"]} {"problem_id": "algo_00490", "original_id": "binary-search", "title": "二分查找", "category": "binarysearch", "difficulty": "easy", "companies": ["Google", "Amazon"], "description": "给定一个 n 个元素有序的(升序)整型数组 nums 和一个目标值 target,写一个函数搜索 nums 中的 target,如果目标值存在返回下标,否则返回 -1。", "solution_python": "def search(nums, target):\n left, right = 0, len(nums) - 1\n while left <= right:\n mid = (left + right) // 2\n if nums[mid] == target: return mid\n elif nums[mid] < target: left = mid + 1\n else: right = mid - 1\n return -1", "solution_java": "public int search(int[] nums, int target) {\n int left = 0, right = nums.length - 1;\n while (left <= right) {\n int mid = left + (right - left) / 2;\n if (nums[mid] == target) return mid;\n else if (nums[mid] < target) left = mid + 1;\n else right = mid - 1;\n }\n return -1;\n}", "solution_cpp": "int search(vector& nums, int target) {\n int left = 0, right = nums.size() - 1;\n while (left <= right) {\n int mid = left + (right - left) / 2;\n if (nums[mid] == target) return mid;\n else if (nums[mid] < target) left = mid + 1;\n else right = mid - 1;\n }\n return -1;\n}", "test_cases": ["nums=[-1,0,3,5,9,12], target=9 -> 4", "nums=[-1,0,3,5,9,12], target=2 -> -1"], "key_points": ["标准模板", "注意防溢出写法"], "tags": ["binarysearch", "easy", "Google", "Amazon"]} {"problem_id": "algo_00491", "original_id": "climbing-stairs", "title": "爬楼梯", "category": "dp", "difficulty": "easy", "companies": ["Amazon", "Google"], "description": "假设你正在爬楼梯。需要 n 阶你才能到达楼顶。每次你可以爬 1 或 2 个台阶。你有多少种不同的方法可以爬到楼顶?", "solution_python": "def climbStairs(n):\n if n <= 2: return n\n a, b = 1, 2\n for _ in range(3, n+1):\n a, b = b, a + b\n return b", "solution_java": "public int climbStairs(int n) {\n if (n <= 2) return n;\n int a = 1, b = 2;\n for (int i = 3; i <= n; i++) { int temp = a + b; a = b; b = temp; }\n return b;\n}", "solution_cpp": "int climbStairs(int n) {\n if (n <= 2) return n;\n int a = 1, b = 2;\n for (int i = 3; i <= n; i++) { int temp = a + b; a = b; b = temp; }\n return b;\n}", "test_cases": ["n=2 -> 2", "n=3 -> 3", "n=5 -> 8"], "key_points": ["斐波那契数列", "滚动数组优化空间"], "tags": ["dp", "easy", "Amazon", "Google"]} {"problem_id": "algo_00492", "original_id": "coin-change", "title": "零钱兑换", "category": "dp", "difficulty": "medium", "companies": ["Google", "Amazon"], "description": "给你一个整数数组 coins 表示不同面额的硬币,以及一个整数 amount 表示总金额。计算并返回可以凑成总金额所需的最少的硬币个数。如果没有任何一种硬币组合能组成总金额,返回 -1。", "solution_python": "def coinChange(coins, amount):\n dp = [float('inf')] * (amount + 1)\n dp[0] = 0\n for coin in coins:\n for x in range(coin, amount + 1):\n dp[x] = min(dp[x], dp[x - coin] + 1)\n return dp[amount] if dp[amount] != float('inf') else -1", "solution_java": "public int coinChange(int[] coins, int amount) {\n int[] dp = new int[amount + 1];\n Arrays.fill(dp, amount + 1);\n dp[0] = 0;\n for (int coin : coins) {\n for (int x = coin; x <= amount; x++) {\n dp[x] = Math.min(dp[x], dp[x - coin] + 1);\n }\n }\n return dp[amount] > amount ? -1 : dp[amount];\n}", "solution_cpp": "int coinChange(vector& coins, int amount) {\n vector dp(amount + 1, amount + 1);\n dp[0] = 0;\n for (int coin : coins) {\n for (int x = coin; x <= amount; x++) {\n dp[x] = min(dp[x], dp[x - coin] + 1);\n }\n }\n return dp[amount] > amount ? -1 : dp[amount];\n}", "test_cases": ["coins=[1,2,5], amount=11 -> 3", "coins=[2], amount=3 -> -1"], "key_points": ["完全背包问题", "dp[x] = min(dp[x-coin]+1)"], "tags": ["dp", "medium", "Google", "Amazon"]} {"problem_id": "algo_00493", "original_id": "subsets", "title": "子集", "category": "backtracking", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "给你一个整数数组 nums ,数组中的元素 互不相同 。返回该数组所有可能的子集(幂集)。", "solution_python": "def subsets(nums):\n result = []\n def backtrack(start, path):\n result.append(path[:])\n for i in range(start, len(nums)):\n path.append(nums[i])\n backtrack(i + 1, path)\n path.pop()\n backtrack(0, [])\n return result", "solution_java": "public List> subsets(int[] nums) {\n List> result = new ArrayList<>();\n backtrack(nums, 0, new ArrayList<>(), result);\n return result;\n}\nprivate void backtrack(int[] nums, int start, List path, List> result) {\n result.add(new ArrayList<>(path));\n for (int i = start; i < nums.length; i++) {\n path.add(nums[i]);\n backtrack(nums, i + 1, path, result);\n path.remove(path.size() - 1);\n }\n}", "solution_cpp": "vector> subsets(vector& nums) {\n vector> result;\n vector path;\n backtrack(nums, 0, path, result);\n return result;\n}\nvoid backtrack(vector& nums, int start, vector& path, vector>& result) {\n result.push_back(path);\n for (int i = start; i < nums.size(); i++) {\n path.push_back(nums[i]);\n backtrack(nums, i + 1, path, result);\n path.pop_back();\n }\n}", "test_cases": ["nums=[1,2,3] -> [[],[1],[2],[1,2],[3],[1,3],[2,3],[1,2,3]]"], "key_points": ["选或不选", "DFS遍历子集树"], "tags": ["backtracking", "medium", "Google", "Microsoft"]} {"problem_id": "algo_00494", "original_id": "permutations", "title": "全排列", "category": "backtracking", "difficulty": "medium", "companies": ["Google", "Facebook"], "description": "给定一个不含重复数字的数组 nums,返回其所有可能的全排列。", "solution_python": "def permute(nums):\n result = []\n def backtrack(path, used):\n if len(path) == len(nums):\n result.append(path[:])\n return\n for i in range(len(nums)):\n if used[i]: continue\n used[i] = True\n path.append(nums[i])\n backtrack(path, used)\n path.pop()\n used[i] = False\n backtrack([], [False]*len(nums))\n return result", "solution_java": "public List> permute(int[] nums) {\n List> result = new ArrayList<>();\n boolean[] used = new boolean[nums.length];\n backtrack(nums, used, new ArrayList<>(), result);\n return result;\n}\nprivate void backtrack(int[] nums, boolean[] used, List path, List> result) {\n if (path.size() == nums.length) { result.add(new ArrayList<>(path)); return; }\n for (int i = 0; i < nums.length; i++) {\n if (used[i]) continue;\n used[i] = true;\n path.add(nums[i]);\n backtrack(nums, used, path, result);\n path.remove(path.size() - 1);\n used[i] = false;\n }\n}", "solution_cpp": "vector> permute(vector& nums) {\n vector> result;\n vector used(nums.size(), false);\n vector path;\n backtrack(nums, used, path, result);\n return result;\n}\nvoid backtrack(vector& nums, vector& used, vector& path, vector>& result) {\n if (path.size() == nums.size()) { result.push_back(path); return; }\n for (int i = 0; i < nums.size(); i++) {\n if (used[i]) continue;\n used[i] = true;\n path.push_back(nums[i]);\n backtrack(nums, used, path, result);\n path.pop_back();\n used[i] = false;\n }\n}", "test_cases": ["nums=[1,2,3] -> [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]"], "key_points": ["标记已使用元素", "回溯经典模板"], "tags": ["backtracking", "medium", "Google", "Facebook"]} {"problem_id": "algo_00495", "original_id": "top-k-frequent", "title": "前K个高频元素", "category": "heap", "difficulty": "medium", "companies": ["Amazon", "Facebook"], "description": "给你一个整数数组 nums 和一个整数 k,请你返回其中出现频率前 k 高的元素。", "solution_python": "import heapq\nfrom collections import Counter\ndef topKFrequent(nums, k):\n count = Counter(nums)\n heap = []\n for num, freq in count.items():\n heapq.heappush(heap, (freq, num))\n if len(heap) > k: heapq.heappop(heap)\n return [num for freq, num in heap]", "solution_java": "public int[] topKFrequent(int[] nums, int k) {\n Map count = new HashMap<>();\n for (int n : nums) count.put(n, count.getOrDefault(n, 0) + 1);\n PriorityQueue> heap = \n new PriorityQueue<>((a, b) -> a.getValue() - b.getValue());\n for (Map.Entry e : count.entrySet()) {\n heap.offer(e);\n if (heap.size() > k) heap.poll();\n }\n int[] res = new int[k];\n for (int i = k - 1; i >= 0; i--) res[i] = heap.poll().getKey();\n return res;\n}", "solution_cpp": "vector topKFrequent(vector& nums, int k) {\n unordered_map count;\n for (int n : nums) count[n]++;\n priority_queue, vector>, greater>> heap;\n for (auto& [num, freq] : count) {\n heap.push({freq, num});\n if (heap.size() > k) heap.pop();\n }\n vector res;\n while (!heap.empty()) { res.push_back(heap.top().second); heap.pop(); }\n reverse(res.begin(), res.end());\n return res;\n}", "test_cases": ["nums=[1,1,1,2,2,3], k=2 -> [1,2]", "nums=[1], k=1 -> [1]"], "key_points": ["小顶堆保持大小k", "时间复杂度O(nlogk)"], "tags": ["heap", "medium", "Amazon", "Facebook"]} {"problem_id": "algo_00496", "original_id": "3sum", "title": "三数之和", "category": "two-pointers", "difficulty": "medium", "companies": ["Google", "Amazon"], "description": "给你一个整数数组 nums,判断是否存在三元组满足和为0,返回所有不重复的三元组。", "solution_python": "def threeSum(nums):\n nums.sort()\n result = []\n for i in range(len(nums) - 2):\n if i > 0 and nums[i] == nums[i-1]: continue\n left, right = i + 1, len(nums) - 1\n while left < right:\n total = nums[i] + nums[left] + nums[right]\n if total < 0: left += 1\n elif total > 0: right -= 1\n else:\n result.append([nums[i], nums[left], nums[right]])\n while left < right and nums[left] == nums[left+1]: left += 1\n while left < right and nums[right] == nums[right-1]: right -= 1\n left += 1; right -= 1\n return result", "solution_java": "public List> threeSum(int[] nums) {\n Arrays.sort(nums);\n List> result = new ArrayList<>();\n for (int i = 0; i < nums.length - 2; i++) {\n if (i > 0 && nums[i] == nums[i-1]) continue;\n int left = i + 1, right = nums.length - 1;\n while (left < right) {\n int total = nums[i] + nums[left] + nums[right];\n if (total < 0) left++;\n else if (total > 0) right--;\n else {\n result.add(Arrays.asList(nums[i], nums[left], nums[right]));\n while (left < right && nums[left] == nums[left+1]) left++;\n while (left < right && nums[right] == nums[right-1]) right--;\n left++; right--;\n }\n }\n }\n return result;\n}", "solution_cpp": "vector> threeSum(vector& nums) {\n sort(nums.begin(), nums.end());\n vector> result;\n for (int i = 0; i < nums.size() - 2; i++) {\n if (i > 0 && nums[i] == nums[i-1]) continue;\n int left = i + 1, right = nums.size() - 1;\n while (left < right) {\n int total = nums[i] + nums[left] + nums[right];\n if (total < 0) left++;\n else if (total > 0) right--;\n else {\n result.push_back({nums[i], nums[left], nums[right]});\n while (left < right && nums[left] == nums[left+1]) left++;\n while (left < right && nums[right] == nums[right-1]) right--;\n left++; right--;\n }\n }\n }\n return result;\n}", "test_cases": ["nums=[-1,0,1,2,-1,-4] -> [[-1,-1,2],[-1,0,1]]"], "key_points": ["排序+双指针", "去重是关键"], "tags": ["two-pointers", "medium", "Google", "Amazon"]} {"problem_id": "algo_00497", "original_id": "container-water", "title": "盛最多水的容器", "category": "two-pointers", "difficulty": "medium", "companies": ["Google", "Uber"], "description": "给定一个长度为 n 的整数数组 height,找出其中的两条线,使得它们与 x 轴共同构成的容器可以容纳最多的水。", "solution_python": "def maxArea(height):\n left, right = 0, len(height) - 1\n max_area = 0\n while left < right:\n h = min(height[left], height[right])\n max_area = max(max_area, h * (right - left))\n if height[left] < height[right]: left += 1\n else: right -= 1\n return max_area", "solution_java": "public int maxArea(int[] height) {\n int left = 0, right = height.length - 1, maxArea = 0;\n while (left < right) {\n int h = Math.min(height[left], height[right]);\n maxArea = Math.max(maxArea, h * (right - left));\n if (height[left] < height[right]) left++;\n else right--;\n }\n return maxArea;\n}", "solution_cpp": "int maxArea(vector& height) {\n int left = 0, right = height.size() - 1, maxArea = 0;\n while (left < right) {\n int h = min(height[left], height[right]);\n maxArea = max(maxArea, h * (right - left));\n if (height[left] < height[right]) left++;\n else right--;\n }\n return maxArea;\n}", "test_cases": ["height=[1,8,6,2,5,4,8,3,7] -> 49"], "key_points": ["移动短边指针", "面积=min(h1,h2)*width"], "tags": ["two-pointers", "medium", "Google", "Uber"]} {"problem_id": "algo_00498", "original_id": "min-stack", "title": "最小栈", "category": "stack", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "设计一个支持 push,pop,top 操作,并能在常数时间内检索到最小元素的栈。", "solution_python": "class MinStack:\n def __init__(self):\n self.stack = []\n self.min_stack = []\n def push(self, val):\n self.stack.append(val)\n self.min_stack.append(min(val, self.min_stack[-1] if self.min_stack else val))\n def pop(self):\n self.stack.pop(); self.min_stack.pop()\n def top(self): return self.stack[-1]\n def getMin(self): return self.min_stack[-1]", "solution_java": "class MinStack {\n Stack stack = new Stack<>();\n Stack minStack = new Stack<>();\n public void push(int val) { stack.push(val); minStack.push(Math.min(val, minStack.isEmpty() ? val : minStack.peek())); }\n public void pop() { stack.pop(); minStack.pop(); }\n public int top() { return stack.peek(); }\n public int getMin() { return minStack.peek(); }\n}", "solution_cpp": "class MinStack {\n stack st, minSt;\npublic:\n void push(int val) { st.push(val); minSt.push(min(val, minSt.empty() ? val : minSt.top())); }\n void pop() { st.pop(); minSt.pop(); }\n int top() { return st.top(); }\n int getMin() { return minSt.top(); }\n};", "test_cases": ["push(-2), push(0), push(-3) -> getMin() returns -3"], "key_points": ["辅助栈记录最小值", "O(1)时间获取最小值"], "tags": ["stack", "medium", "Google", "Microsoft"]} {"problem_id": "algo_00499", "original_id": "lru-cache", "title": "LRU缓存", "category": "design", "difficulty": "hard", "companies": ["Google", "Amazon"], "description": "设计和实现一个 LRU(最近最少使用)缓存机制。", "solution_python": "class LRUCache:\n def __init__(self, capacity):\n self.capacity = capacity\n self.cache = {}\n self.order = []\n def get(self, key):\n if key not in self.cache: return -1\n self.order.remove(key); self.order.append(key)\n return self.cache[key]\n def put(self, key, value):\n if key in self.cache:\n self.order.remove(key)\n elif len(self.cache) >= self.capacity:\n del self.cache[self.order.pop(0)]\n self.cache[key] = value; self.order.append(key)", "solution_java": "class LRUCache {\n int capacity;\n LinkedHashMap cache = new LinkedHashMap<>();\n public LRUCache(int cap) { capacity = cap; }\n public int get(int key) { return cache.containsKey(key) ? cache.remove(key) : -1; }\n public void put(int key, int val) {\n if (cache.containsKey(key)) cache.remove(key);\n else if (cache.size() >= capacity) cache.remove(cache.keySet().iterator().next());\n cache.put(key, val);\n }\n}", "solution_cpp": "class LRUCache {\n int cap;\n list> dll;\n unordered_map>::iterator> cache;\npublic:\n LRUCache(int capacity) : cap(capacity) {}\n int get(int key) {\n auto it = cache.find(key);\n if (it == cache.end()) return -1;\n dll.splice(dll.end(), dll, it->second);\n return it->second->second;\n }\n void put(int key, int value) {\n auto it = cache.find(key);\n if (it != cache.end()) dll.erase(it->second);\n else if (cache.size() >= cap) { cache.erase(dll.front().first); dll.pop_front(); }\n dll.push_back({key, value});\n cache[key] = --dll.end();\n }\n};", "test_cases": ["put(1,1), put(2,2), get(1) -> 1"], "key_points": ["HashMap + 双向链表", "O(1)时间操作"], "tags": ["design", "hard", "Google", "Amazon"]} {"problem_id": "algo_00500", "original_id": "num-islands", "title": "岛屿数量", "category": "graph", "difficulty": "medium", "companies": ["Google", "Facebook"], "description": "给你一个由 '1'(陆地)和 '0'(水)组成的二维网格,请你计算网格中岛屿的数量。岛屿总是被水包围,且只能由水平或垂直方向相邻的陆地连接形成。", "solution_python": "def numIslands(grid):\n if not grid: return 0\n rows, cols = len(grid), len(grid[0])\n count = 0\n def dfs(r, c):\n if r < 0 or r >= rows or c < 0 or c >= cols or grid[r][c] != '1': return\n grid[r][c] = '0'\n dfs(r+1, c); dfs(r-1, c); dfs(r, c+1); dfs(r, c-1)\n for r in range(rows):\n for c in range(cols):\n if grid[r][c] == '1': count += 1; dfs(r, c)\n return count", "solution_java": "public int numIslands(char[][] grid) {\n if (grid.length == 0) return 0;\n int count = 0;\n for (int i = 0; i < grid.length; i++)\n for (int j = 0; j < grid[0].length; j++)\n if (grid[i][j] == '1') { count++; dfs(grid, i, j); }\n return count;\n}\nprivate void dfs(char[][] grid, int r, int c) {\n if (r < 0 || r >= grid.length || c < 0 || c >= grid[0].length || grid[r][c] != '1') return;\n grid[r][c] = '0';\n dfs(grid, r+1, c); dfs(grid, r-1, c); dfs(grid, r, c+1); dfs(grid, r, c-1);\n}", "solution_cpp": "int numIslands(vector>& grid) {\n if (grid.empty()) return 0;\n int count = 0;\n for (int i = 0; i < grid.size(); i++)\n for (int j = 0; j < grid[0].size(); j++)\n if (grid[i][j] == '1') { count++; dfs(grid, i, j); }\n return count;\n}\nvoid dfs(vector>& grid, int r, int c) {\n if (r < 0 || r >= grid.size() || c < 0 || c >= grid[0].size() || grid[r][c] != '1') return;\n grid[r][c] = '0';\n dfs(grid, r+1, c); dfs(grid, r-1, c); dfs(grid, r, c+1); dfs(grid, r, c-1);\n}", "test_cases": ["grid=[[1,1,1,1,0],[1,1,0,1,0],[1,1,0,0,0],[0,0,0,0,0]] -> 1"], "key_points": ["DFS/BFS遍历", "访问后标记为0避免重复"], "tags": ["graph", "medium", "Google", "Facebook"]} {"problem_id": "algo_00501", "original_id": "two-sum", "title": "两数之和", "category": "array", "difficulty": "easy", "companies": ["Amazon", "Google"], "description": "给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那两个整数,并返回他们的数组下标。", "solution_python": "def twoSum(nums, target):\n hashmap = {}\n for i, num in enumerate(nums):\n complement = target - num\n if complement in hashmap:\n return [hashmap[complement], i]\n hashmap[num] = i\n return []", "solution_java": "public int[] twoSum(int[] nums, int target) {\n Map map = new HashMap<>();\n for (int i = 0; i < nums.length; i++) {\n int complement = target - nums[i];\n if (map.containsKey(complement)) return new int[]{map.get(complement), i};\n map.put(nums[i], i);\n }\n return new int[]{};\n}", "solution_cpp": "vector twoSum(vector& nums, int target) {\n unordered_map m;\n for (int i = 0; i < nums.size(); i++) {\n if (m.count(target - nums[i])) return {m[target - nums[i]], i};\n m[nums[i]] = i;\n }\n return {};\n}", "test_cases": ["nums=[2,7,11,15], target=9 -> [0,1]", "nums=[3,2,4], target=6 -> [1,2]"], "key_points": ["哈希表一次遍历", "空间换时间"], "tags": ["array", "easy", "Amazon", "Google"]} {"problem_id": "algo_00502", "original_id": "merge-sorted", "title": "合并两个有序数组", "category": "array", "difficulty": "easy", "companies": ["Microsoft", "Uber"], "description": "给你两个按非递减顺序排列的整数数组 nums1 和 nums2,另有两个整数 m 和 n,分别表示 nums1 和 nums2 中的元素数目。请你合并 nums2 到 nums1 中。", "solution_python": "def merge(nums1, m, nums2, n):\n p1, p2, p = m-1, n-1, m+n-1\n while p1 >= 0 and p2 >= 0:\n if nums1[p1] > nums2[p2]: nums1[p] = nums1[p1]; p1 -= 1\n else: nums1[p] = nums2[p2]; p2 -= 1\n p -= 1\n while p2 >= 0: nums1[p] = nums2[p2]; p2 -= 1; p -= 1", "solution_java": "public void merge(int[] nums1, int m, int[] nums2, int n) {\n int p1 = m-1, p2 = n-1, p = m+n-1;\n while (p1 >= 0 && p2 >= 0) {\n nums1[p--] = nums1[p1] > nums2[p2] ? nums1[p1--] : nums2[p2--];\n }\n while (p2 >= 0) nums1[p--] = nums2[p2--];\n}", "solution_cpp": "void merge(vector& nums1, int m, vector& nums2, int n) {\n int p1 = m-1, p2 = n-1, p = m+n-1;\n while (p1 >= 0 && p2 >= 0) nums1[p--] = nums1[p1] > nums2[p2] ? nums1[p1--] : nums2[p2--];\n while (p2 >= 0) nums1[p--] = nums2[p2--];\n}", "test_cases": ["nums1=[1,2,3], m=3, nums2=[2,5,6], n=3 -> [1,2,2,3,5,6]", "nums1=[], m=0, nums2=[1], n=1 -> [1]"], "key_points": ["从后往前合并", "三指针技巧"], "tags": ["array", "easy", "Microsoft", "Uber"]} {"problem_id": "algo_00503", "original_id": "max-subarray", "title": "最大子数组和", "category": "array", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "给你一个整数数组 nums ,请你找出一个具有最大和的连续子数组,返回其最大和。", "solution_python": "def maxSubArray(nums):\n max_sum = current = nums[0]\n for num in nums[1:]:\n current = max(num, current + num)\n max_sum = max(max_sum, current)\n return max_sum", "solution_java": "public int maxSubArray(int[] nums) {\n int maxSum = nums[0], curr = nums[0];\n for (int i = 1; i < nums.length; i++) {\n curr = Math.max(nums[i], curr + nums[i]);\n maxSum = Math.max(maxSum, curr);\n }\n return maxSum;\n}", "solution_cpp": "int maxSubArray(vector& nums) {\n int maxSum = nums[0], curr = nums[0];\n for (int i = 1; i < nums.size(); i++) {\n curr = max(nums[i], curr + nums[i]);\n maxSum = max(maxSum, curr);\n }\n return maxSum;\n}", "test_cases": ["nums=[-2,1,-3,4,-1,2,1,-5,4] -> 6", "nums=[1] -> 1"], "key_points": ["Kadane算法", "动态规划基础题"], "tags": ["array", "medium", "Google", "Microsoft"]} {"problem_id": "algo_00504", "original_id": "valid-parentheses", "title": "有效的括号", "category": "string", "difficulty": "easy", "companies": ["Google", "Uber"], "description": "给定一个只包括 '(',')','{','}','[',']' 的字符串 s,判断字符串是否有效。", "solution_python": "def isValid(s):\n stack = []\n mapping = {')': '(', ']': '[', '}': '{'}\n for c in s:\n if c in mapping:\n if not stack or stack[-1] != mapping[c]: return False\n stack.pop()\n else: stack.append(c)\n return not stack", "solution_java": "public boolean isValid(String s) {\n Stack stack = new Stack<>();\n Map map = Map.of(')', '(', ']', '[', '}', '{');\n for (char c : s.toCharArray()) {\n if (map.containsValue(c)) stack.push(c);\n else if (!stack.isEmpty() && stack.pop() != map.get(c)) return false;\n }\n return stack.isEmpty();\n}", "solution_cpp": "bool isValid(string s) {\n stack st;\n unordered_map m = {{')','('},{']','['},{'}','{'}};\n for (char c : s) {\n if (m.find(c) == m.end()) st.push(c);\n else if (st.empty() || st.top() != m[c]) return false;\n else st.pop();\n }\n return st.empty();\n}", "test_cases": ["s=\"()\" -> true", "s=\"()[]{}\" -> true", "s=\"(]\" -> false"], "key_points": ["栈匹配法", "注意空栈边界"], "tags": ["string", "easy", "Google", "Uber"]} {"problem_id": "algo_00505", "original_id": "longest-palindrome", "title": "最长回文子串", "category": "string", "difficulty": "medium", "companies": ["Google", "Amazon"], "description": "给你一个字符串 s,找到 s 中最长的回文子串。", "solution_python": "def longestPalindrome(s):\n def expand(l, r):\n while l >= 0 and r < len(s) and s[l] == s[r]: l -= 1; r += 1\n return l + 1, r - 1\n start = end = 0\n for i in range(len(s)):\n l1, r1 = expand(i, i)\n l2, r2 = expand(i, i + 1)\n if r1 - l1 > end - start: start, end = l1, r1\n if r2 - l2 > end - start: start, end = l2, r2\n return s[start:end+1]", "solution_java": "public String longestPalindrome(String s) {\n int start = 0, end = 0;\n for (int i = 0; i < s.length(); i++) {\n int len1 = expand(s, i, i), len2 = expand(s, i, i+1);\n int len = Math.max(len1, len2);\n if (len > end - start) { start = i - (len-1)/2; end = i + len/2; }\n }\n return s.substring(start, end + 1);\n}\nprivate int expand(String s, int l, int r) {\n while (l >= 0 && r < s.length() && s.charAt(l) == s.charAt(r)) { l--; r++; }\n return r - l - 1;\n}", "solution_cpp": "string longestPalindrome(string s) {\n int start = 0, end = 0;\n for (int i = 0; i < s.size(); i++) {\n int len1 = expand(s, i, i), len2 = expand(s, i, i+1);\n if (max(len1, len2) > end - start) { start = i - (max(len1,len2)-1)/2; end = i + max(len1,len2)/2; }\n }\n return s.substr(start, end - start + 1);\n}", "test_cases": ["s=\"babad\" -> bab或aba", "s=\"cbbd\" -> bb"], "key_points": ["中心扩展法", "处理奇偶长度"], "tags": ["string", "medium", "Google", "Amazon"]} {"problem_id": "algo_00506", "original_id": "reverse-list", "title": "反转链表", "category": "linkedlist", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "给你单链表的头节点 head,请你反转链表,并返回反转后的链表。", "solution_python": "def reverseList(head):\n prev = None\n curr = head\n while curr:\n nxt = curr.next\n curr.next = prev\n prev = curr\n curr = nxt\n return prev", "solution_java": "public ListNode reverseList(ListNode head) {\n ListNode prev = null, curr = head;\n while (curr != null) {\n ListNode next = curr.next;\n curr.next = prev;\n prev = curr;\n curr = next;\n }\n return prev;\n}", "solution_cpp": "ListNode* reverseList(ListNode* head) {\n ListNode* prev = nullptr, *curr = head;\n while (curr) {\n ListNode* next = curr->next;\n curr->next = prev;\n prev = curr;\n curr = next;\n }\n return prev;\n}", "test_cases": ["head=[1,2,3,4,5] -> [5,4,3,2,1]", "head=[1,2] -> [2,1]"], "key_points": ["迭代法 O(1)空间", "递归法 O(n)空间"], "tags": ["linkedlist", "medium", "Google", "Microsoft"]} {"problem_id": "algo_00507", "original_id": "middle-node", "title": "链表的中间结点", "category": "linkedlist", "difficulty": "easy", "companies": ["Amazon", "Facebook"], "description": "给你单链表的头节点 head,请你找出并返回链表的中间结点。如果有两个中间结点,则返回第二个中间结点。", "solution_python": "def middleNode(head):\n slow = fast = head\n while fast and fast.next:\n slow = slow.next\n fast = fast.next.next\n return slow", "solution_java": "public ListNode middleNode(ListNode head) {\n ListNode slow = head, fast = head;\n while (fast != null && fast.next != null) {\n slow = slow.next;\n fast = fast.next.next;\n }\n return slow;\n}", "solution_cpp": "ListNode* middleNode(ListNode* head) {\n ListNode* slow = head, *fast = head;\n while (fast && fast->next) { slow = slow->next; fast = fast->next->next; }\n return slow;\n}", "test_cases": ["head=[1,2,3,4,5] -> 3", "head=[1,2,3,4,5,6] -> 4"], "key_points": ["快慢指针", "O(n)时间O(1)空间"], "tags": ["linkedlist", "easy", "Amazon", "Facebook"]} {"problem_id": "algo_00508", "original_id": "max-depth", "title": "二叉树的最大深度", "category": "tree", "difficulty": "easy", "companies": ["Microsoft", "Apple"], "description": "给定一个二叉树 root,返回其最大深度。", "solution_python": "def maxDepth(root):\n if not root: return 0\n return max(maxDepth(root.left), maxDepth(root.right)) + 1", "solution_java": "public int maxDepth(TreeNode root) {\n if (root == null) return 0;\n return Math.max(maxDepth(root.left), maxDepth(root.right)) + 1;\n}", "solution_cpp": "int maxDepth(TreeNode* root) {\n if (!root) return 0;\n return max(maxDepth(root->left), maxDepth(root->right)) + 1;\n}", "test_cases": ["root=[3,9,20,null,null,15,7] -> 3", "root=[1,null,2] -> 2"], "key_points": ["DFS递归", "层序遍历也可"], "tags": ["tree", "easy", "Microsoft", "Apple"]} {"problem_id": "algo_00509", "original_id": "inorder-traversal", "title": "二叉树的中序遍历", "category": "tree", "difficulty": "easy", "companies": ["Google", "Microsoft"], "description": "给定一个二叉树的根节点 root,返回它的中序遍历结果。", "solution_python": "def inorderTraversal(root):\n result = []\n def dfs(node):\n if node:\n dfs(node.left)\n result.append(node.val)\n dfs(node.right)\n dfs(root)\n return result", "solution_java": "public List inorderTraversal(TreeNode root) {\n List res = new ArrayList<>();\n dfs(root, res);\n return res;\n}\nprivate void dfs(TreeNode node, List res) {\n if (node == null) return;\n dfs(node.left, res); res.add(node.val); dfs(node.right, res);\n}", "solution_cpp": "vector inorderTraversal(TreeNode* root) {\n vector res;\n dfs(root, res);\n return res;\n}\nvoid dfs(TreeNode* node, vector& res) {\n if (!node) return;\n dfs(node->left, res); res.push_back(node->val); dfs(node->right, res);\n}", "test_cases": ["root=[1,null,2,3] -> [1,3,2]", "root=[] -> []"], "key_points": ["左-根-右顺序", "递归最简洁"], "tags": ["tree", "easy", "Google", "Microsoft"]} {"problem_id": "algo_00510", "original_id": "binary-search", "title": "二分查找", "category": "binarysearch", "difficulty": "easy", "companies": ["Google", "Amazon"], "description": "给定一个 n 个元素有序的(升序)整型数组 nums 和一个目标值 target,写一个函数搜索 nums 中的 target,如果目标值存在返回下标,否则返回 -1。", "solution_python": "def search(nums, target):\n left, right = 0, len(nums) - 1\n while left <= right:\n mid = (left + right) // 2\n if nums[mid] == target: return mid\n elif nums[mid] < target: left = mid + 1\n else: right = mid - 1\n return -1", "solution_java": "public int search(int[] nums, int target) {\n int left = 0, right = nums.length - 1;\n while (left <= right) {\n int mid = left + (right - left) / 2;\n if (nums[mid] == target) return mid;\n else if (nums[mid] < target) left = mid + 1;\n else right = mid - 1;\n }\n return -1;\n}", "solution_cpp": "int search(vector& nums, int target) {\n int left = 0, right = nums.size() - 1;\n while (left <= right) {\n int mid = left + (right - left) / 2;\n if (nums[mid] == target) return mid;\n else if (nums[mid] < target) left = mid + 1;\n else right = mid - 1;\n }\n return -1;\n}", "test_cases": ["nums=[-1,0,3,5,9,12], target=9 -> 4", "nums=[-1,0,3,5,9,12], target=2 -> -1"], "key_points": ["标准模板", "注意防溢出写法"], "tags": ["binarysearch", "easy", "Google", "Amazon"]} {"problem_id": "algo_00511", "original_id": "climbing-stairs", "title": "爬楼梯", "category": "dp", "difficulty": "easy", "companies": ["Amazon", "Google"], "description": "假设你正在爬楼梯。需要 n 阶你才能到达楼顶。每次你可以爬 1 或 2 个台阶。你有多少种不同的方法可以爬到楼顶?", "solution_python": "def climbStairs(n):\n if n <= 2: return n\n a, b = 1, 2\n for _ in range(3, n+1):\n a, b = b, a + b\n return b", "solution_java": "public int climbStairs(int n) {\n if (n <= 2) return n;\n int a = 1, b = 2;\n for (int i = 3; i <= n; i++) { int temp = a + b; a = b; b = temp; }\n return b;\n}", "solution_cpp": "int climbStairs(int n) {\n if (n <= 2) return n;\n int a = 1, b = 2;\n for (int i = 3; i <= n; i++) { int temp = a + b; a = b; b = temp; }\n return b;\n}", "test_cases": ["n=2 -> 2", "n=3 -> 3", "n=5 -> 8"], "key_points": ["斐波那契数列", "滚动数组优化空间"], "tags": ["dp", "easy", "Amazon", "Google"]} {"problem_id": "algo_00512", "original_id": "coin-change", "title": "零钱兑换", "category": "dp", "difficulty": "medium", "companies": ["Google", "Amazon"], "description": "给你一个整数数组 coins 表示不同面额的硬币,以及一个整数 amount 表示总金额。计算并返回可以凑成总金额所需的最少的硬币个数。如果没有任何一种硬币组合能组成总金额,返回 -1。", "solution_python": "def coinChange(coins, amount):\n dp = [float('inf')] * (amount + 1)\n dp[0] = 0\n for coin in coins:\n for x in range(coin, amount + 1):\n dp[x] = min(dp[x], dp[x - coin] + 1)\n return dp[amount] if dp[amount] != float('inf') else -1", "solution_java": "public int coinChange(int[] coins, int amount) {\n int[] dp = new int[amount + 1];\n Arrays.fill(dp, amount + 1);\n dp[0] = 0;\n for (int coin : coins) {\n for (int x = coin; x <= amount; x++) {\n dp[x] = Math.min(dp[x], dp[x - coin] + 1);\n }\n }\n return dp[amount] > amount ? -1 : dp[amount];\n}", "solution_cpp": "int coinChange(vector& coins, int amount) {\n vector dp(amount + 1, amount + 1);\n dp[0] = 0;\n for (int coin : coins) {\n for (int x = coin; x <= amount; x++) {\n dp[x] = min(dp[x], dp[x - coin] + 1);\n }\n }\n return dp[amount] > amount ? -1 : dp[amount];\n}", "test_cases": ["coins=[1,2,5], amount=11 -> 3", "coins=[2], amount=3 -> -1"], "key_points": ["完全背包问题", "dp[x] = min(dp[x-coin]+1)"], "tags": ["dp", "medium", "Google", "Amazon"]} {"problem_id": "algo_00513", "original_id": "subsets", "title": "子集", "category": "backtracking", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "给你一个整数数组 nums ,数组中的元素 互不相同 。返回该数组所有可能的子集(幂集)。", "solution_python": "def subsets(nums):\n result = []\n def backtrack(start, path):\n result.append(path[:])\n for i in range(start, len(nums)):\n path.append(nums[i])\n backtrack(i + 1, path)\n path.pop()\n backtrack(0, [])\n return result", "solution_java": "public List> subsets(int[] nums) {\n List> result = new ArrayList<>();\n backtrack(nums, 0, new ArrayList<>(), result);\n return result;\n}\nprivate void backtrack(int[] nums, int start, List path, List> result) {\n result.add(new ArrayList<>(path));\n for (int i = start; i < nums.length; i++) {\n path.add(nums[i]);\n backtrack(nums, i + 1, path, result);\n path.remove(path.size() - 1);\n }\n}", "solution_cpp": "vector> subsets(vector& nums) {\n vector> result;\n vector path;\n backtrack(nums, 0, path, result);\n return result;\n}\nvoid backtrack(vector& nums, int start, vector& path, vector>& result) {\n result.push_back(path);\n for (int i = start; i < nums.size(); i++) {\n path.push_back(nums[i]);\n backtrack(nums, i + 1, path, result);\n path.pop_back();\n }\n}", "test_cases": ["nums=[1,2,3] -> [[],[1],[2],[1,2],[3],[1,3],[2,3],[1,2,3]]"], "key_points": ["选或不选", "DFS遍历子集树"], "tags": ["backtracking", "medium", "Google", "Microsoft"]} {"problem_id": "algo_00514", "original_id": "permutations", "title": "全排列", "category": "backtracking", "difficulty": "medium", "companies": ["Google", "Facebook"], "description": "给定一个不含重复数字的数组 nums,返回其所有可能的全排列。", "solution_python": "def permute(nums):\n result = []\n def backtrack(path, used):\n if len(path) == len(nums):\n result.append(path[:])\n return\n for i in range(len(nums)):\n if used[i]: continue\n used[i] = True\n path.append(nums[i])\n backtrack(path, used)\n path.pop()\n used[i] = False\n backtrack([], [False]*len(nums))\n return result", "solution_java": "public List> permute(int[] nums) {\n List> result = new ArrayList<>();\n boolean[] used = new boolean[nums.length];\n backtrack(nums, used, new ArrayList<>(), result);\n return result;\n}\nprivate void backtrack(int[] nums, boolean[] used, List path, List> result) {\n if (path.size() == nums.length) { result.add(new ArrayList<>(path)); return; }\n for (int i = 0; i < nums.length; i++) {\n if (used[i]) continue;\n used[i] = true;\n path.add(nums[i]);\n backtrack(nums, used, path, result);\n path.remove(path.size() - 1);\n used[i] = false;\n }\n}", "solution_cpp": "vector> permute(vector& nums) {\n vector> result;\n vector used(nums.size(), false);\n vector path;\n backtrack(nums, used, path, result);\n return result;\n}\nvoid backtrack(vector& nums, vector& used, vector& path, vector>& result) {\n if (path.size() == nums.size()) { result.push_back(path); return; }\n for (int i = 0; i < nums.size(); i++) {\n if (used[i]) continue;\n used[i] = true;\n path.push_back(nums[i]);\n backtrack(nums, used, path, result);\n path.pop_back();\n used[i] = false;\n }\n}", "test_cases": ["nums=[1,2,3] -> [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]"], "key_points": ["标记已使用元素", "回溯经典模板"], "tags": ["backtracking", "medium", "Google", "Facebook"]} {"problem_id": "algo_00515", "original_id": "top-k-frequent", "title": "前K个高频元素", "category": "heap", "difficulty": "medium", "companies": ["Amazon", "Facebook"], "description": "给你一个整数数组 nums 和一个整数 k,请你返回其中出现频率前 k 高的元素。", "solution_python": "import heapq\nfrom collections import Counter\ndef topKFrequent(nums, k):\n count = Counter(nums)\n heap = []\n for num, freq in count.items():\n heapq.heappush(heap, (freq, num))\n if len(heap) > k: heapq.heappop(heap)\n return [num for freq, num in heap]", "solution_java": "public int[] topKFrequent(int[] nums, int k) {\n Map count = new HashMap<>();\n for (int n : nums) count.put(n, count.getOrDefault(n, 0) + 1);\n PriorityQueue> heap = \n new PriorityQueue<>((a, b) -> a.getValue() - b.getValue());\n for (Map.Entry e : count.entrySet()) {\n heap.offer(e);\n if (heap.size() > k) heap.poll();\n }\n int[] res = new int[k];\n for (int i = k - 1; i >= 0; i--) res[i] = heap.poll().getKey();\n return res;\n}", "solution_cpp": "vector topKFrequent(vector& nums, int k) {\n unordered_map count;\n for (int n : nums) count[n]++;\n priority_queue, vector>, greater>> heap;\n for (auto& [num, freq] : count) {\n heap.push({freq, num});\n if (heap.size() > k) heap.pop();\n }\n vector res;\n while (!heap.empty()) { res.push_back(heap.top().second); heap.pop(); }\n reverse(res.begin(), res.end());\n return res;\n}", "test_cases": ["nums=[1,1,1,2,2,3], k=2 -> [1,2]", "nums=[1], k=1 -> [1]"], "key_points": ["小顶堆保持大小k", "时间复杂度O(nlogk)"], "tags": ["heap", "medium", "Amazon", "Facebook"]} {"problem_id": "algo_00516", "original_id": "3sum", "title": "三数之和", "category": "two-pointers", "difficulty": "medium", "companies": ["Google", "Amazon"], "description": "给你一个整数数组 nums,判断是否存在三元组满足和为0,返回所有不重复的三元组。", "solution_python": "def threeSum(nums):\n nums.sort()\n result = []\n for i in range(len(nums) - 2):\n if i > 0 and nums[i] == nums[i-1]: continue\n left, right = i + 1, len(nums) - 1\n while left < right:\n total = nums[i] + nums[left] + nums[right]\n if total < 0: left += 1\n elif total > 0: right -= 1\n else:\n result.append([nums[i], nums[left], nums[right]])\n while left < right and nums[left] == nums[left+1]: left += 1\n while left < right and nums[right] == nums[right-1]: right -= 1\n left += 1; right -= 1\n return result", "solution_java": "public List> threeSum(int[] nums) {\n Arrays.sort(nums);\n List> result = new ArrayList<>();\n for (int i = 0; i < nums.length - 2; i++) {\n if (i > 0 && nums[i] == nums[i-1]) continue;\n int left = i + 1, right = nums.length - 1;\n while (left < right) {\n int total = nums[i] + nums[left] + nums[right];\n if (total < 0) left++;\n else if (total > 0) right--;\n else {\n result.add(Arrays.asList(nums[i], nums[left], nums[right]));\n while (left < right && nums[left] == nums[left+1]) left++;\n while (left < right && nums[right] == nums[right-1]) right--;\n left++; right--;\n }\n }\n }\n return result;\n}", "solution_cpp": "vector> threeSum(vector& nums) {\n sort(nums.begin(), nums.end());\n vector> result;\n for (int i = 0; i < nums.size() - 2; i++) {\n if (i > 0 && nums[i] == nums[i-1]) continue;\n int left = i + 1, right = nums.size() - 1;\n while (left < right) {\n int total = nums[i] + nums[left] + nums[right];\n if (total < 0) left++;\n else if (total > 0) right--;\n else {\n result.push_back({nums[i], nums[left], nums[right]});\n while (left < right && nums[left] == nums[left+1]) left++;\n while (left < right && nums[right] == nums[right-1]) right--;\n left++; right--;\n }\n }\n }\n return result;\n}", "test_cases": ["nums=[-1,0,1,2,-1,-4] -> [[-1,-1,2],[-1,0,1]]"], "key_points": ["排序+双指针", "去重是关键"], "tags": ["two-pointers", "medium", "Google", "Amazon"]} {"problem_id": "algo_00517", "original_id": "container-water", "title": "盛最多水的容器", "category": "two-pointers", "difficulty": "medium", "companies": ["Google", "Uber"], "description": "给定一个长度为 n 的整数数组 height,找出其中的两条线,使得它们与 x 轴共同构成的容器可以容纳最多的水。", "solution_python": "def maxArea(height):\n left, right = 0, len(height) - 1\n max_area = 0\n while left < right:\n h = min(height[left], height[right])\n max_area = max(max_area, h * (right - left))\n if height[left] < height[right]: left += 1\n else: right -= 1\n return max_area", "solution_java": "public int maxArea(int[] height) {\n int left = 0, right = height.length - 1, maxArea = 0;\n while (left < right) {\n int h = Math.min(height[left], height[right]);\n maxArea = Math.max(maxArea, h * (right - left));\n if (height[left] < height[right]) left++;\n else right--;\n }\n return maxArea;\n}", "solution_cpp": "int maxArea(vector& height) {\n int left = 0, right = height.size() - 1, maxArea = 0;\n while (left < right) {\n int h = min(height[left], height[right]);\n maxArea = max(maxArea, h * (right - left));\n if (height[left] < height[right]) left++;\n else right--;\n }\n return maxArea;\n}", "test_cases": ["height=[1,8,6,2,5,4,8,3,7] -> 49"], "key_points": ["移动短边指针", "面积=min(h1,h2)*width"], "tags": ["two-pointers", "medium", "Google", "Uber"]} {"problem_id": "algo_00518", "original_id": "min-stack", "title": "最小栈", "category": "stack", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "设计一个支持 push,pop,top 操作,并能在常数时间内检索到最小元素的栈。", "solution_python": "class MinStack:\n def __init__(self):\n self.stack = []\n self.min_stack = []\n def push(self, val):\n self.stack.append(val)\n self.min_stack.append(min(val, self.min_stack[-1] if self.min_stack else val))\n def pop(self):\n self.stack.pop(); self.min_stack.pop()\n def top(self): return self.stack[-1]\n def getMin(self): return self.min_stack[-1]", "solution_java": "class MinStack {\n Stack stack = new Stack<>();\n Stack minStack = new Stack<>();\n public void push(int val) { stack.push(val); minStack.push(Math.min(val, minStack.isEmpty() ? val : minStack.peek())); }\n public void pop() { stack.pop(); minStack.pop(); }\n public int top() { return stack.peek(); }\n public int getMin() { return minStack.peek(); }\n}", "solution_cpp": "class MinStack {\n stack st, minSt;\npublic:\n void push(int val) { st.push(val); minSt.push(min(val, minSt.empty() ? val : minSt.top())); }\n void pop() { st.pop(); minSt.pop(); }\n int top() { return st.top(); }\n int getMin() { return minSt.top(); }\n};", "test_cases": ["push(-2), push(0), push(-3) -> getMin() returns -3"], "key_points": ["辅助栈记录最小值", "O(1)时间获取最小值"], "tags": ["stack", "medium", "Google", "Microsoft"]} {"problem_id": "algo_00519", "original_id": "lru-cache", "title": "LRU缓存", "category": "design", "difficulty": "hard", "companies": ["Google", "Amazon"], "description": "设计和实现一个 LRU(最近最少使用)缓存机制。", "solution_python": "class LRUCache:\n def __init__(self, capacity):\n self.capacity = capacity\n self.cache = {}\n self.order = []\n def get(self, key):\n if key not in self.cache: return -1\n self.order.remove(key); self.order.append(key)\n return self.cache[key]\n def put(self, key, value):\n if key in self.cache:\n self.order.remove(key)\n elif len(self.cache) >= self.capacity:\n del self.cache[self.order.pop(0)]\n self.cache[key] = value; self.order.append(key)", "solution_java": "class LRUCache {\n int capacity;\n LinkedHashMap cache = new LinkedHashMap<>();\n public LRUCache(int cap) { capacity = cap; }\n public int get(int key) { return cache.containsKey(key) ? cache.remove(key) : -1; }\n public void put(int key, int val) {\n if (cache.containsKey(key)) cache.remove(key);\n else if (cache.size() >= capacity) cache.remove(cache.keySet().iterator().next());\n cache.put(key, val);\n }\n}", "solution_cpp": "class LRUCache {\n int cap;\n list> dll;\n unordered_map>::iterator> cache;\npublic:\n LRUCache(int capacity) : cap(capacity) {}\n int get(int key) {\n auto it = cache.find(key);\n if (it == cache.end()) return -1;\n dll.splice(dll.end(), dll, it->second);\n return it->second->second;\n }\n void put(int key, int value) {\n auto it = cache.find(key);\n if (it != cache.end()) dll.erase(it->second);\n else if (cache.size() >= cap) { cache.erase(dll.front().first); dll.pop_front(); }\n dll.push_back({key, value});\n cache[key] = --dll.end();\n }\n};", "test_cases": ["put(1,1), put(2,2), get(1) -> 1"], "key_points": ["HashMap + 双向链表", "O(1)时间操作"], "tags": ["design", "hard", "Google", "Amazon"]} {"problem_id": "algo_00520", "original_id": "num-islands", "title": "岛屿数量", "category": "graph", "difficulty": "medium", "companies": ["Google", "Facebook"], "description": "给你一个由 '1'(陆地)和 '0'(水)组成的二维网格,请你计算网格中岛屿的数量。岛屿总是被水包围,且只能由水平或垂直方向相邻的陆地连接形成。", "solution_python": "def numIslands(grid):\n if not grid: return 0\n rows, cols = len(grid), len(grid[0])\n count = 0\n def dfs(r, c):\n if r < 0 or r >= rows or c < 0 or c >= cols or grid[r][c] != '1': return\n grid[r][c] = '0'\n dfs(r+1, c); dfs(r-1, c); dfs(r, c+1); dfs(r, c-1)\n for r in range(rows):\n for c in range(cols):\n if grid[r][c] == '1': count += 1; dfs(r, c)\n return count", "solution_java": "public int numIslands(char[][] grid) {\n if (grid.length == 0) return 0;\n int count = 0;\n for (int i = 0; i < grid.length; i++)\n for (int j = 0; j < grid[0].length; j++)\n if (grid[i][j] == '1') { count++; dfs(grid, i, j); }\n return count;\n}\nprivate void dfs(char[][] grid, int r, int c) {\n if (r < 0 || r >= grid.length || c < 0 || c >= grid[0].length || grid[r][c] != '1') return;\n grid[r][c] = '0';\n dfs(grid, r+1, c); dfs(grid, r-1, c); dfs(grid, r, c+1); dfs(grid, r, c-1);\n}", "solution_cpp": "int numIslands(vector>& grid) {\n if (grid.empty()) return 0;\n int count = 0;\n for (int i = 0; i < grid.size(); i++)\n for (int j = 0; j < grid[0].size(); j++)\n if (grid[i][j] == '1') { count++; dfs(grid, i, j); }\n return count;\n}\nvoid dfs(vector>& grid, int r, int c) {\n if (r < 0 || r >= grid.size() || c < 0 || c >= grid[0].size() || grid[r][c] != '1') return;\n grid[r][c] = '0';\n dfs(grid, r+1, c); dfs(grid, r-1, c); dfs(grid, r, c+1); dfs(grid, r, c-1);\n}", "test_cases": ["grid=[[1,1,1,1,0],[1,1,0,1,0],[1,1,0,0,0],[0,0,0,0,0]] -> 1"], "key_points": ["DFS/BFS遍历", "访问后标记为0避免重复"], "tags": ["graph", "medium", "Google", "Facebook"]} {"problem_id": "algo_00521", "original_id": "two-sum", "title": "两数之和", "category": "array", "difficulty": "easy", "companies": ["Amazon", "Google"], "description": "给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那两个整数,并返回他们的数组下标。", "solution_python": "def twoSum(nums, target):\n hashmap = {}\n for i, num in enumerate(nums):\n complement = target - num\n if complement in hashmap:\n return [hashmap[complement], i]\n hashmap[num] = i\n return []", "solution_java": "public int[] twoSum(int[] nums, int target) {\n Map map = new HashMap<>();\n for (int i = 0; i < nums.length; i++) {\n int complement = target - nums[i];\n if (map.containsKey(complement)) return new int[]{map.get(complement), i};\n map.put(nums[i], i);\n }\n return new int[]{};\n}", "solution_cpp": "vector twoSum(vector& nums, int target) {\n unordered_map m;\n for (int i = 0; i < nums.size(); i++) {\n if (m.count(target - nums[i])) return {m[target - nums[i]], i};\n m[nums[i]] = i;\n }\n return {};\n}", "test_cases": ["nums=[2,7,11,15], target=9 -> [0,1]", "nums=[3,2,4], target=6 -> [1,2]"], "key_points": ["哈希表一次遍历", "空间换时间"], "tags": ["array", "easy", "Amazon", "Google"]} {"problem_id": "algo_00522", "original_id": "merge-sorted", "title": "合并两个有序数组", "category": "array", "difficulty": "easy", "companies": ["Microsoft", "Uber"], "description": "给你两个按非递减顺序排列的整数数组 nums1 和 nums2,另有两个整数 m 和 n,分别表示 nums1 和 nums2 中的元素数目。请你合并 nums2 到 nums1 中。", "solution_python": "def merge(nums1, m, nums2, n):\n p1, p2, p = m-1, n-1, m+n-1\n while p1 >= 0 and p2 >= 0:\n if nums1[p1] > nums2[p2]: nums1[p] = nums1[p1]; p1 -= 1\n else: nums1[p] = nums2[p2]; p2 -= 1\n p -= 1\n while p2 >= 0: nums1[p] = nums2[p2]; p2 -= 1; p -= 1", "solution_java": "public void merge(int[] nums1, int m, int[] nums2, int n) {\n int p1 = m-1, p2 = n-1, p = m+n-1;\n while (p1 >= 0 && p2 >= 0) {\n nums1[p--] = nums1[p1] > nums2[p2] ? nums1[p1--] : nums2[p2--];\n }\n while (p2 >= 0) nums1[p--] = nums2[p2--];\n}", "solution_cpp": "void merge(vector& nums1, int m, vector& nums2, int n) {\n int p1 = m-1, p2 = n-1, p = m+n-1;\n while (p1 >= 0 && p2 >= 0) nums1[p--] = nums1[p1] > nums2[p2] ? nums1[p1--] : nums2[p2--];\n while (p2 >= 0) nums1[p--] = nums2[p2--];\n}", "test_cases": ["nums1=[1,2,3], m=3, nums2=[2,5,6], n=3 -> [1,2,2,3,5,6]", "nums1=[], m=0, nums2=[1], n=1 -> [1]"], "key_points": ["从后往前合并", "三指针技巧"], "tags": ["array", "easy", "Microsoft", "Uber"]} {"problem_id": "algo_00523", "original_id": "max-subarray", "title": "最大子数组和", "category": "array", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "给你一个整数数组 nums ,请你找出一个具有最大和的连续子数组,返回其最大和。", "solution_python": "def maxSubArray(nums):\n max_sum = current = nums[0]\n for num in nums[1:]:\n current = max(num, current + num)\n max_sum = max(max_sum, current)\n return max_sum", "solution_java": "public int maxSubArray(int[] nums) {\n int maxSum = nums[0], curr = nums[0];\n for (int i = 1; i < nums.length; i++) {\n curr = Math.max(nums[i], curr + nums[i]);\n maxSum = Math.max(maxSum, curr);\n }\n return maxSum;\n}", "solution_cpp": "int maxSubArray(vector& nums) {\n int maxSum = nums[0], curr = nums[0];\n for (int i = 1; i < nums.size(); i++) {\n curr = max(nums[i], curr + nums[i]);\n maxSum = max(maxSum, curr);\n }\n return maxSum;\n}", "test_cases": ["nums=[-2,1,-3,4,-1,2,1,-5,4] -> 6", "nums=[1] -> 1"], "key_points": ["Kadane算法", "动态规划基础题"], "tags": ["array", "medium", "Google", "Microsoft"]} {"problem_id": "algo_00524", "original_id": "valid-parentheses", "title": "有效的括号", "category": "string", "difficulty": "easy", "companies": ["Google", "Uber"], "description": "给定一个只包括 '(',')','{','}','[',']' 的字符串 s,判断字符串是否有效。", "solution_python": "def isValid(s):\n stack = []\n mapping = {')': '(', ']': '[', '}': '{'}\n for c in s:\n if c in mapping:\n if not stack or stack[-1] != mapping[c]: return False\n stack.pop()\n else: stack.append(c)\n return not stack", "solution_java": "public boolean isValid(String s) {\n Stack stack = new Stack<>();\n Map map = Map.of(')', '(', ']', '[', '}', '{');\n for (char c : s.toCharArray()) {\n if (map.containsValue(c)) stack.push(c);\n else if (!stack.isEmpty() && stack.pop() != map.get(c)) return false;\n }\n return stack.isEmpty();\n}", "solution_cpp": "bool isValid(string s) {\n stack st;\n unordered_map m = {{')','('},{']','['},{'}','{'}};\n for (char c : s) {\n if (m.find(c) == m.end()) st.push(c);\n else if (st.empty() || st.top() != m[c]) return false;\n else st.pop();\n }\n return st.empty();\n}", "test_cases": ["s=\"()\" -> true", "s=\"()[]{}\" -> true", "s=\"(]\" -> false"], "key_points": ["栈匹配法", "注意空栈边界"], "tags": ["string", "easy", "Google", "Uber"]} {"problem_id": "algo_00525", "original_id": "longest-palindrome", "title": "最长回文子串", "category": "string", "difficulty": "medium", "companies": ["Google", "Amazon"], "description": "给你一个字符串 s,找到 s 中最长的回文子串。", "solution_python": "def longestPalindrome(s):\n def expand(l, r):\n while l >= 0 and r < len(s) and s[l] == s[r]: l -= 1; r += 1\n return l + 1, r - 1\n start = end = 0\n for i in range(len(s)):\n l1, r1 = expand(i, i)\n l2, r2 = expand(i, i + 1)\n if r1 - l1 > end - start: start, end = l1, r1\n if r2 - l2 > end - start: start, end = l2, r2\n return s[start:end+1]", "solution_java": "public String longestPalindrome(String s) {\n int start = 0, end = 0;\n for (int i = 0; i < s.length(); i++) {\n int len1 = expand(s, i, i), len2 = expand(s, i, i+1);\n int len = Math.max(len1, len2);\n if (len > end - start) { start = i - (len-1)/2; end = i + len/2; }\n }\n return s.substring(start, end + 1);\n}\nprivate int expand(String s, int l, int r) {\n while (l >= 0 && r < s.length() && s.charAt(l) == s.charAt(r)) { l--; r++; }\n return r - l - 1;\n}", "solution_cpp": "string longestPalindrome(string s) {\n int start = 0, end = 0;\n for (int i = 0; i < s.size(); i++) {\n int len1 = expand(s, i, i), len2 = expand(s, i, i+1);\n if (max(len1, len2) > end - start) { start = i - (max(len1,len2)-1)/2; end = i + max(len1,len2)/2; }\n }\n return s.substr(start, end - start + 1);\n}", "test_cases": ["s=\"babad\" -> bab或aba", "s=\"cbbd\" -> bb"], "key_points": ["中心扩展法", "处理奇偶长度"], "tags": ["string", "medium", "Google", "Amazon"]} {"problem_id": "algo_00526", "original_id": "reverse-list", "title": "反转链表", "category": "linkedlist", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "给你单链表的头节点 head,请你反转链表,并返回反转后的链表。", "solution_python": "def reverseList(head):\n prev = None\n curr = head\n while curr:\n nxt = curr.next\n curr.next = prev\n prev = curr\n curr = nxt\n return prev", "solution_java": "public ListNode reverseList(ListNode head) {\n ListNode prev = null, curr = head;\n while (curr != null) {\n ListNode next = curr.next;\n curr.next = prev;\n prev = curr;\n curr = next;\n }\n return prev;\n}", "solution_cpp": "ListNode* reverseList(ListNode* head) {\n ListNode* prev = nullptr, *curr = head;\n while (curr) {\n ListNode* next = curr->next;\n curr->next = prev;\n prev = curr;\n curr = next;\n }\n return prev;\n}", "test_cases": ["head=[1,2,3,4,5] -> [5,4,3,2,1]", "head=[1,2] -> [2,1]"], "key_points": ["迭代法 O(1)空间", "递归法 O(n)空间"], "tags": ["linkedlist", "medium", "Google", "Microsoft"]} {"problem_id": "algo_00527", "original_id": "middle-node", "title": "链表的中间结点", "category": "linkedlist", "difficulty": "easy", "companies": ["Amazon", "Facebook"], "description": "给你单链表的头节点 head,请你找出并返回链表的中间结点。如果有两个中间结点,则返回第二个中间结点。", "solution_python": "def middleNode(head):\n slow = fast = head\n while fast and fast.next:\n slow = slow.next\n fast = fast.next.next\n return slow", "solution_java": "public ListNode middleNode(ListNode head) {\n ListNode slow = head, fast = head;\n while (fast != null && fast.next != null) {\n slow = slow.next;\n fast = fast.next.next;\n }\n return slow;\n}", "solution_cpp": "ListNode* middleNode(ListNode* head) {\n ListNode* slow = head, *fast = head;\n while (fast && fast->next) { slow = slow->next; fast = fast->next->next; }\n return slow;\n}", "test_cases": ["head=[1,2,3,4,5] -> 3", "head=[1,2,3,4,5,6] -> 4"], "key_points": ["快慢指针", "O(n)时间O(1)空间"], "tags": ["linkedlist", "easy", "Amazon", "Facebook"]} {"problem_id": "algo_00528", "original_id": "max-depth", "title": "二叉树的最大深度", "category": "tree", "difficulty": "easy", "companies": ["Microsoft", "Apple"], "description": "给定一个二叉树 root,返回其最大深度。", "solution_python": "def maxDepth(root):\n if not root: return 0\n return max(maxDepth(root.left), maxDepth(root.right)) + 1", "solution_java": "public int maxDepth(TreeNode root) {\n if (root == null) return 0;\n return Math.max(maxDepth(root.left), maxDepth(root.right)) + 1;\n}", "solution_cpp": "int maxDepth(TreeNode* root) {\n if (!root) return 0;\n return max(maxDepth(root->left), maxDepth(root->right)) + 1;\n}", "test_cases": ["root=[3,9,20,null,null,15,7] -> 3", "root=[1,null,2] -> 2"], "key_points": ["DFS递归", "层序遍历也可"], "tags": ["tree", "easy", "Microsoft", "Apple"]} {"problem_id": "algo_00529", "original_id": "inorder-traversal", "title": "二叉树的中序遍历", "category": "tree", "difficulty": "easy", "companies": ["Google", "Microsoft"], "description": "给定一个二叉树的根节点 root,返回它的中序遍历结果。", "solution_python": "def inorderTraversal(root):\n result = []\n def dfs(node):\n if node:\n dfs(node.left)\n result.append(node.val)\n dfs(node.right)\n dfs(root)\n return result", "solution_java": "public List inorderTraversal(TreeNode root) {\n List res = new ArrayList<>();\n dfs(root, res);\n return res;\n}\nprivate void dfs(TreeNode node, List res) {\n if (node == null) return;\n dfs(node.left, res); res.add(node.val); dfs(node.right, res);\n}", "solution_cpp": "vector inorderTraversal(TreeNode* root) {\n vector res;\n dfs(root, res);\n return res;\n}\nvoid dfs(TreeNode* node, vector& res) {\n if (!node) return;\n dfs(node->left, res); res.push_back(node->val); dfs(node->right, res);\n}", "test_cases": ["root=[1,null,2,3] -> [1,3,2]", "root=[] -> []"], "key_points": ["左-根-右顺序", "递归最简洁"], "tags": ["tree", "easy", "Google", "Microsoft"]} {"problem_id": "algo_00530", "original_id": "binary-search", "title": "二分查找", "category": "binarysearch", "difficulty": "easy", "companies": ["Google", "Amazon"], "description": "给定一个 n 个元素有序的(升序)整型数组 nums 和一个目标值 target,写一个函数搜索 nums 中的 target,如果目标值存在返回下标,否则返回 -1。", "solution_python": "def search(nums, target):\n left, right = 0, len(nums) - 1\n while left <= right:\n mid = (left + right) // 2\n if nums[mid] == target: return mid\n elif nums[mid] < target: left = mid + 1\n else: right = mid - 1\n return -1", "solution_java": "public int search(int[] nums, int target) {\n int left = 0, right = nums.length - 1;\n while (left <= right) {\n int mid = left + (right - left) / 2;\n if (nums[mid] == target) return mid;\n else if (nums[mid] < target) left = mid + 1;\n else right = mid - 1;\n }\n return -1;\n}", "solution_cpp": "int search(vector& nums, int target) {\n int left = 0, right = nums.size() - 1;\n while (left <= right) {\n int mid = left + (right - left) / 2;\n if (nums[mid] == target) return mid;\n else if (nums[mid] < target) left = mid + 1;\n else right = mid - 1;\n }\n return -1;\n}", "test_cases": ["nums=[-1,0,3,5,9,12], target=9 -> 4", "nums=[-1,0,3,5,9,12], target=2 -> -1"], "key_points": ["标准模板", "注意防溢出写法"], "tags": ["binarysearch", "easy", "Google", "Amazon"]} {"problem_id": "algo_00531", "original_id": "climbing-stairs", "title": "爬楼梯", "category": "dp", "difficulty": "easy", "companies": ["Amazon", "Google"], "description": "假设你正在爬楼梯。需要 n 阶你才能到达楼顶。每次你可以爬 1 或 2 个台阶。你有多少种不同的方法可以爬到楼顶?", "solution_python": "def climbStairs(n):\n if n <= 2: return n\n a, b = 1, 2\n for _ in range(3, n+1):\n a, b = b, a + b\n return b", "solution_java": "public int climbStairs(int n) {\n if (n <= 2) return n;\n int a = 1, b = 2;\n for (int i = 3; i <= n; i++) { int temp = a + b; a = b; b = temp; }\n return b;\n}", "solution_cpp": "int climbStairs(int n) {\n if (n <= 2) return n;\n int a = 1, b = 2;\n for (int i = 3; i <= n; i++) { int temp = a + b; a = b; b = temp; }\n return b;\n}", "test_cases": ["n=2 -> 2", "n=3 -> 3", "n=5 -> 8"], "key_points": ["斐波那契数列", "滚动数组优化空间"], "tags": ["dp", "easy", "Amazon", "Google"]} {"problem_id": "algo_00532", "original_id": "coin-change", "title": "零钱兑换", "category": "dp", "difficulty": "medium", "companies": ["Google", "Amazon"], "description": "给你一个整数数组 coins 表示不同面额的硬币,以及一个整数 amount 表示总金额。计算并返回可以凑成总金额所需的最少的硬币个数。如果没有任何一种硬币组合能组成总金额,返回 -1。", "solution_python": "def coinChange(coins, amount):\n dp = [float('inf')] * (amount + 1)\n dp[0] = 0\n for coin in coins:\n for x in range(coin, amount + 1):\n dp[x] = min(dp[x], dp[x - coin] + 1)\n return dp[amount] if dp[amount] != float('inf') else -1", "solution_java": "public int coinChange(int[] coins, int amount) {\n int[] dp = new int[amount + 1];\n Arrays.fill(dp, amount + 1);\n dp[0] = 0;\n for (int coin : coins) {\n for (int x = coin; x <= amount; x++) {\n dp[x] = Math.min(dp[x], dp[x - coin] + 1);\n }\n }\n return dp[amount] > amount ? -1 : dp[amount];\n}", "solution_cpp": "int coinChange(vector& coins, int amount) {\n vector dp(amount + 1, amount + 1);\n dp[0] = 0;\n for (int coin : coins) {\n for (int x = coin; x <= amount; x++) {\n dp[x] = min(dp[x], dp[x - coin] + 1);\n }\n }\n return dp[amount] > amount ? -1 : dp[amount];\n}", "test_cases": ["coins=[1,2,5], amount=11 -> 3", "coins=[2], amount=3 -> -1"], "key_points": ["完全背包问题", "dp[x] = min(dp[x-coin]+1)"], "tags": ["dp", "medium", "Google", "Amazon"]} {"problem_id": "algo_00533", "original_id": "subsets", "title": "子集", "category": "backtracking", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "给你一个整数数组 nums ,数组中的元素 互不相同 。返回该数组所有可能的子集(幂集)。", "solution_python": "def subsets(nums):\n result = []\n def backtrack(start, path):\n result.append(path[:])\n for i in range(start, len(nums)):\n path.append(nums[i])\n backtrack(i + 1, path)\n path.pop()\n backtrack(0, [])\n return result", "solution_java": "public List> subsets(int[] nums) {\n List> result = new ArrayList<>();\n backtrack(nums, 0, new ArrayList<>(), result);\n return result;\n}\nprivate void backtrack(int[] nums, int start, List path, List> result) {\n result.add(new ArrayList<>(path));\n for (int i = start; i < nums.length; i++) {\n path.add(nums[i]);\n backtrack(nums, i + 1, path, result);\n path.remove(path.size() - 1);\n }\n}", "solution_cpp": "vector> subsets(vector& nums) {\n vector> result;\n vector path;\n backtrack(nums, 0, path, result);\n return result;\n}\nvoid backtrack(vector& nums, int start, vector& path, vector>& result) {\n result.push_back(path);\n for (int i = start; i < nums.size(); i++) {\n path.push_back(nums[i]);\n backtrack(nums, i + 1, path, result);\n path.pop_back();\n }\n}", "test_cases": ["nums=[1,2,3] -> [[],[1],[2],[1,2],[3],[1,3],[2,3],[1,2,3]]"], "key_points": ["选或不选", "DFS遍历子集树"], "tags": ["backtracking", "medium", "Google", "Microsoft"]} {"problem_id": "algo_00534", "original_id": "permutations", "title": "全排列", "category": "backtracking", "difficulty": "medium", "companies": ["Google", "Facebook"], "description": "给定一个不含重复数字的数组 nums,返回其所有可能的全排列。", "solution_python": "def permute(nums):\n result = []\n def backtrack(path, used):\n if len(path) == len(nums):\n result.append(path[:])\n return\n for i in range(len(nums)):\n if used[i]: continue\n used[i] = True\n path.append(nums[i])\n backtrack(path, used)\n path.pop()\n used[i] = False\n backtrack([], [False]*len(nums))\n return result", "solution_java": "public List> permute(int[] nums) {\n List> result = new ArrayList<>();\n boolean[] used = new boolean[nums.length];\n backtrack(nums, used, new ArrayList<>(), result);\n return result;\n}\nprivate void backtrack(int[] nums, boolean[] used, List path, List> result) {\n if (path.size() == nums.length) { result.add(new ArrayList<>(path)); return; }\n for (int i = 0; i < nums.length; i++) {\n if (used[i]) continue;\n used[i] = true;\n path.add(nums[i]);\n backtrack(nums, used, path, result);\n path.remove(path.size() - 1);\n used[i] = false;\n }\n}", "solution_cpp": "vector> permute(vector& nums) {\n vector> result;\n vector used(nums.size(), false);\n vector path;\n backtrack(nums, used, path, result);\n return result;\n}\nvoid backtrack(vector& nums, vector& used, vector& path, vector>& result) {\n if (path.size() == nums.size()) { result.push_back(path); return; }\n for (int i = 0; i < nums.size(); i++) {\n if (used[i]) continue;\n used[i] = true;\n path.push_back(nums[i]);\n backtrack(nums, used, path, result);\n path.pop_back();\n used[i] = false;\n }\n}", "test_cases": ["nums=[1,2,3] -> [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]"], "key_points": ["标记已使用元素", "回溯经典模板"], "tags": ["backtracking", "medium", "Google", "Facebook"]} {"problem_id": "algo_00535", "original_id": "top-k-frequent", "title": "前K个高频元素", "category": "heap", "difficulty": "medium", "companies": ["Amazon", "Facebook"], "description": "给你一个整数数组 nums 和一个整数 k,请你返回其中出现频率前 k 高的元素。", "solution_python": "import heapq\nfrom collections import Counter\ndef topKFrequent(nums, k):\n count = Counter(nums)\n heap = []\n for num, freq in count.items():\n heapq.heappush(heap, (freq, num))\n if len(heap) > k: heapq.heappop(heap)\n return [num for freq, num in heap]", "solution_java": "public int[] topKFrequent(int[] nums, int k) {\n Map count = new HashMap<>();\n for (int n : nums) count.put(n, count.getOrDefault(n, 0) + 1);\n PriorityQueue> heap = \n new PriorityQueue<>((a, b) -> a.getValue() - b.getValue());\n for (Map.Entry e : count.entrySet()) {\n heap.offer(e);\n if (heap.size() > k) heap.poll();\n }\n int[] res = new int[k];\n for (int i = k - 1; i >= 0; i--) res[i] = heap.poll().getKey();\n return res;\n}", "solution_cpp": "vector topKFrequent(vector& nums, int k) {\n unordered_map count;\n for (int n : nums) count[n]++;\n priority_queue, vector>, greater>> heap;\n for (auto& [num, freq] : count) {\n heap.push({freq, num});\n if (heap.size() > k) heap.pop();\n }\n vector res;\n while (!heap.empty()) { res.push_back(heap.top().second); heap.pop(); }\n reverse(res.begin(), res.end());\n return res;\n}", "test_cases": ["nums=[1,1,1,2,2,3], k=2 -> [1,2]", "nums=[1], k=1 -> [1]"], "key_points": ["小顶堆保持大小k", "时间复杂度O(nlogk)"], "tags": ["heap", "medium", "Amazon", "Facebook"]} {"problem_id": "algo_00536", "original_id": "3sum", "title": "三数之和", "category": "two-pointers", "difficulty": "medium", "companies": ["Google", "Amazon"], "description": "给你一个整数数组 nums,判断是否存在三元组满足和为0,返回所有不重复的三元组。", "solution_python": "def threeSum(nums):\n nums.sort()\n result = []\n for i in range(len(nums) - 2):\n if i > 0 and nums[i] == nums[i-1]: continue\n left, right = i + 1, len(nums) - 1\n while left < right:\n total = nums[i] + nums[left] + nums[right]\n if total < 0: left += 1\n elif total > 0: right -= 1\n else:\n result.append([nums[i], nums[left], nums[right]])\n while left < right and nums[left] == nums[left+1]: left += 1\n while left < right and nums[right] == nums[right-1]: right -= 1\n left += 1; right -= 1\n return result", "solution_java": "public List> threeSum(int[] nums) {\n Arrays.sort(nums);\n List> result = new ArrayList<>();\n for (int i = 0; i < nums.length - 2; i++) {\n if (i > 0 && nums[i] == nums[i-1]) continue;\n int left = i + 1, right = nums.length - 1;\n while (left < right) {\n int total = nums[i] + nums[left] + nums[right];\n if (total < 0) left++;\n else if (total > 0) right--;\n else {\n result.add(Arrays.asList(nums[i], nums[left], nums[right]));\n while (left < right && nums[left] == nums[left+1]) left++;\n while (left < right && nums[right] == nums[right-1]) right--;\n left++; right--;\n }\n }\n }\n return result;\n}", "solution_cpp": "vector> threeSum(vector& nums) {\n sort(nums.begin(), nums.end());\n vector> result;\n for (int i = 0; i < nums.size() - 2; i++) {\n if (i > 0 && nums[i] == nums[i-1]) continue;\n int left = i + 1, right = nums.size() - 1;\n while (left < right) {\n int total = nums[i] + nums[left] + nums[right];\n if (total < 0) left++;\n else if (total > 0) right--;\n else {\n result.push_back({nums[i], nums[left], nums[right]});\n while (left < right && nums[left] == nums[left+1]) left++;\n while (left < right && nums[right] == nums[right-1]) right--;\n left++; right--;\n }\n }\n }\n return result;\n}", "test_cases": ["nums=[-1,0,1,2,-1,-4] -> [[-1,-1,2],[-1,0,1]]"], "key_points": ["排序+双指针", "去重是关键"], "tags": ["two-pointers", "medium", "Google", "Amazon"]} {"problem_id": "algo_00537", "original_id": "container-water", "title": "盛最多水的容器", "category": "two-pointers", "difficulty": "medium", "companies": ["Google", "Uber"], "description": "给定一个长度为 n 的整数数组 height,找出其中的两条线,使得它们与 x 轴共同构成的容器可以容纳最多的水。", "solution_python": "def maxArea(height):\n left, right = 0, len(height) - 1\n max_area = 0\n while left < right:\n h = min(height[left], height[right])\n max_area = max(max_area, h * (right - left))\n if height[left] < height[right]: left += 1\n else: right -= 1\n return max_area", "solution_java": "public int maxArea(int[] height) {\n int left = 0, right = height.length - 1, maxArea = 0;\n while (left < right) {\n int h = Math.min(height[left], height[right]);\n maxArea = Math.max(maxArea, h * (right - left));\n if (height[left] < height[right]) left++;\n else right--;\n }\n return maxArea;\n}", "solution_cpp": "int maxArea(vector& height) {\n int left = 0, right = height.size() - 1, maxArea = 0;\n while (left < right) {\n int h = min(height[left], height[right]);\n maxArea = max(maxArea, h * (right - left));\n if (height[left] < height[right]) left++;\n else right--;\n }\n return maxArea;\n}", "test_cases": ["height=[1,8,6,2,5,4,8,3,7] -> 49"], "key_points": ["移动短边指针", "面积=min(h1,h2)*width"], "tags": ["two-pointers", "medium", "Google", "Uber"]} {"problem_id": "algo_00538", "original_id": "min-stack", "title": "最小栈", "category": "stack", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "设计一个支持 push,pop,top 操作,并能在常数时间内检索到最小元素的栈。", "solution_python": "class MinStack:\n def __init__(self):\n self.stack = []\n self.min_stack = []\n def push(self, val):\n self.stack.append(val)\n self.min_stack.append(min(val, self.min_stack[-1] if self.min_stack else val))\n def pop(self):\n self.stack.pop(); self.min_stack.pop()\n def top(self): return self.stack[-1]\n def getMin(self): return self.min_stack[-1]", "solution_java": "class MinStack {\n Stack stack = new Stack<>();\n Stack minStack = new Stack<>();\n public void push(int val) { stack.push(val); minStack.push(Math.min(val, minStack.isEmpty() ? val : minStack.peek())); }\n public void pop() { stack.pop(); minStack.pop(); }\n public int top() { return stack.peek(); }\n public int getMin() { return minStack.peek(); }\n}", "solution_cpp": "class MinStack {\n stack st, minSt;\npublic:\n void push(int val) { st.push(val); minSt.push(min(val, minSt.empty() ? val : minSt.top())); }\n void pop() { st.pop(); minSt.pop(); }\n int top() { return st.top(); }\n int getMin() { return minSt.top(); }\n};", "test_cases": ["push(-2), push(0), push(-3) -> getMin() returns -3"], "key_points": ["辅助栈记录最小值", "O(1)时间获取最小值"], "tags": ["stack", "medium", "Google", "Microsoft"]} {"problem_id": "algo_00539", "original_id": "lru-cache", "title": "LRU缓存", "category": "design", "difficulty": "hard", "companies": ["Google", "Amazon"], "description": "设计和实现一个 LRU(最近最少使用)缓存机制。", "solution_python": "class LRUCache:\n def __init__(self, capacity):\n self.capacity = capacity\n self.cache = {}\n self.order = []\n def get(self, key):\n if key not in self.cache: return -1\n self.order.remove(key); self.order.append(key)\n return self.cache[key]\n def put(self, key, value):\n if key in self.cache:\n self.order.remove(key)\n elif len(self.cache) >= self.capacity:\n del self.cache[self.order.pop(0)]\n self.cache[key] = value; self.order.append(key)", "solution_java": "class LRUCache {\n int capacity;\n LinkedHashMap cache = new LinkedHashMap<>();\n public LRUCache(int cap) { capacity = cap; }\n public int get(int key) { return cache.containsKey(key) ? cache.remove(key) : -1; }\n public void put(int key, int val) {\n if (cache.containsKey(key)) cache.remove(key);\n else if (cache.size() >= capacity) cache.remove(cache.keySet().iterator().next());\n cache.put(key, val);\n }\n}", "solution_cpp": "class LRUCache {\n int cap;\n list> dll;\n unordered_map>::iterator> cache;\npublic:\n LRUCache(int capacity) : cap(capacity) {}\n int get(int key) {\n auto it = cache.find(key);\n if (it == cache.end()) return -1;\n dll.splice(dll.end(), dll, it->second);\n return it->second->second;\n }\n void put(int key, int value) {\n auto it = cache.find(key);\n if (it != cache.end()) dll.erase(it->second);\n else if (cache.size() >= cap) { cache.erase(dll.front().first); dll.pop_front(); }\n dll.push_back({key, value});\n cache[key] = --dll.end();\n }\n};", "test_cases": ["put(1,1), put(2,2), get(1) -> 1"], "key_points": ["HashMap + 双向链表", "O(1)时间操作"], "tags": ["design", "hard", "Google", "Amazon"]} {"problem_id": "algo_00540", "original_id": "num-islands", "title": "岛屿数量", "category": "graph", "difficulty": "medium", "companies": ["Google", "Facebook"], "description": "给你一个由 '1'(陆地)和 '0'(水)组成的二维网格,请你计算网格中岛屿的数量。岛屿总是被水包围,且只能由水平或垂直方向相邻的陆地连接形成。", "solution_python": "def numIslands(grid):\n if not grid: return 0\n rows, cols = len(grid), len(grid[0])\n count = 0\n def dfs(r, c):\n if r < 0 or r >= rows or c < 0 or c >= cols or grid[r][c] != '1': return\n grid[r][c] = '0'\n dfs(r+1, c); dfs(r-1, c); dfs(r, c+1); dfs(r, c-1)\n for r in range(rows):\n for c in range(cols):\n if grid[r][c] == '1': count += 1; dfs(r, c)\n return count", "solution_java": "public int numIslands(char[][] grid) {\n if (grid.length == 0) return 0;\n int count = 0;\n for (int i = 0; i < grid.length; i++)\n for (int j = 0; j < grid[0].length; j++)\n if (grid[i][j] == '1') { count++; dfs(grid, i, j); }\n return count;\n}\nprivate void dfs(char[][] grid, int r, int c) {\n if (r < 0 || r >= grid.length || c < 0 || c >= grid[0].length || grid[r][c] != '1') return;\n grid[r][c] = '0';\n dfs(grid, r+1, c); dfs(grid, r-1, c); dfs(grid, r, c+1); dfs(grid, r, c-1);\n}", "solution_cpp": "int numIslands(vector>& grid) {\n if (grid.empty()) return 0;\n int count = 0;\n for (int i = 0; i < grid.size(); i++)\n for (int j = 0; j < grid[0].size(); j++)\n if (grid[i][j] == '1') { count++; dfs(grid, i, j); }\n return count;\n}\nvoid dfs(vector>& grid, int r, int c) {\n if (r < 0 || r >= grid.size() || c < 0 || c >= grid[0].size() || grid[r][c] != '1') return;\n grid[r][c] = '0';\n dfs(grid, r+1, c); dfs(grid, r-1, c); dfs(grid, r, c+1); dfs(grid, r, c-1);\n}", "test_cases": ["grid=[[1,1,1,1,0],[1,1,0,1,0],[1,1,0,0,0],[0,0,0,0,0]] -> 1"], "key_points": ["DFS/BFS遍历", "访问后标记为0避免重复"], "tags": ["graph", "medium", "Google", "Facebook"]} {"problem_id": "algo_00541", "original_id": "two-sum", "title": "两数之和", "category": "array", "difficulty": "easy", "companies": ["Amazon", "Google"], "description": "给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那两个整数,并返回他们的数组下标。", "solution_python": "def twoSum(nums, target):\n hashmap = {}\n for i, num in enumerate(nums):\n complement = target - num\n if complement in hashmap:\n return [hashmap[complement], i]\n hashmap[num] = i\n return []", "solution_java": "public int[] twoSum(int[] nums, int target) {\n Map map = new HashMap<>();\n for (int i = 0; i < nums.length; i++) {\n int complement = target - nums[i];\n if (map.containsKey(complement)) return new int[]{map.get(complement), i};\n map.put(nums[i], i);\n }\n return new int[]{};\n}", "solution_cpp": "vector twoSum(vector& nums, int target) {\n unordered_map m;\n for (int i = 0; i < nums.size(); i++) {\n if (m.count(target - nums[i])) return {m[target - nums[i]], i};\n m[nums[i]] = i;\n }\n return {};\n}", "test_cases": ["nums=[2,7,11,15], target=9 -> [0,1]", "nums=[3,2,4], target=6 -> [1,2]"], "key_points": ["哈希表一次遍历", "空间换时间"], "tags": ["array", "easy", "Amazon", "Google"]} {"problem_id": "algo_00542", "original_id": "merge-sorted", "title": "合并两个有序数组", "category": "array", "difficulty": "easy", "companies": ["Microsoft", "Uber"], "description": "给你两个按非递减顺序排列的整数数组 nums1 和 nums2,另有两个整数 m 和 n,分别表示 nums1 和 nums2 中的元素数目。请你合并 nums2 到 nums1 中。", "solution_python": "def merge(nums1, m, nums2, n):\n p1, p2, p = m-1, n-1, m+n-1\n while p1 >= 0 and p2 >= 0:\n if nums1[p1] > nums2[p2]: nums1[p] = nums1[p1]; p1 -= 1\n else: nums1[p] = nums2[p2]; p2 -= 1\n p -= 1\n while p2 >= 0: nums1[p] = nums2[p2]; p2 -= 1; p -= 1", "solution_java": "public void merge(int[] nums1, int m, int[] nums2, int n) {\n int p1 = m-1, p2 = n-1, p = m+n-1;\n while (p1 >= 0 && p2 >= 0) {\n nums1[p--] = nums1[p1] > nums2[p2] ? nums1[p1--] : nums2[p2--];\n }\n while (p2 >= 0) nums1[p--] = nums2[p2--];\n}", "solution_cpp": "void merge(vector& nums1, int m, vector& nums2, int n) {\n int p1 = m-1, p2 = n-1, p = m+n-1;\n while (p1 >= 0 && p2 >= 0) nums1[p--] = nums1[p1] > nums2[p2] ? nums1[p1--] : nums2[p2--];\n while (p2 >= 0) nums1[p--] = nums2[p2--];\n}", "test_cases": ["nums1=[1,2,3], m=3, nums2=[2,5,6], n=3 -> [1,2,2,3,5,6]", "nums1=[], m=0, nums2=[1], n=1 -> [1]"], "key_points": ["从后往前合并", "三指针技巧"], "tags": ["array", "easy", "Microsoft", "Uber"]} {"problem_id": "algo_00543", "original_id": "max-subarray", "title": "最大子数组和", "category": "array", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "给你一个整数数组 nums ,请你找出一个具有最大和的连续子数组,返回其最大和。", "solution_python": "def maxSubArray(nums):\n max_sum = current = nums[0]\n for num in nums[1:]:\n current = max(num, current + num)\n max_sum = max(max_sum, current)\n return max_sum", "solution_java": "public int maxSubArray(int[] nums) {\n int maxSum = nums[0], curr = nums[0];\n for (int i = 1; i < nums.length; i++) {\n curr = Math.max(nums[i], curr + nums[i]);\n maxSum = Math.max(maxSum, curr);\n }\n return maxSum;\n}", "solution_cpp": "int maxSubArray(vector& nums) {\n int maxSum = nums[0], curr = nums[0];\n for (int i = 1; i < nums.size(); i++) {\n curr = max(nums[i], curr + nums[i]);\n maxSum = max(maxSum, curr);\n }\n return maxSum;\n}", "test_cases": ["nums=[-2,1,-3,4,-1,2,1,-5,4] -> 6", "nums=[1] -> 1"], "key_points": ["Kadane算法", "动态规划基础题"], "tags": ["array", "medium", "Google", "Microsoft"]} {"problem_id": "algo_00544", "original_id": "valid-parentheses", "title": "有效的括号", "category": "string", "difficulty": "easy", "companies": ["Google", "Uber"], "description": "给定一个只包括 '(',')','{','}','[',']' 的字符串 s,判断字符串是否有效。", "solution_python": "def isValid(s):\n stack = []\n mapping = {')': '(', ']': '[', '}': '{'}\n for c in s:\n if c in mapping:\n if not stack or stack[-1] != mapping[c]: return False\n stack.pop()\n else: stack.append(c)\n return not stack", "solution_java": "public boolean isValid(String s) {\n Stack stack = new Stack<>();\n Map map = Map.of(')', '(', ']', '[', '}', '{');\n for (char c : s.toCharArray()) {\n if (map.containsValue(c)) stack.push(c);\n else if (!stack.isEmpty() && stack.pop() != map.get(c)) return false;\n }\n return stack.isEmpty();\n}", "solution_cpp": "bool isValid(string s) {\n stack st;\n unordered_map m = {{')','('},{']','['},{'}','{'}};\n for (char c : s) {\n if (m.find(c) == m.end()) st.push(c);\n else if (st.empty() || st.top() != m[c]) return false;\n else st.pop();\n }\n return st.empty();\n}", "test_cases": ["s=\"()\" -> true", "s=\"()[]{}\" -> true", "s=\"(]\" -> false"], "key_points": ["栈匹配法", "注意空栈边界"], "tags": ["string", "easy", "Google", "Uber"]} {"problem_id": "algo_00545", "original_id": "longest-palindrome", "title": "最长回文子串", "category": "string", "difficulty": "medium", "companies": ["Google", "Amazon"], "description": "给你一个字符串 s,找到 s 中最长的回文子串。", "solution_python": "def longestPalindrome(s):\n def expand(l, r):\n while l >= 0 and r < len(s) and s[l] == s[r]: l -= 1; r += 1\n return l + 1, r - 1\n start = end = 0\n for i in range(len(s)):\n l1, r1 = expand(i, i)\n l2, r2 = expand(i, i + 1)\n if r1 - l1 > end - start: start, end = l1, r1\n if r2 - l2 > end - start: start, end = l2, r2\n return s[start:end+1]", "solution_java": "public String longestPalindrome(String s) {\n int start = 0, end = 0;\n for (int i = 0; i < s.length(); i++) {\n int len1 = expand(s, i, i), len2 = expand(s, i, i+1);\n int len = Math.max(len1, len2);\n if (len > end - start) { start = i - (len-1)/2; end = i + len/2; }\n }\n return s.substring(start, end + 1);\n}\nprivate int expand(String s, int l, int r) {\n while (l >= 0 && r < s.length() && s.charAt(l) == s.charAt(r)) { l--; r++; }\n return r - l - 1;\n}", "solution_cpp": "string longestPalindrome(string s) {\n int start = 0, end = 0;\n for (int i = 0; i < s.size(); i++) {\n int len1 = expand(s, i, i), len2 = expand(s, i, i+1);\n if (max(len1, len2) > end - start) { start = i - (max(len1,len2)-1)/2; end = i + max(len1,len2)/2; }\n }\n return s.substr(start, end - start + 1);\n}", "test_cases": ["s=\"babad\" -> bab或aba", "s=\"cbbd\" -> bb"], "key_points": ["中心扩展法", "处理奇偶长度"], "tags": ["string", "medium", "Google", "Amazon"]} {"problem_id": "algo_00546", "original_id": "reverse-list", "title": "反转链表", "category": "linkedlist", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "给你单链表的头节点 head,请你反转链表,并返回反转后的链表。", "solution_python": "def reverseList(head):\n prev = None\n curr = head\n while curr:\n nxt = curr.next\n curr.next = prev\n prev = curr\n curr = nxt\n return prev", "solution_java": "public ListNode reverseList(ListNode head) {\n ListNode prev = null, curr = head;\n while (curr != null) {\n ListNode next = curr.next;\n curr.next = prev;\n prev = curr;\n curr = next;\n }\n return prev;\n}", "solution_cpp": "ListNode* reverseList(ListNode* head) {\n ListNode* prev = nullptr, *curr = head;\n while (curr) {\n ListNode* next = curr->next;\n curr->next = prev;\n prev = curr;\n curr = next;\n }\n return prev;\n}", "test_cases": ["head=[1,2,3,4,5] -> [5,4,3,2,1]", "head=[1,2] -> [2,1]"], "key_points": ["迭代法 O(1)空间", "递归法 O(n)空间"], "tags": ["linkedlist", "medium", "Google", "Microsoft"]} {"problem_id": "algo_00547", "original_id": "middle-node", "title": "链表的中间结点", "category": "linkedlist", "difficulty": "easy", "companies": ["Amazon", "Facebook"], "description": "给你单链表的头节点 head,请你找出并返回链表的中间结点。如果有两个中间结点,则返回第二个中间结点。", "solution_python": "def middleNode(head):\n slow = fast = head\n while fast and fast.next:\n slow = slow.next\n fast = fast.next.next\n return slow", "solution_java": "public ListNode middleNode(ListNode head) {\n ListNode slow = head, fast = head;\n while (fast != null && fast.next != null) {\n slow = slow.next;\n fast = fast.next.next;\n }\n return slow;\n}", "solution_cpp": "ListNode* middleNode(ListNode* head) {\n ListNode* slow = head, *fast = head;\n while (fast && fast->next) { slow = slow->next; fast = fast->next->next; }\n return slow;\n}", "test_cases": ["head=[1,2,3,4,5] -> 3", "head=[1,2,3,4,5,6] -> 4"], "key_points": ["快慢指针", "O(n)时间O(1)空间"], "tags": ["linkedlist", "easy", "Amazon", "Facebook"]} {"problem_id": "algo_00548", "original_id": "max-depth", "title": "二叉树的最大深度", "category": "tree", "difficulty": "easy", "companies": ["Microsoft", "Apple"], "description": "给定一个二叉树 root,返回其最大深度。", "solution_python": "def maxDepth(root):\n if not root: return 0\n return max(maxDepth(root.left), maxDepth(root.right)) + 1", "solution_java": "public int maxDepth(TreeNode root) {\n if (root == null) return 0;\n return Math.max(maxDepth(root.left), maxDepth(root.right)) + 1;\n}", "solution_cpp": "int maxDepth(TreeNode* root) {\n if (!root) return 0;\n return max(maxDepth(root->left), maxDepth(root->right)) + 1;\n}", "test_cases": ["root=[3,9,20,null,null,15,7] -> 3", "root=[1,null,2] -> 2"], "key_points": ["DFS递归", "层序遍历也可"], "tags": ["tree", "easy", "Microsoft", "Apple"]} {"problem_id": "algo_00549", "original_id": "inorder-traversal", "title": "二叉树的中序遍历", "category": "tree", "difficulty": "easy", "companies": ["Google", "Microsoft"], "description": "给定一个二叉树的根节点 root,返回它的中序遍历结果。", "solution_python": "def inorderTraversal(root):\n result = []\n def dfs(node):\n if node:\n dfs(node.left)\n result.append(node.val)\n dfs(node.right)\n dfs(root)\n return result", "solution_java": "public List inorderTraversal(TreeNode root) {\n List res = new ArrayList<>();\n dfs(root, res);\n return res;\n}\nprivate void dfs(TreeNode node, List res) {\n if (node == null) return;\n dfs(node.left, res); res.add(node.val); dfs(node.right, res);\n}", "solution_cpp": "vector inorderTraversal(TreeNode* root) {\n vector res;\n dfs(root, res);\n return res;\n}\nvoid dfs(TreeNode* node, vector& res) {\n if (!node) return;\n dfs(node->left, res); res.push_back(node->val); dfs(node->right, res);\n}", "test_cases": ["root=[1,null,2,3] -> [1,3,2]", "root=[] -> []"], "key_points": ["左-根-右顺序", "递归最简洁"], "tags": ["tree", "easy", "Google", "Microsoft"]} {"problem_id": "algo_00550", "original_id": "binary-search", "title": "二分查找", "category": "binarysearch", "difficulty": "easy", "companies": ["Google", "Amazon"], "description": "给定一个 n 个元素有序的(升序)整型数组 nums 和一个目标值 target,写一个函数搜索 nums 中的 target,如果目标值存在返回下标,否则返回 -1。", "solution_python": "def search(nums, target):\n left, right = 0, len(nums) - 1\n while left <= right:\n mid = (left + right) // 2\n if nums[mid] == target: return mid\n elif nums[mid] < target: left = mid + 1\n else: right = mid - 1\n return -1", "solution_java": "public int search(int[] nums, int target) {\n int left = 0, right = nums.length - 1;\n while (left <= right) {\n int mid = left + (right - left) / 2;\n if (nums[mid] == target) return mid;\n else if (nums[mid] < target) left = mid + 1;\n else right = mid - 1;\n }\n return -1;\n}", "solution_cpp": "int search(vector& nums, int target) {\n int left = 0, right = nums.size() - 1;\n while (left <= right) {\n int mid = left + (right - left) / 2;\n if (nums[mid] == target) return mid;\n else if (nums[mid] < target) left = mid + 1;\n else right = mid - 1;\n }\n return -1;\n}", "test_cases": ["nums=[-1,0,3,5,9,12], target=9 -> 4", "nums=[-1,0,3,5,9,12], target=2 -> -1"], "key_points": ["标准模板", "注意防溢出写法"], "tags": ["binarysearch", "easy", "Google", "Amazon"]} {"problem_id": "algo_00551", "original_id": "climbing-stairs", "title": "爬楼梯", "category": "dp", "difficulty": "easy", "companies": ["Amazon", "Google"], "description": "假设你正在爬楼梯。需要 n 阶你才能到达楼顶。每次你可以爬 1 或 2 个台阶。你有多少种不同的方法可以爬到楼顶?", "solution_python": "def climbStairs(n):\n if n <= 2: return n\n a, b = 1, 2\n for _ in range(3, n+1):\n a, b = b, a + b\n return b", "solution_java": "public int climbStairs(int n) {\n if (n <= 2) return n;\n int a = 1, b = 2;\n for (int i = 3; i <= n; i++) { int temp = a + b; a = b; b = temp; }\n return b;\n}", "solution_cpp": "int climbStairs(int n) {\n if (n <= 2) return n;\n int a = 1, b = 2;\n for (int i = 3; i <= n; i++) { int temp = a + b; a = b; b = temp; }\n return b;\n}", "test_cases": ["n=2 -> 2", "n=3 -> 3", "n=5 -> 8"], "key_points": ["斐波那契数列", "滚动数组优化空间"], "tags": ["dp", "easy", "Amazon", "Google"]} {"problem_id": "algo_00552", "original_id": "coin-change", "title": "零钱兑换", "category": "dp", "difficulty": "medium", "companies": ["Google", "Amazon"], "description": "给你一个整数数组 coins 表示不同面额的硬币,以及一个整数 amount 表示总金额。计算并返回可以凑成总金额所需的最少的硬币个数。如果没有任何一种硬币组合能组成总金额,返回 -1。", "solution_python": "def coinChange(coins, amount):\n dp = [float('inf')] * (amount + 1)\n dp[0] = 0\n for coin in coins:\n for x in range(coin, amount + 1):\n dp[x] = min(dp[x], dp[x - coin] + 1)\n return dp[amount] if dp[amount] != float('inf') else -1", "solution_java": "public int coinChange(int[] coins, int amount) {\n int[] dp = new int[amount + 1];\n Arrays.fill(dp, amount + 1);\n dp[0] = 0;\n for (int coin : coins) {\n for (int x = coin; x <= amount; x++) {\n dp[x] = Math.min(dp[x], dp[x - coin] + 1);\n }\n }\n return dp[amount] > amount ? -1 : dp[amount];\n}", "solution_cpp": "int coinChange(vector& coins, int amount) {\n vector dp(amount + 1, amount + 1);\n dp[0] = 0;\n for (int coin : coins) {\n for (int x = coin; x <= amount; x++) {\n dp[x] = min(dp[x], dp[x - coin] + 1);\n }\n }\n return dp[amount] > amount ? -1 : dp[amount];\n}", "test_cases": ["coins=[1,2,5], amount=11 -> 3", "coins=[2], amount=3 -> -1"], "key_points": ["完全背包问题", "dp[x] = min(dp[x-coin]+1)"], "tags": ["dp", "medium", "Google", "Amazon"]} {"problem_id": "algo_00553", "original_id": "subsets", "title": "子集", "category": "backtracking", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "给你一个整数数组 nums ,数组中的元素 互不相同 。返回该数组所有可能的子集(幂集)。", "solution_python": "def subsets(nums):\n result = []\n def backtrack(start, path):\n result.append(path[:])\n for i in range(start, len(nums)):\n path.append(nums[i])\n backtrack(i + 1, path)\n path.pop()\n backtrack(0, [])\n return result", "solution_java": "public List> subsets(int[] nums) {\n List> result = new ArrayList<>();\n backtrack(nums, 0, new ArrayList<>(), result);\n return result;\n}\nprivate void backtrack(int[] nums, int start, List path, List> result) {\n result.add(new ArrayList<>(path));\n for (int i = start; i < nums.length; i++) {\n path.add(nums[i]);\n backtrack(nums, i + 1, path, result);\n path.remove(path.size() - 1);\n }\n}", "solution_cpp": "vector> subsets(vector& nums) {\n vector> result;\n vector path;\n backtrack(nums, 0, path, result);\n return result;\n}\nvoid backtrack(vector& nums, int start, vector& path, vector>& result) {\n result.push_back(path);\n for (int i = start; i < nums.size(); i++) {\n path.push_back(nums[i]);\n backtrack(nums, i + 1, path, result);\n path.pop_back();\n }\n}", "test_cases": ["nums=[1,2,3] -> [[],[1],[2],[1,2],[3],[1,3],[2,3],[1,2,3]]"], "key_points": ["选或不选", "DFS遍历子集树"], "tags": ["backtracking", "medium", "Google", "Microsoft"]} {"problem_id": "algo_00554", "original_id": "permutations", "title": "全排列", "category": "backtracking", "difficulty": "medium", "companies": ["Google", "Facebook"], "description": "给定一个不含重复数字的数组 nums,返回其所有可能的全排列。", "solution_python": "def permute(nums):\n result = []\n def backtrack(path, used):\n if len(path) == len(nums):\n result.append(path[:])\n return\n for i in range(len(nums)):\n if used[i]: continue\n used[i] = True\n path.append(nums[i])\n backtrack(path, used)\n path.pop()\n used[i] = False\n backtrack([], [False]*len(nums))\n return result", "solution_java": "public List> permute(int[] nums) {\n List> result = new ArrayList<>();\n boolean[] used = new boolean[nums.length];\n backtrack(nums, used, new ArrayList<>(), result);\n return result;\n}\nprivate void backtrack(int[] nums, boolean[] used, List path, List> result) {\n if (path.size() == nums.length) { result.add(new ArrayList<>(path)); return; }\n for (int i = 0; i < nums.length; i++) {\n if (used[i]) continue;\n used[i] = true;\n path.add(nums[i]);\n backtrack(nums, used, path, result);\n path.remove(path.size() - 1);\n used[i] = false;\n }\n}", "solution_cpp": "vector> permute(vector& nums) {\n vector> result;\n vector used(nums.size(), false);\n vector path;\n backtrack(nums, used, path, result);\n return result;\n}\nvoid backtrack(vector& nums, vector& used, vector& path, vector>& result) {\n if (path.size() == nums.size()) { result.push_back(path); return; }\n for (int i = 0; i < nums.size(); i++) {\n if (used[i]) continue;\n used[i] = true;\n path.push_back(nums[i]);\n backtrack(nums, used, path, result);\n path.pop_back();\n used[i] = false;\n }\n}", "test_cases": ["nums=[1,2,3] -> [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]"], "key_points": ["标记已使用元素", "回溯经典模板"], "tags": ["backtracking", "medium", "Google", "Facebook"]} {"problem_id": "algo_00555", "original_id": "top-k-frequent", "title": "前K个高频元素", "category": "heap", "difficulty": "medium", "companies": ["Amazon", "Facebook"], "description": "给你一个整数数组 nums 和一个整数 k,请你返回其中出现频率前 k 高的元素。", "solution_python": "import heapq\nfrom collections import Counter\ndef topKFrequent(nums, k):\n count = Counter(nums)\n heap = []\n for num, freq in count.items():\n heapq.heappush(heap, (freq, num))\n if len(heap) > k: heapq.heappop(heap)\n return [num for freq, num in heap]", "solution_java": "public int[] topKFrequent(int[] nums, int k) {\n Map count = new HashMap<>();\n for (int n : nums) count.put(n, count.getOrDefault(n, 0) + 1);\n PriorityQueue> heap = \n new PriorityQueue<>((a, b) -> a.getValue() - b.getValue());\n for (Map.Entry e : count.entrySet()) {\n heap.offer(e);\n if (heap.size() > k) heap.poll();\n }\n int[] res = new int[k];\n for (int i = k - 1; i >= 0; i--) res[i] = heap.poll().getKey();\n return res;\n}", "solution_cpp": "vector topKFrequent(vector& nums, int k) {\n unordered_map count;\n for (int n : nums) count[n]++;\n priority_queue, vector>, greater>> heap;\n for (auto& [num, freq] : count) {\n heap.push({freq, num});\n if (heap.size() > k) heap.pop();\n }\n vector res;\n while (!heap.empty()) { res.push_back(heap.top().second); heap.pop(); }\n reverse(res.begin(), res.end());\n return res;\n}", "test_cases": ["nums=[1,1,1,2,2,3], k=2 -> [1,2]", "nums=[1], k=1 -> [1]"], "key_points": ["小顶堆保持大小k", "时间复杂度O(nlogk)"], "tags": ["heap", "medium", "Amazon", "Facebook"]} {"problem_id": "algo_00556", "original_id": "3sum", "title": "三数之和", "category": "two-pointers", "difficulty": "medium", "companies": ["Google", "Amazon"], "description": "给你一个整数数组 nums,判断是否存在三元组满足和为0,返回所有不重复的三元组。", "solution_python": "def threeSum(nums):\n nums.sort()\n result = []\n for i in range(len(nums) - 2):\n if i > 0 and nums[i] == nums[i-1]: continue\n left, right = i + 1, len(nums) - 1\n while left < right:\n total = nums[i] + nums[left] + nums[right]\n if total < 0: left += 1\n elif total > 0: right -= 1\n else:\n result.append([nums[i], nums[left], nums[right]])\n while left < right and nums[left] == nums[left+1]: left += 1\n while left < right and nums[right] == nums[right-1]: right -= 1\n left += 1; right -= 1\n return result", "solution_java": "public List> threeSum(int[] nums) {\n Arrays.sort(nums);\n List> result = new ArrayList<>();\n for (int i = 0; i < nums.length - 2; i++) {\n if (i > 0 && nums[i] == nums[i-1]) continue;\n int left = i + 1, right = nums.length - 1;\n while (left < right) {\n int total = nums[i] + nums[left] + nums[right];\n if (total < 0) left++;\n else if (total > 0) right--;\n else {\n result.add(Arrays.asList(nums[i], nums[left], nums[right]));\n while (left < right && nums[left] == nums[left+1]) left++;\n while (left < right && nums[right] == nums[right-1]) right--;\n left++; right--;\n }\n }\n }\n return result;\n}", "solution_cpp": "vector> threeSum(vector& nums) {\n sort(nums.begin(), nums.end());\n vector> result;\n for (int i = 0; i < nums.size() - 2; i++) {\n if (i > 0 && nums[i] == nums[i-1]) continue;\n int left = i + 1, right = nums.size() - 1;\n while (left < right) {\n int total = nums[i] + nums[left] + nums[right];\n if (total < 0) left++;\n else if (total > 0) right--;\n else {\n result.push_back({nums[i], nums[left], nums[right]});\n while (left < right && nums[left] == nums[left+1]) left++;\n while (left < right && nums[right] == nums[right-1]) right--;\n left++; right--;\n }\n }\n }\n return result;\n}", "test_cases": ["nums=[-1,0,1,2,-1,-4] -> [[-1,-1,2],[-1,0,1]]"], "key_points": ["排序+双指针", "去重是关键"], "tags": ["two-pointers", "medium", "Google", "Amazon"]} {"problem_id": "algo_00557", "original_id": "container-water", "title": "盛最多水的容器", "category": "two-pointers", "difficulty": "medium", "companies": ["Google", "Uber"], "description": "给定一个长度为 n 的整数数组 height,找出其中的两条线,使得它们与 x 轴共同构成的容器可以容纳最多的水。", "solution_python": "def maxArea(height):\n left, right = 0, len(height) - 1\n max_area = 0\n while left < right:\n h = min(height[left], height[right])\n max_area = max(max_area, h * (right - left))\n if height[left] < height[right]: left += 1\n else: right -= 1\n return max_area", "solution_java": "public int maxArea(int[] height) {\n int left = 0, right = height.length - 1, maxArea = 0;\n while (left < right) {\n int h = Math.min(height[left], height[right]);\n maxArea = Math.max(maxArea, h * (right - left));\n if (height[left] < height[right]) left++;\n else right--;\n }\n return maxArea;\n}", "solution_cpp": "int maxArea(vector& height) {\n int left = 0, right = height.size() - 1, maxArea = 0;\n while (left < right) {\n int h = min(height[left], height[right]);\n maxArea = max(maxArea, h * (right - left));\n if (height[left] < height[right]) left++;\n else right--;\n }\n return maxArea;\n}", "test_cases": ["height=[1,8,6,2,5,4,8,3,7] -> 49"], "key_points": ["移动短边指针", "面积=min(h1,h2)*width"], "tags": ["two-pointers", "medium", "Google", "Uber"]} {"problem_id": "algo_00558", "original_id": "min-stack", "title": "最小栈", "category": "stack", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "设计一个支持 push,pop,top 操作,并能在常数时间内检索到最小元素的栈。", "solution_python": "class MinStack:\n def __init__(self):\n self.stack = []\n self.min_stack = []\n def push(self, val):\n self.stack.append(val)\n self.min_stack.append(min(val, self.min_stack[-1] if self.min_stack else val))\n def pop(self):\n self.stack.pop(); self.min_stack.pop()\n def top(self): return self.stack[-1]\n def getMin(self): return self.min_stack[-1]", "solution_java": "class MinStack {\n Stack stack = new Stack<>();\n Stack minStack = new Stack<>();\n public void push(int val) { stack.push(val); minStack.push(Math.min(val, minStack.isEmpty() ? val : minStack.peek())); }\n public void pop() { stack.pop(); minStack.pop(); }\n public int top() { return stack.peek(); }\n public int getMin() { return minStack.peek(); }\n}", "solution_cpp": "class MinStack {\n stack st, minSt;\npublic:\n void push(int val) { st.push(val); minSt.push(min(val, minSt.empty() ? val : minSt.top())); }\n void pop() { st.pop(); minSt.pop(); }\n int top() { return st.top(); }\n int getMin() { return minSt.top(); }\n};", "test_cases": ["push(-2), push(0), push(-3) -> getMin() returns -3"], "key_points": ["辅助栈记录最小值", "O(1)时间获取最小值"], "tags": ["stack", "medium", "Google", "Microsoft"]} {"problem_id": "algo_00559", "original_id": "lru-cache", "title": "LRU缓存", "category": "design", "difficulty": "hard", "companies": ["Google", "Amazon"], "description": "设计和实现一个 LRU(最近最少使用)缓存机制。", "solution_python": "class LRUCache:\n def __init__(self, capacity):\n self.capacity = capacity\n self.cache = {}\n self.order = []\n def get(self, key):\n if key not in self.cache: return -1\n self.order.remove(key); self.order.append(key)\n return self.cache[key]\n def put(self, key, value):\n if key in self.cache:\n self.order.remove(key)\n elif len(self.cache) >= self.capacity:\n del self.cache[self.order.pop(0)]\n self.cache[key] = value; self.order.append(key)", "solution_java": "class LRUCache {\n int capacity;\n LinkedHashMap cache = new LinkedHashMap<>();\n public LRUCache(int cap) { capacity = cap; }\n public int get(int key) { return cache.containsKey(key) ? cache.remove(key) : -1; }\n public void put(int key, int val) {\n if (cache.containsKey(key)) cache.remove(key);\n else if (cache.size() >= capacity) cache.remove(cache.keySet().iterator().next());\n cache.put(key, val);\n }\n}", "solution_cpp": "class LRUCache {\n int cap;\n list> dll;\n unordered_map>::iterator> cache;\npublic:\n LRUCache(int capacity) : cap(capacity) {}\n int get(int key) {\n auto it = cache.find(key);\n if (it == cache.end()) return -1;\n dll.splice(dll.end(), dll, it->second);\n return it->second->second;\n }\n void put(int key, int value) {\n auto it = cache.find(key);\n if (it != cache.end()) dll.erase(it->second);\n else if (cache.size() >= cap) { cache.erase(dll.front().first); dll.pop_front(); }\n dll.push_back({key, value});\n cache[key] = --dll.end();\n }\n};", "test_cases": ["put(1,1), put(2,2), get(1) -> 1"], "key_points": ["HashMap + 双向链表", "O(1)时间操作"], "tags": ["design", "hard", "Google", "Amazon"]} {"problem_id": "algo_00560", "original_id": "num-islands", "title": "岛屿数量", "category": "graph", "difficulty": "medium", "companies": ["Google", "Facebook"], "description": "给你一个由 '1'(陆地)和 '0'(水)组成的二维网格,请你计算网格中岛屿的数量。岛屿总是被水包围,且只能由水平或垂直方向相邻的陆地连接形成。", "solution_python": "def numIslands(grid):\n if not grid: return 0\n rows, cols = len(grid), len(grid[0])\n count = 0\n def dfs(r, c):\n if r < 0 or r >= rows or c < 0 or c >= cols or grid[r][c] != '1': return\n grid[r][c] = '0'\n dfs(r+1, c); dfs(r-1, c); dfs(r, c+1); dfs(r, c-1)\n for r in range(rows):\n for c in range(cols):\n if grid[r][c] == '1': count += 1; dfs(r, c)\n return count", "solution_java": "public int numIslands(char[][] grid) {\n if (grid.length == 0) return 0;\n int count = 0;\n for (int i = 0; i < grid.length; i++)\n for (int j = 0; j < grid[0].length; j++)\n if (grid[i][j] == '1') { count++; dfs(grid, i, j); }\n return count;\n}\nprivate void dfs(char[][] grid, int r, int c) {\n if (r < 0 || r >= grid.length || c < 0 || c >= grid[0].length || grid[r][c] != '1') return;\n grid[r][c] = '0';\n dfs(grid, r+1, c); dfs(grid, r-1, c); dfs(grid, r, c+1); dfs(grid, r, c-1);\n}", "solution_cpp": "int numIslands(vector>& grid) {\n if (grid.empty()) return 0;\n int count = 0;\n for (int i = 0; i < grid.size(); i++)\n for (int j = 0; j < grid[0].size(); j++)\n if (grid[i][j] == '1') { count++; dfs(grid, i, j); }\n return count;\n}\nvoid dfs(vector>& grid, int r, int c) {\n if (r < 0 || r >= grid.size() || c < 0 || c >= grid[0].size() || grid[r][c] != '1') return;\n grid[r][c] = '0';\n dfs(grid, r+1, c); dfs(grid, r-1, c); dfs(grid, r, c+1); dfs(grid, r, c-1);\n}", "test_cases": ["grid=[[1,1,1,1,0],[1,1,0,1,0],[1,1,0,0,0],[0,0,0,0,0]] -> 1"], "key_points": ["DFS/BFS遍历", "访问后标记为0避免重复"], "tags": ["graph", "medium", "Google", "Facebook"]} {"problem_id": "algo_00561", "original_id": "two-sum", "title": "两数之和", "category": "array", "difficulty": "easy", "companies": ["Amazon", "Google"], "description": "给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那两个整数,并返回他们的数组下标。", "solution_python": "def twoSum(nums, target):\n hashmap = {}\n for i, num in enumerate(nums):\n complement = target - num\n if complement in hashmap:\n return [hashmap[complement], i]\n hashmap[num] = i\n return []", "solution_java": "public int[] twoSum(int[] nums, int target) {\n Map map = new HashMap<>();\n for (int i = 0; i < nums.length; i++) {\n int complement = target - nums[i];\n if (map.containsKey(complement)) return new int[]{map.get(complement), i};\n map.put(nums[i], i);\n }\n return new int[]{};\n}", "solution_cpp": "vector twoSum(vector& nums, int target) {\n unordered_map m;\n for (int i = 0; i < nums.size(); i++) {\n if (m.count(target - nums[i])) return {m[target - nums[i]], i};\n m[nums[i]] = i;\n }\n return {};\n}", "test_cases": ["nums=[2,7,11,15], target=9 -> [0,1]", "nums=[3,2,4], target=6 -> [1,2]"], "key_points": ["哈希表一次遍历", "空间换时间"], "tags": ["array", "easy", "Amazon", "Google"]} {"problem_id": "algo_00562", "original_id": "merge-sorted", "title": "合并两个有序数组", "category": "array", "difficulty": "easy", "companies": ["Microsoft", "Uber"], "description": "给你两个按非递减顺序排列的整数数组 nums1 和 nums2,另有两个整数 m 和 n,分别表示 nums1 和 nums2 中的元素数目。请你合并 nums2 到 nums1 中。", "solution_python": "def merge(nums1, m, nums2, n):\n p1, p2, p = m-1, n-1, m+n-1\n while p1 >= 0 and p2 >= 0:\n if nums1[p1] > nums2[p2]: nums1[p] = nums1[p1]; p1 -= 1\n else: nums1[p] = nums2[p2]; p2 -= 1\n p -= 1\n while p2 >= 0: nums1[p] = nums2[p2]; p2 -= 1; p -= 1", "solution_java": "public void merge(int[] nums1, int m, int[] nums2, int n) {\n int p1 = m-1, p2 = n-1, p = m+n-1;\n while (p1 >= 0 && p2 >= 0) {\n nums1[p--] = nums1[p1] > nums2[p2] ? nums1[p1--] : nums2[p2--];\n }\n while (p2 >= 0) nums1[p--] = nums2[p2--];\n}", "solution_cpp": "void merge(vector& nums1, int m, vector& nums2, int n) {\n int p1 = m-1, p2 = n-1, p = m+n-1;\n while (p1 >= 0 && p2 >= 0) nums1[p--] = nums1[p1] > nums2[p2] ? nums1[p1--] : nums2[p2--];\n while (p2 >= 0) nums1[p--] = nums2[p2--];\n}", "test_cases": ["nums1=[1,2,3], m=3, nums2=[2,5,6], n=3 -> [1,2,2,3,5,6]", "nums1=[], m=0, nums2=[1], n=1 -> [1]"], "key_points": ["从后往前合并", "三指针技巧"], "tags": ["array", "easy", "Microsoft", "Uber"]} {"problem_id": "algo_00563", "original_id": "max-subarray", "title": "最大子数组和", "category": "array", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "给你一个整数数组 nums ,请你找出一个具有最大和的连续子数组,返回其最大和。", "solution_python": "def maxSubArray(nums):\n max_sum = current = nums[0]\n for num in nums[1:]:\n current = max(num, current + num)\n max_sum = max(max_sum, current)\n return max_sum", "solution_java": "public int maxSubArray(int[] nums) {\n int maxSum = nums[0], curr = nums[0];\n for (int i = 1; i < nums.length; i++) {\n curr = Math.max(nums[i], curr + nums[i]);\n maxSum = Math.max(maxSum, curr);\n }\n return maxSum;\n}", "solution_cpp": "int maxSubArray(vector& nums) {\n int maxSum = nums[0], curr = nums[0];\n for (int i = 1; i < nums.size(); i++) {\n curr = max(nums[i], curr + nums[i]);\n maxSum = max(maxSum, curr);\n }\n return maxSum;\n}", "test_cases": ["nums=[-2,1,-3,4,-1,2,1,-5,4] -> 6", "nums=[1] -> 1"], "key_points": ["Kadane算法", "动态规划基础题"], "tags": ["array", "medium", "Google", "Microsoft"]} {"problem_id": "algo_00564", "original_id": "valid-parentheses", "title": "有效的括号", "category": "string", "difficulty": "easy", "companies": ["Google", "Uber"], "description": "给定一个只包括 '(',')','{','}','[',']' 的字符串 s,判断字符串是否有效。", "solution_python": "def isValid(s):\n stack = []\n mapping = {')': '(', ']': '[', '}': '{'}\n for c in s:\n if c in mapping:\n if not stack or stack[-1] != mapping[c]: return False\n stack.pop()\n else: stack.append(c)\n return not stack", "solution_java": "public boolean isValid(String s) {\n Stack stack = new Stack<>();\n Map map = Map.of(')', '(', ']', '[', '}', '{');\n for (char c : s.toCharArray()) {\n if (map.containsValue(c)) stack.push(c);\n else if (!stack.isEmpty() && stack.pop() != map.get(c)) return false;\n }\n return stack.isEmpty();\n}", "solution_cpp": "bool isValid(string s) {\n stack st;\n unordered_map m = {{')','('},{']','['},{'}','{'}};\n for (char c : s) {\n if (m.find(c) == m.end()) st.push(c);\n else if (st.empty() || st.top() != m[c]) return false;\n else st.pop();\n }\n return st.empty();\n}", "test_cases": ["s=\"()\" -> true", "s=\"()[]{}\" -> true", "s=\"(]\" -> false"], "key_points": ["栈匹配法", "注意空栈边界"], "tags": ["string", "easy", "Google", "Uber"]} {"problem_id": "algo_00565", "original_id": "longest-palindrome", "title": "最长回文子串", "category": "string", "difficulty": "medium", "companies": ["Google", "Amazon"], "description": "给你一个字符串 s,找到 s 中最长的回文子串。", "solution_python": "def longestPalindrome(s):\n def expand(l, r):\n while l >= 0 and r < len(s) and s[l] == s[r]: l -= 1; r += 1\n return l + 1, r - 1\n start = end = 0\n for i in range(len(s)):\n l1, r1 = expand(i, i)\n l2, r2 = expand(i, i + 1)\n if r1 - l1 > end - start: start, end = l1, r1\n if r2 - l2 > end - start: start, end = l2, r2\n return s[start:end+1]", "solution_java": "public String longestPalindrome(String s) {\n int start = 0, end = 0;\n for (int i = 0; i < s.length(); i++) {\n int len1 = expand(s, i, i), len2 = expand(s, i, i+1);\n int len = Math.max(len1, len2);\n if (len > end - start) { start = i - (len-1)/2; end = i + len/2; }\n }\n return s.substring(start, end + 1);\n}\nprivate int expand(String s, int l, int r) {\n while (l >= 0 && r < s.length() && s.charAt(l) == s.charAt(r)) { l--; r++; }\n return r - l - 1;\n}", "solution_cpp": "string longestPalindrome(string s) {\n int start = 0, end = 0;\n for (int i = 0; i < s.size(); i++) {\n int len1 = expand(s, i, i), len2 = expand(s, i, i+1);\n if (max(len1, len2) > end - start) { start = i - (max(len1,len2)-1)/2; end = i + max(len1,len2)/2; }\n }\n return s.substr(start, end - start + 1);\n}", "test_cases": ["s=\"babad\" -> bab或aba", "s=\"cbbd\" -> bb"], "key_points": ["中心扩展法", "处理奇偶长度"], "tags": ["string", "medium", "Google", "Amazon"]} {"problem_id": "algo_00566", "original_id": "reverse-list", "title": "反转链表", "category": "linkedlist", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "给你单链表的头节点 head,请你反转链表,并返回反转后的链表。", "solution_python": "def reverseList(head):\n prev = None\n curr = head\n while curr:\n nxt = curr.next\n curr.next = prev\n prev = curr\n curr = nxt\n return prev", "solution_java": "public ListNode reverseList(ListNode head) {\n ListNode prev = null, curr = head;\n while (curr != null) {\n ListNode next = curr.next;\n curr.next = prev;\n prev = curr;\n curr = next;\n }\n return prev;\n}", "solution_cpp": "ListNode* reverseList(ListNode* head) {\n ListNode* prev = nullptr, *curr = head;\n while (curr) {\n ListNode* next = curr->next;\n curr->next = prev;\n prev = curr;\n curr = next;\n }\n return prev;\n}", "test_cases": ["head=[1,2,3,4,5] -> [5,4,3,2,1]", "head=[1,2] -> [2,1]"], "key_points": ["迭代法 O(1)空间", "递归法 O(n)空间"], "tags": ["linkedlist", "medium", "Google", "Microsoft"]} {"problem_id": "algo_00567", "original_id": "middle-node", "title": "链表的中间结点", "category": "linkedlist", "difficulty": "easy", "companies": ["Amazon", "Facebook"], "description": "给你单链表的头节点 head,请你找出并返回链表的中间结点。如果有两个中间结点,则返回第二个中间结点。", "solution_python": "def middleNode(head):\n slow = fast = head\n while fast and fast.next:\n slow = slow.next\n fast = fast.next.next\n return slow", "solution_java": "public ListNode middleNode(ListNode head) {\n ListNode slow = head, fast = head;\n while (fast != null && fast.next != null) {\n slow = slow.next;\n fast = fast.next.next;\n }\n return slow;\n}", "solution_cpp": "ListNode* middleNode(ListNode* head) {\n ListNode* slow = head, *fast = head;\n while (fast && fast->next) { slow = slow->next; fast = fast->next->next; }\n return slow;\n}", "test_cases": ["head=[1,2,3,4,5] -> 3", "head=[1,2,3,4,5,6] -> 4"], "key_points": ["快慢指针", "O(n)时间O(1)空间"], "tags": ["linkedlist", "easy", "Amazon", "Facebook"]} {"problem_id": "algo_00568", "original_id": "max-depth", "title": "二叉树的最大深度", "category": "tree", "difficulty": "easy", "companies": ["Microsoft", "Apple"], "description": "给定一个二叉树 root,返回其最大深度。", "solution_python": "def maxDepth(root):\n if not root: return 0\n return max(maxDepth(root.left), maxDepth(root.right)) + 1", "solution_java": "public int maxDepth(TreeNode root) {\n if (root == null) return 0;\n return Math.max(maxDepth(root.left), maxDepth(root.right)) + 1;\n}", "solution_cpp": "int maxDepth(TreeNode* root) {\n if (!root) return 0;\n return max(maxDepth(root->left), maxDepth(root->right)) + 1;\n}", "test_cases": ["root=[3,9,20,null,null,15,7] -> 3", "root=[1,null,2] -> 2"], "key_points": ["DFS递归", "层序遍历也可"], "tags": ["tree", "easy", "Microsoft", "Apple"]} {"problem_id": "algo_00569", "original_id": "inorder-traversal", "title": "二叉树的中序遍历", "category": "tree", "difficulty": "easy", "companies": ["Google", "Microsoft"], "description": "给定一个二叉树的根节点 root,返回它的中序遍历结果。", "solution_python": "def inorderTraversal(root):\n result = []\n def dfs(node):\n if node:\n dfs(node.left)\n result.append(node.val)\n dfs(node.right)\n dfs(root)\n return result", "solution_java": "public List inorderTraversal(TreeNode root) {\n List res = new ArrayList<>();\n dfs(root, res);\n return res;\n}\nprivate void dfs(TreeNode node, List res) {\n if (node == null) return;\n dfs(node.left, res); res.add(node.val); dfs(node.right, res);\n}", "solution_cpp": "vector inorderTraversal(TreeNode* root) {\n vector res;\n dfs(root, res);\n return res;\n}\nvoid dfs(TreeNode* node, vector& res) {\n if (!node) return;\n dfs(node->left, res); res.push_back(node->val); dfs(node->right, res);\n}", "test_cases": ["root=[1,null,2,3] -> [1,3,2]", "root=[] -> []"], "key_points": ["左-根-右顺序", "递归最简洁"], "tags": ["tree", "easy", "Google", "Microsoft"]} {"problem_id": "algo_00570", "original_id": "binary-search", "title": "二分查找", "category": "binarysearch", "difficulty": "easy", "companies": ["Google", "Amazon"], "description": "给定一个 n 个元素有序的(升序)整型数组 nums 和一个目标值 target,写一个函数搜索 nums 中的 target,如果目标值存在返回下标,否则返回 -1。", "solution_python": "def search(nums, target):\n left, right = 0, len(nums) - 1\n while left <= right:\n mid = (left + right) // 2\n if nums[mid] == target: return mid\n elif nums[mid] < target: left = mid + 1\n else: right = mid - 1\n return -1", "solution_java": "public int search(int[] nums, int target) {\n int left = 0, right = nums.length - 1;\n while (left <= right) {\n int mid = left + (right - left) / 2;\n if (nums[mid] == target) return mid;\n else if (nums[mid] < target) left = mid + 1;\n else right = mid - 1;\n }\n return -1;\n}", "solution_cpp": "int search(vector& nums, int target) {\n int left = 0, right = nums.size() - 1;\n while (left <= right) {\n int mid = left + (right - left) / 2;\n if (nums[mid] == target) return mid;\n else if (nums[mid] < target) left = mid + 1;\n else right = mid - 1;\n }\n return -1;\n}", "test_cases": ["nums=[-1,0,3,5,9,12], target=9 -> 4", "nums=[-1,0,3,5,9,12], target=2 -> -1"], "key_points": ["标准模板", "注意防溢出写法"], "tags": ["binarysearch", "easy", "Google", "Amazon"]} {"problem_id": "algo_00571", "original_id": "climbing-stairs", "title": "爬楼梯", "category": "dp", "difficulty": "easy", "companies": ["Amazon", "Google"], "description": "假设你正在爬楼梯。需要 n 阶你才能到达楼顶。每次你可以爬 1 或 2 个台阶。你有多少种不同的方法可以爬到楼顶?", "solution_python": "def climbStairs(n):\n if n <= 2: return n\n a, b = 1, 2\n for _ in range(3, n+1):\n a, b = b, a + b\n return b", "solution_java": "public int climbStairs(int n) {\n if (n <= 2) return n;\n int a = 1, b = 2;\n for (int i = 3; i <= n; i++) { int temp = a + b; a = b; b = temp; }\n return b;\n}", "solution_cpp": "int climbStairs(int n) {\n if (n <= 2) return n;\n int a = 1, b = 2;\n for (int i = 3; i <= n; i++) { int temp = a + b; a = b; b = temp; }\n return b;\n}", "test_cases": ["n=2 -> 2", "n=3 -> 3", "n=5 -> 8"], "key_points": ["斐波那契数列", "滚动数组优化空间"], "tags": ["dp", "easy", "Amazon", "Google"]} {"problem_id": "algo_00572", "original_id": "coin-change", "title": "零钱兑换", "category": "dp", "difficulty": "medium", "companies": ["Google", "Amazon"], "description": "给你一个整数数组 coins 表示不同面额的硬币,以及一个整数 amount 表示总金额。计算并返回可以凑成总金额所需的最少的硬币个数。如果没有任何一种硬币组合能组成总金额,返回 -1。", "solution_python": "def coinChange(coins, amount):\n dp = [float('inf')] * (amount + 1)\n dp[0] = 0\n for coin in coins:\n for x in range(coin, amount + 1):\n dp[x] = min(dp[x], dp[x - coin] + 1)\n return dp[amount] if dp[amount] != float('inf') else -1", "solution_java": "public int coinChange(int[] coins, int amount) {\n int[] dp = new int[amount + 1];\n Arrays.fill(dp, amount + 1);\n dp[0] = 0;\n for (int coin : coins) {\n for (int x = coin; x <= amount; x++) {\n dp[x] = Math.min(dp[x], dp[x - coin] + 1);\n }\n }\n return dp[amount] > amount ? -1 : dp[amount];\n}", "solution_cpp": "int coinChange(vector& coins, int amount) {\n vector dp(amount + 1, amount + 1);\n dp[0] = 0;\n for (int coin : coins) {\n for (int x = coin; x <= amount; x++) {\n dp[x] = min(dp[x], dp[x - coin] + 1);\n }\n }\n return dp[amount] > amount ? -1 : dp[amount];\n}", "test_cases": ["coins=[1,2,5], amount=11 -> 3", "coins=[2], amount=3 -> -1"], "key_points": ["完全背包问题", "dp[x] = min(dp[x-coin]+1)"], "tags": ["dp", "medium", "Google", "Amazon"]} {"problem_id": "algo_00573", "original_id": "subsets", "title": "子集", "category": "backtracking", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "给你一个整数数组 nums ,数组中的元素 互不相同 。返回该数组所有可能的子集(幂集)。", "solution_python": "def subsets(nums):\n result = []\n def backtrack(start, path):\n result.append(path[:])\n for i in range(start, len(nums)):\n path.append(nums[i])\n backtrack(i + 1, path)\n path.pop()\n backtrack(0, [])\n return result", "solution_java": "public List> subsets(int[] nums) {\n List> result = new ArrayList<>();\n backtrack(nums, 0, new ArrayList<>(), result);\n return result;\n}\nprivate void backtrack(int[] nums, int start, List path, List> result) {\n result.add(new ArrayList<>(path));\n for (int i = start; i < nums.length; i++) {\n path.add(nums[i]);\n backtrack(nums, i + 1, path, result);\n path.remove(path.size() - 1);\n }\n}", "solution_cpp": "vector> subsets(vector& nums) {\n vector> result;\n vector path;\n backtrack(nums, 0, path, result);\n return result;\n}\nvoid backtrack(vector& nums, int start, vector& path, vector>& result) {\n result.push_back(path);\n for (int i = start; i < nums.size(); i++) {\n path.push_back(nums[i]);\n backtrack(nums, i + 1, path, result);\n path.pop_back();\n }\n}", "test_cases": ["nums=[1,2,3] -> [[],[1],[2],[1,2],[3],[1,3],[2,3],[1,2,3]]"], "key_points": ["选或不选", "DFS遍历子集树"], "tags": ["backtracking", "medium", "Google", "Microsoft"]} {"problem_id": "algo_00574", "original_id": "permutations", "title": "全排列", "category": "backtracking", "difficulty": "medium", "companies": ["Google", "Facebook"], "description": "给定一个不含重复数字的数组 nums,返回其所有可能的全排列。", "solution_python": "def permute(nums):\n result = []\n def backtrack(path, used):\n if len(path) == len(nums):\n result.append(path[:])\n return\n for i in range(len(nums)):\n if used[i]: continue\n used[i] = True\n path.append(nums[i])\n backtrack(path, used)\n path.pop()\n used[i] = False\n backtrack([], [False]*len(nums))\n return result", "solution_java": "public List> permute(int[] nums) {\n List> result = new ArrayList<>();\n boolean[] used = new boolean[nums.length];\n backtrack(nums, used, new ArrayList<>(), result);\n return result;\n}\nprivate void backtrack(int[] nums, boolean[] used, List path, List> result) {\n if (path.size() == nums.length) { result.add(new ArrayList<>(path)); return; }\n for (int i = 0; i < nums.length; i++) {\n if (used[i]) continue;\n used[i] = true;\n path.add(nums[i]);\n backtrack(nums, used, path, result);\n path.remove(path.size() - 1);\n used[i] = false;\n }\n}", "solution_cpp": "vector> permute(vector& nums) {\n vector> result;\n vector used(nums.size(), false);\n vector path;\n backtrack(nums, used, path, result);\n return result;\n}\nvoid backtrack(vector& nums, vector& used, vector& path, vector>& result) {\n if (path.size() == nums.size()) { result.push_back(path); return; }\n for (int i = 0; i < nums.size(); i++) {\n if (used[i]) continue;\n used[i] = true;\n path.push_back(nums[i]);\n backtrack(nums, used, path, result);\n path.pop_back();\n used[i] = false;\n }\n}", "test_cases": ["nums=[1,2,3] -> [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]"], "key_points": ["标记已使用元素", "回溯经典模板"], "tags": ["backtracking", "medium", "Google", "Facebook"]} {"problem_id": "algo_00575", "original_id": "top-k-frequent", "title": "前K个高频元素", "category": "heap", "difficulty": "medium", "companies": ["Amazon", "Facebook"], "description": "给你一个整数数组 nums 和一个整数 k,请你返回其中出现频率前 k 高的元素。", "solution_python": "import heapq\nfrom collections import Counter\ndef topKFrequent(nums, k):\n count = Counter(nums)\n heap = []\n for num, freq in count.items():\n heapq.heappush(heap, (freq, num))\n if len(heap) > k: heapq.heappop(heap)\n return [num for freq, num in heap]", "solution_java": "public int[] topKFrequent(int[] nums, int k) {\n Map count = new HashMap<>();\n for (int n : nums) count.put(n, count.getOrDefault(n, 0) + 1);\n PriorityQueue> heap = \n new PriorityQueue<>((a, b) -> a.getValue() - b.getValue());\n for (Map.Entry e : count.entrySet()) {\n heap.offer(e);\n if (heap.size() > k) heap.poll();\n }\n int[] res = new int[k];\n for (int i = k - 1; i >= 0; i--) res[i] = heap.poll().getKey();\n return res;\n}", "solution_cpp": "vector topKFrequent(vector& nums, int k) {\n unordered_map count;\n for (int n : nums) count[n]++;\n priority_queue, vector>, greater>> heap;\n for (auto& [num, freq] : count) {\n heap.push({freq, num});\n if (heap.size() > k) heap.pop();\n }\n vector res;\n while (!heap.empty()) { res.push_back(heap.top().second); heap.pop(); }\n reverse(res.begin(), res.end());\n return res;\n}", "test_cases": ["nums=[1,1,1,2,2,3], k=2 -> [1,2]", "nums=[1], k=1 -> [1]"], "key_points": ["小顶堆保持大小k", "时间复杂度O(nlogk)"], "tags": ["heap", "medium", "Amazon", "Facebook"]} {"problem_id": "algo_00576", "original_id": "3sum", "title": "三数之和", "category": "two-pointers", "difficulty": "medium", "companies": ["Google", "Amazon"], "description": "给你一个整数数组 nums,判断是否存在三元组满足和为0,返回所有不重复的三元组。", "solution_python": "def threeSum(nums):\n nums.sort()\n result = []\n for i in range(len(nums) - 2):\n if i > 0 and nums[i] == nums[i-1]: continue\n left, right = i + 1, len(nums) - 1\n while left < right:\n total = nums[i] + nums[left] + nums[right]\n if total < 0: left += 1\n elif total > 0: right -= 1\n else:\n result.append([nums[i], nums[left], nums[right]])\n while left < right and nums[left] == nums[left+1]: left += 1\n while left < right and nums[right] == nums[right-1]: right -= 1\n left += 1; right -= 1\n return result", "solution_java": "public List> threeSum(int[] nums) {\n Arrays.sort(nums);\n List> result = new ArrayList<>();\n for (int i = 0; i < nums.length - 2; i++) {\n if (i > 0 && nums[i] == nums[i-1]) continue;\n int left = i + 1, right = nums.length - 1;\n while (left < right) {\n int total = nums[i] + nums[left] + nums[right];\n if (total < 0) left++;\n else if (total > 0) right--;\n else {\n result.add(Arrays.asList(nums[i], nums[left], nums[right]));\n while (left < right && nums[left] == nums[left+1]) left++;\n while (left < right && nums[right] == nums[right-1]) right--;\n left++; right--;\n }\n }\n }\n return result;\n}", "solution_cpp": "vector> threeSum(vector& nums) {\n sort(nums.begin(), nums.end());\n vector> result;\n for (int i = 0; i < nums.size() - 2; i++) {\n if (i > 0 && nums[i] == nums[i-1]) continue;\n int left = i + 1, right = nums.size() - 1;\n while (left < right) {\n int total = nums[i] + nums[left] + nums[right];\n if (total < 0) left++;\n else if (total > 0) right--;\n else {\n result.push_back({nums[i], nums[left], nums[right]});\n while (left < right && nums[left] == nums[left+1]) left++;\n while (left < right && nums[right] == nums[right-1]) right--;\n left++; right--;\n }\n }\n }\n return result;\n}", "test_cases": ["nums=[-1,0,1,2,-1,-4] -> [[-1,-1,2],[-1,0,1]]"], "key_points": ["排序+双指针", "去重是关键"], "tags": ["two-pointers", "medium", "Google", "Amazon"]} {"problem_id": "algo_00577", "original_id": "container-water", "title": "盛最多水的容器", "category": "two-pointers", "difficulty": "medium", "companies": ["Google", "Uber"], "description": "给定一个长度为 n 的整数数组 height,找出其中的两条线,使得它们与 x 轴共同构成的容器可以容纳最多的水。", "solution_python": "def maxArea(height):\n left, right = 0, len(height) - 1\n max_area = 0\n while left < right:\n h = min(height[left], height[right])\n max_area = max(max_area, h * (right - left))\n if height[left] < height[right]: left += 1\n else: right -= 1\n return max_area", "solution_java": "public int maxArea(int[] height) {\n int left = 0, right = height.length - 1, maxArea = 0;\n while (left < right) {\n int h = Math.min(height[left], height[right]);\n maxArea = Math.max(maxArea, h * (right - left));\n if (height[left] < height[right]) left++;\n else right--;\n }\n return maxArea;\n}", "solution_cpp": "int maxArea(vector& height) {\n int left = 0, right = height.size() - 1, maxArea = 0;\n while (left < right) {\n int h = min(height[left], height[right]);\n maxArea = max(maxArea, h * (right - left));\n if (height[left] < height[right]) left++;\n else right--;\n }\n return maxArea;\n}", "test_cases": ["height=[1,8,6,2,5,4,8,3,7] -> 49"], "key_points": ["移动短边指针", "面积=min(h1,h2)*width"], "tags": ["two-pointers", "medium", "Google", "Uber"]} {"problem_id": "algo_00578", "original_id": "min-stack", "title": "最小栈", "category": "stack", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "设计一个支持 push,pop,top 操作,并能在常数时间内检索到最小元素的栈。", "solution_python": "class MinStack:\n def __init__(self):\n self.stack = []\n self.min_stack = []\n def push(self, val):\n self.stack.append(val)\n self.min_stack.append(min(val, self.min_stack[-1] if self.min_stack else val))\n def pop(self):\n self.stack.pop(); self.min_stack.pop()\n def top(self): return self.stack[-1]\n def getMin(self): return self.min_stack[-1]", "solution_java": "class MinStack {\n Stack stack = new Stack<>();\n Stack minStack = new Stack<>();\n public void push(int val) { stack.push(val); minStack.push(Math.min(val, minStack.isEmpty() ? val : minStack.peek())); }\n public void pop() { stack.pop(); minStack.pop(); }\n public int top() { return stack.peek(); }\n public int getMin() { return minStack.peek(); }\n}", "solution_cpp": "class MinStack {\n stack st, minSt;\npublic:\n void push(int val) { st.push(val); minSt.push(min(val, minSt.empty() ? val : minSt.top())); }\n void pop() { st.pop(); minSt.pop(); }\n int top() { return st.top(); }\n int getMin() { return minSt.top(); }\n};", "test_cases": ["push(-2), push(0), push(-3) -> getMin() returns -3"], "key_points": ["辅助栈记录最小值", "O(1)时间获取最小值"], "tags": ["stack", "medium", "Google", "Microsoft"]} {"problem_id": "algo_00579", "original_id": "lru-cache", "title": "LRU缓存", "category": "design", "difficulty": "hard", "companies": ["Google", "Amazon"], "description": "设计和实现一个 LRU(最近最少使用)缓存机制。", "solution_python": "class LRUCache:\n def __init__(self, capacity):\n self.capacity = capacity\n self.cache = {}\n self.order = []\n def get(self, key):\n if key not in self.cache: return -1\n self.order.remove(key); self.order.append(key)\n return self.cache[key]\n def put(self, key, value):\n if key in self.cache:\n self.order.remove(key)\n elif len(self.cache) >= self.capacity:\n del self.cache[self.order.pop(0)]\n self.cache[key] = value; self.order.append(key)", "solution_java": "class LRUCache {\n int capacity;\n LinkedHashMap cache = new LinkedHashMap<>();\n public LRUCache(int cap) { capacity = cap; }\n public int get(int key) { return cache.containsKey(key) ? cache.remove(key) : -1; }\n public void put(int key, int val) {\n if (cache.containsKey(key)) cache.remove(key);\n else if (cache.size() >= capacity) cache.remove(cache.keySet().iterator().next());\n cache.put(key, val);\n }\n}", "solution_cpp": "class LRUCache {\n int cap;\n list> dll;\n unordered_map>::iterator> cache;\npublic:\n LRUCache(int capacity) : cap(capacity) {}\n int get(int key) {\n auto it = cache.find(key);\n if (it == cache.end()) return -1;\n dll.splice(dll.end(), dll, it->second);\n return it->second->second;\n }\n void put(int key, int value) {\n auto it = cache.find(key);\n if (it != cache.end()) dll.erase(it->second);\n else if (cache.size() >= cap) { cache.erase(dll.front().first); dll.pop_front(); }\n dll.push_back({key, value});\n cache[key] = --dll.end();\n }\n};", "test_cases": ["put(1,1), put(2,2), get(1) -> 1"], "key_points": ["HashMap + 双向链表", "O(1)时间操作"], "tags": ["design", "hard", "Google", "Amazon"]} {"problem_id": "algo_00580", "original_id": "num-islands", "title": "岛屿数量", "category": "graph", "difficulty": "medium", "companies": ["Google", "Facebook"], "description": "给你一个由 '1'(陆地)和 '0'(水)组成的二维网格,请你计算网格中岛屿的数量。岛屿总是被水包围,且只能由水平或垂直方向相邻的陆地连接形成。", "solution_python": "def numIslands(grid):\n if not grid: return 0\n rows, cols = len(grid), len(grid[0])\n count = 0\n def dfs(r, c):\n if r < 0 or r >= rows or c < 0 or c >= cols or grid[r][c] != '1': return\n grid[r][c] = '0'\n dfs(r+1, c); dfs(r-1, c); dfs(r, c+1); dfs(r, c-1)\n for r in range(rows):\n for c in range(cols):\n if grid[r][c] == '1': count += 1; dfs(r, c)\n return count", "solution_java": "public int numIslands(char[][] grid) {\n if (grid.length == 0) return 0;\n int count = 0;\n for (int i = 0; i < grid.length; i++)\n for (int j = 0; j < grid[0].length; j++)\n if (grid[i][j] == '1') { count++; dfs(grid, i, j); }\n return count;\n}\nprivate void dfs(char[][] grid, int r, int c) {\n if (r < 0 || r >= grid.length || c < 0 || c >= grid[0].length || grid[r][c] != '1') return;\n grid[r][c] = '0';\n dfs(grid, r+1, c); dfs(grid, r-1, c); dfs(grid, r, c+1); dfs(grid, r, c-1);\n}", "solution_cpp": "int numIslands(vector>& grid) {\n if (grid.empty()) return 0;\n int count = 0;\n for (int i = 0; i < grid.size(); i++)\n for (int j = 0; j < grid[0].size(); j++)\n if (grid[i][j] == '1') { count++; dfs(grid, i, j); }\n return count;\n}\nvoid dfs(vector>& grid, int r, int c) {\n if (r < 0 || r >= grid.size() || c < 0 || c >= grid[0].size() || grid[r][c] != '1') return;\n grid[r][c] = '0';\n dfs(grid, r+1, c); dfs(grid, r-1, c); dfs(grid, r, c+1); dfs(grid, r, c-1);\n}", "test_cases": ["grid=[[1,1,1,1,0],[1,1,0,1,0],[1,1,0,0,0],[0,0,0,0,0]] -> 1"], "key_points": ["DFS/BFS遍历", "访问后标记为0避免重复"], "tags": ["graph", "medium", "Google", "Facebook"]} {"problem_id": "algo_00581", "original_id": "two-sum", "title": "两数之和", "category": "array", "difficulty": "easy", "companies": ["Amazon", "Google"], "description": "给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那两个整数,并返回他们的数组下标。", "solution_python": "def twoSum(nums, target):\n hashmap = {}\n for i, num in enumerate(nums):\n complement = target - num\n if complement in hashmap:\n return [hashmap[complement], i]\n hashmap[num] = i\n return []", "solution_java": "public int[] twoSum(int[] nums, int target) {\n Map map = new HashMap<>();\n for (int i = 0; i < nums.length; i++) {\n int complement = target - nums[i];\n if (map.containsKey(complement)) return new int[]{map.get(complement), i};\n map.put(nums[i], i);\n }\n return new int[]{};\n}", "solution_cpp": "vector twoSum(vector& nums, int target) {\n unordered_map m;\n for (int i = 0; i < nums.size(); i++) {\n if (m.count(target - nums[i])) return {m[target - nums[i]], i};\n m[nums[i]] = i;\n }\n return {};\n}", "test_cases": ["nums=[2,7,11,15], target=9 -> [0,1]", "nums=[3,2,4], target=6 -> [1,2]"], "key_points": ["哈希表一次遍历", "空间换时间"], "tags": ["array", "easy", "Amazon", "Google"]} {"problem_id": "algo_00582", "original_id": "merge-sorted", "title": "合并两个有序数组", "category": "array", "difficulty": "easy", "companies": ["Microsoft", "Uber"], "description": "给你两个按非递减顺序排列的整数数组 nums1 和 nums2,另有两个整数 m 和 n,分别表示 nums1 和 nums2 中的元素数目。请你合并 nums2 到 nums1 中。", "solution_python": "def merge(nums1, m, nums2, n):\n p1, p2, p = m-1, n-1, m+n-1\n while p1 >= 0 and p2 >= 0:\n if nums1[p1] > nums2[p2]: nums1[p] = nums1[p1]; p1 -= 1\n else: nums1[p] = nums2[p2]; p2 -= 1\n p -= 1\n while p2 >= 0: nums1[p] = nums2[p2]; p2 -= 1; p -= 1", "solution_java": "public void merge(int[] nums1, int m, int[] nums2, int n) {\n int p1 = m-1, p2 = n-1, p = m+n-1;\n while (p1 >= 0 && p2 >= 0) {\n nums1[p--] = nums1[p1] > nums2[p2] ? nums1[p1--] : nums2[p2--];\n }\n while (p2 >= 0) nums1[p--] = nums2[p2--];\n}", "solution_cpp": "void merge(vector& nums1, int m, vector& nums2, int n) {\n int p1 = m-1, p2 = n-1, p = m+n-1;\n while (p1 >= 0 && p2 >= 0) nums1[p--] = nums1[p1] > nums2[p2] ? nums1[p1--] : nums2[p2--];\n while (p2 >= 0) nums1[p--] = nums2[p2--];\n}", "test_cases": ["nums1=[1,2,3], m=3, nums2=[2,5,6], n=3 -> [1,2,2,3,5,6]", "nums1=[], m=0, nums2=[1], n=1 -> [1]"], "key_points": ["从后往前合并", "三指针技巧"], "tags": ["array", "easy", "Microsoft", "Uber"]} {"problem_id": "algo_00583", "original_id": "max-subarray", "title": "最大子数组和", "category": "array", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "给你一个整数数组 nums ,请你找出一个具有最大和的连续子数组,返回其最大和。", "solution_python": "def maxSubArray(nums):\n max_sum = current = nums[0]\n for num in nums[1:]:\n current = max(num, current + num)\n max_sum = max(max_sum, current)\n return max_sum", "solution_java": "public int maxSubArray(int[] nums) {\n int maxSum = nums[0], curr = nums[0];\n for (int i = 1; i < nums.length; i++) {\n curr = Math.max(nums[i], curr + nums[i]);\n maxSum = Math.max(maxSum, curr);\n }\n return maxSum;\n}", "solution_cpp": "int maxSubArray(vector& nums) {\n int maxSum = nums[0], curr = nums[0];\n for (int i = 1; i < nums.size(); i++) {\n curr = max(nums[i], curr + nums[i]);\n maxSum = max(maxSum, curr);\n }\n return maxSum;\n}", "test_cases": ["nums=[-2,1,-3,4,-1,2,1,-5,4] -> 6", "nums=[1] -> 1"], "key_points": ["Kadane算法", "动态规划基础题"], "tags": ["array", "medium", "Google", "Microsoft"]} {"problem_id": "algo_00584", "original_id": "valid-parentheses", "title": "有效的括号", "category": "string", "difficulty": "easy", "companies": ["Google", "Uber"], "description": "给定一个只包括 '(',')','{','}','[',']' 的字符串 s,判断字符串是否有效。", "solution_python": "def isValid(s):\n stack = []\n mapping = {')': '(', ']': '[', '}': '{'}\n for c in s:\n if c in mapping:\n if not stack or stack[-1] != mapping[c]: return False\n stack.pop()\n else: stack.append(c)\n return not stack", "solution_java": "public boolean isValid(String s) {\n Stack stack = new Stack<>();\n Map map = Map.of(')', '(', ']', '[', '}', '{');\n for (char c : s.toCharArray()) {\n if (map.containsValue(c)) stack.push(c);\n else if (!stack.isEmpty() && stack.pop() != map.get(c)) return false;\n }\n return stack.isEmpty();\n}", "solution_cpp": "bool isValid(string s) {\n stack st;\n unordered_map m = {{')','('},{']','['},{'}','{'}};\n for (char c : s) {\n if (m.find(c) == m.end()) st.push(c);\n else if (st.empty() || st.top() != m[c]) return false;\n else st.pop();\n }\n return st.empty();\n}", "test_cases": ["s=\"()\" -> true", "s=\"()[]{}\" -> true", "s=\"(]\" -> false"], "key_points": ["栈匹配法", "注意空栈边界"], "tags": ["string", "easy", "Google", "Uber"]} {"problem_id": "algo_00585", "original_id": "longest-palindrome", "title": "最长回文子串", "category": "string", "difficulty": "medium", "companies": ["Google", "Amazon"], "description": "给你一个字符串 s,找到 s 中最长的回文子串。", "solution_python": "def longestPalindrome(s):\n def expand(l, r):\n while l >= 0 and r < len(s) and s[l] == s[r]: l -= 1; r += 1\n return l + 1, r - 1\n start = end = 0\n for i in range(len(s)):\n l1, r1 = expand(i, i)\n l2, r2 = expand(i, i + 1)\n if r1 - l1 > end - start: start, end = l1, r1\n if r2 - l2 > end - start: start, end = l2, r2\n return s[start:end+1]", "solution_java": "public String longestPalindrome(String s) {\n int start = 0, end = 0;\n for (int i = 0; i < s.length(); i++) {\n int len1 = expand(s, i, i), len2 = expand(s, i, i+1);\n int len = Math.max(len1, len2);\n if (len > end - start) { start = i - (len-1)/2; end = i + len/2; }\n }\n return s.substring(start, end + 1);\n}\nprivate int expand(String s, int l, int r) {\n while (l >= 0 && r < s.length() && s.charAt(l) == s.charAt(r)) { l--; r++; }\n return r - l - 1;\n}", "solution_cpp": "string longestPalindrome(string s) {\n int start = 0, end = 0;\n for (int i = 0; i < s.size(); i++) {\n int len1 = expand(s, i, i), len2 = expand(s, i, i+1);\n if (max(len1, len2) > end - start) { start = i - (max(len1,len2)-1)/2; end = i + max(len1,len2)/2; }\n }\n return s.substr(start, end - start + 1);\n}", "test_cases": ["s=\"babad\" -> bab或aba", "s=\"cbbd\" -> bb"], "key_points": ["中心扩展法", "处理奇偶长度"], "tags": ["string", "medium", "Google", "Amazon"]} {"problem_id": "algo_00586", "original_id": "reverse-list", "title": "反转链表", "category": "linkedlist", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "给你单链表的头节点 head,请你反转链表,并返回反转后的链表。", "solution_python": "def reverseList(head):\n prev = None\n curr = head\n while curr:\n nxt = curr.next\n curr.next = prev\n prev = curr\n curr = nxt\n return prev", "solution_java": "public ListNode reverseList(ListNode head) {\n ListNode prev = null, curr = head;\n while (curr != null) {\n ListNode next = curr.next;\n curr.next = prev;\n prev = curr;\n curr = next;\n }\n return prev;\n}", "solution_cpp": "ListNode* reverseList(ListNode* head) {\n ListNode* prev = nullptr, *curr = head;\n while (curr) {\n ListNode* next = curr->next;\n curr->next = prev;\n prev = curr;\n curr = next;\n }\n return prev;\n}", "test_cases": ["head=[1,2,3,4,5] -> [5,4,3,2,1]", "head=[1,2] -> [2,1]"], "key_points": ["迭代法 O(1)空间", "递归法 O(n)空间"], "tags": ["linkedlist", "medium", "Google", "Microsoft"]} {"problem_id": "algo_00587", "original_id": "middle-node", "title": "链表的中间结点", "category": "linkedlist", "difficulty": "easy", "companies": ["Amazon", "Facebook"], "description": "给你单链表的头节点 head,请你找出并返回链表的中间结点。如果有两个中间结点,则返回第二个中间结点。", "solution_python": "def middleNode(head):\n slow = fast = head\n while fast and fast.next:\n slow = slow.next\n fast = fast.next.next\n return slow", "solution_java": "public ListNode middleNode(ListNode head) {\n ListNode slow = head, fast = head;\n while (fast != null && fast.next != null) {\n slow = slow.next;\n fast = fast.next.next;\n }\n return slow;\n}", "solution_cpp": "ListNode* middleNode(ListNode* head) {\n ListNode* slow = head, *fast = head;\n while (fast && fast->next) { slow = slow->next; fast = fast->next->next; }\n return slow;\n}", "test_cases": ["head=[1,2,3,4,5] -> 3", "head=[1,2,3,4,5,6] -> 4"], "key_points": ["快慢指针", "O(n)时间O(1)空间"], "tags": ["linkedlist", "easy", "Amazon", "Facebook"]} {"problem_id": "algo_00588", "original_id": "max-depth", "title": "二叉树的最大深度", "category": "tree", "difficulty": "easy", "companies": ["Microsoft", "Apple"], "description": "给定一个二叉树 root,返回其最大深度。", "solution_python": "def maxDepth(root):\n if not root: return 0\n return max(maxDepth(root.left), maxDepth(root.right)) + 1", "solution_java": "public int maxDepth(TreeNode root) {\n if (root == null) return 0;\n return Math.max(maxDepth(root.left), maxDepth(root.right)) + 1;\n}", "solution_cpp": "int maxDepth(TreeNode* root) {\n if (!root) return 0;\n return max(maxDepth(root->left), maxDepth(root->right)) + 1;\n}", "test_cases": ["root=[3,9,20,null,null,15,7] -> 3", "root=[1,null,2] -> 2"], "key_points": ["DFS递归", "层序遍历也可"], "tags": ["tree", "easy", "Microsoft", "Apple"]} {"problem_id": "algo_00589", "original_id": "inorder-traversal", "title": "二叉树的中序遍历", "category": "tree", "difficulty": "easy", "companies": ["Google", "Microsoft"], "description": "给定一个二叉树的根节点 root,返回它的中序遍历结果。", "solution_python": "def inorderTraversal(root):\n result = []\n def dfs(node):\n if node:\n dfs(node.left)\n result.append(node.val)\n dfs(node.right)\n dfs(root)\n return result", "solution_java": "public List inorderTraversal(TreeNode root) {\n List res = new ArrayList<>();\n dfs(root, res);\n return res;\n}\nprivate void dfs(TreeNode node, List res) {\n if (node == null) return;\n dfs(node.left, res); res.add(node.val); dfs(node.right, res);\n}", "solution_cpp": "vector inorderTraversal(TreeNode* root) {\n vector res;\n dfs(root, res);\n return res;\n}\nvoid dfs(TreeNode* node, vector& res) {\n if (!node) return;\n dfs(node->left, res); res.push_back(node->val); dfs(node->right, res);\n}", "test_cases": ["root=[1,null,2,3] -> [1,3,2]", "root=[] -> []"], "key_points": ["左-根-右顺序", "递归最简洁"], "tags": ["tree", "easy", "Google", "Microsoft"]} {"problem_id": "algo_00590", "original_id": "binary-search", "title": "二分查找", "category": "binarysearch", "difficulty": "easy", "companies": ["Google", "Amazon"], "description": "给定一个 n 个元素有序的(升序)整型数组 nums 和一个目标值 target,写一个函数搜索 nums 中的 target,如果目标值存在返回下标,否则返回 -1。", "solution_python": "def search(nums, target):\n left, right = 0, len(nums) - 1\n while left <= right:\n mid = (left + right) // 2\n if nums[mid] == target: return mid\n elif nums[mid] < target: left = mid + 1\n else: right = mid - 1\n return -1", "solution_java": "public int search(int[] nums, int target) {\n int left = 0, right = nums.length - 1;\n while (left <= right) {\n int mid = left + (right - left) / 2;\n if (nums[mid] == target) return mid;\n else if (nums[mid] < target) left = mid + 1;\n else right = mid - 1;\n }\n return -1;\n}", "solution_cpp": "int search(vector& nums, int target) {\n int left = 0, right = nums.size() - 1;\n while (left <= right) {\n int mid = left + (right - left) / 2;\n if (nums[mid] == target) return mid;\n else if (nums[mid] < target) left = mid + 1;\n else right = mid - 1;\n }\n return -1;\n}", "test_cases": ["nums=[-1,0,3,5,9,12], target=9 -> 4", "nums=[-1,0,3,5,9,12], target=2 -> -1"], "key_points": ["标准模板", "注意防溢出写法"], "tags": ["binarysearch", "easy", "Google", "Amazon"]} {"problem_id": "algo_00591", "original_id": "climbing-stairs", "title": "爬楼梯", "category": "dp", "difficulty": "easy", "companies": ["Amazon", "Google"], "description": "假设你正在爬楼梯。需要 n 阶你才能到达楼顶。每次你可以爬 1 或 2 个台阶。你有多少种不同的方法可以爬到楼顶?", "solution_python": "def climbStairs(n):\n if n <= 2: return n\n a, b = 1, 2\n for _ in range(3, n+1):\n a, b = b, a + b\n return b", "solution_java": "public int climbStairs(int n) {\n if (n <= 2) return n;\n int a = 1, b = 2;\n for (int i = 3; i <= n; i++) { int temp = a + b; a = b; b = temp; }\n return b;\n}", "solution_cpp": "int climbStairs(int n) {\n if (n <= 2) return n;\n int a = 1, b = 2;\n for (int i = 3; i <= n; i++) { int temp = a + b; a = b; b = temp; }\n return b;\n}", "test_cases": ["n=2 -> 2", "n=3 -> 3", "n=5 -> 8"], "key_points": ["斐波那契数列", "滚动数组优化空间"], "tags": ["dp", "easy", "Amazon", "Google"]} {"problem_id": "algo_00592", "original_id": "coin-change", "title": "零钱兑换", "category": "dp", "difficulty": "medium", "companies": ["Google", "Amazon"], "description": "给你一个整数数组 coins 表示不同面额的硬币,以及一个整数 amount 表示总金额。计算并返回可以凑成总金额所需的最少的硬币个数。如果没有任何一种硬币组合能组成总金额,返回 -1。", "solution_python": "def coinChange(coins, amount):\n dp = [float('inf')] * (amount + 1)\n dp[0] = 0\n for coin in coins:\n for x in range(coin, amount + 1):\n dp[x] = min(dp[x], dp[x - coin] + 1)\n return dp[amount] if dp[amount] != float('inf') else -1", "solution_java": "public int coinChange(int[] coins, int amount) {\n int[] dp = new int[amount + 1];\n Arrays.fill(dp, amount + 1);\n dp[0] = 0;\n for (int coin : coins) {\n for (int x = coin; x <= amount; x++) {\n dp[x] = Math.min(dp[x], dp[x - coin] + 1);\n }\n }\n return dp[amount] > amount ? -1 : dp[amount];\n}", "solution_cpp": "int coinChange(vector& coins, int amount) {\n vector dp(amount + 1, amount + 1);\n dp[0] = 0;\n for (int coin : coins) {\n for (int x = coin; x <= amount; x++) {\n dp[x] = min(dp[x], dp[x - coin] + 1);\n }\n }\n return dp[amount] > amount ? -1 : dp[amount];\n}", "test_cases": ["coins=[1,2,5], amount=11 -> 3", "coins=[2], amount=3 -> -1"], "key_points": ["完全背包问题", "dp[x] = min(dp[x-coin]+1)"], "tags": ["dp", "medium", "Google", "Amazon"]} {"problem_id": "algo_00593", "original_id": "subsets", "title": "子集", "category": "backtracking", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "给你一个整数数组 nums ,数组中的元素 互不相同 。返回该数组所有可能的子集(幂集)。", "solution_python": "def subsets(nums):\n result = []\n def backtrack(start, path):\n result.append(path[:])\n for i in range(start, len(nums)):\n path.append(nums[i])\n backtrack(i + 1, path)\n path.pop()\n backtrack(0, [])\n return result", "solution_java": "public List> subsets(int[] nums) {\n List> result = new ArrayList<>();\n backtrack(nums, 0, new ArrayList<>(), result);\n return result;\n}\nprivate void backtrack(int[] nums, int start, List path, List> result) {\n result.add(new ArrayList<>(path));\n for (int i = start; i < nums.length; i++) {\n path.add(nums[i]);\n backtrack(nums, i + 1, path, result);\n path.remove(path.size() - 1);\n }\n}", "solution_cpp": "vector> subsets(vector& nums) {\n vector> result;\n vector path;\n backtrack(nums, 0, path, result);\n return result;\n}\nvoid backtrack(vector& nums, int start, vector& path, vector>& result) {\n result.push_back(path);\n for (int i = start; i < nums.size(); i++) {\n path.push_back(nums[i]);\n backtrack(nums, i + 1, path, result);\n path.pop_back();\n }\n}", "test_cases": ["nums=[1,2,3] -> [[],[1],[2],[1,2],[3],[1,3],[2,3],[1,2,3]]"], "key_points": ["选或不选", "DFS遍历子集树"], "tags": ["backtracking", "medium", "Google", "Microsoft"]} {"problem_id": "algo_00594", "original_id": "permutations", "title": "全排列", "category": "backtracking", "difficulty": "medium", "companies": ["Google", "Facebook"], "description": "给定一个不含重复数字的数组 nums,返回其所有可能的全排列。", "solution_python": "def permute(nums):\n result = []\n def backtrack(path, used):\n if len(path) == len(nums):\n result.append(path[:])\n return\n for i in range(len(nums)):\n if used[i]: continue\n used[i] = True\n path.append(nums[i])\n backtrack(path, used)\n path.pop()\n used[i] = False\n backtrack([], [False]*len(nums))\n return result", "solution_java": "public List> permute(int[] nums) {\n List> result = new ArrayList<>();\n boolean[] used = new boolean[nums.length];\n backtrack(nums, used, new ArrayList<>(), result);\n return result;\n}\nprivate void backtrack(int[] nums, boolean[] used, List path, List> result) {\n if (path.size() == nums.length) { result.add(new ArrayList<>(path)); return; }\n for (int i = 0; i < nums.length; i++) {\n if (used[i]) continue;\n used[i] = true;\n path.add(nums[i]);\n backtrack(nums, used, path, result);\n path.remove(path.size() - 1);\n used[i] = false;\n }\n}", "solution_cpp": "vector> permute(vector& nums) {\n vector> result;\n vector used(nums.size(), false);\n vector path;\n backtrack(nums, used, path, result);\n return result;\n}\nvoid backtrack(vector& nums, vector& used, vector& path, vector>& result) {\n if (path.size() == nums.size()) { result.push_back(path); return; }\n for (int i = 0; i < nums.size(); i++) {\n if (used[i]) continue;\n used[i] = true;\n path.push_back(nums[i]);\n backtrack(nums, used, path, result);\n path.pop_back();\n used[i] = false;\n }\n}", "test_cases": ["nums=[1,2,3] -> [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]"], "key_points": ["标记已使用元素", "回溯经典模板"], "tags": ["backtracking", "medium", "Google", "Facebook"]} {"problem_id": "algo_00595", "original_id": "top-k-frequent", "title": "前K个高频元素", "category": "heap", "difficulty": "medium", "companies": ["Amazon", "Facebook"], "description": "给你一个整数数组 nums 和一个整数 k,请你返回其中出现频率前 k 高的元素。", "solution_python": "import heapq\nfrom collections import Counter\ndef topKFrequent(nums, k):\n count = Counter(nums)\n heap = []\n for num, freq in count.items():\n heapq.heappush(heap, (freq, num))\n if len(heap) > k: heapq.heappop(heap)\n return [num for freq, num in heap]", "solution_java": "public int[] topKFrequent(int[] nums, int k) {\n Map count = new HashMap<>();\n for (int n : nums) count.put(n, count.getOrDefault(n, 0) + 1);\n PriorityQueue> heap = \n new PriorityQueue<>((a, b) -> a.getValue() - b.getValue());\n for (Map.Entry e : count.entrySet()) {\n heap.offer(e);\n if (heap.size() > k) heap.poll();\n }\n int[] res = new int[k];\n for (int i = k - 1; i >= 0; i--) res[i] = heap.poll().getKey();\n return res;\n}", "solution_cpp": "vector topKFrequent(vector& nums, int k) {\n unordered_map count;\n for (int n : nums) count[n]++;\n priority_queue, vector>, greater>> heap;\n for (auto& [num, freq] : count) {\n heap.push({freq, num});\n if (heap.size() > k) heap.pop();\n }\n vector res;\n while (!heap.empty()) { res.push_back(heap.top().second); heap.pop(); }\n reverse(res.begin(), res.end());\n return res;\n}", "test_cases": ["nums=[1,1,1,2,2,3], k=2 -> [1,2]", "nums=[1], k=1 -> [1]"], "key_points": ["小顶堆保持大小k", "时间复杂度O(nlogk)"], "tags": ["heap", "medium", "Amazon", "Facebook"]} {"problem_id": "algo_00596", "original_id": "3sum", "title": "三数之和", "category": "two-pointers", "difficulty": "medium", "companies": ["Google", "Amazon"], "description": "给你一个整数数组 nums,判断是否存在三元组满足和为0,返回所有不重复的三元组。", "solution_python": "def threeSum(nums):\n nums.sort()\n result = []\n for i in range(len(nums) - 2):\n if i > 0 and nums[i] == nums[i-1]: continue\n left, right = i + 1, len(nums) - 1\n while left < right:\n total = nums[i] + nums[left] + nums[right]\n if total < 0: left += 1\n elif total > 0: right -= 1\n else:\n result.append([nums[i], nums[left], nums[right]])\n while left < right and nums[left] == nums[left+1]: left += 1\n while left < right and nums[right] == nums[right-1]: right -= 1\n left += 1; right -= 1\n return result", "solution_java": "public List> threeSum(int[] nums) {\n Arrays.sort(nums);\n List> result = new ArrayList<>();\n for (int i = 0; i < nums.length - 2; i++) {\n if (i > 0 && nums[i] == nums[i-1]) continue;\n int left = i + 1, right = nums.length - 1;\n while (left < right) {\n int total = nums[i] + nums[left] + nums[right];\n if (total < 0) left++;\n else if (total > 0) right--;\n else {\n result.add(Arrays.asList(nums[i], nums[left], nums[right]));\n while (left < right && nums[left] == nums[left+1]) left++;\n while (left < right && nums[right] == nums[right-1]) right--;\n left++; right--;\n }\n }\n }\n return result;\n}", "solution_cpp": "vector> threeSum(vector& nums) {\n sort(nums.begin(), nums.end());\n vector> result;\n for (int i = 0; i < nums.size() - 2; i++) {\n if (i > 0 && nums[i] == nums[i-1]) continue;\n int left = i + 1, right = nums.size() - 1;\n while (left < right) {\n int total = nums[i] + nums[left] + nums[right];\n if (total < 0) left++;\n else if (total > 0) right--;\n else {\n result.push_back({nums[i], nums[left], nums[right]});\n while (left < right && nums[left] == nums[left+1]) left++;\n while (left < right && nums[right] == nums[right-1]) right--;\n left++; right--;\n }\n }\n }\n return result;\n}", "test_cases": ["nums=[-1,0,1,2,-1,-4] -> [[-1,-1,2],[-1,0,1]]"], "key_points": ["排序+双指针", "去重是关键"], "tags": ["two-pointers", "medium", "Google", "Amazon"]} {"problem_id": "algo_00597", "original_id": "container-water", "title": "盛最多水的容器", "category": "two-pointers", "difficulty": "medium", "companies": ["Google", "Uber"], "description": "给定一个长度为 n 的整数数组 height,找出其中的两条线,使得它们与 x 轴共同构成的容器可以容纳最多的水。", "solution_python": "def maxArea(height):\n left, right = 0, len(height) - 1\n max_area = 0\n while left < right:\n h = min(height[left], height[right])\n max_area = max(max_area, h * (right - left))\n if height[left] < height[right]: left += 1\n else: right -= 1\n return max_area", "solution_java": "public int maxArea(int[] height) {\n int left = 0, right = height.length - 1, maxArea = 0;\n while (left < right) {\n int h = Math.min(height[left], height[right]);\n maxArea = Math.max(maxArea, h * (right - left));\n if (height[left] < height[right]) left++;\n else right--;\n }\n return maxArea;\n}", "solution_cpp": "int maxArea(vector& height) {\n int left = 0, right = height.size() - 1, maxArea = 0;\n while (left < right) {\n int h = min(height[left], height[right]);\n maxArea = max(maxArea, h * (right - left));\n if (height[left] < height[right]) left++;\n else right--;\n }\n return maxArea;\n}", "test_cases": ["height=[1,8,6,2,5,4,8,3,7] -> 49"], "key_points": ["移动短边指针", "面积=min(h1,h2)*width"], "tags": ["two-pointers", "medium", "Google", "Uber"]} {"problem_id": "algo_00598", "original_id": "min-stack", "title": "最小栈", "category": "stack", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "设计一个支持 push,pop,top 操作,并能在常数时间内检索到最小元素的栈。", "solution_python": "class MinStack:\n def __init__(self):\n self.stack = []\n self.min_stack = []\n def push(self, val):\n self.stack.append(val)\n self.min_stack.append(min(val, self.min_stack[-1] if self.min_stack else val))\n def pop(self):\n self.stack.pop(); self.min_stack.pop()\n def top(self): return self.stack[-1]\n def getMin(self): return self.min_stack[-1]", "solution_java": "class MinStack {\n Stack stack = new Stack<>();\n Stack minStack = new Stack<>();\n public void push(int val) { stack.push(val); minStack.push(Math.min(val, minStack.isEmpty() ? val : minStack.peek())); }\n public void pop() { stack.pop(); minStack.pop(); }\n public int top() { return stack.peek(); }\n public int getMin() { return minStack.peek(); }\n}", "solution_cpp": "class MinStack {\n stack st, minSt;\npublic:\n void push(int val) { st.push(val); minSt.push(min(val, minSt.empty() ? val : minSt.top())); }\n void pop() { st.pop(); minSt.pop(); }\n int top() { return st.top(); }\n int getMin() { return minSt.top(); }\n};", "test_cases": ["push(-2), push(0), push(-3) -> getMin() returns -3"], "key_points": ["辅助栈记录最小值", "O(1)时间获取最小值"], "tags": ["stack", "medium", "Google", "Microsoft"]} {"problem_id": "algo_00599", "original_id": "lru-cache", "title": "LRU缓存", "category": "design", "difficulty": "hard", "companies": ["Google", "Amazon"], "description": "设计和实现一个 LRU(最近最少使用)缓存机制。", "solution_python": "class LRUCache:\n def __init__(self, capacity):\n self.capacity = capacity\n self.cache = {}\n self.order = []\n def get(self, key):\n if key not in self.cache: return -1\n self.order.remove(key); self.order.append(key)\n return self.cache[key]\n def put(self, key, value):\n if key in self.cache:\n self.order.remove(key)\n elif len(self.cache) >= self.capacity:\n del self.cache[self.order.pop(0)]\n self.cache[key] = value; self.order.append(key)", "solution_java": "class LRUCache {\n int capacity;\n LinkedHashMap cache = new LinkedHashMap<>();\n public LRUCache(int cap) { capacity = cap; }\n public int get(int key) { return cache.containsKey(key) ? cache.remove(key) : -1; }\n public void put(int key, int val) {\n if (cache.containsKey(key)) cache.remove(key);\n else if (cache.size() >= capacity) cache.remove(cache.keySet().iterator().next());\n cache.put(key, val);\n }\n}", "solution_cpp": "class LRUCache {\n int cap;\n list> dll;\n unordered_map>::iterator> cache;\npublic:\n LRUCache(int capacity) : cap(capacity) {}\n int get(int key) {\n auto it = cache.find(key);\n if (it == cache.end()) return -1;\n dll.splice(dll.end(), dll, it->second);\n return it->second->second;\n }\n void put(int key, int value) {\n auto it = cache.find(key);\n if (it != cache.end()) dll.erase(it->second);\n else if (cache.size() >= cap) { cache.erase(dll.front().first); dll.pop_front(); }\n dll.push_back({key, value});\n cache[key] = --dll.end();\n }\n};", "test_cases": ["put(1,1), put(2,2), get(1) -> 1"], "key_points": ["HashMap + 双向链表", "O(1)时间操作"], "tags": ["design", "hard", "Google", "Amazon"]} {"problem_id": "algo_00600", "original_id": "num-islands", "title": "岛屿数量", "category": "graph", "difficulty": "medium", "companies": ["Google", "Facebook"], "description": "给你一个由 '1'(陆地)和 '0'(水)组成的二维网格,请你计算网格中岛屿的数量。岛屿总是被水包围,且只能由水平或垂直方向相邻的陆地连接形成。", "solution_python": "def numIslands(grid):\n if not grid: return 0\n rows, cols = len(grid), len(grid[0])\n count = 0\n def dfs(r, c):\n if r < 0 or r >= rows or c < 0 or c >= cols or grid[r][c] != '1': return\n grid[r][c] = '0'\n dfs(r+1, c); dfs(r-1, c); dfs(r, c+1); dfs(r, c-1)\n for r in range(rows):\n for c in range(cols):\n if grid[r][c] == '1': count += 1; dfs(r, c)\n return count", "solution_java": "public int numIslands(char[][] grid) {\n if (grid.length == 0) return 0;\n int count = 0;\n for (int i = 0; i < grid.length; i++)\n for (int j = 0; j < grid[0].length; j++)\n if (grid[i][j] == '1') { count++; dfs(grid, i, j); }\n return count;\n}\nprivate void dfs(char[][] grid, int r, int c) {\n if (r < 0 || r >= grid.length || c < 0 || c >= grid[0].length || grid[r][c] != '1') return;\n grid[r][c] = '0';\n dfs(grid, r+1, c); dfs(grid, r-1, c); dfs(grid, r, c+1); dfs(grid, r, c-1);\n}", "solution_cpp": "int numIslands(vector>& grid) {\n if (grid.empty()) return 0;\n int count = 0;\n for (int i = 0; i < grid.size(); i++)\n for (int j = 0; j < grid[0].size(); j++)\n if (grid[i][j] == '1') { count++; dfs(grid, i, j); }\n return count;\n}\nvoid dfs(vector>& grid, int r, int c) {\n if (r < 0 || r >= grid.size() || c < 0 || c >= grid[0].size() || grid[r][c] != '1') return;\n grid[r][c] = '0';\n dfs(grid, r+1, c); dfs(grid, r-1, c); dfs(grid, r, c+1); dfs(grid, r, c-1);\n}", "test_cases": ["grid=[[1,1,1,1,0],[1,1,0,1,0],[1,1,0,0,0],[0,0,0,0,0]] -> 1"], "key_points": ["DFS/BFS遍历", "访问后标记为0避免重复"], "tags": ["graph", "medium", "Google", "Facebook"]} {"problem_id": "algo_00601", "original_id": "two-sum", "title": "两数之和", "category": "array", "difficulty": "easy", "companies": ["Amazon", "Google"], "description": "给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那两个整数,并返回他们的数组下标。", "solution_python": "def twoSum(nums, target):\n hashmap = {}\n for i, num in enumerate(nums):\n complement = target - num\n if complement in hashmap:\n return [hashmap[complement], i]\n hashmap[num] = i\n return []", "solution_java": "public int[] twoSum(int[] nums, int target) {\n Map map = new HashMap<>();\n for (int i = 0; i < nums.length; i++) {\n int complement = target - nums[i];\n if (map.containsKey(complement)) return new int[]{map.get(complement), i};\n map.put(nums[i], i);\n }\n return new int[]{};\n}", "solution_cpp": "vector twoSum(vector& nums, int target) {\n unordered_map m;\n for (int i = 0; i < nums.size(); i++) {\n if (m.count(target - nums[i])) return {m[target - nums[i]], i};\n m[nums[i]] = i;\n }\n return {};\n}", "test_cases": ["nums=[2,7,11,15], target=9 -> [0,1]", "nums=[3,2,4], target=6 -> [1,2]"], "key_points": ["哈希表一次遍历", "空间换时间"], "tags": ["array", "easy", "Amazon", "Google"]} {"problem_id": "algo_00602", "original_id": "merge-sorted", "title": "合并两个有序数组", "category": "array", "difficulty": "easy", "companies": ["Microsoft", "Uber"], "description": "给你两个按非递减顺序排列的整数数组 nums1 和 nums2,另有两个整数 m 和 n,分别表示 nums1 和 nums2 中的元素数目。请你合并 nums2 到 nums1 中。", "solution_python": "def merge(nums1, m, nums2, n):\n p1, p2, p = m-1, n-1, m+n-1\n while p1 >= 0 and p2 >= 0:\n if nums1[p1] > nums2[p2]: nums1[p] = nums1[p1]; p1 -= 1\n else: nums1[p] = nums2[p2]; p2 -= 1\n p -= 1\n while p2 >= 0: nums1[p] = nums2[p2]; p2 -= 1; p -= 1", "solution_java": "public void merge(int[] nums1, int m, int[] nums2, int n) {\n int p1 = m-1, p2 = n-1, p = m+n-1;\n while (p1 >= 0 && p2 >= 0) {\n nums1[p--] = nums1[p1] > nums2[p2] ? nums1[p1--] : nums2[p2--];\n }\n while (p2 >= 0) nums1[p--] = nums2[p2--];\n}", "solution_cpp": "void merge(vector& nums1, int m, vector& nums2, int n) {\n int p1 = m-1, p2 = n-1, p = m+n-1;\n while (p1 >= 0 && p2 >= 0) nums1[p--] = nums1[p1] > nums2[p2] ? nums1[p1--] : nums2[p2--];\n while (p2 >= 0) nums1[p--] = nums2[p2--];\n}", "test_cases": ["nums1=[1,2,3], m=3, nums2=[2,5,6], n=3 -> [1,2,2,3,5,6]", "nums1=[], m=0, nums2=[1], n=1 -> [1]"], "key_points": ["从后往前合并", "三指针技巧"], "tags": ["array", "easy", "Microsoft", "Uber"]} {"problem_id": "algo_00603", "original_id": "max-subarray", "title": "最大子数组和", "category": "array", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "给你一个整数数组 nums ,请你找出一个具有最大和的连续子数组,返回其最大和。", "solution_python": "def maxSubArray(nums):\n max_sum = current = nums[0]\n for num in nums[1:]:\n current = max(num, current + num)\n max_sum = max(max_sum, current)\n return max_sum", "solution_java": "public int maxSubArray(int[] nums) {\n int maxSum = nums[0], curr = nums[0];\n for (int i = 1; i < nums.length; i++) {\n curr = Math.max(nums[i], curr + nums[i]);\n maxSum = Math.max(maxSum, curr);\n }\n return maxSum;\n}", "solution_cpp": "int maxSubArray(vector& nums) {\n int maxSum = nums[0], curr = nums[0];\n for (int i = 1; i < nums.size(); i++) {\n curr = max(nums[i], curr + nums[i]);\n maxSum = max(maxSum, curr);\n }\n return maxSum;\n}", "test_cases": ["nums=[-2,1,-3,4,-1,2,1,-5,4] -> 6", "nums=[1] -> 1"], "key_points": ["Kadane算法", "动态规划基础题"], "tags": ["array", "medium", "Google", "Microsoft"]} {"problem_id": "algo_00604", "original_id": "valid-parentheses", "title": "有效的括号", "category": "string", "difficulty": "easy", "companies": ["Google", "Uber"], "description": "给定一个只包括 '(',')','{','}','[',']' 的字符串 s,判断字符串是否有效。", "solution_python": "def isValid(s):\n stack = []\n mapping = {')': '(', ']': '[', '}': '{'}\n for c in s:\n if c in mapping:\n if not stack or stack[-1] != mapping[c]: return False\n stack.pop()\n else: stack.append(c)\n return not stack", "solution_java": "public boolean isValid(String s) {\n Stack stack = new Stack<>();\n Map map = Map.of(')', '(', ']', '[', '}', '{');\n for (char c : s.toCharArray()) {\n if (map.containsValue(c)) stack.push(c);\n else if (!stack.isEmpty() && stack.pop() != map.get(c)) return false;\n }\n return stack.isEmpty();\n}", "solution_cpp": "bool isValid(string s) {\n stack st;\n unordered_map m = {{')','('},{']','['},{'}','{'}};\n for (char c : s) {\n if (m.find(c) == m.end()) st.push(c);\n else if (st.empty() || st.top() != m[c]) return false;\n else st.pop();\n }\n return st.empty();\n}", "test_cases": ["s=\"()\" -> true", "s=\"()[]{}\" -> true", "s=\"(]\" -> false"], "key_points": ["栈匹配法", "注意空栈边界"], "tags": ["string", "easy", "Google", "Uber"]} {"problem_id": "algo_00605", "original_id": "longest-palindrome", "title": "最长回文子串", "category": "string", "difficulty": "medium", "companies": ["Google", "Amazon"], "description": "给你一个字符串 s,找到 s 中最长的回文子串。", "solution_python": "def longestPalindrome(s):\n def expand(l, r):\n while l >= 0 and r < len(s) and s[l] == s[r]: l -= 1; r += 1\n return l + 1, r - 1\n start = end = 0\n for i in range(len(s)):\n l1, r1 = expand(i, i)\n l2, r2 = expand(i, i + 1)\n if r1 - l1 > end - start: start, end = l1, r1\n if r2 - l2 > end - start: start, end = l2, r2\n return s[start:end+1]", "solution_java": "public String longestPalindrome(String s) {\n int start = 0, end = 0;\n for (int i = 0; i < s.length(); i++) {\n int len1 = expand(s, i, i), len2 = expand(s, i, i+1);\n int len = Math.max(len1, len2);\n if (len > end - start) { start = i - (len-1)/2; end = i + len/2; }\n }\n return s.substring(start, end + 1);\n}\nprivate int expand(String s, int l, int r) {\n while (l >= 0 && r < s.length() && s.charAt(l) == s.charAt(r)) { l--; r++; }\n return r - l - 1;\n}", "solution_cpp": "string longestPalindrome(string s) {\n int start = 0, end = 0;\n for (int i = 0; i < s.size(); i++) {\n int len1 = expand(s, i, i), len2 = expand(s, i, i+1);\n if (max(len1, len2) > end - start) { start = i - (max(len1,len2)-1)/2; end = i + max(len1,len2)/2; }\n }\n return s.substr(start, end - start + 1);\n}", "test_cases": ["s=\"babad\" -> bab或aba", "s=\"cbbd\" -> bb"], "key_points": ["中心扩展法", "处理奇偶长度"], "tags": ["string", "medium", "Google", "Amazon"]} {"problem_id": "algo_00606", "original_id": "reverse-list", "title": "反转链表", "category": "linkedlist", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "给你单链表的头节点 head,请你反转链表,并返回反转后的链表。", "solution_python": "def reverseList(head):\n prev = None\n curr = head\n while curr:\n nxt = curr.next\n curr.next = prev\n prev = curr\n curr = nxt\n return prev", "solution_java": "public ListNode reverseList(ListNode head) {\n ListNode prev = null, curr = head;\n while (curr != null) {\n ListNode next = curr.next;\n curr.next = prev;\n prev = curr;\n curr = next;\n }\n return prev;\n}", "solution_cpp": "ListNode* reverseList(ListNode* head) {\n ListNode* prev = nullptr, *curr = head;\n while (curr) {\n ListNode* next = curr->next;\n curr->next = prev;\n prev = curr;\n curr = next;\n }\n return prev;\n}", "test_cases": ["head=[1,2,3,4,5] -> [5,4,3,2,1]", "head=[1,2] -> [2,1]"], "key_points": ["迭代法 O(1)空间", "递归法 O(n)空间"], "tags": ["linkedlist", "medium", "Google", "Microsoft"]} {"problem_id": "algo_00607", "original_id": "middle-node", "title": "链表的中间结点", "category": "linkedlist", "difficulty": "easy", "companies": ["Amazon", "Facebook"], "description": "给你单链表的头节点 head,请你找出并返回链表的中间结点。如果有两个中间结点,则返回第二个中间结点。", "solution_python": "def middleNode(head):\n slow = fast = head\n while fast and fast.next:\n slow = slow.next\n fast = fast.next.next\n return slow", "solution_java": "public ListNode middleNode(ListNode head) {\n ListNode slow = head, fast = head;\n while (fast != null && fast.next != null) {\n slow = slow.next;\n fast = fast.next.next;\n }\n return slow;\n}", "solution_cpp": "ListNode* middleNode(ListNode* head) {\n ListNode* slow = head, *fast = head;\n while (fast && fast->next) { slow = slow->next; fast = fast->next->next; }\n return slow;\n}", "test_cases": ["head=[1,2,3,4,5] -> 3", "head=[1,2,3,4,5,6] -> 4"], "key_points": ["快慢指针", "O(n)时间O(1)空间"], "tags": ["linkedlist", "easy", "Amazon", "Facebook"]} {"problem_id": "algo_00608", "original_id": "max-depth", "title": "二叉树的最大深度", "category": "tree", "difficulty": "easy", "companies": ["Microsoft", "Apple"], "description": "给定一个二叉树 root,返回其最大深度。", "solution_python": "def maxDepth(root):\n if not root: return 0\n return max(maxDepth(root.left), maxDepth(root.right)) + 1", "solution_java": "public int maxDepth(TreeNode root) {\n if (root == null) return 0;\n return Math.max(maxDepth(root.left), maxDepth(root.right)) + 1;\n}", "solution_cpp": "int maxDepth(TreeNode* root) {\n if (!root) return 0;\n return max(maxDepth(root->left), maxDepth(root->right)) + 1;\n}", "test_cases": ["root=[3,9,20,null,null,15,7] -> 3", "root=[1,null,2] -> 2"], "key_points": ["DFS递归", "层序遍历也可"], "tags": ["tree", "easy", "Microsoft", "Apple"]} {"problem_id": "algo_00609", "original_id": "inorder-traversal", "title": "二叉树的中序遍历", "category": "tree", "difficulty": "easy", "companies": ["Google", "Microsoft"], "description": "给定一个二叉树的根节点 root,返回它的中序遍历结果。", "solution_python": "def inorderTraversal(root):\n result = []\n def dfs(node):\n if node:\n dfs(node.left)\n result.append(node.val)\n dfs(node.right)\n dfs(root)\n return result", "solution_java": "public List inorderTraversal(TreeNode root) {\n List res = new ArrayList<>();\n dfs(root, res);\n return res;\n}\nprivate void dfs(TreeNode node, List res) {\n if (node == null) return;\n dfs(node.left, res); res.add(node.val); dfs(node.right, res);\n}", "solution_cpp": "vector inorderTraversal(TreeNode* root) {\n vector res;\n dfs(root, res);\n return res;\n}\nvoid dfs(TreeNode* node, vector& res) {\n if (!node) return;\n dfs(node->left, res); res.push_back(node->val); dfs(node->right, res);\n}", "test_cases": ["root=[1,null,2,3] -> [1,3,2]", "root=[] -> []"], "key_points": ["左-根-右顺序", "递归最简洁"], "tags": ["tree", "easy", "Google", "Microsoft"]} {"problem_id": "algo_00610", "original_id": "binary-search", "title": "二分查找", "category": "binarysearch", "difficulty": "easy", "companies": ["Google", "Amazon"], "description": "给定一个 n 个元素有序的(升序)整型数组 nums 和一个目标值 target,写一个函数搜索 nums 中的 target,如果目标值存在返回下标,否则返回 -1。", "solution_python": "def search(nums, target):\n left, right = 0, len(nums) - 1\n while left <= right:\n mid = (left + right) // 2\n if nums[mid] == target: return mid\n elif nums[mid] < target: left = mid + 1\n else: right = mid - 1\n return -1", "solution_java": "public int search(int[] nums, int target) {\n int left = 0, right = nums.length - 1;\n while (left <= right) {\n int mid = left + (right - left) / 2;\n if (nums[mid] == target) return mid;\n else if (nums[mid] < target) left = mid + 1;\n else right = mid - 1;\n }\n return -1;\n}", "solution_cpp": "int search(vector& nums, int target) {\n int left = 0, right = nums.size() - 1;\n while (left <= right) {\n int mid = left + (right - left) / 2;\n if (nums[mid] == target) return mid;\n else if (nums[mid] < target) left = mid + 1;\n else right = mid - 1;\n }\n return -1;\n}", "test_cases": ["nums=[-1,0,3,5,9,12], target=9 -> 4", "nums=[-1,0,3,5,9,12], target=2 -> -1"], "key_points": ["标准模板", "注意防溢出写法"], "tags": ["binarysearch", "easy", "Google", "Amazon"]} {"problem_id": "algo_00611", "original_id": "climbing-stairs", "title": "爬楼梯", "category": "dp", "difficulty": "easy", "companies": ["Amazon", "Google"], "description": "假设你正在爬楼梯。需要 n 阶你才能到达楼顶。每次你可以爬 1 或 2 个台阶。你有多少种不同的方法可以爬到楼顶?", "solution_python": "def climbStairs(n):\n if n <= 2: return n\n a, b = 1, 2\n for _ in range(3, n+1):\n a, b = b, a + b\n return b", "solution_java": "public int climbStairs(int n) {\n if (n <= 2) return n;\n int a = 1, b = 2;\n for (int i = 3; i <= n; i++) { int temp = a + b; a = b; b = temp; }\n return b;\n}", "solution_cpp": "int climbStairs(int n) {\n if (n <= 2) return n;\n int a = 1, b = 2;\n for (int i = 3; i <= n; i++) { int temp = a + b; a = b; b = temp; }\n return b;\n}", "test_cases": ["n=2 -> 2", "n=3 -> 3", "n=5 -> 8"], "key_points": ["斐波那契数列", "滚动数组优化空间"], "tags": ["dp", "easy", "Amazon", "Google"]} {"problem_id": "algo_00612", "original_id": "coin-change", "title": "零钱兑换", "category": "dp", "difficulty": "medium", "companies": ["Google", "Amazon"], "description": "给你一个整数数组 coins 表示不同面额的硬币,以及一个整数 amount 表示总金额。计算并返回可以凑成总金额所需的最少的硬币个数。如果没有任何一种硬币组合能组成总金额,返回 -1。", "solution_python": "def coinChange(coins, amount):\n dp = [float('inf')] * (amount + 1)\n dp[0] = 0\n for coin in coins:\n for x in range(coin, amount + 1):\n dp[x] = min(dp[x], dp[x - coin] + 1)\n return dp[amount] if dp[amount] != float('inf') else -1", "solution_java": "public int coinChange(int[] coins, int amount) {\n int[] dp = new int[amount + 1];\n Arrays.fill(dp, amount + 1);\n dp[0] = 0;\n for (int coin : coins) {\n for (int x = coin; x <= amount; x++) {\n dp[x] = Math.min(dp[x], dp[x - coin] + 1);\n }\n }\n return dp[amount] > amount ? -1 : dp[amount];\n}", "solution_cpp": "int coinChange(vector& coins, int amount) {\n vector dp(amount + 1, amount + 1);\n dp[0] = 0;\n for (int coin : coins) {\n for (int x = coin; x <= amount; x++) {\n dp[x] = min(dp[x], dp[x - coin] + 1);\n }\n }\n return dp[amount] > amount ? -1 : dp[amount];\n}", "test_cases": ["coins=[1,2,5], amount=11 -> 3", "coins=[2], amount=3 -> -1"], "key_points": ["完全背包问题", "dp[x] = min(dp[x-coin]+1)"], "tags": ["dp", "medium", "Google", "Amazon"]} {"problem_id": "algo_00613", "original_id": "subsets", "title": "子集", "category": "backtracking", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "给你一个整数数组 nums ,数组中的元素 互不相同 。返回该数组所有可能的子集(幂集)。", "solution_python": "def subsets(nums):\n result = []\n def backtrack(start, path):\n result.append(path[:])\n for i in range(start, len(nums)):\n path.append(nums[i])\n backtrack(i + 1, path)\n path.pop()\n backtrack(0, [])\n return result", "solution_java": "public List> subsets(int[] nums) {\n List> result = new ArrayList<>();\n backtrack(nums, 0, new ArrayList<>(), result);\n return result;\n}\nprivate void backtrack(int[] nums, int start, List path, List> result) {\n result.add(new ArrayList<>(path));\n for (int i = start; i < nums.length; i++) {\n path.add(nums[i]);\n backtrack(nums, i + 1, path, result);\n path.remove(path.size() - 1);\n }\n}", "solution_cpp": "vector> subsets(vector& nums) {\n vector> result;\n vector path;\n backtrack(nums, 0, path, result);\n return result;\n}\nvoid backtrack(vector& nums, int start, vector& path, vector>& result) {\n result.push_back(path);\n for (int i = start; i < nums.size(); i++) {\n path.push_back(nums[i]);\n backtrack(nums, i + 1, path, result);\n path.pop_back();\n }\n}", "test_cases": ["nums=[1,2,3] -> [[],[1],[2],[1,2],[3],[1,3],[2,3],[1,2,3]]"], "key_points": ["选或不选", "DFS遍历子集树"], "tags": ["backtracking", "medium", "Google", "Microsoft"]} {"problem_id": "algo_00614", "original_id": "permutations", "title": "全排列", "category": "backtracking", "difficulty": "medium", "companies": ["Google", "Facebook"], "description": "给定一个不含重复数字的数组 nums,返回其所有可能的全排列。", "solution_python": "def permute(nums):\n result = []\n def backtrack(path, used):\n if len(path) == len(nums):\n result.append(path[:])\n return\n for i in range(len(nums)):\n if used[i]: continue\n used[i] = True\n path.append(nums[i])\n backtrack(path, used)\n path.pop()\n used[i] = False\n backtrack([], [False]*len(nums))\n return result", "solution_java": "public List> permute(int[] nums) {\n List> result = new ArrayList<>();\n boolean[] used = new boolean[nums.length];\n backtrack(nums, used, new ArrayList<>(), result);\n return result;\n}\nprivate void backtrack(int[] nums, boolean[] used, List path, List> result) {\n if (path.size() == nums.length) { result.add(new ArrayList<>(path)); return; }\n for (int i = 0; i < nums.length; i++) {\n if (used[i]) continue;\n used[i] = true;\n path.add(nums[i]);\n backtrack(nums, used, path, result);\n path.remove(path.size() - 1);\n used[i] = false;\n }\n}", "solution_cpp": "vector> permute(vector& nums) {\n vector> result;\n vector used(nums.size(), false);\n vector path;\n backtrack(nums, used, path, result);\n return result;\n}\nvoid backtrack(vector& nums, vector& used, vector& path, vector>& result) {\n if (path.size() == nums.size()) { result.push_back(path); return; }\n for (int i = 0; i < nums.size(); i++) {\n if (used[i]) continue;\n used[i] = true;\n path.push_back(nums[i]);\n backtrack(nums, used, path, result);\n path.pop_back();\n used[i] = false;\n }\n}", "test_cases": ["nums=[1,2,3] -> [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]"], "key_points": ["标记已使用元素", "回溯经典模板"], "tags": ["backtracking", "medium", "Google", "Facebook"]} {"problem_id": "algo_00615", "original_id": "top-k-frequent", "title": "前K个高频元素", "category": "heap", "difficulty": "medium", "companies": ["Amazon", "Facebook"], "description": "给你一个整数数组 nums 和一个整数 k,请你返回其中出现频率前 k 高的元素。", "solution_python": "import heapq\nfrom collections import Counter\ndef topKFrequent(nums, k):\n count = Counter(nums)\n heap = []\n for num, freq in count.items():\n heapq.heappush(heap, (freq, num))\n if len(heap) > k: heapq.heappop(heap)\n return [num for freq, num in heap]", "solution_java": "public int[] topKFrequent(int[] nums, int k) {\n Map count = new HashMap<>();\n for (int n : nums) count.put(n, count.getOrDefault(n, 0) + 1);\n PriorityQueue> heap = \n new PriorityQueue<>((a, b) -> a.getValue() - b.getValue());\n for (Map.Entry e : count.entrySet()) {\n heap.offer(e);\n if (heap.size() > k) heap.poll();\n }\n int[] res = new int[k];\n for (int i = k - 1; i >= 0; i--) res[i] = heap.poll().getKey();\n return res;\n}", "solution_cpp": "vector topKFrequent(vector& nums, int k) {\n unordered_map count;\n for (int n : nums) count[n]++;\n priority_queue, vector>, greater>> heap;\n for (auto& [num, freq] : count) {\n heap.push({freq, num});\n if (heap.size() > k) heap.pop();\n }\n vector res;\n while (!heap.empty()) { res.push_back(heap.top().second); heap.pop(); }\n reverse(res.begin(), res.end());\n return res;\n}", "test_cases": ["nums=[1,1,1,2,2,3], k=2 -> [1,2]", "nums=[1], k=1 -> [1]"], "key_points": ["小顶堆保持大小k", "时间复杂度O(nlogk)"], "tags": ["heap", "medium", "Amazon", "Facebook"]} {"problem_id": "algo_00616", "original_id": "3sum", "title": "三数之和", "category": "two-pointers", "difficulty": "medium", "companies": ["Google", "Amazon"], "description": "给你一个整数数组 nums,判断是否存在三元组满足和为0,返回所有不重复的三元组。", "solution_python": "def threeSum(nums):\n nums.sort()\n result = []\n for i in range(len(nums) - 2):\n if i > 0 and nums[i] == nums[i-1]: continue\n left, right = i + 1, len(nums) - 1\n while left < right:\n total = nums[i] + nums[left] + nums[right]\n if total < 0: left += 1\n elif total > 0: right -= 1\n else:\n result.append([nums[i], nums[left], nums[right]])\n while left < right and nums[left] == nums[left+1]: left += 1\n while left < right and nums[right] == nums[right-1]: right -= 1\n left += 1; right -= 1\n return result", "solution_java": "public List> threeSum(int[] nums) {\n Arrays.sort(nums);\n List> result = new ArrayList<>();\n for (int i = 0; i < nums.length - 2; i++) {\n if (i > 0 && nums[i] == nums[i-1]) continue;\n int left = i + 1, right = nums.length - 1;\n while (left < right) {\n int total = nums[i] + nums[left] + nums[right];\n if (total < 0) left++;\n else if (total > 0) right--;\n else {\n result.add(Arrays.asList(nums[i], nums[left], nums[right]));\n while (left < right && nums[left] == nums[left+1]) left++;\n while (left < right && nums[right] == nums[right-1]) right--;\n left++; right--;\n }\n }\n }\n return result;\n}", "solution_cpp": "vector> threeSum(vector& nums) {\n sort(nums.begin(), nums.end());\n vector> result;\n for (int i = 0; i < nums.size() - 2; i++) {\n if (i > 0 && nums[i] == nums[i-1]) continue;\n int left = i + 1, right = nums.size() - 1;\n while (left < right) {\n int total = nums[i] + nums[left] + nums[right];\n if (total < 0) left++;\n else if (total > 0) right--;\n else {\n result.push_back({nums[i], nums[left], nums[right]});\n while (left < right && nums[left] == nums[left+1]) left++;\n while (left < right && nums[right] == nums[right-1]) right--;\n left++; right--;\n }\n }\n }\n return result;\n}", "test_cases": ["nums=[-1,0,1,2,-1,-4] -> [[-1,-1,2],[-1,0,1]]"], "key_points": ["排序+双指针", "去重是关键"], "tags": ["two-pointers", "medium", "Google", "Amazon"]} {"problem_id": "algo_00617", "original_id": "container-water", "title": "盛最多水的容器", "category": "two-pointers", "difficulty": "medium", "companies": ["Google", "Uber"], "description": "给定一个长度为 n 的整数数组 height,找出其中的两条线,使得它们与 x 轴共同构成的容器可以容纳最多的水。", "solution_python": "def maxArea(height):\n left, right = 0, len(height) - 1\n max_area = 0\n while left < right:\n h = min(height[left], height[right])\n max_area = max(max_area, h * (right - left))\n if height[left] < height[right]: left += 1\n else: right -= 1\n return max_area", "solution_java": "public int maxArea(int[] height) {\n int left = 0, right = height.length - 1, maxArea = 0;\n while (left < right) {\n int h = Math.min(height[left], height[right]);\n maxArea = Math.max(maxArea, h * (right - left));\n if (height[left] < height[right]) left++;\n else right--;\n }\n return maxArea;\n}", "solution_cpp": "int maxArea(vector& height) {\n int left = 0, right = height.size() - 1, maxArea = 0;\n while (left < right) {\n int h = min(height[left], height[right]);\n maxArea = max(maxArea, h * (right - left));\n if (height[left] < height[right]) left++;\n else right--;\n }\n return maxArea;\n}", "test_cases": ["height=[1,8,6,2,5,4,8,3,7] -> 49"], "key_points": ["移动短边指针", "面积=min(h1,h2)*width"], "tags": ["two-pointers", "medium", "Google", "Uber"]} {"problem_id": "algo_00618", "original_id": "min-stack", "title": "最小栈", "category": "stack", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "设计一个支持 push,pop,top 操作,并能在常数时间内检索到最小元素的栈。", "solution_python": "class MinStack:\n def __init__(self):\n self.stack = []\n self.min_stack = []\n def push(self, val):\n self.stack.append(val)\n self.min_stack.append(min(val, self.min_stack[-1] if self.min_stack else val))\n def pop(self):\n self.stack.pop(); self.min_stack.pop()\n def top(self): return self.stack[-1]\n def getMin(self): return self.min_stack[-1]", "solution_java": "class MinStack {\n Stack stack = new Stack<>();\n Stack minStack = new Stack<>();\n public void push(int val) { stack.push(val); minStack.push(Math.min(val, minStack.isEmpty() ? val : minStack.peek())); }\n public void pop() { stack.pop(); minStack.pop(); }\n public int top() { return stack.peek(); }\n public int getMin() { return minStack.peek(); }\n}", "solution_cpp": "class MinStack {\n stack st, minSt;\npublic:\n void push(int val) { st.push(val); minSt.push(min(val, minSt.empty() ? val : minSt.top())); }\n void pop() { st.pop(); minSt.pop(); }\n int top() { return st.top(); }\n int getMin() { return minSt.top(); }\n};", "test_cases": ["push(-2), push(0), push(-3) -> getMin() returns -3"], "key_points": ["辅助栈记录最小值", "O(1)时间获取最小值"], "tags": ["stack", "medium", "Google", "Microsoft"]} {"problem_id": "algo_00619", "original_id": "lru-cache", "title": "LRU缓存", "category": "design", "difficulty": "hard", "companies": ["Google", "Amazon"], "description": "设计和实现一个 LRU(最近最少使用)缓存机制。", "solution_python": "class LRUCache:\n def __init__(self, capacity):\n self.capacity = capacity\n self.cache = {}\n self.order = []\n def get(self, key):\n if key not in self.cache: return -1\n self.order.remove(key); self.order.append(key)\n return self.cache[key]\n def put(self, key, value):\n if key in self.cache:\n self.order.remove(key)\n elif len(self.cache) >= self.capacity:\n del self.cache[self.order.pop(0)]\n self.cache[key] = value; self.order.append(key)", "solution_java": "class LRUCache {\n int capacity;\n LinkedHashMap cache = new LinkedHashMap<>();\n public LRUCache(int cap) { capacity = cap; }\n public int get(int key) { return cache.containsKey(key) ? cache.remove(key) : -1; }\n public void put(int key, int val) {\n if (cache.containsKey(key)) cache.remove(key);\n else if (cache.size() >= capacity) cache.remove(cache.keySet().iterator().next());\n cache.put(key, val);\n }\n}", "solution_cpp": "class LRUCache {\n int cap;\n list> dll;\n unordered_map>::iterator> cache;\npublic:\n LRUCache(int capacity) : cap(capacity) {}\n int get(int key) {\n auto it = cache.find(key);\n if (it == cache.end()) return -1;\n dll.splice(dll.end(), dll, it->second);\n return it->second->second;\n }\n void put(int key, int value) {\n auto it = cache.find(key);\n if (it != cache.end()) dll.erase(it->second);\n else if (cache.size() >= cap) { cache.erase(dll.front().first); dll.pop_front(); }\n dll.push_back({key, value});\n cache[key] = --dll.end();\n }\n};", "test_cases": ["put(1,1), put(2,2), get(1) -> 1"], "key_points": ["HashMap + 双向链表", "O(1)时间操作"], "tags": ["design", "hard", "Google", "Amazon"]} {"problem_id": "algo_00620", "original_id": "num-islands", "title": "岛屿数量", "category": "graph", "difficulty": "medium", "companies": ["Google", "Facebook"], "description": "给你一个由 '1'(陆地)和 '0'(水)组成的二维网格,请你计算网格中岛屿的数量。岛屿总是被水包围,且只能由水平或垂直方向相邻的陆地连接形成。", "solution_python": "def numIslands(grid):\n if not grid: return 0\n rows, cols = len(grid), len(grid[0])\n count = 0\n def dfs(r, c):\n if r < 0 or r >= rows or c < 0 or c >= cols or grid[r][c] != '1': return\n grid[r][c] = '0'\n dfs(r+1, c); dfs(r-1, c); dfs(r, c+1); dfs(r, c-1)\n for r in range(rows):\n for c in range(cols):\n if grid[r][c] == '1': count += 1; dfs(r, c)\n return count", "solution_java": "public int numIslands(char[][] grid) {\n if (grid.length == 0) return 0;\n int count = 0;\n for (int i = 0; i < grid.length; i++)\n for (int j = 0; j < grid[0].length; j++)\n if (grid[i][j] == '1') { count++; dfs(grid, i, j); }\n return count;\n}\nprivate void dfs(char[][] grid, int r, int c) {\n if (r < 0 || r >= grid.length || c < 0 || c >= grid[0].length || grid[r][c] != '1') return;\n grid[r][c] = '0';\n dfs(grid, r+1, c); dfs(grid, r-1, c); dfs(grid, r, c+1); dfs(grid, r, c-1);\n}", "solution_cpp": "int numIslands(vector>& grid) {\n if (grid.empty()) return 0;\n int count = 0;\n for (int i = 0; i < grid.size(); i++)\n for (int j = 0; j < grid[0].size(); j++)\n if (grid[i][j] == '1') { count++; dfs(grid, i, j); }\n return count;\n}\nvoid dfs(vector>& grid, int r, int c) {\n if (r < 0 || r >= grid.size() || c < 0 || c >= grid[0].size() || grid[r][c] != '1') return;\n grid[r][c] = '0';\n dfs(grid, r+1, c); dfs(grid, r-1, c); dfs(grid, r, c+1); dfs(grid, r, c-1);\n}", "test_cases": ["grid=[[1,1,1,1,0],[1,1,0,1,0],[1,1,0,0,0],[0,0,0,0,0]] -> 1"], "key_points": ["DFS/BFS遍历", "访问后标记为0避免重复"], "tags": ["graph", "medium", "Google", "Facebook"]} {"problem_id": "algo_00621", "original_id": "two-sum", "title": "两数之和", "category": "array", "difficulty": "easy", "companies": ["Amazon", "Google"], "description": "给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那两个整数,并返回他们的数组下标。", "solution_python": "def twoSum(nums, target):\n hashmap = {}\n for i, num in enumerate(nums):\n complement = target - num\n if complement in hashmap:\n return [hashmap[complement], i]\n hashmap[num] = i\n return []", "solution_java": "public int[] twoSum(int[] nums, int target) {\n Map map = new HashMap<>();\n for (int i = 0; i < nums.length; i++) {\n int complement = target - nums[i];\n if (map.containsKey(complement)) return new int[]{map.get(complement), i};\n map.put(nums[i], i);\n }\n return new int[]{};\n}", "solution_cpp": "vector twoSum(vector& nums, int target) {\n unordered_map m;\n for (int i = 0; i < nums.size(); i++) {\n if (m.count(target - nums[i])) return {m[target - nums[i]], i};\n m[nums[i]] = i;\n }\n return {};\n}", "test_cases": ["nums=[2,7,11,15], target=9 -> [0,1]", "nums=[3,2,4], target=6 -> [1,2]"], "key_points": ["哈希表一次遍历", "空间换时间"], "tags": ["array", "easy", "Amazon", "Google"]} {"problem_id": "algo_00622", "original_id": "merge-sorted", "title": "合并两个有序数组", "category": "array", "difficulty": "easy", "companies": ["Microsoft", "Uber"], "description": "给你两个按非递减顺序排列的整数数组 nums1 和 nums2,另有两个整数 m 和 n,分别表示 nums1 和 nums2 中的元素数目。请你合并 nums2 到 nums1 中。", "solution_python": "def merge(nums1, m, nums2, n):\n p1, p2, p = m-1, n-1, m+n-1\n while p1 >= 0 and p2 >= 0:\n if nums1[p1] > nums2[p2]: nums1[p] = nums1[p1]; p1 -= 1\n else: nums1[p] = nums2[p2]; p2 -= 1\n p -= 1\n while p2 >= 0: nums1[p] = nums2[p2]; p2 -= 1; p -= 1", "solution_java": "public void merge(int[] nums1, int m, int[] nums2, int n) {\n int p1 = m-1, p2 = n-1, p = m+n-1;\n while (p1 >= 0 && p2 >= 0) {\n nums1[p--] = nums1[p1] > nums2[p2] ? nums1[p1--] : nums2[p2--];\n }\n while (p2 >= 0) nums1[p--] = nums2[p2--];\n}", "solution_cpp": "void merge(vector& nums1, int m, vector& nums2, int n) {\n int p1 = m-1, p2 = n-1, p = m+n-1;\n while (p1 >= 0 && p2 >= 0) nums1[p--] = nums1[p1] > nums2[p2] ? nums1[p1--] : nums2[p2--];\n while (p2 >= 0) nums1[p--] = nums2[p2--];\n}", "test_cases": ["nums1=[1,2,3], m=3, nums2=[2,5,6], n=3 -> [1,2,2,3,5,6]", "nums1=[], m=0, nums2=[1], n=1 -> [1]"], "key_points": ["从后往前合并", "三指针技巧"], "tags": ["array", "easy", "Microsoft", "Uber"]} {"problem_id": "algo_00623", "original_id": "max-subarray", "title": "最大子数组和", "category": "array", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "给你一个整数数组 nums ,请你找出一个具有最大和的连续子数组,返回其最大和。", "solution_python": "def maxSubArray(nums):\n max_sum = current = nums[0]\n for num in nums[1:]:\n current = max(num, current + num)\n max_sum = max(max_sum, current)\n return max_sum", "solution_java": "public int maxSubArray(int[] nums) {\n int maxSum = nums[0], curr = nums[0];\n for (int i = 1; i < nums.length; i++) {\n curr = Math.max(nums[i], curr + nums[i]);\n maxSum = Math.max(maxSum, curr);\n }\n return maxSum;\n}", "solution_cpp": "int maxSubArray(vector& nums) {\n int maxSum = nums[0], curr = nums[0];\n for (int i = 1; i < nums.size(); i++) {\n curr = max(nums[i], curr + nums[i]);\n maxSum = max(maxSum, curr);\n }\n return maxSum;\n}", "test_cases": ["nums=[-2,1,-3,4,-1,2,1,-5,4] -> 6", "nums=[1] -> 1"], "key_points": ["Kadane算法", "动态规划基础题"], "tags": ["array", "medium", "Google", "Microsoft"]} {"problem_id": "algo_00624", "original_id": "valid-parentheses", "title": "有效的括号", "category": "string", "difficulty": "easy", "companies": ["Google", "Uber"], "description": "给定一个只包括 '(',')','{','}','[',']' 的字符串 s,判断字符串是否有效。", "solution_python": "def isValid(s):\n stack = []\n mapping = {')': '(', ']': '[', '}': '{'}\n for c in s:\n if c in mapping:\n if not stack or stack[-1] != mapping[c]: return False\n stack.pop()\n else: stack.append(c)\n return not stack", "solution_java": "public boolean isValid(String s) {\n Stack stack = new Stack<>();\n Map map = Map.of(')', '(', ']', '[', '}', '{');\n for (char c : s.toCharArray()) {\n if (map.containsValue(c)) stack.push(c);\n else if (!stack.isEmpty() && stack.pop() != map.get(c)) return false;\n }\n return stack.isEmpty();\n}", "solution_cpp": "bool isValid(string s) {\n stack st;\n unordered_map m = {{')','('},{']','['},{'}','{'}};\n for (char c : s) {\n if (m.find(c) == m.end()) st.push(c);\n else if (st.empty() || st.top() != m[c]) return false;\n else st.pop();\n }\n return st.empty();\n}", "test_cases": ["s=\"()\" -> true", "s=\"()[]{}\" -> true", "s=\"(]\" -> false"], "key_points": ["栈匹配法", "注意空栈边界"], "tags": ["string", "easy", "Google", "Uber"]} {"problem_id": "algo_00625", "original_id": "longest-palindrome", "title": "最长回文子串", "category": "string", "difficulty": "medium", "companies": ["Google", "Amazon"], "description": "给你一个字符串 s,找到 s 中最长的回文子串。", "solution_python": "def longestPalindrome(s):\n def expand(l, r):\n while l >= 0 and r < len(s) and s[l] == s[r]: l -= 1; r += 1\n return l + 1, r - 1\n start = end = 0\n for i in range(len(s)):\n l1, r1 = expand(i, i)\n l2, r2 = expand(i, i + 1)\n if r1 - l1 > end - start: start, end = l1, r1\n if r2 - l2 > end - start: start, end = l2, r2\n return s[start:end+1]", "solution_java": "public String longestPalindrome(String s) {\n int start = 0, end = 0;\n for (int i = 0; i < s.length(); i++) {\n int len1 = expand(s, i, i), len2 = expand(s, i, i+1);\n int len = Math.max(len1, len2);\n if (len > end - start) { start = i - (len-1)/2; end = i + len/2; }\n }\n return s.substring(start, end + 1);\n}\nprivate int expand(String s, int l, int r) {\n while (l >= 0 && r < s.length() && s.charAt(l) == s.charAt(r)) { l--; r++; }\n return r - l - 1;\n}", "solution_cpp": "string longestPalindrome(string s) {\n int start = 0, end = 0;\n for (int i = 0; i < s.size(); i++) {\n int len1 = expand(s, i, i), len2 = expand(s, i, i+1);\n if (max(len1, len2) > end - start) { start = i - (max(len1,len2)-1)/2; end = i + max(len1,len2)/2; }\n }\n return s.substr(start, end - start + 1);\n}", "test_cases": ["s=\"babad\" -> bab或aba", "s=\"cbbd\" -> bb"], "key_points": ["中心扩展法", "处理奇偶长度"], "tags": ["string", "medium", "Google", "Amazon"]} {"problem_id": "algo_00626", "original_id": "reverse-list", "title": "反转链表", "category": "linkedlist", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "给你单链表的头节点 head,请你反转链表,并返回反转后的链表。", "solution_python": "def reverseList(head):\n prev = None\n curr = head\n while curr:\n nxt = curr.next\n curr.next = prev\n prev = curr\n curr = nxt\n return prev", "solution_java": "public ListNode reverseList(ListNode head) {\n ListNode prev = null, curr = head;\n while (curr != null) {\n ListNode next = curr.next;\n curr.next = prev;\n prev = curr;\n curr = next;\n }\n return prev;\n}", "solution_cpp": "ListNode* reverseList(ListNode* head) {\n ListNode* prev = nullptr, *curr = head;\n while (curr) {\n ListNode* next = curr->next;\n curr->next = prev;\n prev = curr;\n curr = next;\n }\n return prev;\n}", "test_cases": ["head=[1,2,3,4,5] -> [5,4,3,2,1]", "head=[1,2] -> [2,1]"], "key_points": ["迭代法 O(1)空间", "递归法 O(n)空间"], "tags": ["linkedlist", "medium", "Google", "Microsoft"]} {"problem_id": "algo_00627", "original_id": "middle-node", "title": "链表的中间结点", "category": "linkedlist", "difficulty": "easy", "companies": ["Amazon", "Facebook"], "description": "给你单链表的头节点 head,请你找出并返回链表的中间结点。如果有两个中间结点,则返回第二个中间结点。", "solution_python": "def middleNode(head):\n slow = fast = head\n while fast and fast.next:\n slow = slow.next\n fast = fast.next.next\n return slow", "solution_java": "public ListNode middleNode(ListNode head) {\n ListNode slow = head, fast = head;\n while (fast != null && fast.next != null) {\n slow = slow.next;\n fast = fast.next.next;\n }\n return slow;\n}", "solution_cpp": "ListNode* middleNode(ListNode* head) {\n ListNode* slow = head, *fast = head;\n while (fast && fast->next) { slow = slow->next; fast = fast->next->next; }\n return slow;\n}", "test_cases": ["head=[1,2,3,4,5] -> 3", "head=[1,2,3,4,5,6] -> 4"], "key_points": ["快慢指针", "O(n)时间O(1)空间"], "tags": ["linkedlist", "easy", "Amazon", "Facebook"]} {"problem_id": "algo_00628", "original_id": "max-depth", "title": "二叉树的最大深度", "category": "tree", "difficulty": "easy", "companies": ["Microsoft", "Apple"], "description": "给定一个二叉树 root,返回其最大深度。", "solution_python": "def maxDepth(root):\n if not root: return 0\n return max(maxDepth(root.left), maxDepth(root.right)) + 1", "solution_java": "public int maxDepth(TreeNode root) {\n if (root == null) return 0;\n return Math.max(maxDepth(root.left), maxDepth(root.right)) + 1;\n}", "solution_cpp": "int maxDepth(TreeNode* root) {\n if (!root) return 0;\n return max(maxDepth(root->left), maxDepth(root->right)) + 1;\n}", "test_cases": ["root=[3,9,20,null,null,15,7] -> 3", "root=[1,null,2] -> 2"], "key_points": ["DFS递归", "层序遍历也可"], "tags": ["tree", "easy", "Microsoft", "Apple"]} {"problem_id": "algo_00629", "original_id": "inorder-traversal", "title": "二叉树的中序遍历", "category": "tree", "difficulty": "easy", "companies": ["Google", "Microsoft"], "description": "给定一个二叉树的根节点 root,返回它的中序遍历结果。", "solution_python": "def inorderTraversal(root):\n result = []\n def dfs(node):\n if node:\n dfs(node.left)\n result.append(node.val)\n dfs(node.right)\n dfs(root)\n return result", "solution_java": "public List inorderTraversal(TreeNode root) {\n List res = new ArrayList<>();\n dfs(root, res);\n return res;\n}\nprivate void dfs(TreeNode node, List res) {\n if (node == null) return;\n dfs(node.left, res); res.add(node.val); dfs(node.right, res);\n}", "solution_cpp": "vector inorderTraversal(TreeNode* root) {\n vector res;\n dfs(root, res);\n return res;\n}\nvoid dfs(TreeNode* node, vector& res) {\n if (!node) return;\n dfs(node->left, res); res.push_back(node->val); dfs(node->right, res);\n}", "test_cases": ["root=[1,null,2,3] -> [1,3,2]", "root=[] -> []"], "key_points": ["左-根-右顺序", "递归最简洁"], "tags": ["tree", "easy", "Google", "Microsoft"]} {"problem_id": "algo_00630", "original_id": "binary-search", "title": "二分查找", "category": "binarysearch", "difficulty": "easy", "companies": ["Google", "Amazon"], "description": "给定一个 n 个元素有序的(升序)整型数组 nums 和一个目标值 target,写一个函数搜索 nums 中的 target,如果目标值存在返回下标,否则返回 -1。", "solution_python": "def search(nums, target):\n left, right = 0, len(nums) - 1\n while left <= right:\n mid = (left + right) // 2\n if nums[mid] == target: return mid\n elif nums[mid] < target: left = mid + 1\n else: right = mid - 1\n return -1", "solution_java": "public int search(int[] nums, int target) {\n int left = 0, right = nums.length - 1;\n while (left <= right) {\n int mid = left + (right - left) / 2;\n if (nums[mid] == target) return mid;\n else if (nums[mid] < target) left = mid + 1;\n else right = mid - 1;\n }\n return -1;\n}", "solution_cpp": "int search(vector& nums, int target) {\n int left = 0, right = nums.size() - 1;\n while (left <= right) {\n int mid = left + (right - left) / 2;\n if (nums[mid] == target) return mid;\n else if (nums[mid] < target) left = mid + 1;\n else right = mid - 1;\n }\n return -1;\n}", "test_cases": ["nums=[-1,0,3,5,9,12], target=9 -> 4", "nums=[-1,0,3,5,9,12], target=2 -> -1"], "key_points": ["标准模板", "注意防溢出写法"], "tags": ["binarysearch", "easy", "Google", "Amazon"]} {"problem_id": "algo_00631", "original_id": "climbing-stairs", "title": "爬楼梯", "category": "dp", "difficulty": "easy", "companies": ["Amazon", "Google"], "description": "假设你正在爬楼梯。需要 n 阶你才能到达楼顶。每次你可以爬 1 或 2 个台阶。你有多少种不同的方法可以爬到楼顶?", "solution_python": "def climbStairs(n):\n if n <= 2: return n\n a, b = 1, 2\n for _ in range(3, n+1):\n a, b = b, a + b\n return b", "solution_java": "public int climbStairs(int n) {\n if (n <= 2) return n;\n int a = 1, b = 2;\n for (int i = 3; i <= n; i++) { int temp = a + b; a = b; b = temp; }\n return b;\n}", "solution_cpp": "int climbStairs(int n) {\n if (n <= 2) return n;\n int a = 1, b = 2;\n for (int i = 3; i <= n; i++) { int temp = a + b; a = b; b = temp; }\n return b;\n}", "test_cases": ["n=2 -> 2", "n=3 -> 3", "n=5 -> 8"], "key_points": ["斐波那契数列", "滚动数组优化空间"], "tags": ["dp", "easy", "Amazon", "Google"]} {"problem_id": "algo_00632", "original_id": "coin-change", "title": "零钱兑换", "category": "dp", "difficulty": "medium", "companies": ["Google", "Amazon"], "description": "给你一个整数数组 coins 表示不同面额的硬币,以及一个整数 amount 表示总金额。计算并返回可以凑成总金额所需的最少的硬币个数。如果没有任何一种硬币组合能组成总金额,返回 -1。", "solution_python": "def coinChange(coins, amount):\n dp = [float('inf')] * (amount + 1)\n dp[0] = 0\n for coin in coins:\n for x in range(coin, amount + 1):\n dp[x] = min(dp[x], dp[x - coin] + 1)\n return dp[amount] if dp[amount] != float('inf') else -1", "solution_java": "public int coinChange(int[] coins, int amount) {\n int[] dp = new int[amount + 1];\n Arrays.fill(dp, amount + 1);\n dp[0] = 0;\n for (int coin : coins) {\n for (int x = coin; x <= amount; x++) {\n dp[x] = Math.min(dp[x], dp[x - coin] + 1);\n }\n }\n return dp[amount] > amount ? -1 : dp[amount];\n}", "solution_cpp": "int coinChange(vector& coins, int amount) {\n vector dp(amount + 1, amount + 1);\n dp[0] = 0;\n for (int coin : coins) {\n for (int x = coin; x <= amount; x++) {\n dp[x] = min(dp[x], dp[x - coin] + 1);\n }\n }\n return dp[amount] > amount ? -1 : dp[amount];\n}", "test_cases": ["coins=[1,2,5], amount=11 -> 3", "coins=[2], amount=3 -> -1"], "key_points": ["完全背包问题", "dp[x] = min(dp[x-coin]+1)"], "tags": ["dp", "medium", "Google", "Amazon"]} {"problem_id": "algo_00633", "original_id": "subsets", "title": "子集", "category": "backtracking", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "给你一个整数数组 nums ,数组中的元素 互不相同 。返回该数组所有可能的子集(幂集)。", "solution_python": "def subsets(nums):\n result = []\n def backtrack(start, path):\n result.append(path[:])\n for i in range(start, len(nums)):\n path.append(nums[i])\n backtrack(i + 1, path)\n path.pop()\n backtrack(0, [])\n return result", "solution_java": "public List> subsets(int[] nums) {\n List> result = new ArrayList<>();\n backtrack(nums, 0, new ArrayList<>(), result);\n return result;\n}\nprivate void backtrack(int[] nums, int start, List path, List> result) {\n result.add(new ArrayList<>(path));\n for (int i = start; i < nums.length; i++) {\n path.add(nums[i]);\n backtrack(nums, i + 1, path, result);\n path.remove(path.size() - 1);\n }\n}", "solution_cpp": "vector> subsets(vector& nums) {\n vector> result;\n vector path;\n backtrack(nums, 0, path, result);\n return result;\n}\nvoid backtrack(vector& nums, int start, vector& path, vector>& result) {\n result.push_back(path);\n for (int i = start; i < nums.size(); i++) {\n path.push_back(nums[i]);\n backtrack(nums, i + 1, path, result);\n path.pop_back();\n }\n}", "test_cases": ["nums=[1,2,3] -> [[],[1],[2],[1,2],[3],[1,3],[2,3],[1,2,3]]"], "key_points": ["选或不选", "DFS遍历子集树"], "tags": ["backtracking", "medium", "Google", "Microsoft"]} {"problem_id": "algo_00634", "original_id": "permutations", "title": "全排列", "category": "backtracking", "difficulty": "medium", "companies": ["Google", "Facebook"], "description": "给定一个不含重复数字的数组 nums,返回其所有可能的全排列。", "solution_python": "def permute(nums):\n result = []\n def backtrack(path, used):\n if len(path) == len(nums):\n result.append(path[:])\n return\n for i in range(len(nums)):\n if used[i]: continue\n used[i] = True\n path.append(nums[i])\n backtrack(path, used)\n path.pop()\n used[i] = False\n backtrack([], [False]*len(nums))\n return result", "solution_java": "public List> permute(int[] nums) {\n List> result = new ArrayList<>();\n boolean[] used = new boolean[nums.length];\n backtrack(nums, used, new ArrayList<>(), result);\n return result;\n}\nprivate void backtrack(int[] nums, boolean[] used, List path, List> result) {\n if (path.size() == nums.length) { result.add(new ArrayList<>(path)); return; }\n for (int i = 0; i < nums.length; i++) {\n if (used[i]) continue;\n used[i] = true;\n path.add(nums[i]);\n backtrack(nums, used, path, result);\n path.remove(path.size() - 1);\n used[i] = false;\n }\n}", "solution_cpp": "vector> permute(vector& nums) {\n vector> result;\n vector used(nums.size(), false);\n vector path;\n backtrack(nums, used, path, result);\n return result;\n}\nvoid backtrack(vector& nums, vector& used, vector& path, vector>& result) {\n if (path.size() == nums.size()) { result.push_back(path); return; }\n for (int i = 0; i < nums.size(); i++) {\n if (used[i]) continue;\n used[i] = true;\n path.push_back(nums[i]);\n backtrack(nums, used, path, result);\n path.pop_back();\n used[i] = false;\n }\n}", "test_cases": ["nums=[1,2,3] -> [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]"], "key_points": ["标记已使用元素", "回溯经典模板"], "tags": ["backtracking", "medium", "Google", "Facebook"]} {"problem_id": "algo_00635", "original_id": "top-k-frequent", "title": "前K个高频元素", "category": "heap", "difficulty": "medium", "companies": ["Amazon", "Facebook"], "description": "给你一个整数数组 nums 和一个整数 k,请你返回其中出现频率前 k 高的元素。", "solution_python": "import heapq\nfrom collections import Counter\ndef topKFrequent(nums, k):\n count = Counter(nums)\n heap = []\n for num, freq in count.items():\n heapq.heappush(heap, (freq, num))\n if len(heap) > k: heapq.heappop(heap)\n return [num for freq, num in heap]", "solution_java": "public int[] topKFrequent(int[] nums, int k) {\n Map count = new HashMap<>();\n for (int n : nums) count.put(n, count.getOrDefault(n, 0) + 1);\n PriorityQueue> heap = \n new PriorityQueue<>((a, b) -> a.getValue() - b.getValue());\n for (Map.Entry e : count.entrySet()) {\n heap.offer(e);\n if (heap.size() > k) heap.poll();\n }\n int[] res = new int[k];\n for (int i = k - 1; i >= 0; i--) res[i] = heap.poll().getKey();\n return res;\n}", "solution_cpp": "vector topKFrequent(vector& nums, int k) {\n unordered_map count;\n for (int n : nums) count[n]++;\n priority_queue, vector>, greater>> heap;\n for (auto& [num, freq] : count) {\n heap.push({freq, num});\n if (heap.size() > k) heap.pop();\n }\n vector res;\n while (!heap.empty()) { res.push_back(heap.top().second); heap.pop(); }\n reverse(res.begin(), res.end());\n return res;\n}", "test_cases": ["nums=[1,1,1,2,2,3], k=2 -> [1,2]", "nums=[1], k=1 -> [1]"], "key_points": ["小顶堆保持大小k", "时间复杂度O(nlogk)"], "tags": ["heap", "medium", "Amazon", "Facebook"]} {"problem_id": "algo_00636", "original_id": "3sum", "title": "三数之和", "category": "two-pointers", "difficulty": "medium", "companies": ["Google", "Amazon"], "description": "给你一个整数数组 nums,判断是否存在三元组满足和为0,返回所有不重复的三元组。", "solution_python": "def threeSum(nums):\n nums.sort()\n result = []\n for i in range(len(nums) - 2):\n if i > 0 and nums[i] == nums[i-1]: continue\n left, right = i + 1, len(nums) - 1\n while left < right:\n total = nums[i] + nums[left] + nums[right]\n if total < 0: left += 1\n elif total > 0: right -= 1\n else:\n result.append([nums[i], nums[left], nums[right]])\n while left < right and nums[left] == nums[left+1]: left += 1\n while left < right and nums[right] == nums[right-1]: right -= 1\n left += 1; right -= 1\n return result", "solution_java": "public List> threeSum(int[] nums) {\n Arrays.sort(nums);\n List> result = new ArrayList<>();\n for (int i = 0; i < nums.length - 2; i++) {\n if (i > 0 && nums[i] == nums[i-1]) continue;\n int left = i + 1, right = nums.length - 1;\n while (left < right) {\n int total = nums[i] + nums[left] + nums[right];\n if (total < 0) left++;\n else if (total > 0) right--;\n else {\n result.add(Arrays.asList(nums[i], nums[left], nums[right]));\n while (left < right && nums[left] == nums[left+1]) left++;\n while (left < right && nums[right] == nums[right-1]) right--;\n left++; right--;\n }\n }\n }\n return result;\n}", "solution_cpp": "vector> threeSum(vector& nums) {\n sort(nums.begin(), nums.end());\n vector> result;\n for (int i = 0; i < nums.size() - 2; i++) {\n if (i > 0 && nums[i] == nums[i-1]) continue;\n int left = i + 1, right = nums.size() - 1;\n while (left < right) {\n int total = nums[i] + nums[left] + nums[right];\n if (total < 0) left++;\n else if (total > 0) right--;\n else {\n result.push_back({nums[i], nums[left], nums[right]});\n while (left < right && nums[left] == nums[left+1]) left++;\n while (left < right && nums[right] == nums[right-1]) right--;\n left++; right--;\n }\n }\n }\n return result;\n}", "test_cases": ["nums=[-1,0,1,2,-1,-4] -> [[-1,-1,2],[-1,0,1]]"], "key_points": ["排序+双指针", "去重是关键"], "tags": ["two-pointers", "medium", "Google", "Amazon"]} {"problem_id": "algo_00637", "original_id": "container-water", "title": "盛最多水的容器", "category": "two-pointers", "difficulty": "medium", "companies": ["Google", "Uber"], "description": "给定一个长度为 n 的整数数组 height,找出其中的两条线,使得它们与 x 轴共同构成的容器可以容纳最多的水。", "solution_python": "def maxArea(height):\n left, right = 0, len(height) - 1\n max_area = 0\n while left < right:\n h = min(height[left], height[right])\n max_area = max(max_area, h * (right - left))\n if height[left] < height[right]: left += 1\n else: right -= 1\n return max_area", "solution_java": "public int maxArea(int[] height) {\n int left = 0, right = height.length - 1, maxArea = 0;\n while (left < right) {\n int h = Math.min(height[left], height[right]);\n maxArea = Math.max(maxArea, h * (right - left));\n if (height[left] < height[right]) left++;\n else right--;\n }\n return maxArea;\n}", "solution_cpp": "int maxArea(vector& height) {\n int left = 0, right = height.size() - 1, maxArea = 0;\n while (left < right) {\n int h = min(height[left], height[right]);\n maxArea = max(maxArea, h * (right - left));\n if (height[left] < height[right]) left++;\n else right--;\n }\n return maxArea;\n}", "test_cases": ["height=[1,8,6,2,5,4,8,3,7] -> 49"], "key_points": ["移动短边指针", "面积=min(h1,h2)*width"], "tags": ["two-pointers", "medium", "Google", "Uber"]} {"problem_id": "algo_00638", "original_id": "min-stack", "title": "最小栈", "category": "stack", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "设计一个支持 push,pop,top 操作,并能在常数时间内检索到最小元素的栈。", "solution_python": "class MinStack:\n def __init__(self):\n self.stack = []\n self.min_stack = []\n def push(self, val):\n self.stack.append(val)\n self.min_stack.append(min(val, self.min_stack[-1] if self.min_stack else val))\n def pop(self):\n self.stack.pop(); self.min_stack.pop()\n def top(self): return self.stack[-1]\n def getMin(self): return self.min_stack[-1]", "solution_java": "class MinStack {\n Stack stack = new Stack<>();\n Stack minStack = new Stack<>();\n public void push(int val) { stack.push(val); minStack.push(Math.min(val, minStack.isEmpty() ? val : minStack.peek())); }\n public void pop() { stack.pop(); minStack.pop(); }\n public int top() { return stack.peek(); }\n public int getMin() { return minStack.peek(); }\n}", "solution_cpp": "class MinStack {\n stack st, minSt;\npublic:\n void push(int val) { st.push(val); minSt.push(min(val, minSt.empty() ? val : minSt.top())); }\n void pop() { st.pop(); minSt.pop(); }\n int top() { return st.top(); }\n int getMin() { return minSt.top(); }\n};", "test_cases": ["push(-2), push(0), push(-3) -> getMin() returns -3"], "key_points": ["辅助栈记录最小值", "O(1)时间获取最小值"], "tags": ["stack", "medium", "Google", "Microsoft"]} {"problem_id": "algo_00639", "original_id": "lru-cache", "title": "LRU缓存", "category": "design", "difficulty": "hard", "companies": ["Google", "Amazon"], "description": "设计和实现一个 LRU(最近最少使用)缓存机制。", "solution_python": "class LRUCache:\n def __init__(self, capacity):\n self.capacity = capacity\n self.cache = {}\n self.order = []\n def get(self, key):\n if key not in self.cache: return -1\n self.order.remove(key); self.order.append(key)\n return self.cache[key]\n def put(self, key, value):\n if key in self.cache:\n self.order.remove(key)\n elif len(self.cache) >= self.capacity:\n del self.cache[self.order.pop(0)]\n self.cache[key] = value; self.order.append(key)", "solution_java": "class LRUCache {\n int capacity;\n LinkedHashMap cache = new LinkedHashMap<>();\n public LRUCache(int cap) { capacity = cap; }\n public int get(int key) { return cache.containsKey(key) ? cache.remove(key) : -1; }\n public void put(int key, int val) {\n if (cache.containsKey(key)) cache.remove(key);\n else if (cache.size() >= capacity) cache.remove(cache.keySet().iterator().next());\n cache.put(key, val);\n }\n}", "solution_cpp": "class LRUCache {\n int cap;\n list> dll;\n unordered_map>::iterator> cache;\npublic:\n LRUCache(int capacity) : cap(capacity) {}\n int get(int key) {\n auto it = cache.find(key);\n if (it == cache.end()) return -1;\n dll.splice(dll.end(), dll, it->second);\n return it->second->second;\n }\n void put(int key, int value) {\n auto it = cache.find(key);\n if (it != cache.end()) dll.erase(it->second);\n else if (cache.size() >= cap) { cache.erase(dll.front().first); dll.pop_front(); }\n dll.push_back({key, value});\n cache[key] = --dll.end();\n }\n};", "test_cases": ["put(1,1), put(2,2), get(1) -> 1"], "key_points": ["HashMap + 双向链表", "O(1)时间操作"], "tags": ["design", "hard", "Google", "Amazon"]} {"problem_id": "algo_00640", "original_id": "num-islands", "title": "岛屿数量", "category": "graph", "difficulty": "medium", "companies": ["Google", "Facebook"], "description": "给你一个由 '1'(陆地)和 '0'(水)组成的二维网格,请你计算网格中岛屿的数量。岛屿总是被水包围,且只能由水平或垂直方向相邻的陆地连接形成。", "solution_python": "def numIslands(grid):\n if not grid: return 0\n rows, cols = len(grid), len(grid[0])\n count = 0\n def dfs(r, c):\n if r < 0 or r >= rows or c < 0 or c >= cols or grid[r][c] != '1': return\n grid[r][c] = '0'\n dfs(r+1, c); dfs(r-1, c); dfs(r, c+1); dfs(r, c-1)\n for r in range(rows):\n for c in range(cols):\n if grid[r][c] == '1': count += 1; dfs(r, c)\n return count", "solution_java": "public int numIslands(char[][] grid) {\n if (grid.length == 0) return 0;\n int count = 0;\n for (int i = 0; i < grid.length; i++)\n for (int j = 0; j < grid[0].length; j++)\n if (grid[i][j] == '1') { count++; dfs(grid, i, j); }\n return count;\n}\nprivate void dfs(char[][] grid, int r, int c) {\n if (r < 0 || r >= grid.length || c < 0 || c >= grid[0].length || grid[r][c] != '1') return;\n grid[r][c] = '0';\n dfs(grid, r+1, c); dfs(grid, r-1, c); dfs(grid, r, c+1); dfs(grid, r, c-1);\n}", "solution_cpp": "int numIslands(vector>& grid) {\n if (grid.empty()) return 0;\n int count = 0;\n for (int i = 0; i < grid.size(); i++)\n for (int j = 0; j < grid[0].size(); j++)\n if (grid[i][j] == '1') { count++; dfs(grid, i, j); }\n return count;\n}\nvoid dfs(vector>& grid, int r, int c) {\n if (r < 0 || r >= grid.size() || c < 0 || c >= grid[0].size() || grid[r][c] != '1') return;\n grid[r][c] = '0';\n dfs(grid, r+1, c); dfs(grid, r-1, c); dfs(grid, r, c+1); dfs(grid, r, c-1);\n}", "test_cases": ["grid=[[1,1,1,1,0],[1,1,0,1,0],[1,1,0,0,0],[0,0,0,0,0]] -> 1"], "key_points": ["DFS/BFS遍历", "访问后标记为0避免重复"], "tags": ["graph", "medium", "Google", "Facebook"]} {"problem_id": "algo_00641", "original_id": "two-sum", "title": "两数之和", "category": "array", "difficulty": "easy", "companies": ["Amazon", "Google"], "description": "给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那两个整数,并返回他们的数组下标。", "solution_python": "def twoSum(nums, target):\n hashmap = {}\n for i, num in enumerate(nums):\n complement = target - num\n if complement in hashmap:\n return [hashmap[complement], i]\n hashmap[num] = i\n return []", "solution_java": "public int[] twoSum(int[] nums, int target) {\n Map map = new HashMap<>();\n for (int i = 0; i < nums.length; i++) {\n int complement = target - nums[i];\n if (map.containsKey(complement)) return new int[]{map.get(complement), i};\n map.put(nums[i], i);\n }\n return new int[]{};\n}", "solution_cpp": "vector twoSum(vector& nums, int target) {\n unordered_map m;\n for (int i = 0; i < nums.size(); i++) {\n if (m.count(target - nums[i])) return {m[target - nums[i]], i};\n m[nums[i]] = i;\n }\n return {};\n}", "test_cases": ["nums=[2,7,11,15], target=9 -> [0,1]", "nums=[3,2,4], target=6 -> [1,2]"], "key_points": ["哈希表一次遍历", "空间换时间"], "tags": ["array", "easy", "Amazon", "Google"]} {"problem_id": "algo_00642", "original_id": "merge-sorted", "title": "合并两个有序数组", "category": "array", "difficulty": "easy", "companies": ["Microsoft", "Uber"], "description": "给你两个按非递减顺序排列的整数数组 nums1 和 nums2,另有两个整数 m 和 n,分别表示 nums1 和 nums2 中的元素数目。请你合并 nums2 到 nums1 中。", "solution_python": "def merge(nums1, m, nums2, n):\n p1, p2, p = m-1, n-1, m+n-1\n while p1 >= 0 and p2 >= 0:\n if nums1[p1] > nums2[p2]: nums1[p] = nums1[p1]; p1 -= 1\n else: nums1[p] = nums2[p2]; p2 -= 1\n p -= 1\n while p2 >= 0: nums1[p] = nums2[p2]; p2 -= 1; p -= 1", "solution_java": "public void merge(int[] nums1, int m, int[] nums2, int n) {\n int p1 = m-1, p2 = n-1, p = m+n-1;\n while (p1 >= 0 && p2 >= 0) {\n nums1[p--] = nums1[p1] > nums2[p2] ? nums1[p1--] : nums2[p2--];\n }\n while (p2 >= 0) nums1[p--] = nums2[p2--];\n}", "solution_cpp": "void merge(vector& nums1, int m, vector& nums2, int n) {\n int p1 = m-1, p2 = n-1, p = m+n-1;\n while (p1 >= 0 && p2 >= 0) nums1[p--] = nums1[p1] > nums2[p2] ? nums1[p1--] : nums2[p2--];\n while (p2 >= 0) nums1[p--] = nums2[p2--];\n}", "test_cases": ["nums1=[1,2,3], m=3, nums2=[2,5,6], n=3 -> [1,2,2,3,5,6]", "nums1=[], m=0, nums2=[1], n=1 -> [1]"], "key_points": ["从后往前合并", "三指针技巧"], "tags": ["array", "easy", "Microsoft", "Uber"]} {"problem_id": "algo_00643", "original_id": "max-subarray", "title": "最大子数组和", "category": "array", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "给你一个整数数组 nums ,请你找出一个具有最大和的连续子数组,返回其最大和。", "solution_python": "def maxSubArray(nums):\n max_sum = current = nums[0]\n for num in nums[1:]:\n current = max(num, current + num)\n max_sum = max(max_sum, current)\n return max_sum", "solution_java": "public int maxSubArray(int[] nums) {\n int maxSum = nums[0], curr = nums[0];\n for (int i = 1; i < nums.length; i++) {\n curr = Math.max(nums[i], curr + nums[i]);\n maxSum = Math.max(maxSum, curr);\n }\n return maxSum;\n}", "solution_cpp": "int maxSubArray(vector& nums) {\n int maxSum = nums[0], curr = nums[0];\n for (int i = 1; i < nums.size(); i++) {\n curr = max(nums[i], curr + nums[i]);\n maxSum = max(maxSum, curr);\n }\n return maxSum;\n}", "test_cases": ["nums=[-2,1,-3,4,-1,2,1,-5,4] -> 6", "nums=[1] -> 1"], "key_points": ["Kadane算法", "动态规划基础题"], "tags": ["array", "medium", "Google", "Microsoft"]} {"problem_id": "algo_00644", "original_id": "valid-parentheses", "title": "有效的括号", "category": "string", "difficulty": "easy", "companies": ["Google", "Uber"], "description": "给定一个只包括 '(',')','{','}','[',']' 的字符串 s,判断字符串是否有效。", "solution_python": "def isValid(s):\n stack = []\n mapping = {')': '(', ']': '[', '}': '{'}\n for c in s:\n if c in mapping:\n if not stack or stack[-1] != mapping[c]: return False\n stack.pop()\n else: stack.append(c)\n return not stack", "solution_java": "public boolean isValid(String s) {\n Stack stack = new Stack<>();\n Map map = Map.of(')', '(', ']', '[', '}', '{');\n for (char c : s.toCharArray()) {\n if (map.containsValue(c)) stack.push(c);\n else if (!stack.isEmpty() && stack.pop() != map.get(c)) return false;\n }\n return stack.isEmpty();\n}", "solution_cpp": "bool isValid(string s) {\n stack st;\n unordered_map m = {{')','('},{']','['},{'}','{'}};\n for (char c : s) {\n if (m.find(c) == m.end()) st.push(c);\n else if (st.empty() || st.top() != m[c]) return false;\n else st.pop();\n }\n return st.empty();\n}", "test_cases": ["s=\"()\" -> true", "s=\"()[]{}\" -> true", "s=\"(]\" -> false"], "key_points": ["栈匹配法", "注意空栈边界"], "tags": ["string", "easy", "Google", "Uber"]} {"problem_id": "algo_00645", "original_id": "longest-palindrome", "title": "最长回文子串", "category": "string", "difficulty": "medium", "companies": ["Google", "Amazon"], "description": "给你一个字符串 s,找到 s 中最长的回文子串。", "solution_python": "def longestPalindrome(s):\n def expand(l, r):\n while l >= 0 and r < len(s) and s[l] == s[r]: l -= 1; r += 1\n return l + 1, r - 1\n start = end = 0\n for i in range(len(s)):\n l1, r1 = expand(i, i)\n l2, r2 = expand(i, i + 1)\n if r1 - l1 > end - start: start, end = l1, r1\n if r2 - l2 > end - start: start, end = l2, r2\n return s[start:end+1]", "solution_java": "public String longestPalindrome(String s) {\n int start = 0, end = 0;\n for (int i = 0; i < s.length(); i++) {\n int len1 = expand(s, i, i), len2 = expand(s, i, i+1);\n int len = Math.max(len1, len2);\n if (len > end - start) { start = i - (len-1)/2; end = i + len/2; }\n }\n return s.substring(start, end + 1);\n}\nprivate int expand(String s, int l, int r) {\n while (l >= 0 && r < s.length() && s.charAt(l) == s.charAt(r)) { l--; r++; }\n return r - l - 1;\n}", "solution_cpp": "string longestPalindrome(string s) {\n int start = 0, end = 0;\n for (int i = 0; i < s.size(); i++) {\n int len1 = expand(s, i, i), len2 = expand(s, i, i+1);\n if (max(len1, len2) > end - start) { start = i - (max(len1,len2)-1)/2; end = i + max(len1,len2)/2; }\n }\n return s.substr(start, end - start + 1);\n}", "test_cases": ["s=\"babad\" -> bab或aba", "s=\"cbbd\" -> bb"], "key_points": ["中心扩展法", "处理奇偶长度"], "tags": ["string", "medium", "Google", "Amazon"]} {"problem_id": "algo_00646", "original_id": "reverse-list", "title": "反转链表", "category": "linkedlist", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "给你单链表的头节点 head,请你反转链表,并返回反转后的链表。", "solution_python": "def reverseList(head):\n prev = None\n curr = head\n while curr:\n nxt = curr.next\n curr.next = prev\n prev = curr\n curr = nxt\n return prev", "solution_java": "public ListNode reverseList(ListNode head) {\n ListNode prev = null, curr = head;\n while (curr != null) {\n ListNode next = curr.next;\n curr.next = prev;\n prev = curr;\n curr = next;\n }\n return prev;\n}", "solution_cpp": "ListNode* reverseList(ListNode* head) {\n ListNode* prev = nullptr, *curr = head;\n while (curr) {\n ListNode* next = curr->next;\n curr->next = prev;\n prev = curr;\n curr = next;\n }\n return prev;\n}", "test_cases": ["head=[1,2,3,4,5] -> [5,4,3,2,1]", "head=[1,2] -> [2,1]"], "key_points": ["迭代法 O(1)空间", "递归法 O(n)空间"], "tags": ["linkedlist", "medium", "Google", "Microsoft"]} {"problem_id": "algo_00647", "original_id": "middle-node", "title": "链表的中间结点", "category": "linkedlist", "difficulty": "easy", "companies": ["Amazon", "Facebook"], "description": "给你单链表的头节点 head,请你找出并返回链表的中间结点。如果有两个中间结点,则返回第二个中间结点。", "solution_python": "def middleNode(head):\n slow = fast = head\n while fast and fast.next:\n slow = slow.next\n fast = fast.next.next\n return slow", "solution_java": "public ListNode middleNode(ListNode head) {\n ListNode slow = head, fast = head;\n while (fast != null && fast.next != null) {\n slow = slow.next;\n fast = fast.next.next;\n }\n return slow;\n}", "solution_cpp": "ListNode* middleNode(ListNode* head) {\n ListNode* slow = head, *fast = head;\n while (fast && fast->next) { slow = slow->next; fast = fast->next->next; }\n return slow;\n}", "test_cases": ["head=[1,2,3,4,5] -> 3", "head=[1,2,3,4,5,6] -> 4"], "key_points": ["快慢指针", "O(n)时间O(1)空间"], "tags": ["linkedlist", "easy", "Amazon", "Facebook"]} {"problem_id": "algo_00648", "original_id": "max-depth", "title": "二叉树的最大深度", "category": "tree", "difficulty": "easy", "companies": ["Microsoft", "Apple"], "description": "给定一个二叉树 root,返回其最大深度。", "solution_python": "def maxDepth(root):\n if not root: return 0\n return max(maxDepth(root.left), maxDepth(root.right)) + 1", "solution_java": "public int maxDepth(TreeNode root) {\n if (root == null) return 0;\n return Math.max(maxDepth(root.left), maxDepth(root.right)) + 1;\n}", "solution_cpp": "int maxDepth(TreeNode* root) {\n if (!root) return 0;\n return max(maxDepth(root->left), maxDepth(root->right)) + 1;\n}", "test_cases": ["root=[3,9,20,null,null,15,7] -> 3", "root=[1,null,2] -> 2"], "key_points": ["DFS递归", "层序遍历也可"], "tags": ["tree", "easy", "Microsoft", "Apple"]} {"problem_id": "algo_00649", "original_id": "inorder-traversal", "title": "二叉树的中序遍历", "category": "tree", "difficulty": "easy", "companies": ["Google", "Microsoft"], "description": "给定一个二叉树的根节点 root,返回它的中序遍历结果。", "solution_python": "def inorderTraversal(root):\n result = []\n def dfs(node):\n if node:\n dfs(node.left)\n result.append(node.val)\n dfs(node.right)\n dfs(root)\n return result", "solution_java": "public List inorderTraversal(TreeNode root) {\n List res = new ArrayList<>();\n dfs(root, res);\n return res;\n}\nprivate void dfs(TreeNode node, List res) {\n if (node == null) return;\n dfs(node.left, res); res.add(node.val); dfs(node.right, res);\n}", "solution_cpp": "vector inorderTraversal(TreeNode* root) {\n vector res;\n dfs(root, res);\n return res;\n}\nvoid dfs(TreeNode* node, vector& res) {\n if (!node) return;\n dfs(node->left, res); res.push_back(node->val); dfs(node->right, res);\n}", "test_cases": ["root=[1,null,2,3] -> [1,3,2]", "root=[] -> []"], "key_points": ["左-根-右顺序", "递归最简洁"], "tags": ["tree", "easy", "Google", "Microsoft"]} {"problem_id": "algo_00650", "original_id": "binary-search", "title": "二分查找", "category": "binarysearch", "difficulty": "easy", "companies": ["Google", "Amazon"], "description": "给定一个 n 个元素有序的(升序)整型数组 nums 和一个目标值 target,写一个函数搜索 nums 中的 target,如果目标值存在返回下标,否则返回 -1。", "solution_python": "def search(nums, target):\n left, right = 0, len(nums) - 1\n while left <= right:\n mid = (left + right) // 2\n if nums[mid] == target: return mid\n elif nums[mid] < target: left = mid + 1\n else: right = mid - 1\n return -1", "solution_java": "public int search(int[] nums, int target) {\n int left = 0, right = nums.length - 1;\n while (left <= right) {\n int mid = left + (right - left) / 2;\n if (nums[mid] == target) return mid;\n else if (nums[mid] < target) left = mid + 1;\n else right = mid - 1;\n }\n return -1;\n}", "solution_cpp": "int search(vector& nums, int target) {\n int left = 0, right = nums.size() - 1;\n while (left <= right) {\n int mid = left + (right - left) / 2;\n if (nums[mid] == target) return mid;\n else if (nums[mid] < target) left = mid + 1;\n else right = mid - 1;\n }\n return -1;\n}", "test_cases": ["nums=[-1,0,3,5,9,12], target=9 -> 4", "nums=[-1,0,3,5,9,12], target=2 -> -1"], "key_points": ["标准模板", "注意防溢出写法"], "tags": ["binarysearch", "easy", "Google", "Amazon"]} {"problem_id": "algo_00651", "original_id": "climbing-stairs", "title": "爬楼梯", "category": "dp", "difficulty": "easy", "companies": ["Amazon", "Google"], "description": "假设你正在爬楼梯。需要 n 阶你才能到达楼顶。每次你可以爬 1 或 2 个台阶。你有多少种不同的方法可以爬到楼顶?", "solution_python": "def climbStairs(n):\n if n <= 2: return n\n a, b = 1, 2\n for _ in range(3, n+1):\n a, b = b, a + b\n return b", "solution_java": "public int climbStairs(int n) {\n if (n <= 2) return n;\n int a = 1, b = 2;\n for (int i = 3; i <= n; i++) { int temp = a + b; a = b; b = temp; }\n return b;\n}", "solution_cpp": "int climbStairs(int n) {\n if (n <= 2) return n;\n int a = 1, b = 2;\n for (int i = 3; i <= n; i++) { int temp = a + b; a = b; b = temp; }\n return b;\n}", "test_cases": ["n=2 -> 2", "n=3 -> 3", "n=5 -> 8"], "key_points": ["斐波那契数列", "滚动数组优化空间"], "tags": ["dp", "easy", "Amazon", "Google"]} {"problem_id": "algo_00652", "original_id": "coin-change", "title": "零钱兑换", "category": "dp", "difficulty": "medium", "companies": ["Google", "Amazon"], "description": "给你一个整数数组 coins 表示不同面额的硬币,以及一个整数 amount 表示总金额。计算并返回可以凑成总金额所需的最少的硬币个数。如果没有任何一种硬币组合能组成总金额,返回 -1。", "solution_python": "def coinChange(coins, amount):\n dp = [float('inf')] * (amount + 1)\n dp[0] = 0\n for coin in coins:\n for x in range(coin, amount + 1):\n dp[x] = min(dp[x], dp[x - coin] + 1)\n return dp[amount] if dp[amount] != float('inf') else -1", "solution_java": "public int coinChange(int[] coins, int amount) {\n int[] dp = new int[amount + 1];\n Arrays.fill(dp, amount + 1);\n dp[0] = 0;\n for (int coin : coins) {\n for (int x = coin; x <= amount; x++) {\n dp[x] = Math.min(dp[x], dp[x - coin] + 1);\n }\n }\n return dp[amount] > amount ? -1 : dp[amount];\n}", "solution_cpp": "int coinChange(vector& coins, int amount) {\n vector dp(amount + 1, amount + 1);\n dp[0] = 0;\n for (int coin : coins) {\n for (int x = coin; x <= amount; x++) {\n dp[x] = min(dp[x], dp[x - coin] + 1);\n }\n }\n return dp[amount] > amount ? -1 : dp[amount];\n}", "test_cases": ["coins=[1,2,5], amount=11 -> 3", "coins=[2], amount=3 -> -1"], "key_points": ["完全背包问题", "dp[x] = min(dp[x-coin]+1)"], "tags": ["dp", "medium", "Google", "Amazon"]} {"problem_id": "algo_00653", "original_id": "subsets", "title": "子集", "category": "backtracking", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "给你一个整数数组 nums ,数组中的元素 互不相同 。返回该数组所有可能的子集(幂集)。", "solution_python": "def subsets(nums):\n result = []\n def backtrack(start, path):\n result.append(path[:])\n for i in range(start, len(nums)):\n path.append(nums[i])\n backtrack(i + 1, path)\n path.pop()\n backtrack(0, [])\n return result", "solution_java": "public List> subsets(int[] nums) {\n List> result = new ArrayList<>();\n backtrack(nums, 0, new ArrayList<>(), result);\n return result;\n}\nprivate void backtrack(int[] nums, int start, List path, List> result) {\n result.add(new ArrayList<>(path));\n for (int i = start; i < nums.length; i++) {\n path.add(nums[i]);\n backtrack(nums, i + 1, path, result);\n path.remove(path.size() - 1);\n }\n}", "solution_cpp": "vector> subsets(vector& nums) {\n vector> result;\n vector path;\n backtrack(nums, 0, path, result);\n return result;\n}\nvoid backtrack(vector& nums, int start, vector& path, vector>& result) {\n result.push_back(path);\n for (int i = start; i < nums.size(); i++) {\n path.push_back(nums[i]);\n backtrack(nums, i + 1, path, result);\n path.pop_back();\n }\n}", "test_cases": ["nums=[1,2,3] -> [[],[1],[2],[1,2],[3],[1,3],[2,3],[1,2,3]]"], "key_points": ["选或不选", "DFS遍历子集树"], "tags": ["backtracking", "medium", "Google", "Microsoft"]} {"problem_id": "algo_00654", "original_id": "permutations", "title": "全排列", "category": "backtracking", "difficulty": "medium", "companies": ["Google", "Facebook"], "description": "给定一个不含重复数字的数组 nums,返回其所有可能的全排列。", "solution_python": "def permute(nums):\n result = []\n def backtrack(path, used):\n if len(path) == len(nums):\n result.append(path[:])\n return\n for i in range(len(nums)):\n if used[i]: continue\n used[i] = True\n path.append(nums[i])\n backtrack(path, used)\n path.pop()\n used[i] = False\n backtrack([], [False]*len(nums))\n return result", "solution_java": "public List> permute(int[] nums) {\n List> result = new ArrayList<>();\n boolean[] used = new boolean[nums.length];\n backtrack(nums, used, new ArrayList<>(), result);\n return result;\n}\nprivate void backtrack(int[] nums, boolean[] used, List path, List> result) {\n if (path.size() == nums.length) { result.add(new ArrayList<>(path)); return; }\n for (int i = 0; i < nums.length; i++) {\n if (used[i]) continue;\n used[i] = true;\n path.add(nums[i]);\n backtrack(nums, used, path, result);\n path.remove(path.size() - 1);\n used[i] = false;\n }\n}", "solution_cpp": "vector> permute(vector& nums) {\n vector> result;\n vector used(nums.size(), false);\n vector path;\n backtrack(nums, used, path, result);\n return result;\n}\nvoid backtrack(vector& nums, vector& used, vector& path, vector>& result) {\n if (path.size() == nums.size()) { result.push_back(path); return; }\n for (int i = 0; i < nums.size(); i++) {\n if (used[i]) continue;\n used[i] = true;\n path.push_back(nums[i]);\n backtrack(nums, used, path, result);\n path.pop_back();\n used[i] = false;\n }\n}", "test_cases": ["nums=[1,2,3] -> [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]"], "key_points": ["标记已使用元素", "回溯经典模板"], "tags": ["backtracking", "medium", "Google", "Facebook"]} {"problem_id": "algo_00655", "original_id": "top-k-frequent", "title": "前K个高频元素", "category": "heap", "difficulty": "medium", "companies": ["Amazon", "Facebook"], "description": "给你一个整数数组 nums 和一个整数 k,请你返回其中出现频率前 k 高的元素。", "solution_python": "import heapq\nfrom collections import Counter\ndef topKFrequent(nums, k):\n count = Counter(nums)\n heap = []\n for num, freq in count.items():\n heapq.heappush(heap, (freq, num))\n if len(heap) > k: heapq.heappop(heap)\n return [num for freq, num in heap]", "solution_java": "public int[] topKFrequent(int[] nums, int k) {\n Map count = new HashMap<>();\n for (int n : nums) count.put(n, count.getOrDefault(n, 0) + 1);\n PriorityQueue> heap = \n new PriorityQueue<>((a, b) -> a.getValue() - b.getValue());\n for (Map.Entry e : count.entrySet()) {\n heap.offer(e);\n if (heap.size() > k) heap.poll();\n }\n int[] res = new int[k];\n for (int i = k - 1; i >= 0; i--) res[i] = heap.poll().getKey();\n return res;\n}", "solution_cpp": "vector topKFrequent(vector& nums, int k) {\n unordered_map count;\n for (int n : nums) count[n]++;\n priority_queue, vector>, greater>> heap;\n for (auto& [num, freq] : count) {\n heap.push({freq, num});\n if (heap.size() > k) heap.pop();\n }\n vector res;\n while (!heap.empty()) { res.push_back(heap.top().second); heap.pop(); }\n reverse(res.begin(), res.end());\n return res;\n}", "test_cases": ["nums=[1,1,1,2,2,3], k=2 -> [1,2]", "nums=[1], k=1 -> [1]"], "key_points": ["小顶堆保持大小k", "时间复杂度O(nlogk)"], "tags": ["heap", "medium", "Amazon", "Facebook"]} {"problem_id": "algo_00656", "original_id": "3sum", "title": "三数之和", "category": "two-pointers", "difficulty": "medium", "companies": ["Google", "Amazon"], "description": "给你一个整数数组 nums,判断是否存在三元组满足和为0,返回所有不重复的三元组。", "solution_python": "def threeSum(nums):\n nums.sort()\n result = []\n for i in range(len(nums) - 2):\n if i > 0 and nums[i] == nums[i-1]: continue\n left, right = i + 1, len(nums) - 1\n while left < right:\n total = nums[i] + nums[left] + nums[right]\n if total < 0: left += 1\n elif total > 0: right -= 1\n else:\n result.append([nums[i], nums[left], nums[right]])\n while left < right and nums[left] == nums[left+1]: left += 1\n while left < right and nums[right] == nums[right-1]: right -= 1\n left += 1; right -= 1\n return result", "solution_java": "public List> threeSum(int[] nums) {\n Arrays.sort(nums);\n List> result = new ArrayList<>();\n for (int i = 0; i < nums.length - 2; i++) {\n if (i > 0 && nums[i] == nums[i-1]) continue;\n int left = i + 1, right = nums.length - 1;\n while (left < right) {\n int total = nums[i] + nums[left] + nums[right];\n if (total < 0) left++;\n else if (total > 0) right--;\n else {\n result.add(Arrays.asList(nums[i], nums[left], nums[right]));\n while (left < right && nums[left] == nums[left+1]) left++;\n while (left < right && nums[right] == nums[right-1]) right--;\n left++; right--;\n }\n }\n }\n return result;\n}", "solution_cpp": "vector> threeSum(vector& nums) {\n sort(nums.begin(), nums.end());\n vector> result;\n for (int i = 0; i < nums.size() - 2; i++) {\n if (i > 0 && nums[i] == nums[i-1]) continue;\n int left = i + 1, right = nums.size() - 1;\n while (left < right) {\n int total = nums[i] + nums[left] + nums[right];\n if (total < 0) left++;\n else if (total > 0) right--;\n else {\n result.push_back({nums[i], nums[left], nums[right]});\n while (left < right && nums[left] == nums[left+1]) left++;\n while (left < right && nums[right] == nums[right-1]) right--;\n left++; right--;\n }\n }\n }\n return result;\n}", "test_cases": ["nums=[-1,0,1,2,-1,-4] -> [[-1,-1,2],[-1,0,1]]"], "key_points": ["排序+双指针", "去重是关键"], "tags": ["two-pointers", "medium", "Google", "Amazon"]} {"problem_id": "algo_00657", "original_id": "container-water", "title": "盛最多水的容器", "category": "two-pointers", "difficulty": "medium", "companies": ["Google", "Uber"], "description": "给定一个长度为 n 的整数数组 height,找出其中的两条线,使得它们与 x 轴共同构成的容器可以容纳最多的水。", "solution_python": "def maxArea(height):\n left, right = 0, len(height) - 1\n max_area = 0\n while left < right:\n h = min(height[left], height[right])\n max_area = max(max_area, h * (right - left))\n if height[left] < height[right]: left += 1\n else: right -= 1\n return max_area", "solution_java": "public int maxArea(int[] height) {\n int left = 0, right = height.length - 1, maxArea = 0;\n while (left < right) {\n int h = Math.min(height[left], height[right]);\n maxArea = Math.max(maxArea, h * (right - left));\n if (height[left] < height[right]) left++;\n else right--;\n }\n return maxArea;\n}", "solution_cpp": "int maxArea(vector& height) {\n int left = 0, right = height.size() - 1, maxArea = 0;\n while (left < right) {\n int h = min(height[left], height[right]);\n maxArea = max(maxArea, h * (right - left));\n if (height[left] < height[right]) left++;\n else right--;\n }\n return maxArea;\n}", "test_cases": ["height=[1,8,6,2,5,4,8,3,7] -> 49"], "key_points": ["移动短边指针", "面积=min(h1,h2)*width"], "tags": ["two-pointers", "medium", "Google", "Uber"]} {"problem_id": "algo_00658", "original_id": "min-stack", "title": "最小栈", "category": "stack", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "设计一个支持 push,pop,top 操作,并能在常数时间内检索到最小元素的栈。", "solution_python": "class MinStack:\n def __init__(self):\n self.stack = []\n self.min_stack = []\n def push(self, val):\n self.stack.append(val)\n self.min_stack.append(min(val, self.min_stack[-1] if self.min_stack else val))\n def pop(self):\n self.stack.pop(); self.min_stack.pop()\n def top(self): return self.stack[-1]\n def getMin(self): return self.min_stack[-1]", "solution_java": "class MinStack {\n Stack stack = new Stack<>();\n Stack minStack = new Stack<>();\n public void push(int val) { stack.push(val); minStack.push(Math.min(val, minStack.isEmpty() ? val : minStack.peek())); }\n public void pop() { stack.pop(); minStack.pop(); }\n public int top() { return stack.peek(); }\n public int getMin() { return minStack.peek(); }\n}", "solution_cpp": "class MinStack {\n stack st, minSt;\npublic:\n void push(int val) { st.push(val); minSt.push(min(val, minSt.empty() ? val : minSt.top())); }\n void pop() { st.pop(); minSt.pop(); }\n int top() { return st.top(); }\n int getMin() { return minSt.top(); }\n};", "test_cases": ["push(-2), push(0), push(-3) -> getMin() returns -3"], "key_points": ["辅助栈记录最小值", "O(1)时间获取最小值"], "tags": ["stack", "medium", "Google", "Microsoft"]} {"problem_id": "algo_00659", "original_id": "lru-cache", "title": "LRU缓存", "category": "design", "difficulty": "hard", "companies": ["Google", "Amazon"], "description": "设计和实现一个 LRU(最近最少使用)缓存机制。", "solution_python": "class LRUCache:\n def __init__(self, capacity):\n self.capacity = capacity\n self.cache = {}\n self.order = []\n def get(self, key):\n if key not in self.cache: return -1\n self.order.remove(key); self.order.append(key)\n return self.cache[key]\n def put(self, key, value):\n if key in self.cache:\n self.order.remove(key)\n elif len(self.cache) >= self.capacity:\n del self.cache[self.order.pop(0)]\n self.cache[key] = value; self.order.append(key)", "solution_java": "class LRUCache {\n int capacity;\n LinkedHashMap cache = new LinkedHashMap<>();\n public LRUCache(int cap) { capacity = cap; }\n public int get(int key) { return cache.containsKey(key) ? cache.remove(key) : -1; }\n public void put(int key, int val) {\n if (cache.containsKey(key)) cache.remove(key);\n else if (cache.size() >= capacity) cache.remove(cache.keySet().iterator().next());\n cache.put(key, val);\n }\n}", "solution_cpp": "class LRUCache {\n int cap;\n list> dll;\n unordered_map>::iterator> cache;\npublic:\n LRUCache(int capacity) : cap(capacity) {}\n int get(int key) {\n auto it = cache.find(key);\n if (it == cache.end()) return -1;\n dll.splice(dll.end(), dll, it->second);\n return it->second->second;\n }\n void put(int key, int value) {\n auto it = cache.find(key);\n if (it != cache.end()) dll.erase(it->second);\n else if (cache.size() >= cap) { cache.erase(dll.front().first); dll.pop_front(); }\n dll.push_back({key, value});\n cache[key] = --dll.end();\n }\n};", "test_cases": ["put(1,1), put(2,2), get(1) -> 1"], "key_points": ["HashMap + 双向链表", "O(1)时间操作"], "tags": ["design", "hard", "Google", "Amazon"]} {"problem_id": "algo_00660", "original_id": "num-islands", "title": "岛屿数量", "category": "graph", "difficulty": "medium", "companies": ["Google", "Facebook"], "description": "给你一个由 '1'(陆地)和 '0'(水)组成的二维网格,请你计算网格中岛屿的数量。岛屿总是被水包围,且只能由水平或垂直方向相邻的陆地连接形成。", "solution_python": "def numIslands(grid):\n if not grid: return 0\n rows, cols = len(grid), len(grid[0])\n count = 0\n def dfs(r, c):\n if r < 0 or r >= rows or c < 0 or c >= cols or grid[r][c] != '1': return\n grid[r][c] = '0'\n dfs(r+1, c); dfs(r-1, c); dfs(r, c+1); dfs(r, c-1)\n for r in range(rows):\n for c in range(cols):\n if grid[r][c] == '1': count += 1; dfs(r, c)\n return count", "solution_java": "public int numIslands(char[][] grid) {\n if (grid.length == 0) return 0;\n int count = 0;\n for (int i = 0; i < grid.length; i++)\n for (int j = 0; j < grid[0].length; j++)\n if (grid[i][j] == '1') { count++; dfs(grid, i, j); }\n return count;\n}\nprivate void dfs(char[][] grid, int r, int c) {\n if (r < 0 || r >= grid.length || c < 0 || c >= grid[0].length || grid[r][c] != '1') return;\n grid[r][c] = '0';\n dfs(grid, r+1, c); dfs(grid, r-1, c); dfs(grid, r, c+1); dfs(grid, r, c-1);\n}", "solution_cpp": "int numIslands(vector>& grid) {\n if (grid.empty()) return 0;\n int count = 0;\n for (int i = 0; i < grid.size(); i++)\n for (int j = 0; j < grid[0].size(); j++)\n if (grid[i][j] == '1') { count++; dfs(grid, i, j); }\n return count;\n}\nvoid dfs(vector>& grid, int r, int c) {\n if (r < 0 || r >= grid.size() || c < 0 || c >= grid[0].size() || grid[r][c] != '1') return;\n grid[r][c] = '0';\n dfs(grid, r+1, c); dfs(grid, r-1, c); dfs(grid, r, c+1); dfs(grid, r, c-1);\n}", "test_cases": ["grid=[[1,1,1,1,0],[1,1,0,1,0],[1,1,0,0,0],[0,0,0,0,0]] -> 1"], "key_points": ["DFS/BFS遍历", "访问后标记为0避免重复"], "tags": ["graph", "medium", "Google", "Facebook"]} {"problem_id": "algo_00661", "original_id": "two-sum", "title": "两数之和", "category": "array", "difficulty": "easy", "companies": ["Amazon", "Google"], "description": "给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那两个整数,并返回他们的数组下标。", "solution_python": "def twoSum(nums, target):\n hashmap = {}\n for i, num in enumerate(nums):\n complement = target - num\n if complement in hashmap:\n return [hashmap[complement], i]\n hashmap[num] = i\n return []", "solution_java": "public int[] twoSum(int[] nums, int target) {\n Map map = new HashMap<>();\n for (int i = 0; i < nums.length; i++) {\n int complement = target - nums[i];\n if (map.containsKey(complement)) return new int[]{map.get(complement), i};\n map.put(nums[i], i);\n }\n return new int[]{};\n}", "solution_cpp": "vector twoSum(vector& nums, int target) {\n unordered_map m;\n for (int i = 0; i < nums.size(); i++) {\n if (m.count(target - nums[i])) return {m[target - nums[i]], i};\n m[nums[i]] = i;\n }\n return {};\n}", "test_cases": ["nums=[2,7,11,15], target=9 -> [0,1]", "nums=[3,2,4], target=6 -> [1,2]"], "key_points": ["哈希表一次遍历", "空间换时间"], "tags": ["array", "easy", "Amazon", "Google"]} {"problem_id": "algo_00662", "original_id": "merge-sorted", "title": "合并两个有序数组", "category": "array", "difficulty": "easy", "companies": ["Microsoft", "Uber"], "description": "给你两个按非递减顺序排列的整数数组 nums1 和 nums2,另有两个整数 m 和 n,分别表示 nums1 和 nums2 中的元素数目。请你合并 nums2 到 nums1 中。", "solution_python": "def merge(nums1, m, nums2, n):\n p1, p2, p = m-1, n-1, m+n-1\n while p1 >= 0 and p2 >= 0:\n if nums1[p1] > nums2[p2]: nums1[p] = nums1[p1]; p1 -= 1\n else: nums1[p] = nums2[p2]; p2 -= 1\n p -= 1\n while p2 >= 0: nums1[p] = nums2[p2]; p2 -= 1; p -= 1", "solution_java": "public void merge(int[] nums1, int m, int[] nums2, int n) {\n int p1 = m-1, p2 = n-1, p = m+n-1;\n while (p1 >= 0 && p2 >= 0) {\n nums1[p--] = nums1[p1] > nums2[p2] ? nums1[p1--] : nums2[p2--];\n }\n while (p2 >= 0) nums1[p--] = nums2[p2--];\n}", "solution_cpp": "void merge(vector& nums1, int m, vector& nums2, int n) {\n int p1 = m-1, p2 = n-1, p = m+n-1;\n while (p1 >= 0 && p2 >= 0) nums1[p--] = nums1[p1] > nums2[p2] ? nums1[p1--] : nums2[p2--];\n while (p2 >= 0) nums1[p--] = nums2[p2--];\n}", "test_cases": ["nums1=[1,2,3], m=3, nums2=[2,5,6], n=3 -> [1,2,2,3,5,6]", "nums1=[], m=0, nums2=[1], n=1 -> [1]"], "key_points": ["从后往前合并", "三指针技巧"], "tags": ["array", "easy", "Microsoft", "Uber"]} {"problem_id": "algo_00663", "original_id": "max-subarray", "title": "最大子数组和", "category": "array", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "给你一个整数数组 nums ,请你找出一个具有最大和的连续子数组,返回其最大和。", "solution_python": "def maxSubArray(nums):\n max_sum = current = nums[0]\n for num in nums[1:]:\n current = max(num, current + num)\n max_sum = max(max_sum, current)\n return max_sum", "solution_java": "public int maxSubArray(int[] nums) {\n int maxSum = nums[0], curr = nums[0];\n for (int i = 1; i < nums.length; i++) {\n curr = Math.max(nums[i], curr + nums[i]);\n maxSum = Math.max(maxSum, curr);\n }\n return maxSum;\n}", "solution_cpp": "int maxSubArray(vector& nums) {\n int maxSum = nums[0], curr = nums[0];\n for (int i = 1; i < nums.size(); i++) {\n curr = max(nums[i], curr + nums[i]);\n maxSum = max(maxSum, curr);\n }\n return maxSum;\n}", "test_cases": ["nums=[-2,1,-3,4,-1,2,1,-5,4] -> 6", "nums=[1] -> 1"], "key_points": ["Kadane算法", "动态规划基础题"], "tags": ["array", "medium", "Google", "Microsoft"]} {"problem_id": "algo_00664", "original_id": "valid-parentheses", "title": "有效的括号", "category": "string", "difficulty": "easy", "companies": ["Google", "Uber"], "description": "给定一个只包括 '(',')','{','}','[',']' 的字符串 s,判断字符串是否有效。", "solution_python": "def isValid(s):\n stack = []\n mapping = {')': '(', ']': '[', '}': '{'}\n for c in s:\n if c in mapping:\n if not stack or stack[-1] != mapping[c]: return False\n stack.pop()\n else: stack.append(c)\n return not stack", "solution_java": "public boolean isValid(String s) {\n Stack stack = new Stack<>();\n Map map = Map.of(')', '(', ']', '[', '}', '{');\n for (char c : s.toCharArray()) {\n if (map.containsValue(c)) stack.push(c);\n else if (!stack.isEmpty() && stack.pop() != map.get(c)) return false;\n }\n return stack.isEmpty();\n}", "solution_cpp": "bool isValid(string s) {\n stack st;\n unordered_map m = {{')','('},{']','['},{'}','{'}};\n for (char c : s) {\n if (m.find(c) == m.end()) st.push(c);\n else if (st.empty() || st.top() != m[c]) return false;\n else st.pop();\n }\n return st.empty();\n}", "test_cases": ["s=\"()\" -> true", "s=\"()[]{}\" -> true", "s=\"(]\" -> false"], "key_points": ["栈匹配法", "注意空栈边界"], "tags": ["string", "easy", "Google", "Uber"]} {"problem_id": "algo_00665", "original_id": "longest-palindrome", "title": "最长回文子串", "category": "string", "difficulty": "medium", "companies": ["Google", "Amazon"], "description": "给你一个字符串 s,找到 s 中最长的回文子串。", "solution_python": "def longestPalindrome(s):\n def expand(l, r):\n while l >= 0 and r < len(s) and s[l] == s[r]: l -= 1; r += 1\n return l + 1, r - 1\n start = end = 0\n for i in range(len(s)):\n l1, r1 = expand(i, i)\n l2, r2 = expand(i, i + 1)\n if r1 - l1 > end - start: start, end = l1, r1\n if r2 - l2 > end - start: start, end = l2, r2\n return s[start:end+1]", "solution_java": "public String longestPalindrome(String s) {\n int start = 0, end = 0;\n for (int i = 0; i < s.length(); i++) {\n int len1 = expand(s, i, i), len2 = expand(s, i, i+1);\n int len = Math.max(len1, len2);\n if (len > end - start) { start = i - (len-1)/2; end = i + len/2; }\n }\n return s.substring(start, end + 1);\n}\nprivate int expand(String s, int l, int r) {\n while (l >= 0 && r < s.length() && s.charAt(l) == s.charAt(r)) { l--; r++; }\n return r - l - 1;\n}", "solution_cpp": "string longestPalindrome(string s) {\n int start = 0, end = 0;\n for (int i = 0; i < s.size(); i++) {\n int len1 = expand(s, i, i), len2 = expand(s, i, i+1);\n if (max(len1, len2) > end - start) { start = i - (max(len1,len2)-1)/2; end = i + max(len1,len2)/2; }\n }\n return s.substr(start, end - start + 1);\n}", "test_cases": ["s=\"babad\" -> bab或aba", "s=\"cbbd\" -> bb"], "key_points": ["中心扩展法", "处理奇偶长度"], "tags": ["string", "medium", "Google", "Amazon"]} {"problem_id": "algo_00666", "original_id": "reverse-list", "title": "反转链表", "category": "linkedlist", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "给你单链表的头节点 head,请你反转链表,并返回反转后的链表。", "solution_python": "def reverseList(head):\n prev = None\n curr = head\n while curr:\n nxt = curr.next\n curr.next = prev\n prev = curr\n curr = nxt\n return prev", "solution_java": "public ListNode reverseList(ListNode head) {\n ListNode prev = null, curr = head;\n while (curr != null) {\n ListNode next = curr.next;\n curr.next = prev;\n prev = curr;\n curr = next;\n }\n return prev;\n}", "solution_cpp": "ListNode* reverseList(ListNode* head) {\n ListNode* prev = nullptr, *curr = head;\n while (curr) {\n ListNode* next = curr->next;\n curr->next = prev;\n prev = curr;\n curr = next;\n }\n return prev;\n}", "test_cases": ["head=[1,2,3,4,5] -> [5,4,3,2,1]", "head=[1,2] -> [2,1]"], "key_points": ["迭代法 O(1)空间", "递归法 O(n)空间"], "tags": ["linkedlist", "medium", "Google", "Microsoft"]} {"problem_id": "algo_00667", "original_id": "middle-node", "title": "链表的中间结点", "category": "linkedlist", "difficulty": "easy", "companies": ["Amazon", "Facebook"], "description": "给你单链表的头节点 head,请你找出并返回链表的中间结点。如果有两个中间结点,则返回第二个中间结点。", "solution_python": "def middleNode(head):\n slow = fast = head\n while fast and fast.next:\n slow = slow.next\n fast = fast.next.next\n return slow", "solution_java": "public ListNode middleNode(ListNode head) {\n ListNode slow = head, fast = head;\n while (fast != null && fast.next != null) {\n slow = slow.next;\n fast = fast.next.next;\n }\n return slow;\n}", "solution_cpp": "ListNode* middleNode(ListNode* head) {\n ListNode* slow = head, *fast = head;\n while (fast && fast->next) { slow = slow->next; fast = fast->next->next; }\n return slow;\n}", "test_cases": ["head=[1,2,3,4,5] -> 3", "head=[1,2,3,4,5,6] -> 4"], "key_points": ["快慢指针", "O(n)时间O(1)空间"], "tags": ["linkedlist", "easy", "Amazon", "Facebook"]} {"problem_id": "algo_00668", "original_id": "max-depth", "title": "二叉树的最大深度", "category": "tree", "difficulty": "easy", "companies": ["Microsoft", "Apple"], "description": "给定一个二叉树 root,返回其最大深度。", "solution_python": "def maxDepth(root):\n if not root: return 0\n return max(maxDepth(root.left), maxDepth(root.right)) + 1", "solution_java": "public int maxDepth(TreeNode root) {\n if (root == null) return 0;\n return Math.max(maxDepth(root.left), maxDepth(root.right)) + 1;\n}", "solution_cpp": "int maxDepth(TreeNode* root) {\n if (!root) return 0;\n return max(maxDepth(root->left), maxDepth(root->right)) + 1;\n}", "test_cases": ["root=[3,9,20,null,null,15,7] -> 3", "root=[1,null,2] -> 2"], "key_points": ["DFS递归", "层序遍历也可"], "tags": ["tree", "easy", "Microsoft", "Apple"]} {"problem_id": "algo_00669", "original_id": "inorder-traversal", "title": "二叉树的中序遍历", "category": "tree", "difficulty": "easy", "companies": ["Google", "Microsoft"], "description": "给定一个二叉树的根节点 root,返回它的中序遍历结果。", "solution_python": "def inorderTraversal(root):\n result = []\n def dfs(node):\n if node:\n dfs(node.left)\n result.append(node.val)\n dfs(node.right)\n dfs(root)\n return result", "solution_java": "public List inorderTraversal(TreeNode root) {\n List res = new ArrayList<>();\n dfs(root, res);\n return res;\n}\nprivate void dfs(TreeNode node, List res) {\n if (node == null) return;\n dfs(node.left, res); res.add(node.val); dfs(node.right, res);\n}", "solution_cpp": "vector inorderTraversal(TreeNode* root) {\n vector res;\n dfs(root, res);\n return res;\n}\nvoid dfs(TreeNode* node, vector& res) {\n if (!node) return;\n dfs(node->left, res); res.push_back(node->val); dfs(node->right, res);\n}", "test_cases": ["root=[1,null,2,3] -> [1,3,2]", "root=[] -> []"], "key_points": ["左-根-右顺序", "递归最简洁"], "tags": ["tree", "easy", "Google", "Microsoft"]} {"problem_id": "algo_00670", "original_id": "binary-search", "title": "二分查找", "category": "binarysearch", "difficulty": "easy", "companies": ["Google", "Amazon"], "description": "给定一个 n 个元素有序的(升序)整型数组 nums 和一个目标值 target,写一个函数搜索 nums 中的 target,如果目标值存在返回下标,否则返回 -1。", "solution_python": "def search(nums, target):\n left, right = 0, len(nums) - 1\n while left <= right:\n mid = (left + right) // 2\n if nums[mid] == target: return mid\n elif nums[mid] < target: left = mid + 1\n else: right = mid - 1\n return -1", "solution_java": "public int search(int[] nums, int target) {\n int left = 0, right = nums.length - 1;\n while (left <= right) {\n int mid = left + (right - left) / 2;\n if (nums[mid] == target) return mid;\n else if (nums[mid] < target) left = mid + 1;\n else right = mid - 1;\n }\n return -1;\n}", "solution_cpp": "int search(vector& nums, int target) {\n int left = 0, right = nums.size() - 1;\n while (left <= right) {\n int mid = left + (right - left) / 2;\n if (nums[mid] == target) return mid;\n else if (nums[mid] < target) left = mid + 1;\n else right = mid - 1;\n }\n return -1;\n}", "test_cases": ["nums=[-1,0,3,5,9,12], target=9 -> 4", "nums=[-1,0,3,5,9,12], target=2 -> -1"], "key_points": ["标准模板", "注意防溢出写法"], "tags": ["binarysearch", "easy", "Google", "Amazon"]} {"problem_id": "algo_00671", "original_id": "climbing-stairs", "title": "爬楼梯", "category": "dp", "difficulty": "easy", "companies": ["Amazon", "Google"], "description": "假设你正在爬楼梯。需要 n 阶你才能到达楼顶。每次你可以爬 1 或 2 个台阶。你有多少种不同的方法可以爬到楼顶?", "solution_python": "def climbStairs(n):\n if n <= 2: return n\n a, b = 1, 2\n for _ in range(3, n+1):\n a, b = b, a + b\n return b", "solution_java": "public int climbStairs(int n) {\n if (n <= 2) return n;\n int a = 1, b = 2;\n for (int i = 3; i <= n; i++) { int temp = a + b; a = b; b = temp; }\n return b;\n}", "solution_cpp": "int climbStairs(int n) {\n if (n <= 2) return n;\n int a = 1, b = 2;\n for (int i = 3; i <= n; i++) { int temp = a + b; a = b; b = temp; }\n return b;\n}", "test_cases": ["n=2 -> 2", "n=3 -> 3", "n=5 -> 8"], "key_points": ["斐波那契数列", "滚动数组优化空间"], "tags": ["dp", "easy", "Amazon", "Google"]} {"problem_id": "algo_00672", "original_id": "coin-change", "title": "零钱兑换", "category": "dp", "difficulty": "medium", "companies": ["Google", "Amazon"], "description": "给你一个整数数组 coins 表示不同面额的硬币,以及一个整数 amount 表示总金额。计算并返回可以凑成总金额所需的最少的硬币个数。如果没有任何一种硬币组合能组成总金额,返回 -1。", "solution_python": "def coinChange(coins, amount):\n dp = [float('inf')] * (amount + 1)\n dp[0] = 0\n for coin in coins:\n for x in range(coin, amount + 1):\n dp[x] = min(dp[x], dp[x - coin] + 1)\n return dp[amount] if dp[amount] != float('inf') else -1", "solution_java": "public int coinChange(int[] coins, int amount) {\n int[] dp = new int[amount + 1];\n Arrays.fill(dp, amount + 1);\n dp[0] = 0;\n for (int coin : coins) {\n for (int x = coin; x <= amount; x++) {\n dp[x] = Math.min(dp[x], dp[x - coin] + 1);\n }\n }\n return dp[amount] > amount ? -1 : dp[amount];\n}", "solution_cpp": "int coinChange(vector& coins, int amount) {\n vector dp(amount + 1, amount + 1);\n dp[0] = 0;\n for (int coin : coins) {\n for (int x = coin; x <= amount; x++) {\n dp[x] = min(dp[x], dp[x - coin] + 1);\n }\n }\n return dp[amount] > amount ? -1 : dp[amount];\n}", "test_cases": ["coins=[1,2,5], amount=11 -> 3", "coins=[2], amount=3 -> -1"], "key_points": ["完全背包问题", "dp[x] = min(dp[x-coin]+1)"], "tags": ["dp", "medium", "Google", "Amazon"]} {"problem_id": "algo_00673", "original_id": "subsets", "title": "子集", "category": "backtracking", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "给你一个整数数组 nums ,数组中的元素 互不相同 。返回该数组所有可能的子集(幂集)。", "solution_python": "def subsets(nums):\n result = []\n def backtrack(start, path):\n result.append(path[:])\n for i in range(start, len(nums)):\n path.append(nums[i])\n backtrack(i + 1, path)\n path.pop()\n backtrack(0, [])\n return result", "solution_java": "public List> subsets(int[] nums) {\n List> result = new ArrayList<>();\n backtrack(nums, 0, new ArrayList<>(), result);\n return result;\n}\nprivate void backtrack(int[] nums, int start, List path, List> result) {\n result.add(new ArrayList<>(path));\n for (int i = start; i < nums.length; i++) {\n path.add(nums[i]);\n backtrack(nums, i + 1, path, result);\n path.remove(path.size() - 1);\n }\n}", "solution_cpp": "vector> subsets(vector& nums) {\n vector> result;\n vector path;\n backtrack(nums, 0, path, result);\n return result;\n}\nvoid backtrack(vector& nums, int start, vector& path, vector>& result) {\n result.push_back(path);\n for (int i = start; i < nums.size(); i++) {\n path.push_back(nums[i]);\n backtrack(nums, i + 1, path, result);\n path.pop_back();\n }\n}", "test_cases": ["nums=[1,2,3] -> [[],[1],[2],[1,2],[3],[1,3],[2,3],[1,2,3]]"], "key_points": ["选或不选", "DFS遍历子集树"], "tags": ["backtracking", "medium", "Google", "Microsoft"]} {"problem_id": "algo_00674", "original_id": "permutations", "title": "全排列", "category": "backtracking", "difficulty": "medium", "companies": ["Google", "Facebook"], "description": "给定一个不含重复数字的数组 nums,返回其所有可能的全排列。", "solution_python": "def permute(nums):\n result = []\n def backtrack(path, used):\n if len(path) == len(nums):\n result.append(path[:])\n return\n for i in range(len(nums)):\n if used[i]: continue\n used[i] = True\n path.append(nums[i])\n backtrack(path, used)\n path.pop()\n used[i] = False\n backtrack([], [False]*len(nums))\n return result", "solution_java": "public List> permute(int[] nums) {\n List> result = new ArrayList<>();\n boolean[] used = new boolean[nums.length];\n backtrack(nums, used, new ArrayList<>(), result);\n return result;\n}\nprivate void backtrack(int[] nums, boolean[] used, List path, List> result) {\n if (path.size() == nums.length) { result.add(new ArrayList<>(path)); return; }\n for (int i = 0; i < nums.length; i++) {\n if (used[i]) continue;\n used[i] = true;\n path.add(nums[i]);\n backtrack(nums, used, path, result);\n path.remove(path.size() - 1);\n used[i] = false;\n }\n}", "solution_cpp": "vector> permute(vector& nums) {\n vector> result;\n vector used(nums.size(), false);\n vector path;\n backtrack(nums, used, path, result);\n return result;\n}\nvoid backtrack(vector& nums, vector& used, vector& path, vector>& result) {\n if (path.size() == nums.size()) { result.push_back(path); return; }\n for (int i = 0; i < nums.size(); i++) {\n if (used[i]) continue;\n used[i] = true;\n path.push_back(nums[i]);\n backtrack(nums, used, path, result);\n path.pop_back();\n used[i] = false;\n }\n}", "test_cases": ["nums=[1,2,3] -> [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]"], "key_points": ["标记已使用元素", "回溯经典模板"], "tags": ["backtracking", "medium", "Google", "Facebook"]} {"problem_id": "algo_00675", "original_id": "top-k-frequent", "title": "前K个高频元素", "category": "heap", "difficulty": "medium", "companies": ["Amazon", "Facebook"], "description": "给你一个整数数组 nums 和一个整数 k,请你返回其中出现频率前 k 高的元素。", "solution_python": "import heapq\nfrom collections import Counter\ndef topKFrequent(nums, k):\n count = Counter(nums)\n heap = []\n for num, freq in count.items():\n heapq.heappush(heap, (freq, num))\n if len(heap) > k: heapq.heappop(heap)\n return [num for freq, num in heap]", "solution_java": "public int[] topKFrequent(int[] nums, int k) {\n Map count = new HashMap<>();\n for (int n : nums) count.put(n, count.getOrDefault(n, 0) + 1);\n PriorityQueue> heap = \n new PriorityQueue<>((a, b) -> a.getValue() - b.getValue());\n for (Map.Entry e : count.entrySet()) {\n heap.offer(e);\n if (heap.size() > k) heap.poll();\n }\n int[] res = new int[k];\n for (int i = k - 1; i >= 0; i--) res[i] = heap.poll().getKey();\n return res;\n}", "solution_cpp": "vector topKFrequent(vector& nums, int k) {\n unordered_map count;\n for (int n : nums) count[n]++;\n priority_queue, vector>, greater>> heap;\n for (auto& [num, freq] : count) {\n heap.push({freq, num});\n if (heap.size() > k) heap.pop();\n }\n vector res;\n while (!heap.empty()) { res.push_back(heap.top().second); heap.pop(); }\n reverse(res.begin(), res.end());\n return res;\n}", "test_cases": ["nums=[1,1,1,2,2,3], k=2 -> [1,2]", "nums=[1], k=1 -> [1]"], "key_points": ["小顶堆保持大小k", "时间复杂度O(nlogk)"], "tags": ["heap", "medium", "Amazon", "Facebook"]} {"problem_id": "algo_00676", "original_id": "3sum", "title": "三数之和", "category": "two-pointers", "difficulty": "medium", "companies": ["Google", "Amazon"], "description": "给你一个整数数组 nums,判断是否存在三元组满足和为0,返回所有不重复的三元组。", "solution_python": "def threeSum(nums):\n nums.sort()\n result = []\n for i in range(len(nums) - 2):\n if i > 0 and nums[i] == nums[i-1]: continue\n left, right = i + 1, len(nums) - 1\n while left < right:\n total = nums[i] + nums[left] + nums[right]\n if total < 0: left += 1\n elif total > 0: right -= 1\n else:\n result.append([nums[i], nums[left], nums[right]])\n while left < right and nums[left] == nums[left+1]: left += 1\n while left < right and nums[right] == nums[right-1]: right -= 1\n left += 1; right -= 1\n return result", "solution_java": "public List> threeSum(int[] nums) {\n Arrays.sort(nums);\n List> result = new ArrayList<>();\n for (int i = 0; i < nums.length - 2; i++) {\n if (i > 0 && nums[i] == nums[i-1]) continue;\n int left = i + 1, right = nums.length - 1;\n while (left < right) {\n int total = nums[i] + nums[left] + nums[right];\n if (total < 0) left++;\n else if (total > 0) right--;\n else {\n result.add(Arrays.asList(nums[i], nums[left], nums[right]));\n while (left < right && nums[left] == nums[left+1]) left++;\n while (left < right && nums[right] == nums[right-1]) right--;\n left++; right--;\n }\n }\n }\n return result;\n}", "solution_cpp": "vector> threeSum(vector& nums) {\n sort(nums.begin(), nums.end());\n vector> result;\n for (int i = 0; i < nums.size() - 2; i++) {\n if (i > 0 && nums[i] == nums[i-1]) continue;\n int left = i + 1, right = nums.size() - 1;\n while (left < right) {\n int total = nums[i] + nums[left] + nums[right];\n if (total < 0) left++;\n else if (total > 0) right--;\n else {\n result.push_back({nums[i], nums[left], nums[right]});\n while (left < right && nums[left] == nums[left+1]) left++;\n while (left < right && nums[right] == nums[right-1]) right--;\n left++; right--;\n }\n }\n }\n return result;\n}", "test_cases": ["nums=[-1,0,1,2,-1,-4] -> [[-1,-1,2],[-1,0,1]]"], "key_points": ["排序+双指针", "去重是关键"], "tags": ["two-pointers", "medium", "Google", "Amazon"]} {"problem_id": "algo_00677", "original_id": "container-water", "title": "盛最多水的容器", "category": "two-pointers", "difficulty": "medium", "companies": ["Google", "Uber"], "description": "给定一个长度为 n 的整数数组 height,找出其中的两条线,使得它们与 x 轴共同构成的容器可以容纳最多的水。", "solution_python": "def maxArea(height):\n left, right = 0, len(height) - 1\n max_area = 0\n while left < right:\n h = min(height[left], height[right])\n max_area = max(max_area, h * (right - left))\n if height[left] < height[right]: left += 1\n else: right -= 1\n return max_area", "solution_java": "public int maxArea(int[] height) {\n int left = 0, right = height.length - 1, maxArea = 0;\n while (left < right) {\n int h = Math.min(height[left], height[right]);\n maxArea = Math.max(maxArea, h * (right - left));\n if (height[left] < height[right]) left++;\n else right--;\n }\n return maxArea;\n}", "solution_cpp": "int maxArea(vector& height) {\n int left = 0, right = height.size() - 1, maxArea = 0;\n while (left < right) {\n int h = min(height[left], height[right]);\n maxArea = max(maxArea, h * (right - left));\n if (height[left] < height[right]) left++;\n else right--;\n }\n return maxArea;\n}", "test_cases": ["height=[1,8,6,2,5,4,8,3,7] -> 49"], "key_points": ["移动短边指针", "面积=min(h1,h2)*width"], "tags": ["two-pointers", "medium", "Google", "Uber"]} {"problem_id": "algo_00678", "original_id": "min-stack", "title": "最小栈", "category": "stack", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "设计一个支持 push,pop,top 操作,并能在常数时间内检索到最小元素的栈。", "solution_python": "class MinStack:\n def __init__(self):\n self.stack = []\n self.min_stack = []\n def push(self, val):\n self.stack.append(val)\n self.min_stack.append(min(val, self.min_stack[-1] if self.min_stack else val))\n def pop(self):\n self.stack.pop(); self.min_stack.pop()\n def top(self): return self.stack[-1]\n def getMin(self): return self.min_stack[-1]", "solution_java": "class MinStack {\n Stack stack = new Stack<>();\n Stack minStack = new Stack<>();\n public void push(int val) { stack.push(val); minStack.push(Math.min(val, minStack.isEmpty() ? val : minStack.peek())); }\n public void pop() { stack.pop(); minStack.pop(); }\n public int top() { return stack.peek(); }\n public int getMin() { return minStack.peek(); }\n}", "solution_cpp": "class MinStack {\n stack st, minSt;\npublic:\n void push(int val) { st.push(val); minSt.push(min(val, minSt.empty() ? val : minSt.top())); }\n void pop() { st.pop(); minSt.pop(); }\n int top() { return st.top(); }\n int getMin() { return minSt.top(); }\n};", "test_cases": ["push(-2), push(0), push(-3) -> getMin() returns -3"], "key_points": ["辅助栈记录最小值", "O(1)时间获取最小值"], "tags": ["stack", "medium", "Google", "Microsoft"]} {"problem_id": "algo_00679", "original_id": "lru-cache", "title": "LRU缓存", "category": "design", "difficulty": "hard", "companies": ["Google", "Amazon"], "description": "设计和实现一个 LRU(最近最少使用)缓存机制。", "solution_python": "class LRUCache:\n def __init__(self, capacity):\n self.capacity = capacity\n self.cache = {}\n self.order = []\n def get(self, key):\n if key not in self.cache: return -1\n self.order.remove(key); self.order.append(key)\n return self.cache[key]\n def put(self, key, value):\n if key in self.cache:\n self.order.remove(key)\n elif len(self.cache) >= self.capacity:\n del self.cache[self.order.pop(0)]\n self.cache[key] = value; self.order.append(key)", "solution_java": "class LRUCache {\n int capacity;\n LinkedHashMap cache = new LinkedHashMap<>();\n public LRUCache(int cap) { capacity = cap; }\n public int get(int key) { return cache.containsKey(key) ? cache.remove(key) : -1; }\n public void put(int key, int val) {\n if (cache.containsKey(key)) cache.remove(key);\n else if (cache.size() >= capacity) cache.remove(cache.keySet().iterator().next());\n cache.put(key, val);\n }\n}", "solution_cpp": "class LRUCache {\n int cap;\n list> dll;\n unordered_map>::iterator> cache;\npublic:\n LRUCache(int capacity) : cap(capacity) {}\n int get(int key) {\n auto it = cache.find(key);\n if (it == cache.end()) return -1;\n dll.splice(dll.end(), dll, it->second);\n return it->second->second;\n }\n void put(int key, int value) {\n auto it = cache.find(key);\n if (it != cache.end()) dll.erase(it->second);\n else if (cache.size() >= cap) { cache.erase(dll.front().first); dll.pop_front(); }\n dll.push_back({key, value});\n cache[key] = --dll.end();\n }\n};", "test_cases": ["put(1,1), put(2,2), get(1) -> 1"], "key_points": ["HashMap + 双向链表", "O(1)时间操作"], "tags": ["design", "hard", "Google", "Amazon"]} {"problem_id": "algo_00680", "original_id": "num-islands", "title": "岛屿数量", "category": "graph", "difficulty": "medium", "companies": ["Google", "Facebook"], "description": "给你一个由 '1'(陆地)和 '0'(水)组成的二维网格,请你计算网格中岛屿的数量。岛屿总是被水包围,且只能由水平或垂直方向相邻的陆地连接形成。", "solution_python": "def numIslands(grid):\n if not grid: return 0\n rows, cols = len(grid), len(grid[0])\n count = 0\n def dfs(r, c):\n if r < 0 or r >= rows or c < 0 or c >= cols or grid[r][c] != '1': return\n grid[r][c] = '0'\n dfs(r+1, c); dfs(r-1, c); dfs(r, c+1); dfs(r, c-1)\n for r in range(rows):\n for c in range(cols):\n if grid[r][c] == '1': count += 1; dfs(r, c)\n return count", "solution_java": "public int numIslands(char[][] grid) {\n if (grid.length == 0) return 0;\n int count = 0;\n for (int i = 0; i < grid.length; i++)\n for (int j = 0; j < grid[0].length; j++)\n if (grid[i][j] == '1') { count++; dfs(grid, i, j); }\n return count;\n}\nprivate void dfs(char[][] grid, int r, int c) {\n if (r < 0 || r >= grid.length || c < 0 || c >= grid[0].length || grid[r][c] != '1') return;\n grid[r][c] = '0';\n dfs(grid, r+1, c); dfs(grid, r-1, c); dfs(grid, r, c+1); dfs(grid, r, c-1);\n}", "solution_cpp": "int numIslands(vector>& grid) {\n if (grid.empty()) return 0;\n int count = 0;\n for (int i = 0; i < grid.size(); i++)\n for (int j = 0; j < grid[0].size(); j++)\n if (grid[i][j] == '1') { count++; dfs(grid, i, j); }\n return count;\n}\nvoid dfs(vector>& grid, int r, int c) {\n if (r < 0 || r >= grid.size() || c < 0 || c >= grid[0].size() || grid[r][c] != '1') return;\n grid[r][c] = '0';\n dfs(grid, r+1, c); dfs(grid, r-1, c); dfs(grid, r, c+1); dfs(grid, r, c-1);\n}", "test_cases": ["grid=[[1,1,1,1,0],[1,1,0,1,0],[1,1,0,0,0],[0,0,0,0,0]] -> 1"], "key_points": ["DFS/BFS遍历", "访问后标记为0避免重复"], "tags": ["graph", "medium", "Google", "Facebook"]} {"problem_id": "algo_00681", "original_id": "two-sum", "title": "两数之和", "category": "array", "difficulty": "easy", "companies": ["Amazon", "Google"], "description": "给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那两个整数,并返回他们的数组下标。", "solution_python": "def twoSum(nums, target):\n hashmap = {}\n for i, num in enumerate(nums):\n complement = target - num\n if complement in hashmap:\n return [hashmap[complement], i]\n hashmap[num] = i\n return []", "solution_java": "public int[] twoSum(int[] nums, int target) {\n Map map = new HashMap<>();\n for (int i = 0; i < nums.length; i++) {\n int complement = target - nums[i];\n if (map.containsKey(complement)) return new int[]{map.get(complement), i};\n map.put(nums[i], i);\n }\n return new int[]{};\n}", "solution_cpp": "vector twoSum(vector& nums, int target) {\n unordered_map m;\n for (int i = 0; i < nums.size(); i++) {\n if (m.count(target - nums[i])) return {m[target - nums[i]], i};\n m[nums[i]] = i;\n }\n return {};\n}", "test_cases": ["nums=[2,7,11,15], target=9 -> [0,1]", "nums=[3,2,4], target=6 -> [1,2]"], "key_points": ["哈希表一次遍历", "空间换时间"], "tags": ["array", "easy", "Amazon", "Google"]} {"problem_id": "algo_00682", "original_id": "merge-sorted", "title": "合并两个有序数组", "category": "array", "difficulty": "easy", "companies": ["Microsoft", "Uber"], "description": "给你两个按非递减顺序排列的整数数组 nums1 和 nums2,另有两个整数 m 和 n,分别表示 nums1 和 nums2 中的元素数目。请你合并 nums2 到 nums1 中。", "solution_python": "def merge(nums1, m, nums2, n):\n p1, p2, p = m-1, n-1, m+n-1\n while p1 >= 0 and p2 >= 0:\n if nums1[p1] > nums2[p2]: nums1[p] = nums1[p1]; p1 -= 1\n else: nums1[p] = nums2[p2]; p2 -= 1\n p -= 1\n while p2 >= 0: nums1[p] = nums2[p2]; p2 -= 1; p -= 1", "solution_java": "public void merge(int[] nums1, int m, int[] nums2, int n) {\n int p1 = m-1, p2 = n-1, p = m+n-1;\n while (p1 >= 0 && p2 >= 0) {\n nums1[p--] = nums1[p1] > nums2[p2] ? nums1[p1--] : nums2[p2--];\n }\n while (p2 >= 0) nums1[p--] = nums2[p2--];\n}", "solution_cpp": "void merge(vector& nums1, int m, vector& nums2, int n) {\n int p1 = m-1, p2 = n-1, p = m+n-1;\n while (p1 >= 0 && p2 >= 0) nums1[p--] = nums1[p1] > nums2[p2] ? nums1[p1--] : nums2[p2--];\n while (p2 >= 0) nums1[p--] = nums2[p2--];\n}", "test_cases": ["nums1=[1,2,3], m=3, nums2=[2,5,6], n=3 -> [1,2,2,3,5,6]", "nums1=[], m=0, nums2=[1], n=1 -> [1]"], "key_points": ["从后往前合并", "三指针技巧"], "tags": ["array", "easy", "Microsoft", "Uber"]} {"problem_id": "algo_00683", "original_id": "max-subarray", "title": "最大子数组和", "category": "array", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "给你一个整数数组 nums ,请你找出一个具有最大和的连续子数组,返回其最大和。", "solution_python": "def maxSubArray(nums):\n max_sum = current = nums[0]\n for num in nums[1:]:\n current = max(num, current + num)\n max_sum = max(max_sum, current)\n return max_sum", "solution_java": "public int maxSubArray(int[] nums) {\n int maxSum = nums[0], curr = nums[0];\n for (int i = 1; i < nums.length; i++) {\n curr = Math.max(nums[i], curr + nums[i]);\n maxSum = Math.max(maxSum, curr);\n }\n return maxSum;\n}", "solution_cpp": "int maxSubArray(vector& nums) {\n int maxSum = nums[0], curr = nums[0];\n for (int i = 1; i < nums.size(); i++) {\n curr = max(nums[i], curr + nums[i]);\n maxSum = max(maxSum, curr);\n }\n return maxSum;\n}", "test_cases": ["nums=[-2,1,-3,4,-1,2,1,-5,4] -> 6", "nums=[1] -> 1"], "key_points": ["Kadane算法", "动态规划基础题"], "tags": ["array", "medium", "Google", "Microsoft"]} {"problem_id": "algo_00684", "original_id": "valid-parentheses", "title": "有效的括号", "category": "string", "difficulty": "easy", "companies": ["Google", "Uber"], "description": "给定一个只包括 '(',')','{','}','[',']' 的字符串 s,判断字符串是否有效。", "solution_python": "def isValid(s):\n stack = []\n mapping = {')': '(', ']': '[', '}': '{'}\n for c in s:\n if c in mapping:\n if not stack or stack[-1] != mapping[c]: return False\n stack.pop()\n else: stack.append(c)\n return not stack", "solution_java": "public boolean isValid(String s) {\n Stack stack = new Stack<>();\n Map map = Map.of(')', '(', ']', '[', '}', '{');\n for (char c : s.toCharArray()) {\n if (map.containsValue(c)) stack.push(c);\n else if (!stack.isEmpty() && stack.pop() != map.get(c)) return false;\n }\n return stack.isEmpty();\n}", "solution_cpp": "bool isValid(string s) {\n stack st;\n unordered_map m = {{')','('},{']','['},{'}','{'}};\n for (char c : s) {\n if (m.find(c) == m.end()) st.push(c);\n else if (st.empty() || st.top() != m[c]) return false;\n else st.pop();\n }\n return st.empty();\n}", "test_cases": ["s=\"()\" -> true", "s=\"()[]{}\" -> true", "s=\"(]\" -> false"], "key_points": ["栈匹配法", "注意空栈边界"], "tags": ["string", "easy", "Google", "Uber"]} {"problem_id": "algo_00685", "original_id": "longest-palindrome", "title": "最长回文子串", "category": "string", "difficulty": "medium", "companies": ["Google", "Amazon"], "description": "给你一个字符串 s,找到 s 中最长的回文子串。", "solution_python": "def longestPalindrome(s):\n def expand(l, r):\n while l >= 0 and r < len(s) and s[l] == s[r]: l -= 1; r += 1\n return l + 1, r - 1\n start = end = 0\n for i in range(len(s)):\n l1, r1 = expand(i, i)\n l2, r2 = expand(i, i + 1)\n if r1 - l1 > end - start: start, end = l1, r1\n if r2 - l2 > end - start: start, end = l2, r2\n return s[start:end+1]", "solution_java": "public String longestPalindrome(String s) {\n int start = 0, end = 0;\n for (int i = 0; i < s.length(); i++) {\n int len1 = expand(s, i, i), len2 = expand(s, i, i+1);\n int len = Math.max(len1, len2);\n if (len > end - start) { start = i - (len-1)/2; end = i + len/2; }\n }\n return s.substring(start, end + 1);\n}\nprivate int expand(String s, int l, int r) {\n while (l >= 0 && r < s.length() && s.charAt(l) == s.charAt(r)) { l--; r++; }\n return r - l - 1;\n}", "solution_cpp": "string longestPalindrome(string s) {\n int start = 0, end = 0;\n for (int i = 0; i < s.size(); i++) {\n int len1 = expand(s, i, i), len2 = expand(s, i, i+1);\n if (max(len1, len2) > end - start) { start = i - (max(len1,len2)-1)/2; end = i + max(len1,len2)/2; }\n }\n return s.substr(start, end - start + 1);\n}", "test_cases": ["s=\"babad\" -> bab或aba", "s=\"cbbd\" -> bb"], "key_points": ["中心扩展法", "处理奇偶长度"], "tags": ["string", "medium", "Google", "Amazon"]} {"problem_id": "algo_00686", "original_id": "reverse-list", "title": "反转链表", "category": "linkedlist", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "给你单链表的头节点 head,请你反转链表,并返回反转后的链表。", "solution_python": "def reverseList(head):\n prev = None\n curr = head\n while curr:\n nxt = curr.next\n curr.next = prev\n prev = curr\n curr = nxt\n return prev", "solution_java": "public ListNode reverseList(ListNode head) {\n ListNode prev = null, curr = head;\n while (curr != null) {\n ListNode next = curr.next;\n curr.next = prev;\n prev = curr;\n curr = next;\n }\n return prev;\n}", "solution_cpp": "ListNode* reverseList(ListNode* head) {\n ListNode* prev = nullptr, *curr = head;\n while (curr) {\n ListNode* next = curr->next;\n curr->next = prev;\n prev = curr;\n curr = next;\n }\n return prev;\n}", "test_cases": ["head=[1,2,3,4,5] -> [5,4,3,2,1]", "head=[1,2] -> [2,1]"], "key_points": ["迭代法 O(1)空间", "递归法 O(n)空间"], "tags": ["linkedlist", "medium", "Google", "Microsoft"]} {"problem_id": "algo_00687", "original_id": "middle-node", "title": "链表的中间结点", "category": "linkedlist", "difficulty": "easy", "companies": ["Amazon", "Facebook"], "description": "给你单链表的头节点 head,请你找出并返回链表的中间结点。如果有两个中间结点,则返回第二个中间结点。", "solution_python": "def middleNode(head):\n slow = fast = head\n while fast and fast.next:\n slow = slow.next\n fast = fast.next.next\n return slow", "solution_java": "public ListNode middleNode(ListNode head) {\n ListNode slow = head, fast = head;\n while (fast != null && fast.next != null) {\n slow = slow.next;\n fast = fast.next.next;\n }\n return slow;\n}", "solution_cpp": "ListNode* middleNode(ListNode* head) {\n ListNode* slow = head, *fast = head;\n while (fast && fast->next) { slow = slow->next; fast = fast->next->next; }\n return slow;\n}", "test_cases": ["head=[1,2,3,4,5] -> 3", "head=[1,2,3,4,5,6] -> 4"], "key_points": ["快慢指针", "O(n)时间O(1)空间"], "tags": ["linkedlist", "easy", "Amazon", "Facebook"]} {"problem_id": "algo_00688", "original_id": "max-depth", "title": "二叉树的最大深度", "category": "tree", "difficulty": "easy", "companies": ["Microsoft", "Apple"], "description": "给定一个二叉树 root,返回其最大深度。", "solution_python": "def maxDepth(root):\n if not root: return 0\n return max(maxDepth(root.left), maxDepth(root.right)) + 1", "solution_java": "public int maxDepth(TreeNode root) {\n if (root == null) return 0;\n return Math.max(maxDepth(root.left), maxDepth(root.right)) + 1;\n}", "solution_cpp": "int maxDepth(TreeNode* root) {\n if (!root) return 0;\n return max(maxDepth(root->left), maxDepth(root->right)) + 1;\n}", "test_cases": ["root=[3,9,20,null,null,15,7] -> 3", "root=[1,null,2] -> 2"], "key_points": ["DFS递归", "层序遍历也可"], "tags": ["tree", "easy", "Microsoft", "Apple"]} {"problem_id": "algo_00689", "original_id": "inorder-traversal", "title": "二叉树的中序遍历", "category": "tree", "difficulty": "easy", "companies": ["Google", "Microsoft"], "description": "给定一个二叉树的根节点 root,返回它的中序遍历结果。", "solution_python": "def inorderTraversal(root):\n result = []\n def dfs(node):\n if node:\n dfs(node.left)\n result.append(node.val)\n dfs(node.right)\n dfs(root)\n return result", "solution_java": "public List inorderTraversal(TreeNode root) {\n List res = new ArrayList<>();\n dfs(root, res);\n return res;\n}\nprivate void dfs(TreeNode node, List res) {\n if (node == null) return;\n dfs(node.left, res); res.add(node.val); dfs(node.right, res);\n}", "solution_cpp": "vector inorderTraversal(TreeNode* root) {\n vector res;\n dfs(root, res);\n return res;\n}\nvoid dfs(TreeNode* node, vector& res) {\n if (!node) return;\n dfs(node->left, res); res.push_back(node->val); dfs(node->right, res);\n}", "test_cases": ["root=[1,null,2,3] -> [1,3,2]", "root=[] -> []"], "key_points": ["左-根-右顺序", "递归最简洁"], "tags": ["tree", "easy", "Google", "Microsoft"]} {"problem_id": "algo_00690", "original_id": "binary-search", "title": "二分查找", "category": "binarysearch", "difficulty": "easy", "companies": ["Google", "Amazon"], "description": "给定一个 n 个元素有序的(升序)整型数组 nums 和一个目标值 target,写一个函数搜索 nums 中的 target,如果目标值存在返回下标,否则返回 -1。", "solution_python": "def search(nums, target):\n left, right = 0, len(nums) - 1\n while left <= right:\n mid = (left + right) // 2\n if nums[mid] == target: return mid\n elif nums[mid] < target: left = mid + 1\n else: right = mid - 1\n return -1", "solution_java": "public int search(int[] nums, int target) {\n int left = 0, right = nums.length - 1;\n while (left <= right) {\n int mid = left + (right - left) / 2;\n if (nums[mid] == target) return mid;\n else if (nums[mid] < target) left = mid + 1;\n else right = mid - 1;\n }\n return -1;\n}", "solution_cpp": "int search(vector& nums, int target) {\n int left = 0, right = nums.size() - 1;\n while (left <= right) {\n int mid = left + (right - left) / 2;\n if (nums[mid] == target) return mid;\n else if (nums[mid] < target) left = mid + 1;\n else right = mid - 1;\n }\n return -1;\n}", "test_cases": ["nums=[-1,0,3,5,9,12], target=9 -> 4", "nums=[-1,0,3,5,9,12], target=2 -> -1"], "key_points": ["标准模板", "注意防溢出写法"], "tags": ["binarysearch", "easy", "Google", "Amazon"]} {"problem_id": "algo_00691", "original_id": "climbing-stairs", "title": "爬楼梯", "category": "dp", "difficulty": "easy", "companies": ["Amazon", "Google"], "description": "假设你正在爬楼梯。需要 n 阶你才能到达楼顶。每次你可以爬 1 或 2 个台阶。你有多少种不同的方法可以爬到楼顶?", "solution_python": "def climbStairs(n):\n if n <= 2: return n\n a, b = 1, 2\n for _ in range(3, n+1):\n a, b = b, a + b\n return b", "solution_java": "public int climbStairs(int n) {\n if (n <= 2) return n;\n int a = 1, b = 2;\n for (int i = 3; i <= n; i++) { int temp = a + b; a = b; b = temp; }\n return b;\n}", "solution_cpp": "int climbStairs(int n) {\n if (n <= 2) return n;\n int a = 1, b = 2;\n for (int i = 3; i <= n; i++) { int temp = a + b; a = b; b = temp; }\n return b;\n}", "test_cases": ["n=2 -> 2", "n=3 -> 3", "n=5 -> 8"], "key_points": ["斐波那契数列", "滚动数组优化空间"], "tags": ["dp", "easy", "Amazon", "Google"]} {"problem_id": "algo_00692", "original_id": "coin-change", "title": "零钱兑换", "category": "dp", "difficulty": "medium", "companies": ["Google", "Amazon"], "description": "给你一个整数数组 coins 表示不同面额的硬币,以及一个整数 amount 表示总金额。计算并返回可以凑成总金额所需的最少的硬币个数。如果没有任何一种硬币组合能组成总金额,返回 -1。", "solution_python": "def coinChange(coins, amount):\n dp = [float('inf')] * (amount + 1)\n dp[0] = 0\n for coin in coins:\n for x in range(coin, amount + 1):\n dp[x] = min(dp[x], dp[x - coin] + 1)\n return dp[amount] if dp[amount] != float('inf') else -1", "solution_java": "public int coinChange(int[] coins, int amount) {\n int[] dp = new int[amount + 1];\n Arrays.fill(dp, amount + 1);\n dp[0] = 0;\n for (int coin : coins) {\n for (int x = coin; x <= amount; x++) {\n dp[x] = Math.min(dp[x], dp[x - coin] + 1);\n }\n }\n return dp[amount] > amount ? -1 : dp[amount];\n}", "solution_cpp": "int coinChange(vector& coins, int amount) {\n vector dp(amount + 1, amount + 1);\n dp[0] = 0;\n for (int coin : coins) {\n for (int x = coin; x <= amount; x++) {\n dp[x] = min(dp[x], dp[x - coin] + 1);\n }\n }\n return dp[amount] > amount ? -1 : dp[amount];\n}", "test_cases": ["coins=[1,2,5], amount=11 -> 3", "coins=[2], amount=3 -> -1"], "key_points": ["完全背包问题", "dp[x] = min(dp[x-coin]+1)"], "tags": ["dp", "medium", "Google", "Amazon"]} {"problem_id": "algo_00693", "original_id": "subsets", "title": "子集", "category": "backtracking", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "给你一个整数数组 nums ,数组中的元素 互不相同 。返回该数组所有可能的子集(幂集)。", "solution_python": "def subsets(nums):\n result = []\n def backtrack(start, path):\n result.append(path[:])\n for i in range(start, len(nums)):\n path.append(nums[i])\n backtrack(i + 1, path)\n path.pop()\n backtrack(0, [])\n return result", "solution_java": "public List> subsets(int[] nums) {\n List> result = new ArrayList<>();\n backtrack(nums, 0, new ArrayList<>(), result);\n return result;\n}\nprivate void backtrack(int[] nums, int start, List path, List> result) {\n result.add(new ArrayList<>(path));\n for (int i = start; i < nums.length; i++) {\n path.add(nums[i]);\n backtrack(nums, i + 1, path, result);\n path.remove(path.size() - 1);\n }\n}", "solution_cpp": "vector> subsets(vector& nums) {\n vector> result;\n vector path;\n backtrack(nums, 0, path, result);\n return result;\n}\nvoid backtrack(vector& nums, int start, vector& path, vector>& result) {\n result.push_back(path);\n for (int i = start; i < nums.size(); i++) {\n path.push_back(nums[i]);\n backtrack(nums, i + 1, path, result);\n path.pop_back();\n }\n}", "test_cases": ["nums=[1,2,3] -> [[],[1],[2],[1,2],[3],[1,3],[2,3],[1,2,3]]"], "key_points": ["选或不选", "DFS遍历子集树"], "tags": ["backtracking", "medium", "Google", "Microsoft"]} {"problem_id": "algo_00694", "original_id": "permutations", "title": "全排列", "category": "backtracking", "difficulty": "medium", "companies": ["Google", "Facebook"], "description": "给定一个不含重复数字的数组 nums,返回其所有可能的全排列。", "solution_python": "def permute(nums):\n result = []\n def backtrack(path, used):\n if len(path) == len(nums):\n result.append(path[:])\n return\n for i in range(len(nums)):\n if used[i]: continue\n used[i] = True\n path.append(nums[i])\n backtrack(path, used)\n path.pop()\n used[i] = False\n backtrack([], [False]*len(nums))\n return result", "solution_java": "public List> permute(int[] nums) {\n List> result = new ArrayList<>();\n boolean[] used = new boolean[nums.length];\n backtrack(nums, used, new ArrayList<>(), result);\n return result;\n}\nprivate void backtrack(int[] nums, boolean[] used, List path, List> result) {\n if (path.size() == nums.length) { result.add(new ArrayList<>(path)); return; }\n for (int i = 0; i < nums.length; i++) {\n if (used[i]) continue;\n used[i] = true;\n path.add(nums[i]);\n backtrack(nums, used, path, result);\n path.remove(path.size() - 1);\n used[i] = false;\n }\n}", "solution_cpp": "vector> permute(vector& nums) {\n vector> result;\n vector used(nums.size(), false);\n vector path;\n backtrack(nums, used, path, result);\n return result;\n}\nvoid backtrack(vector& nums, vector& used, vector& path, vector>& result) {\n if (path.size() == nums.size()) { result.push_back(path); return; }\n for (int i = 0; i < nums.size(); i++) {\n if (used[i]) continue;\n used[i] = true;\n path.push_back(nums[i]);\n backtrack(nums, used, path, result);\n path.pop_back();\n used[i] = false;\n }\n}", "test_cases": ["nums=[1,2,3] -> [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]"], "key_points": ["标记已使用元素", "回溯经典模板"], "tags": ["backtracking", "medium", "Google", "Facebook"]} {"problem_id": "algo_00695", "original_id": "top-k-frequent", "title": "前K个高频元素", "category": "heap", "difficulty": "medium", "companies": ["Amazon", "Facebook"], "description": "给你一个整数数组 nums 和一个整数 k,请你返回其中出现频率前 k 高的元素。", "solution_python": "import heapq\nfrom collections import Counter\ndef topKFrequent(nums, k):\n count = Counter(nums)\n heap = []\n for num, freq in count.items():\n heapq.heappush(heap, (freq, num))\n if len(heap) > k: heapq.heappop(heap)\n return [num for freq, num in heap]", "solution_java": "public int[] topKFrequent(int[] nums, int k) {\n Map count = new HashMap<>();\n for (int n : nums) count.put(n, count.getOrDefault(n, 0) + 1);\n PriorityQueue> heap = \n new PriorityQueue<>((a, b) -> a.getValue() - b.getValue());\n for (Map.Entry e : count.entrySet()) {\n heap.offer(e);\n if (heap.size() > k) heap.poll();\n }\n int[] res = new int[k];\n for (int i = k - 1; i >= 0; i--) res[i] = heap.poll().getKey();\n return res;\n}", "solution_cpp": "vector topKFrequent(vector& nums, int k) {\n unordered_map count;\n for (int n : nums) count[n]++;\n priority_queue, vector>, greater>> heap;\n for (auto& [num, freq] : count) {\n heap.push({freq, num});\n if (heap.size() > k) heap.pop();\n }\n vector res;\n while (!heap.empty()) { res.push_back(heap.top().second); heap.pop(); }\n reverse(res.begin(), res.end());\n return res;\n}", "test_cases": ["nums=[1,1,1,2,2,3], k=2 -> [1,2]", "nums=[1], k=1 -> [1]"], "key_points": ["小顶堆保持大小k", "时间复杂度O(nlogk)"], "tags": ["heap", "medium", "Amazon", "Facebook"]} {"problem_id": "algo_00696", "original_id": "3sum", "title": "三数之和", "category": "two-pointers", "difficulty": "medium", "companies": ["Google", "Amazon"], "description": "给你一个整数数组 nums,判断是否存在三元组满足和为0,返回所有不重复的三元组。", "solution_python": "def threeSum(nums):\n nums.sort()\n result = []\n for i in range(len(nums) - 2):\n if i > 0 and nums[i] == nums[i-1]: continue\n left, right = i + 1, len(nums) - 1\n while left < right:\n total = nums[i] + nums[left] + nums[right]\n if total < 0: left += 1\n elif total > 0: right -= 1\n else:\n result.append([nums[i], nums[left], nums[right]])\n while left < right and nums[left] == nums[left+1]: left += 1\n while left < right and nums[right] == nums[right-1]: right -= 1\n left += 1; right -= 1\n return result", "solution_java": "public List> threeSum(int[] nums) {\n Arrays.sort(nums);\n List> result = new ArrayList<>();\n for (int i = 0; i < nums.length - 2; i++) {\n if (i > 0 && nums[i] == nums[i-1]) continue;\n int left = i + 1, right = nums.length - 1;\n while (left < right) {\n int total = nums[i] + nums[left] + nums[right];\n if (total < 0) left++;\n else if (total > 0) right--;\n else {\n result.add(Arrays.asList(nums[i], nums[left], nums[right]));\n while (left < right && nums[left] == nums[left+1]) left++;\n while (left < right && nums[right] == nums[right-1]) right--;\n left++; right--;\n }\n }\n }\n return result;\n}", "solution_cpp": "vector> threeSum(vector& nums) {\n sort(nums.begin(), nums.end());\n vector> result;\n for (int i = 0; i < nums.size() - 2; i++) {\n if (i > 0 && nums[i] == nums[i-1]) continue;\n int left = i + 1, right = nums.size() - 1;\n while (left < right) {\n int total = nums[i] + nums[left] + nums[right];\n if (total < 0) left++;\n else if (total > 0) right--;\n else {\n result.push_back({nums[i], nums[left], nums[right]});\n while (left < right && nums[left] == nums[left+1]) left++;\n while (left < right && nums[right] == nums[right-1]) right--;\n left++; right--;\n }\n }\n }\n return result;\n}", "test_cases": ["nums=[-1,0,1,2,-1,-4] -> [[-1,-1,2],[-1,0,1]]"], "key_points": ["排序+双指针", "去重是关键"], "tags": ["two-pointers", "medium", "Google", "Amazon"]} {"problem_id": "algo_00697", "original_id": "container-water", "title": "盛最多水的容器", "category": "two-pointers", "difficulty": "medium", "companies": ["Google", "Uber"], "description": "给定一个长度为 n 的整数数组 height,找出其中的两条线,使得它们与 x 轴共同构成的容器可以容纳最多的水。", "solution_python": "def maxArea(height):\n left, right = 0, len(height) - 1\n max_area = 0\n while left < right:\n h = min(height[left], height[right])\n max_area = max(max_area, h * (right - left))\n if height[left] < height[right]: left += 1\n else: right -= 1\n return max_area", "solution_java": "public int maxArea(int[] height) {\n int left = 0, right = height.length - 1, maxArea = 0;\n while (left < right) {\n int h = Math.min(height[left], height[right]);\n maxArea = Math.max(maxArea, h * (right - left));\n if (height[left] < height[right]) left++;\n else right--;\n }\n return maxArea;\n}", "solution_cpp": "int maxArea(vector& height) {\n int left = 0, right = height.size() - 1, maxArea = 0;\n while (left < right) {\n int h = min(height[left], height[right]);\n maxArea = max(maxArea, h * (right - left));\n if (height[left] < height[right]) left++;\n else right--;\n }\n return maxArea;\n}", "test_cases": ["height=[1,8,6,2,5,4,8,3,7] -> 49"], "key_points": ["移动短边指针", "面积=min(h1,h2)*width"], "tags": ["two-pointers", "medium", "Google", "Uber"]} {"problem_id": "algo_00698", "original_id": "min-stack", "title": "最小栈", "category": "stack", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "设计一个支持 push,pop,top 操作,并能在常数时间内检索到最小元素的栈。", "solution_python": "class MinStack:\n def __init__(self):\n self.stack = []\n self.min_stack = []\n def push(self, val):\n self.stack.append(val)\n self.min_stack.append(min(val, self.min_stack[-1] if self.min_stack else val))\n def pop(self):\n self.stack.pop(); self.min_stack.pop()\n def top(self): return self.stack[-1]\n def getMin(self): return self.min_stack[-1]", "solution_java": "class MinStack {\n Stack stack = new Stack<>();\n Stack minStack = new Stack<>();\n public void push(int val) { stack.push(val); minStack.push(Math.min(val, minStack.isEmpty() ? val : minStack.peek())); }\n public void pop() { stack.pop(); minStack.pop(); }\n public int top() { return stack.peek(); }\n public int getMin() { return minStack.peek(); }\n}", "solution_cpp": "class MinStack {\n stack st, minSt;\npublic:\n void push(int val) { st.push(val); minSt.push(min(val, minSt.empty() ? val : minSt.top())); }\n void pop() { st.pop(); minSt.pop(); }\n int top() { return st.top(); }\n int getMin() { return minSt.top(); }\n};", "test_cases": ["push(-2), push(0), push(-3) -> getMin() returns -3"], "key_points": ["辅助栈记录最小值", "O(1)时间获取最小值"], "tags": ["stack", "medium", "Google", "Microsoft"]} {"problem_id": "algo_00699", "original_id": "lru-cache", "title": "LRU缓存", "category": "design", "difficulty": "hard", "companies": ["Google", "Amazon"], "description": "设计和实现一个 LRU(最近最少使用)缓存机制。", "solution_python": "class LRUCache:\n def __init__(self, capacity):\n self.capacity = capacity\n self.cache = {}\n self.order = []\n def get(self, key):\n if key not in self.cache: return -1\n self.order.remove(key); self.order.append(key)\n return self.cache[key]\n def put(self, key, value):\n if key in self.cache:\n self.order.remove(key)\n elif len(self.cache) >= self.capacity:\n del self.cache[self.order.pop(0)]\n self.cache[key] = value; self.order.append(key)", "solution_java": "class LRUCache {\n int capacity;\n LinkedHashMap cache = new LinkedHashMap<>();\n public LRUCache(int cap) { capacity = cap; }\n public int get(int key) { return cache.containsKey(key) ? cache.remove(key) : -1; }\n public void put(int key, int val) {\n if (cache.containsKey(key)) cache.remove(key);\n else if (cache.size() >= capacity) cache.remove(cache.keySet().iterator().next());\n cache.put(key, val);\n }\n}", "solution_cpp": "class LRUCache {\n int cap;\n list> dll;\n unordered_map>::iterator> cache;\npublic:\n LRUCache(int capacity) : cap(capacity) {}\n int get(int key) {\n auto it = cache.find(key);\n if (it == cache.end()) return -1;\n dll.splice(dll.end(), dll, it->second);\n return it->second->second;\n }\n void put(int key, int value) {\n auto it = cache.find(key);\n if (it != cache.end()) dll.erase(it->second);\n else if (cache.size() >= cap) { cache.erase(dll.front().first); dll.pop_front(); }\n dll.push_back({key, value});\n cache[key] = --dll.end();\n }\n};", "test_cases": ["put(1,1), put(2,2), get(1) -> 1"], "key_points": ["HashMap + 双向链表", "O(1)时间操作"], "tags": ["design", "hard", "Google", "Amazon"]} {"problem_id": "algo_00700", "original_id": "num-islands", "title": "岛屿数量", "category": "graph", "difficulty": "medium", "companies": ["Google", "Facebook"], "description": "给你一个由 '1'(陆地)和 '0'(水)组成的二维网格,请你计算网格中岛屿的数量。岛屿总是被水包围,且只能由水平或垂直方向相邻的陆地连接形成。", "solution_python": "def numIslands(grid):\n if not grid: return 0\n rows, cols = len(grid), len(grid[0])\n count = 0\n def dfs(r, c):\n if r < 0 or r >= rows or c < 0 or c >= cols or grid[r][c] != '1': return\n grid[r][c] = '0'\n dfs(r+1, c); dfs(r-1, c); dfs(r, c+1); dfs(r, c-1)\n for r in range(rows):\n for c in range(cols):\n if grid[r][c] == '1': count += 1; dfs(r, c)\n return count", "solution_java": "public int numIslands(char[][] grid) {\n if (grid.length == 0) return 0;\n int count = 0;\n for (int i = 0; i < grid.length; i++)\n for (int j = 0; j < grid[0].length; j++)\n if (grid[i][j] == '1') { count++; dfs(grid, i, j); }\n return count;\n}\nprivate void dfs(char[][] grid, int r, int c) {\n if (r < 0 || r >= grid.length || c < 0 || c >= grid[0].length || grid[r][c] != '1') return;\n grid[r][c] = '0';\n dfs(grid, r+1, c); dfs(grid, r-1, c); dfs(grid, r, c+1); dfs(grid, r, c-1);\n}", "solution_cpp": "int numIslands(vector>& grid) {\n if (grid.empty()) return 0;\n int count = 0;\n for (int i = 0; i < grid.size(); i++)\n for (int j = 0; j < grid[0].size(); j++)\n if (grid[i][j] == '1') { count++; dfs(grid, i, j); }\n return count;\n}\nvoid dfs(vector>& grid, int r, int c) {\n if (r < 0 || r >= grid.size() || c < 0 || c >= grid[0].size() || grid[r][c] != '1') return;\n grid[r][c] = '0';\n dfs(grid, r+1, c); dfs(grid, r-1, c); dfs(grid, r, c+1); dfs(grid, r, c-1);\n}", "test_cases": ["grid=[[1,1,1,1,0],[1,1,0,1,0],[1,1,0,0,0],[0,0,0,0,0]] -> 1"], "key_points": ["DFS/BFS遍历", "访问后标记为0避免重复"], "tags": ["graph", "medium", "Google", "Facebook"]} {"problem_id": "algo_00701", "original_id": "two-sum", "title": "两数之和", "category": "array", "difficulty": "easy", "companies": ["Amazon", "Google"], "description": "给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那两个整数,并返回他们的数组下标。", "solution_python": "def twoSum(nums, target):\n hashmap = {}\n for i, num in enumerate(nums):\n complement = target - num\n if complement in hashmap:\n return [hashmap[complement], i]\n hashmap[num] = i\n return []", "solution_java": "public int[] twoSum(int[] nums, int target) {\n Map map = new HashMap<>();\n for (int i = 0; i < nums.length; i++) {\n int complement = target - nums[i];\n if (map.containsKey(complement)) return new int[]{map.get(complement), i};\n map.put(nums[i], i);\n }\n return new int[]{};\n}", "solution_cpp": "vector twoSum(vector& nums, int target) {\n unordered_map m;\n for (int i = 0; i < nums.size(); i++) {\n if (m.count(target - nums[i])) return {m[target - nums[i]], i};\n m[nums[i]] = i;\n }\n return {};\n}", "test_cases": ["nums=[2,7,11,15], target=9 -> [0,1]", "nums=[3,2,4], target=6 -> [1,2]"], "key_points": ["哈希表一次遍历", "空间换时间"], "tags": ["array", "easy", "Amazon", "Google"]} {"problem_id": "algo_00702", "original_id": "merge-sorted", "title": "合并两个有序数组", "category": "array", "difficulty": "easy", "companies": ["Microsoft", "Uber"], "description": "给你两个按非递减顺序排列的整数数组 nums1 和 nums2,另有两个整数 m 和 n,分别表示 nums1 和 nums2 中的元素数目。请你合并 nums2 到 nums1 中。", "solution_python": "def merge(nums1, m, nums2, n):\n p1, p2, p = m-1, n-1, m+n-1\n while p1 >= 0 and p2 >= 0:\n if nums1[p1] > nums2[p2]: nums1[p] = nums1[p1]; p1 -= 1\n else: nums1[p] = nums2[p2]; p2 -= 1\n p -= 1\n while p2 >= 0: nums1[p] = nums2[p2]; p2 -= 1; p -= 1", "solution_java": "public void merge(int[] nums1, int m, int[] nums2, int n) {\n int p1 = m-1, p2 = n-1, p = m+n-1;\n while (p1 >= 0 && p2 >= 0) {\n nums1[p--] = nums1[p1] > nums2[p2] ? nums1[p1--] : nums2[p2--];\n }\n while (p2 >= 0) nums1[p--] = nums2[p2--];\n}", "solution_cpp": "void merge(vector& nums1, int m, vector& nums2, int n) {\n int p1 = m-1, p2 = n-1, p = m+n-1;\n while (p1 >= 0 && p2 >= 0) nums1[p--] = nums1[p1] > nums2[p2] ? nums1[p1--] : nums2[p2--];\n while (p2 >= 0) nums1[p--] = nums2[p2--];\n}", "test_cases": ["nums1=[1,2,3], m=3, nums2=[2,5,6], n=3 -> [1,2,2,3,5,6]", "nums1=[], m=0, nums2=[1], n=1 -> [1]"], "key_points": ["从后往前合并", "三指针技巧"], "tags": ["array", "easy", "Microsoft", "Uber"]} {"problem_id": "algo_00703", "original_id": "max-subarray", "title": "最大子数组和", "category": "array", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "给你一个整数数组 nums ,请你找出一个具有最大和的连续子数组,返回其最大和。", "solution_python": "def maxSubArray(nums):\n max_sum = current = nums[0]\n for num in nums[1:]:\n current = max(num, current + num)\n max_sum = max(max_sum, current)\n return max_sum", "solution_java": "public int maxSubArray(int[] nums) {\n int maxSum = nums[0], curr = nums[0];\n for (int i = 1; i < nums.length; i++) {\n curr = Math.max(nums[i], curr + nums[i]);\n maxSum = Math.max(maxSum, curr);\n }\n return maxSum;\n}", "solution_cpp": "int maxSubArray(vector& nums) {\n int maxSum = nums[0], curr = nums[0];\n for (int i = 1; i < nums.size(); i++) {\n curr = max(nums[i], curr + nums[i]);\n maxSum = max(maxSum, curr);\n }\n return maxSum;\n}", "test_cases": ["nums=[-2,1,-3,4,-1,2,1,-5,4] -> 6", "nums=[1] -> 1"], "key_points": ["Kadane算法", "动态规划基础题"], "tags": ["array", "medium", "Google", "Microsoft"]} {"problem_id": "algo_00704", "original_id": "valid-parentheses", "title": "有效的括号", "category": "string", "difficulty": "easy", "companies": ["Google", "Uber"], "description": "给定一个只包括 '(',')','{','}','[',']' 的字符串 s,判断字符串是否有效。", "solution_python": "def isValid(s):\n stack = []\n mapping = {')': '(', ']': '[', '}': '{'}\n for c in s:\n if c in mapping:\n if not stack or stack[-1] != mapping[c]: return False\n stack.pop()\n else: stack.append(c)\n return not stack", "solution_java": "public boolean isValid(String s) {\n Stack stack = new Stack<>();\n Map map = Map.of(')', '(', ']', '[', '}', '{');\n for (char c : s.toCharArray()) {\n if (map.containsValue(c)) stack.push(c);\n else if (!stack.isEmpty() && stack.pop() != map.get(c)) return false;\n }\n return stack.isEmpty();\n}", "solution_cpp": "bool isValid(string s) {\n stack st;\n unordered_map m = {{')','('},{']','['},{'}','{'}};\n for (char c : s) {\n if (m.find(c) == m.end()) st.push(c);\n else if (st.empty() || st.top() != m[c]) return false;\n else st.pop();\n }\n return st.empty();\n}", "test_cases": ["s=\"()\" -> true", "s=\"()[]{}\" -> true", "s=\"(]\" -> false"], "key_points": ["栈匹配法", "注意空栈边界"], "tags": ["string", "easy", "Google", "Uber"]} {"problem_id": "algo_00705", "original_id": "longest-palindrome", "title": "最长回文子串", "category": "string", "difficulty": "medium", "companies": ["Google", "Amazon"], "description": "给你一个字符串 s,找到 s 中最长的回文子串。", "solution_python": "def longestPalindrome(s):\n def expand(l, r):\n while l >= 0 and r < len(s) and s[l] == s[r]: l -= 1; r += 1\n return l + 1, r - 1\n start = end = 0\n for i in range(len(s)):\n l1, r1 = expand(i, i)\n l2, r2 = expand(i, i + 1)\n if r1 - l1 > end - start: start, end = l1, r1\n if r2 - l2 > end - start: start, end = l2, r2\n return s[start:end+1]", "solution_java": "public String longestPalindrome(String s) {\n int start = 0, end = 0;\n for (int i = 0; i < s.length(); i++) {\n int len1 = expand(s, i, i), len2 = expand(s, i, i+1);\n int len = Math.max(len1, len2);\n if (len > end - start) { start = i - (len-1)/2; end = i + len/2; }\n }\n return s.substring(start, end + 1);\n}\nprivate int expand(String s, int l, int r) {\n while (l >= 0 && r < s.length() && s.charAt(l) == s.charAt(r)) { l--; r++; }\n return r - l - 1;\n}", "solution_cpp": "string longestPalindrome(string s) {\n int start = 0, end = 0;\n for (int i = 0; i < s.size(); i++) {\n int len1 = expand(s, i, i), len2 = expand(s, i, i+1);\n if (max(len1, len2) > end - start) { start = i - (max(len1,len2)-1)/2; end = i + max(len1,len2)/2; }\n }\n return s.substr(start, end - start + 1);\n}", "test_cases": ["s=\"babad\" -> bab或aba", "s=\"cbbd\" -> bb"], "key_points": ["中心扩展法", "处理奇偶长度"], "tags": ["string", "medium", "Google", "Amazon"]} {"problem_id": "algo_00706", "original_id": "reverse-list", "title": "反转链表", "category": "linkedlist", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "给你单链表的头节点 head,请你反转链表,并返回反转后的链表。", "solution_python": "def reverseList(head):\n prev = None\n curr = head\n while curr:\n nxt = curr.next\n curr.next = prev\n prev = curr\n curr = nxt\n return prev", "solution_java": "public ListNode reverseList(ListNode head) {\n ListNode prev = null, curr = head;\n while (curr != null) {\n ListNode next = curr.next;\n curr.next = prev;\n prev = curr;\n curr = next;\n }\n return prev;\n}", "solution_cpp": "ListNode* reverseList(ListNode* head) {\n ListNode* prev = nullptr, *curr = head;\n while (curr) {\n ListNode* next = curr->next;\n curr->next = prev;\n prev = curr;\n curr = next;\n }\n return prev;\n}", "test_cases": ["head=[1,2,3,4,5] -> [5,4,3,2,1]", "head=[1,2] -> [2,1]"], "key_points": ["迭代法 O(1)空间", "递归法 O(n)空间"], "tags": ["linkedlist", "medium", "Google", "Microsoft"]} {"problem_id": "algo_00707", "original_id": "middle-node", "title": "链表的中间结点", "category": "linkedlist", "difficulty": "easy", "companies": ["Amazon", "Facebook"], "description": "给你单链表的头节点 head,请你找出并返回链表的中间结点。如果有两个中间结点,则返回第二个中间结点。", "solution_python": "def middleNode(head):\n slow = fast = head\n while fast and fast.next:\n slow = slow.next\n fast = fast.next.next\n return slow", "solution_java": "public ListNode middleNode(ListNode head) {\n ListNode slow = head, fast = head;\n while (fast != null && fast.next != null) {\n slow = slow.next;\n fast = fast.next.next;\n }\n return slow;\n}", "solution_cpp": "ListNode* middleNode(ListNode* head) {\n ListNode* slow = head, *fast = head;\n while (fast && fast->next) { slow = slow->next; fast = fast->next->next; }\n return slow;\n}", "test_cases": ["head=[1,2,3,4,5] -> 3", "head=[1,2,3,4,5,6] -> 4"], "key_points": ["快慢指针", "O(n)时间O(1)空间"], "tags": ["linkedlist", "easy", "Amazon", "Facebook"]} {"problem_id": "algo_00708", "original_id": "max-depth", "title": "二叉树的最大深度", "category": "tree", "difficulty": "easy", "companies": ["Microsoft", "Apple"], "description": "给定一个二叉树 root,返回其最大深度。", "solution_python": "def maxDepth(root):\n if not root: return 0\n return max(maxDepth(root.left), maxDepth(root.right)) + 1", "solution_java": "public int maxDepth(TreeNode root) {\n if (root == null) return 0;\n return Math.max(maxDepth(root.left), maxDepth(root.right)) + 1;\n}", "solution_cpp": "int maxDepth(TreeNode* root) {\n if (!root) return 0;\n return max(maxDepth(root->left), maxDepth(root->right)) + 1;\n}", "test_cases": ["root=[3,9,20,null,null,15,7] -> 3", "root=[1,null,2] -> 2"], "key_points": ["DFS递归", "层序遍历也可"], "tags": ["tree", "easy", "Microsoft", "Apple"]} {"problem_id": "algo_00709", "original_id": "inorder-traversal", "title": "二叉树的中序遍历", "category": "tree", "difficulty": "easy", "companies": ["Google", "Microsoft"], "description": "给定一个二叉树的根节点 root,返回它的中序遍历结果。", "solution_python": "def inorderTraversal(root):\n result = []\n def dfs(node):\n if node:\n dfs(node.left)\n result.append(node.val)\n dfs(node.right)\n dfs(root)\n return result", "solution_java": "public List inorderTraversal(TreeNode root) {\n List res = new ArrayList<>();\n dfs(root, res);\n return res;\n}\nprivate void dfs(TreeNode node, List res) {\n if (node == null) return;\n dfs(node.left, res); res.add(node.val); dfs(node.right, res);\n}", "solution_cpp": "vector inorderTraversal(TreeNode* root) {\n vector res;\n dfs(root, res);\n return res;\n}\nvoid dfs(TreeNode* node, vector& res) {\n if (!node) return;\n dfs(node->left, res); res.push_back(node->val); dfs(node->right, res);\n}", "test_cases": ["root=[1,null,2,3] -> [1,3,2]", "root=[] -> []"], "key_points": ["左-根-右顺序", "递归最简洁"], "tags": ["tree", "easy", "Google", "Microsoft"]} {"problem_id": "algo_00710", "original_id": "binary-search", "title": "二分查找", "category": "binarysearch", "difficulty": "easy", "companies": ["Google", "Amazon"], "description": "给定一个 n 个元素有序的(升序)整型数组 nums 和一个目标值 target,写一个函数搜索 nums 中的 target,如果目标值存在返回下标,否则返回 -1。", "solution_python": "def search(nums, target):\n left, right = 0, len(nums) - 1\n while left <= right:\n mid = (left + right) // 2\n if nums[mid] == target: return mid\n elif nums[mid] < target: left = mid + 1\n else: right = mid - 1\n return -1", "solution_java": "public int search(int[] nums, int target) {\n int left = 0, right = nums.length - 1;\n while (left <= right) {\n int mid = left + (right - left) / 2;\n if (nums[mid] == target) return mid;\n else if (nums[mid] < target) left = mid + 1;\n else right = mid - 1;\n }\n return -1;\n}", "solution_cpp": "int search(vector& nums, int target) {\n int left = 0, right = nums.size() - 1;\n while (left <= right) {\n int mid = left + (right - left) / 2;\n if (nums[mid] == target) return mid;\n else if (nums[mid] < target) left = mid + 1;\n else right = mid - 1;\n }\n return -1;\n}", "test_cases": ["nums=[-1,0,3,5,9,12], target=9 -> 4", "nums=[-1,0,3,5,9,12], target=2 -> -1"], "key_points": ["标准模板", "注意防溢出写法"], "tags": ["binarysearch", "easy", "Google", "Amazon"]} {"problem_id": "algo_00711", "original_id": "climbing-stairs", "title": "爬楼梯", "category": "dp", "difficulty": "easy", "companies": ["Amazon", "Google"], "description": "假设你正在爬楼梯。需要 n 阶你才能到达楼顶。每次你可以爬 1 或 2 个台阶。你有多少种不同的方法可以爬到楼顶?", "solution_python": "def climbStairs(n):\n if n <= 2: return n\n a, b = 1, 2\n for _ in range(3, n+1):\n a, b = b, a + b\n return b", "solution_java": "public int climbStairs(int n) {\n if (n <= 2) return n;\n int a = 1, b = 2;\n for (int i = 3; i <= n; i++) { int temp = a + b; a = b; b = temp; }\n return b;\n}", "solution_cpp": "int climbStairs(int n) {\n if (n <= 2) return n;\n int a = 1, b = 2;\n for (int i = 3; i <= n; i++) { int temp = a + b; a = b; b = temp; }\n return b;\n}", "test_cases": ["n=2 -> 2", "n=3 -> 3", "n=5 -> 8"], "key_points": ["斐波那契数列", "滚动数组优化空间"], "tags": ["dp", "easy", "Amazon", "Google"]} {"problem_id": "algo_00712", "original_id": "coin-change", "title": "零钱兑换", "category": "dp", "difficulty": "medium", "companies": ["Google", "Amazon"], "description": "给你一个整数数组 coins 表示不同面额的硬币,以及一个整数 amount 表示总金额。计算并返回可以凑成总金额所需的最少的硬币个数。如果没有任何一种硬币组合能组成总金额,返回 -1。", "solution_python": "def coinChange(coins, amount):\n dp = [float('inf')] * (amount + 1)\n dp[0] = 0\n for coin in coins:\n for x in range(coin, amount + 1):\n dp[x] = min(dp[x], dp[x - coin] + 1)\n return dp[amount] if dp[amount] != float('inf') else -1", "solution_java": "public int coinChange(int[] coins, int amount) {\n int[] dp = new int[amount + 1];\n Arrays.fill(dp, amount + 1);\n dp[0] = 0;\n for (int coin : coins) {\n for (int x = coin; x <= amount; x++) {\n dp[x] = Math.min(dp[x], dp[x - coin] + 1);\n }\n }\n return dp[amount] > amount ? -1 : dp[amount];\n}", "solution_cpp": "int coinChange(vector& coins, int amount) {\n vector dp(amount + 1, amount + 1);\n dp[0] = 0;\n for (int coin : coins) {\n for (int x = coin; x <= amount; x++) {\n dp[x] = min(dp[x], dp[x - coin] + 1);\n }\n }\n return dp[amount] > amount ? -1 : dp[amount];\n}", "test_cases": ["coins=[1,2,5], amount=11 -> 3", "coins=[2], amount=3 -> -1"], "key_points": ["完全背包问题", "dp[x] = min(dp[x-coin]+1)"], "tags": ["dp", "medium", "Google", "Amazon"]} {"problem_id": "algo_00713", "original_id": "subsets", "title": "子集", "category": "backtracking", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "给你一个整数数组 nums ,数组中的元素 互不相同 。返回该数组所有可能的子集(幂集)。", "solution_python": "def subsets(nums):\n result = []\n def backtrack(start, path):\n result.append(path[:])\n for i in range(start, len(nums)):\n path.append(nums[i])\n backtrack(i + 1, path)\n path.pop()\n backtrack(0, [])\n return result", "solution_java": "public List> subsets(int[] nums) {\n List> result = new ArrayList<>();\n backtrack(nums, 0, new ArrayList<>(), result);\n return result;\n}\nprivate void backtrack(int[] nums, int start, List path, List> result) {\n result.add(new ArrayList<>(path));\n for (int i = start; i < nums.length; i++) {\n path.add(nums[i]);\n backtrack(nums, i + 1, path, result);\n path.remove(path.size() - 1);\n }\n}", "solution_cpp": "vector> subsets(vector& nums) {\n vector> result;\n vector path;\n backtrack(nums, 0, path, result);\n return result;\n}\nvoid backtrack(vector& nums, int start, vector& path, vector>& result) {\n result.push_back(path);\n for (int i = start; i < nums.size(); i++) {\n path.push_back(nums[i]);\n backtrack(nums, i + 1, path, result);\n path.pop_back();\n }\n}", "test_cases": ["nums=[1,2,3] -> [[],[1],[2],[1,2],[3],[1,3],[2,3],[1,2,3]]"], "key_points": ["选或不选", "DFS遍历子集树"], "tags": ["backtracking", "medium", "Google", "Microsoft"]} {"problem_id": "algo_00714", "original_id": "permutations", "title": "全排列", "category": "backtracking", "difficulty": "medium", "companies": ["Google", "Facebook"], "description": "给定一个不含重复数字的数组 nums,返回其所有可能的全排列。", "solution_python": "def permute(nums):\n result = []\n def backtrack(path, used):\n if len(path) == len(nums):\n result.append(path[:])\n return\n for i in range(len(nums)):\n if used[i]: continue\n used[i] = True\n path.append(nums[i])\n backtrack(path, used)\n path.pop()\n used[i] = False\n backtrack([], [False]*len(nums))\n return result", "solution_java": "public List> permute(int[] nums) {\n List> result = new ArrayList<>();\n boolean[] used = new boolean[nums.length];\n backtrack(nums, used, new ArrayList<>(), result);\n return result;\n}\nprivate void backtrack(int[] nums, boolean[] used, List path, List> result) {\n if (path.size() == nums.length) { result.add(new ArrayList<>(path)); return; }\n for (int i = 0; i < nums.length; i++) {\n if (used[i]) continue;\n used[i] = true;\n path.add(nums[i]);\n backtrack(nums, used, path, result);\n path.remove(path.size() - 1);\n used[i] = false;\n }\n}", "solution_cpp": "vector> permute(vector& nums) {\n vector> result;\n vector used(nums.size(), false);\n vector path;\n backtrack(nums, used, path, result);\n return result;\n}\nvoid backtrack(vector& nums, vector& used, vector& path, vector>& result) {\n if (path.size() == nums.size()) { result.push_back(path); return; }\n for (int i = 0; i < nums.size(); i++) {\n if (used[i]) continue;\n used[i] = true;\n path.push_back(nums[i]);\n backtrack(nums, used, path, result);\n path.pop_back();\n used[i] = false;\n }\n}", "test_cases": ["nums=[1,2,3] -> [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]"], "key_points": ["标记已使用元素", "回溯经典模板"], "tags": ["backtracking", "medium", "Google", "Facebook"]} {"problem_id": "algo_00715", "original_id": "top-k-frequent", "title": "前K个高频元素", "category": "heap", "difficulty": "medium", "companies": ["Amazon", "Facebook"], "description": "给你一个整数数组 nums 和一个整数 k,请你返回其中出现频率前 k 高的元素。", "solution_python": "import heapq\nfrom collections import Counter\ndef topKFrequent(nums, k):\n count = Counter(nums)\n heap = []\n for num, freq in count.items():\n heapq.heappush(heap, (freq, num))\n if len(heap) > k: heapq.heappop(heap)\n return [num for freq, num in heap]", "solution_java": "public int[] topKFrequent(int[] nums, int k) {\n Map count = new HashMap<>();\n for (int n : nums) count.put(n, count.getOrDefault(n, 0) + 1);\n PriorityQueue> heap = \n new PriorityQueue<>((a, b) -> a.getValue() - b.getValue());\n for (Map.Entry e : count.entrySet()) {\n heap.offer(e);\n if (heap.size() > k) heap.poll();\n }\n int[] res = new int[k];\n for (int i = k - 1; i >= 0; i--) res[i] = heap.poll().getKey();\n return res;\n}", "solution_cpp": "vector topKFrequent(vector& nums, int k) {\n unordered_map count;\n for (int n : nums) count[n]++;\n priority_queue, vector>, greater>> heap;\n for (auto& [num, freq] : count) {\n heap.push({freq, num});\n if (heap.size() > k) heap.pop();\n }\n vector res;\n while (!heap.empty()) { res.push_back(heap.top().second); heap.pop(); }\n reverse(res.begin(), res.end());\n return res;\n}", "test_cases": ["nums=[1,1,1,2,2,3], k=2 -> [1,2]", "nums=[1], k=1 -> [1]"], "key_points": ["小顶堆保持大小k", "时间复杂度O(nlogk)"], "tags": ["heap", "medium", "Amazon", "Facebook"]} {"problem_id": "algo_00716", "original_id": "3sum", "title": "三数之和", "category": "two-pointers", "difficulty": "medium", "companies": ["Google", "Amazon"], "description": "给你一个整数数组 nums,判断是否存在三元组满足和为0,返回所有不重复的三元组。", "solution_python": "def threeSum(nums):\n nums.sort()\n result = []\n for i in range(len(nums) - 2):\n if i > 0 and nums[i] == nums[i-1]: continue\n left, right = i + 1, len(nums) - 1\n while left < right:\n total = nums[i] + nums[left] + nums[right]\n if total < 0: left += 1\n elif total > 0: right -= 1\n else:\n result.append([nums[i], nums[left], nums[right]])\n while left < right and nums[left] == nums[left+1]: left += 1\n while left < right and nums[right] == nums[right-1]: right -= 1\n left += 1; right -= 1\n return result", "solution_java": "public List> threeSum(int[] nums) {\n Arrays.sort(nums);\n List> result = new ArrayList<>();\n for (int i = 0; i < nums.length - 2; i++) {\n if (i > 0 && nums[i] == nums[i-1]) continue;\n int left = i + 1, right = nums.length - 1;\n while (left < right) {\n int total = nums[i] + nums[left] + nums[right];\n if (total < 0) left++;\n else if (total > 0) right--;\n else {\n result.add(Arrays.asList(nums[i], nums[left], nums[right]));\n while (left < right && nums[left] == nums[left+1]) left++;\n while (left < right && nums[right] == nums[right-1]) right--;\n left++; right--;\n }\n }\n }\n return result;\n}", "solution_cpp": "vector> threeSum(vector& nums) {\n sort(nums.begin(), nums.end());\n vector> result;\n for (int i = 0; i < nums.size() - 2; i++) {\n if (i > 0 && nums[i] == nums[i-1]) continue;\n int left = i + 1, right = nums.size() - 1;\n while (left < right) {\n int total = nums[i] + nums[left] + nums[right];\n if (total < 0) left++;\n else if (total > 0) right--;\n else {\n result.push_back({nums[i], nums[left], nums[right]});\n while (left < right && nums[left] == nums[left+1]) left++;\n while (left < right && nums[right] == nums[right-1]) right--;\n left++; right--;\n }\n }\n }\n return result;\n}", "test_cases": ["nums=[-1,0,1,2,-1,-4] -> [[-1,-1,2],[-1,0,1]]"], "key_points": ["排序+双指针", "去重是关键"], "tags": ["two-pointers", "medium", "Google", "Amazon"]} {"problem_id": "algo_00717", "original_id": "container-water", "title": "盛最多水的容器", "category": "two-pointers", "difficulty": "medium", "companies": ["Google", "Uber"], "description": "给定一个长度为 n 的整数数组 height,找出其中的两条线,使得它们与 x 轴共同构成的容器可以容纳最多的水。", "solution_python": "def maxArea(height):\n left, right = 0, len(height) - 1\n max_area = 0\n while left < right:\n h = min(height[left], height[right])\n max_area = max(max_area, h * (right - left))\n if height[left] < height[right]: left += 1\n else: right -= 1\n return max_area", "solution_java": "public int maxArea(int[] height) {\n int left = 0, right = height.length - 1, maxArea = 0;\n while (left < right) {\n int h = Math.min(height[left], height[right]);\n maxArea = Math.max(maxArea, h * (right - left));\n if (height[left] < height[right]) left++;\n else right--;\n }\n return maxArea;\n}", "solution_cpp": "int maxArea(vector& height) {\n int left = 0, right = height.size() - 1, maxArea = 0;\n while (left < right) {\n int h = min(height[left], height[right]);\n maxArea = max(maxArea, h * (right - left));\n if (height[left] < height[right]) left++;\n else right--;\n }\n return maxArea;\n}", "test_cases": ["height=[1,8,6,2,5,4,8,3,7] -> 49"], "key_points": ["移动短边指针", "面积=min(h1,h2)*width"], "tags": ["two-pointers", "medium", "Google", "Uber"]} {"problem_id": "algo_00718", "original_id": "min-stack", "title": "最小栈", "category": "stack", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "设计一个支持 push,pop,top 操作,并能在常数时间内检索到最小元素的栈。", "solution_python": "class MinStack:\n def __init__(self):\n self.stack = []\n self.min_stack = []\n def push(self, val):\n self.stack.append(val)\n self.min_stack.append(min(val, self.min_stack[-1] if self.min_stack else val))\n def pop(self):\n self.stack.pop(); self.min_stack.pop()\n def top(self): return self.stack[-1]\n def getMin(self): return self.min_stack[-1]", "solution_java": "class MinStack {\n Stack stack = new Stack<>();\n Stack minStack = new Stack<>();\n public void push(int val) { stack.push(val); minStack.push(Math.min(val, minStack.isEmpty() ? val : minStack.peek())); }\n public void pop() { stack.pop(); minStack.pop(); }\n public int top() { return stack.peek(); }\n public int getMin() { return minStack.peek(); }\n}", "solution_cpp": "class MinStack {\n stack st, minSt;\npublic:\n void push(int val) { st.push(val); minSt.push(min(val, minSt.empty() ? val : minSt.top())); }\n void pop() { st.pop(); minSt.pop(); }\n int top() { return st.top(); }\n int getMin() { return minSt.top(); }\n};", "test_cases": ["push(-2), push(0), push(-3) -> getMin() returns -3"], "key_points": ["辅助栈记录最小值", "O(1)时间获取最小值"], "tags": ["stack", "medium", "Google", "Microsoft"]} {"problem_id": "algo_00719", "original_id": "lru-cache", "title": "LRU缓存", "category": "design", "difficulty": "hard", "companies": ["Google", "Amazon"], "description": "设计和实现一个 LRU(最近最少使用)缓存机制。", "solution_python": "class LRUCache:\n def __init__(self, capacity):\n self.capacity = capacity\n self.cache = {}\n self.order = []\n def get(self, key):\n if key not in self.cache: return -1\n self.order.remove(key); self.order.append(key)\n return self.cache[key]\n def put(self, key, value):\n if key in self.cache:\n self.order.remove(key)\n elif len(self.cache) >= self.capacity:\n del self.cache[self.order.pop(0)]\n self.cache[key] = value; self.order.append(key)", "solution_java": "class LRUCache {\n int capacity;\n LinkedHashMap cache = new LinkedHashMap<>();\n public LRUCache(int cap) { capacity = cap; }\n public int get(int key) { return cache.containsKey(key) ? cache.remove(key) : -1; }\n public void put(int key, int val) {\n if (cache.containsKey(key)) cache.remove(key);\n else if (cache.size() >= capacity) cache.remove(cache.keySet().iterator().next());\n cache.put(key, val);\n }\n}", "solution_cpp": "class LRUCache {\n int cap;\n list> dll;\n unordered_map>::iterator> cache;\npublic:\n LRUCache(int capacity) : cap(capacity) {}\n int get(int key) {\n auto it = cache.find(key);\n if (it == cache.end()) return -1;\n dll.splice(dll.end(), dll, it->second);\n return it->second->second;\n }\n void put(int key, int value) {\n auto it = cache.find(key);\n if (it != cache.end()) dll.erase(it->second);\n else if (cache.size() >= cap) { cache.erase(dll.front().first); dll.pop_front(); }\n dll.push_back({key, value});\n cache[key] = --dll.end();\n }\n};", "test_cases": ["put(1,1), put(2,2), get(1) -> 1"], "key_points": ["HashMap + 双向链表", "O(1)时间操作"], "tags": ["design", "hard", "Google", "Amazon"]} {"problem_id": "algo_00720", "original_id": "num-islands", "title": "岛屿数量", "category": "graph", "difficulty": "medium", "companies": ["Google", "Facebook"], "description": "给你一个由 '1'(陆地)和 '0'(水)组成的二维网格,请你计算网格中岛屿的数量。岛屿总是被水包围,且只能由水平或垂直方向相邻的陆地连接形成。", "solution_python": "def numIslands(grid):\n if not grid: return 0\n rows, cols = len(grid), len(grid[0])\n count = 0\n def dfs(r, c):\n if r < 0 or r >= rows or c < 0 or c >= cols or grid[r][c] != '1': return\n grid[r][c] = '0'\n dfs(r+1, c); dfs(r-1, c); dfs(r, c+1); dfs(r, c-1)\n for r in range(rows):\n for c in range(cols):\n if grid[r][c] == '1': count += 1; dfs(r, c)\n return count", "solution_java": "public int numIslands(char[][] grid) {\n if (grid.length == 0) return 0;\n int count = 0;\n for (int i = 0; i < grid.length; i++)\n for (int j = 0; j < grid[0].length; j++)\n if (grid[i][j] == '1') { count++; dfs(grid, i, j); }\n return count;\n}\nprivate void dfs(char[][] grid, int r, int c) {\n if (r < 0 || r >= grid.length || c < 0 || c >= grid[0].length || grid[r][c] != '1') return;\n grid[r][c] = '0';\n dfs(grid, r+1, c); dfs(grid, r-1, c); dfs(grid, r, c+1); dfs(grid, r, c-1);\n}", "solution_cpp": "int numIslands(vector>& grid) {\n if (grid.empty()) return 0;\n int count = 0;\n for (int i = 0; i < grid.size(); i++)\n for (int j = 0; j < grid[0].size(); j++)\n if (grid[i][j] == '1') { count++; dfs(grid, i, j); }\n return count;\n}\nvoid dfs(vector>& grid, int r, int c) {\n if (r < 0 || r >= grid.size() || c < 0 || c >= grid[0].size() || grid[r][c] != '1') return;\n grid[r][c] = '0';\n dfs(grid, r+1, c); dfs(grid, r-1, c); dfs(grid, r, c+1); dfs(grid, r, c-1);\n}", "test_cases": ["grid=[[1,1,1,1,0],[1,1,0,1,0],[1,1,0,0,0],[0,0,0,0,0]] -> 1"], "key_points": ["DFS/BFS遍历", "访问后标记为0避免重复"], "tags": ["graph", "medium", "Google", "Facebook"]} {"problem_id": "algo_00721", "original_id": "two-sum", "title": "两数之和", "category": "array", "difficulty": "easy", "companies": ["Amazon", "Google"], "description": "给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那两个整数,并返回他们的数组下标。", "solution_python": "def twoSum(nums, target):\n hashmap = {}\n for i, num in enumerate(nums):\n complement = target - num\n if complement in hashmap:\n return [hashmap[complement], i]\n hashmap[num] = i\n return []", "solution_java": "public int[] twoSum(int[] nums, int target) {\n Map map = new HashMap<>();\n for (int i = 0; i < nums.length; i++) {\n int complement = target - nums[i];\n if (map.containsKey(complement)) return new int[]{map.get(complement), i};\n map.put(nums[i], i);\n }\n return new int[]{};\n}", "solution_cpp": "vector twoSum(vector& nums, int target) {\n unordered_map m;\n for (int i = 0; i < nums.size(); i++) {\n if (m.count(target - nums[i])) return {m[target - nums[i]], i};\n m[nums[i]] = i;\n }\n return {};\n}", "test_cases": ["nums=[2,7,11,15], target=9 -> [0,1]", "nums=[3,2,4], target=6 -> [1,2]"], "key_points": ["哈希表一次遍历", "空间换时间"], "tags": ["array", "easy", "Amazon", "Google"]} {"problem_id": "algo_00722", "original_id": "merge-sorted", "title": "合并两个有序数组", "category": "array", "difficulty": "easy", "companies": ["Microsoft", "Uber"], "description": "给你两个按非递减顺序排列的整数数组 nums1 和 nums2,另有两个整数 m 和 n,分别表示 nums1 和 nums2 中的元素数目。请你合并 nums2 到 nums1 中。", "solution_python": "def merge(nums1, m, nums2, n):\n p1, p2, p = m-1, n-1, m+n-1\n while p1 >= 0 and p2 >= 0:\n if nums1[p1] > nums2[p2]: nums1[p] = nums1[p1]; p1 -= 1\n else: nums1[p] = nums2[p2]; p2 -= 1\n p -= 1\n while p2 >= 0: nums1[p] = nums2[p2]; p2 -= 1; p -= 1", "solution_java": "public void merge(int[] nums1, int m, int[] nums2, int n) {\n int p1 = m-1, p2 = n-1, p = m+n-1;\n while (p1 >= 0 && p2 >= 0) {\n nums1[p--] = nums1[p1] > nums2[p2] ? nums1[p1--] : nums2[p2--];\n }\n while (p2 >= 0) nums1[p--] = nums2[p2--];\n}", "solution_cpp": "void merge(vector& nums1, int m, vector& nums2, int n) {\n int p1 = m-1, p2 = n-1, p = m+n-1;\n while (p1 >= 0 && p2 >= 0) nums1[p--] = nums1[p1] > nums2[p2] ? nums1[p1--] : nums2[p2--];\n while (p2 >= 0) nums1[p--] = nums2[p2--];\n}", "test_cases": ["nums1=[1,2,3], m=3, nums2=[2,5,6], n=3 -> [1,2,2,3,5,6]", "nums1=[], m=0, nums2=[1], n=1 -> [1]"], "key_points": ["从后往前合并", "三指针技巧"], "tags": ["array", "easy", "Microsoft", "Uber"]} {"problem_id": "algo_00723", "original_id": "max-subarray", "title": "最大子数组和", "category": "array", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "给你一个整数数组 nums ,请你找出一个具有最大和的连续子数组,返回其最大和。", "solution_python": "def maxSubArray(nums):\n max_sum = current = nums[0]\n for num in nums[1:]:\n current = max(num, current + num)\n max_sum = max(max_sum, current)\n return max_sum", "solution_java": "public int maxSubArray(int[] nums) {\n int maxSum = nums[0], curr = nums[0];\n for (int i = 1; i < nums.length; i++) {\n curr = Math.max(nums[i], curr + nums[i]);\n maxSum = Math.max(maxSum, curr);\n }\n return maxSum;\n}", "solution_cpp": "int maxSubArray(vector& nums) {\n int maxSum = nums[0], curr = nums[0];\n for (int i = 1; i < nums.size(); i++) {\n curr = max(nums[i], curr + nums[i]);\n maxSum = max(maxSum, curr);\n }\n return maxSum;\n}", "test_cases": ["nums=[-2,1,-3,4,-1,2,1,-5,4] -> 6", "nums=[1] -> 1"], "key_points": ["Kadane算法", "动态规划基础题"], "tags": ["array", "medium", "Google", "Microsoft"]} {"problem_id": "algo_00724", "original_id": "valid-parentheses", "title": "有效的括号", "category": "string", "difficulty": "easy", "companies": ["Google", "Uber"], "description": "给定一个只包括 '(',')','{','}','[',']' 的字符串 s,判断字符串是否有效。", "solution_python": "def isValid(s):\n stack = []\n mapping = {')': '(', ']': '[', '}': '{'}\n for c in s:\n if c in mapping:\n if not stack or stack[-1] != mapping[c]: return False\n stack.pop()\n else: stack.append(c)\n return not stack", "solution_java": "public boolean isValid(String s) {\n Stack stack = new Stack<>();\n Map map = Map.of(')', '(', ']', '[', '}', '{');\n for (char c : s.toCharArray()) {\n if (map.containsValue(c)) stack.push(c);\n else if (!stack.isEmpty() && stack.pop() != map.get(c)) return false;\n }\n return stack.isEmpty();\n}", "solution_cpp": "bool isValid(string s) {\n stack st;\n unordered_map m = {{')','('},{']','['},{'}','{'}};\n for (char c : s) {\n if (m.find(c) == m.end()) st.push(c);\n else if (st.empty() || st.top() != m[c]) return false;\n else st.pop();\n }\n return st.empty();\n}", "test_cases": ["s=\"()\" -> true", "s=\"()[]{}\" -> true", "s=\"(]\" -> false"], "key_points": ["栈匹配法", "注意空栈边界"], "tags": ["string", "easy", "Google", "Uber"]} {"problem_id": "algo_00725", "original_id": "longest-palindrome", "title": "最长回文子串", "category": "string", "difficulty": "medium", "companies": ["Google", "Amazon"], "description": "给你一个字符串 s,找到 s 中最长的回文子串。", "solution_python": "def longestPalindrome(s):\n def expand(l, r):\n while l >= 0 and r < len(s) and s[l] == s[r]: l -= 1; r += 1\n return l + 1, r - 1\n start = end = 0\n for i in range(len(s)):\n l1, r1 = expand(i, i)\n l2, r2 = expand(i, i + 1)\n if r1 - l1 > end - start: start, end = l1, r1\n if r2 - l2 > end - start: start, end = l2, r2\n return s[start:end+1]", "solution_java": "public String longestPalindrome(String s) {\n int start = 0, end = 0;\n for (int i = 0; i < s.length(); i++) {\n int len1 = expand(s, i, i), len2 = expand(s, i, i+1);\n int len = Math.max(len1, len2);\n if (len > end - start) { start = i - (len-1)/2; end = i + len/2; }\n }\n return s.substring(start, end + 1);\n}\nprivate int expand(String s, int l, int r) {\n while (l >= 0 && r < s.length() && s.charAt(l) == s.charAt(r)) { l--; r++; }\n return r - l - 1;\n}", "solution_cpp": "string longestPalindrome(string s) {\n int start = 0, end = 0;\n for (int i = 0; i < s.size(); i++) {\n int len1 = expand(s, i, i), len2 = expand(s, i, i+1);\n if (max(len1, len2) > end - start) { start = i - (max(len1,len2)-1)/2; end = i + max(len1,len2)/2; }\n }\n return s.substr(start, end - start + 1);\n}", "test_cases": ["s=\"babad\" -> bab或aba", "s=\"cbbd\" -> bb"], "key_points": ["中心扩展法", "处理奇偶长度"], "tags": ["string", "medium", "Google", "Amazon"]} {"problem_id": "algo_00726", "original_id": "reverse-list", "title": "反转链表", "category": "linkedlist", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "给你单链表的头节点 head,请你反转链表,并返回反转后的链表。", "solution_python": "def reverseList(head):\n prev = None\n curr = head\n while curr:\n nxt = curr.next\n curr.next = prev\n prev = curr\n curr = nxt\n return prev", "solution_java": "public ListNode reverseList(ListNode head) {\n ListNode prev = null, curr = head;\n while (curr != null) {\n ListNode next = curr.next;\n curr.next = prev;\n prev = curr;\n curr = next;\n }\n return prev;\n}", "solution_cpp": "ListNode* reverseList(ListNode* head) {\n ListNode* prev = nullptr, *curr = head;\n while (curr) {\n ListNode* next = curr->next;\n curr->next = prev;\n prev = curr;\n curr = next;\n }\n return prev;\n}", "test_cases": ["head=[1,2,3,4,5] -> [5,4,3,2,1]", "head=[1,2] -> [2,1]"], "key_points": ["迭代法 O(1)空间", "递归法 O(n)空间"], "tags": ["linkedlist", "medium", "Google", "Microsoft"]} {"problem_id": "algo_00727", "original_id": "middle-node", "title": "链表的中间结点", "category": "linkedlist", "difficulty": "easy", "companies": ["Amazon", "Facebook"], "description": "给你单链表的头节点 head,请你找出并返回链表的中间结点。如果有两个中间结点,则返回第二个中间结点。", "solution_python": "def middleNode(head):\n slow = fast = head\n while fast and fast.next:\n slow = slow.next\n fast = fast.next.next\n return slow", "solution_java": "public ListNode middleNode(ListNode head) {\n ListNode slow = head, fast = head;\n while (fast != null && fast.next != null) {\n slow = slow.next;\n fast = fast.next.next;\n }\n return slow;\n}", "solution_cpp": "ListNode* middleNode(ListNode* head) {\n ListNode* slow = head, *fast = head;\n while (fast && fast->next) { slow = slow->next; fast = fast->next->next; }\n return slow;\n}", "test_cases": ["head=[1,2,3,4,5] -> 3", "head=[1,2,3,4,5,6] -> 4"], "key_points": ["快慢指针", "O(n)时间O(1)空间"], "tags": ["linkedlist", "easy", "Amazon", "Facebook"]} {"problem_id": "algo_00728", "original_id": "max-depth", "title": "二叉树的最大深度", "category": "tree", "difficulty": "easy", "companies": ["Microsoft", "Apple"], "description": "给定一个二叉树 root,返回其最大深度。", "solution_python": "def maxDepth(root):\n if not root: return 0\n return max(maxDepth(root.left), maxDepth(root.right)) + 1", "solution_java": "public int maxDepth(TreeNode root) {\n if (root == null) return 0;\n return Math.max(maxDepth(root.left), maxDepth(root.right)) + 1;\n}", "solution_cpp": "int maxDepth(TreeNode* root) {\n if (!root) return 0;\n return max(maxDepth(root->left), maxDepth(root->right)) + 1;\n}", "test_cases": ["root=[3,9,20,null,null,15,7] -> 3", "root=[1,null,2] -> 2"], "key_points": ["DFS递归", "层序遍历也可"], "tags": ["tree", "easy", "Microsoft", "Apple"]} {"problem_id": "algo_00729", "original_id": "inorder-traversal", "title": "二叉树的中序遍历", "category": "tree", "difficulty": "easy", "companies": ["Google", "Microsoft"], "description": "给定一个二叉树的根节点 root,返回它的中序遍历结果。", "solution_python": "def inorderTraversal(root):\n result = []\n def dfs(node):\n if node:\n dfs(node.left)\n result.append(node.val)\n dfs(node.right)\n dfs(root)\n return result", "solution_java": "public List inorderTraversal(TreeNode root) {\n List res = new ArrayList<>();\n dfs(root, res);\n return res;\n}\nprivate void dfs(TreeNode node, List res) {\n if (node == null) return;\n dfs(node.left, res); res.add(node.val); dfs(node.right, res);\n}", "solution_cpp": "vector inorderTraversal(TreeNode* root) {\n vector res;\n dfs(root, res);\n return res;\n}\nvoid dfs(TreeNode* node, vector& res) {\n if (!node) return;\n dfs(node->left, res); res.push_back(node->val); dfs(node->right, res);\n}", "test_cases": ["root=[1,null,2,3] -> [1,3,2]", "root=[] -> []"], "key_points": ["左-根-右顺序", "递归最简洁"], "tags": ["tree", "easy", "Google", "Microsoft"]} {"problem_id": "algo_00730", "original_id": "binary-search", "title": "二分查找", "category": "binarysearch", "difficulty": "easy", "companies": ["Google", "Amazon"], "description": "给定一个 n 个元素有序的(升序)整型数组 nums 和一个目标值 target,写一个函数搜索 nums 中的 target,如果目标值存在返回下标,否则返回 -1。", "solution_python": "def search(nums, target):\n left, right = 0, len(nums) - 1\n while left <= right:\n mid = (left + right) // 2\n if nums[mid] == target: return mid\n elif nums[mid] < target: left = mid + 1\n else: right = mid - 1\n return -1", "solution_java": "public int search(int[] nums, int target) {\n int left = 0, right = nums.length - 1;\n while (left <= right) {\n int mid = left + (right - left) / 2;\n if (nums[mid] == target) return mid;\n else if (nums[mid] < target) left = mid + 1;\n else right = mid - 1;\n }\n return -1;\n}", "solution_cpp": "int search(vector& nums, int target) {\n int left = 0, right = nums.size() - 1;\n while (left <= right) {\n int mid = left + (right - left) / 2;\n if (nums[mid] == target) return mid;\n else if (nums[mid] < target) left = mid + 1;\n else right = mid - 1;\n }\n return -1;\n}", "test_cases": ["nums=[-1,0,3,5,9,12], target=9 -> 4", "nums=[-1,0,3,5,9,12], target=2 -> -1"], "key_points": ["标准模板", "注意防溢出写法"], "tags": ["binarysearch", "easy", "Google", "Amazon"]} {"problem_id": "algo_00731", "original_id": "climbing-stairs", "title": "爬楼梯", "category": "dp", "difficulty": "easy", "companies": ["Amazon", "Google"], "description": "假设你正在爬楼梯。需要 n 阶你才能到达楼顶。每次你可以爬 1 或 2 个台阶。你有多少种不同的方法可以爬到楼顶?", "solution_python": "def climbStairs(n):\n if n <= 2: return n\n a, b = 1, 2\n for _ in range(3, n+1):\n a, b = b, a + b\n return b", "solution_java": "public int climbStairs(int n) {\n if (n <= 2) return n;\n int a = 1, b = 2;\n for (int i = 3; i <= n; i++) { int temp = a + b; a = b; b = temp; }\n return b;\n}", "solution_cpp": "int climbStairs(int n) {\n if (n <= 2) return n;\n int a = 1, b = 2;\n for (int i = 3; i <= n; i++) { int temp = a + b; a = b; b = temp; }\n return b;\n}", "test_cases": ["n=2 -> 2", "n=3 -> 3", "n=5 -> 8"], "key_points": ["斐波那契数列", "滚动数组优化空间"], "tags": ["dp", "easy", "Amazon", "Google"]} {"problem_id": "algo_00732", "original_id": "coin-change", "title": "零钱兑换", "category": "dp", "difficulty": "medium", "companies": ["Google", "Amazon"], "description": "给你一个整数数组 coins 表示不同面额的硬币,以及一个整数 amount 表示总金额。计算并返回可以凑成总金额所需的最少的硬币个数。如果没有任何一种硬币组合能组成总金额,返回 -1。", "solution_python": "def coinChange(coins, amount):\n dp = [float('inf')] * (amount + 1)\n dp[0] = 0\n for coin in coins:\n for x in range(coin, amount + 1):\n dp[x] = min(dp[x], dp[x - coin] + 1)\n return dp[amount] if dp[amount] != float('inf') else -1", "solution_java": "public int coinChange(int[] coins, int amount) {\n int[] dp = new int[amount + 1];\n Arrays.fill(dp, amount + 1);\n dp[0] = 0;\n for (int coin : coins) {\n for (int x = coin; x <= amount; x++) {\n dp[x] = Math.min(dp[x], dp[x - coin] + 1);\n }\n }\n return dp[amount] > amount ? -1 : dp[amount];\n}", "solution_cpp": "int coinChange(vector& coins, int amount) {\n vector dp(amount + 1, amount + 1);\n dp[0] = 0;\n for (int coin : coins) {\n for (int x = coin; x <= amount; x++) {\n dp[x] = min(dp[x], dp[x - coin] + 1);\n }\n }\n return dp[amount] > amount ? -1 : dp[amount];\n}", "test_cases": ["coins=[1,2,5], amount=11 -> 3", "coins=[2], amount=3 -> -1"], "key_points": ["完全背包问题", "dp[x] = min(dp[x-coin]+1)"], "tags": ["dp", "medium", "Google", "Amazon"]} {"problem_id": "algo_00733", "original_id": "subsets", "title": "子集", "category": "backtracking", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "给你一个整数数组 nums ,数组中的元素 互不相同 。返回该数组所有可能的子集(幂集)。", "solution_python": "def subsets(nums):\n result = []\n def backtrack(start, path):\n result.append(path[:])\n for i in range(start, len(nums)):\n path.append(nums[i])\n backtrack(i + 1, path)\n path.pop()\n backtrack(0, [])\n return result", "solution_java": "public List> subsets(int[] nums) {\n List> result = new ArrayList<>();\n backtrack(nums, 0, new ArrayList<>(), result);\n return result;\n}\nprivate void backtrack(int[] nums, int start, List path, List> result) {\n result.add(new ArrayList<>(path));\n for (int i = start; i < nums.length; i++) {\n path.add(nums[i]);\n backtrack(nums, i + 1, path, result);\n path.remove(path.size() - 1);\n }\n}", "solution_cpp": "vector> subsets(vector& nums) {\n vector> result;\n vector path;\n backtrack(nums, 0, path, result);\n return result;\n}\nvoid backtrack(vector& nums, int start, vector& path, vector>& result) {\n result.push_back(path);\n for (int i = start; i < nums.size(); i++) {\n path.push_back(nums[i]);\n backtrack(nums, i + 1, path, result);\n path.pop_back();\n }\n}", "test_cases": ["nums=[1,2,3] -> [[],[1],[2],[1,2],[3],[1,3],[2,3],[1,2,3]]"], "key_points": ["选或不选", "DFS遍历子集树"], "tags": ["backtracking", "medium", "Google", "Microsoft"]} {"problem_id": "algo_00734", "original_id": "permutations", "title": "全排列", "category": "backtracking", "difficulty": "medium", "companies": ["Google", "Facebook"], "description": "给定一个不含重复数字的数组 nums,返回其所有可能的全排列。", "solution_python": "def permute(nums):\n result = []\n def backtrack(path, used):\n if len(path) == len(nums):\n result.append(path[:])\n return\n for i in range(len(nums)):\n if used[i]: continue\n used[i] = True\n path.append(nums[i])\n backtrack(path, used)\n path.pop()\n used[i] = False\n backtrack([], [False]*len(nums))\n return result", "solution_java": "public List> permute(int[] nums) {\n List> result = new ArrayList<>();\n boolean[] used = new boolean[nums.length];\n backtrack(nums, used, new ArrayList<>(), result);\n return result;\n}\nprivate void backtrack(int[] nums, boolean[] used, List path, List> result) {\n if (path.size() == nums.length) { result.add(new ArrayList<>(path)); return; }\n for (int i = 0; i < nums.length; i++) {\n if (used[i]) continue;\n used[i] = true;\n path.add(nums[i]);\n backtrack(nums, used, path, result);\n path.remove(path.size() - 1);\n used[i] = false;\n }\n}", "solution_cpp": "vector> permute(vector& nums) {\n vector> result;\n vector used(nums.size(), false);\n vector path;\n backtrack(nums, used, path, result);\n return result;\n}\nvoid backtrack(vector& nums, vector& used, vector& path, vector>& result) {\n if (path.size() == nums.size()) { result.push_back(path); return; }\n for (int i = 0; i < nums.size(); i++) {\n if (used[i]) continue;\n used[i] = true;\n path.push_back(nums[i]);\n backtrack(nums, used, path, result);\n path.pop_back();\n used[i] = false;\n }\n}", "test_cases": ["nums=[1,2,3] -> [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]"], "key_points": ["标记已使用元素", "回溯经典模板"], "tags": ["backtracking", "medium", "Google", "Facebook"]} {"problem_id": "algo_00735", "original_id": "top-k-frequent", "title": "前K个高频元素", "category": "heap", "difficulty": "medium", "companies": ["Amazon", "Facebook"], "description": "给你一个整数数组 nums 和一个整数 k,请你返回其中出现频率前 k 高的元素。", "solution_python": "import heapq\nfrom collections import Counter\ndef topKFrequent(nums, k):\n count = Counter(nums)\n heap = []\n for num, freq in count.items():\n heapq.heappush(heap, (freq, num))\n if len(heap) > k: heapq.heappop(heap)\n return [num for freq, num in heap]", "solution_java": "public int[] topKFrequent(int[] nums, int k) {\n Map count = new HashMap<>();\n for (int n : nums) count.put(n, count.getOrDefault(n, 0) + 1);\n PriorityQueue> heap = \n new PriorityQueue<>((a, b) -> a.getValue() - b.getValue());\n for (Map.Entry e : count.entrySet()) {\n heap.offer(e);\n if (heap.size() > k) heap.poll();\n }\n int[] res = new int[k];\n for (int i = k - 1; i >= 0; i--) res[i] = heap.poll().getKey();\n return res;\n}", "solution_cpp": "vector topKFrequent(vector& nums, int k) {\n unordered_map count;\n for (int n : nums) count[n]++;\n priority_queue, vector>, greater>> heap;\n for (auto& [num, freq] : count) {\n heap.push({freq, num});\n if (heap.size() > k) heap.pop();\n }\n vector res;\n while (!heap.empty()) { res.push_back(heap.top().second); heap.pop(); }\n reverse(res.begin(), res.end());\n return res;\n}", "test_cases": ["nums=[1,1,1,2,2,3], k=2 -> [1,2]", "nums=[1], k=1 -> [1]"], "key_points": ["小顶堆保持大小k", "时间复杂度O(nlogk)"], "tags": ["heap", "medium", "Amazon", "Facebook"]} {"problem_id": "algo_00736", "original_id": "3sum", "title": "三数之和", "category": "two-pointers", "difficulty": "medium", "companies": ["Google", "Amazon"], "description": "给你一个整数数组 nums,判断是否存在三元组满足和为0,返回所有不重复的三元组。", "solution_python": "def threeSum(nums):\n nums.sort()\n result = []\n for i in range(len(nums) - 2):\n if i > 0 and nums[i] == nums[i-1]: continue\n left, right = i + 1, len(nums) - 1\n while left < right:\n total = nums[i] + nums[left] + nums[right]\n if total < 0: left += 1\n elif total > 0: right -= 1\n else:\n result.append([nums[i], nums[left], nums[right]])\n while left < right and nums[left] == nums[left+1]: left += 1\n while left < right and nums[right] == nums[right-1]: right -= 1\n left += 1; right -= 1\n return result", "solution_java": "public List> threeSum(int[] nums) {\n Arrays.sort(nums);\n List> result = new ArrayList<>();\n for (int i = 0; i < nums.length - 2; i++) {\n if (i > 0 && nums[i] == nums[i-1]) continue;\n int left = i + 1, right = nums.length - 1;\n while (left < right) {\n int total = nums[i] + nums[left] + nums[right];\n if (total < 0) left++;\n else if (total > 0) right--;\n else {\n result.add(Arrays.asList(nums[i], nums[left], nums[right]));\n while (left < right && nums[left] == nums[left+1]) left++;\n while (left < right && nums[right] == nums[right-1]) right--;\n left++; right--;\n }\n }\n }\n return result;\n}", "solution_cpp": "vector> threeSum(vector& nums) {\n sort(nums.begin(), nums.end());\n vector> result;\n for (int i = 0; i < nums.size() - 2; i++) {\n if (i > 0 && nums[i] == nums[i-1]) continue;\n int left = i + 1, right = nums.size() - 1;\n while (left < right) {\n int total = nums[i] + nums[left] + nums[right];\n if (total < 0) left++;\n else if (total > 0) right--;\n else {\n result.push_back({nums[i], nums[left], nums[right]});\n while (left < right && nums[left] == nums[left+1]) left++;\n while (left < right && nums[right] == nums[right-1]) right--;\n left++; right--;\n }\n }\n }\n return result;\n}", "test_cases": ["nums=[-1,0,1,2,-1,-4] -> [[-1,-1,2],[-1,0,1]]"], "key_points": ["排序+双指针", "去重是关键"], "tags": ["two-pointers", "medium", "Google", "Amazon"]} {"problem_id": "algo_00737", "original_id": "container-water", "title": "盛最多水的容器", "category": "two-pointers", "difficulty": "medium", "companies": ["Google", "Uber"], "description": "给定一个长度为 n 的整数数组 height,找出其中的两条线,使得它们与 x 轴共同构成的容器可以容纳最多的水。", "solution_python": "def maxArea(height):\n left, right = 0, len(height) - 1\n max_area = 0\n while left < right:\n h = min(height[left], height[right])\n max_area = max(max_area, h * (right - left))\n if height[left] < height[right]: left += 1\n else: right -= 1\n return max_area", "solution_java": "public int maxArea(int[] height) {\n int left = 0, right = height.length - 1, maxArea = 0;\n while (left < right) {\n int h = Math.min(height[left], height[right]);\n maxArea = Math.max(maxArea, h * (right - left));\n if (height[left] < height[right]) left++;\n else right--;\n }\n return maxArea;\n}", "solution_cpp": "int maxArea(vector& height) {\n int left = 0, right = height.size() - 1, maxArea = 0;\n while (left < right) {\n int h = min(height[left], height[right]);\n maxArea = max(maxArea, h * (right - left));\n if (height[left] < height[right]) left++;\n else right--;\n }\n return maxArea;\n}", "test_cases": ["height=[1,8,6,2,5,4,8,3,7] -> 49"], "key_points": ["移动短边指针", "面积=min(h1,h2)*width"], "tags": ["two-pointers", "medium", "Google", "Uber"]} {"problem_id": "algo_00738", "original_id": "min-stack", "title": "最小栈", "category": "stack", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "设计一个支持 push,pop,top 操作,并能在常数时间内检索到最小元素的栈。", "solution_python": "class MinStack:\n def __init__(self):\n self.stack = []\n self.min_stack = []\n def push(self, val):\n self.stack.append(val)\n self.min_stack.append(min(val, self.min_stack[-1] if self.min_stack else val))\n def pop(self):\n self.stack.pop(); self.min_stack.pop()\n def top(self): return self.stack[-1]\n def getMin(self): return self.min_stack[-1]", "solution_java": "class MinStack {\n Stack stack = new Stack<>();\n Stack minStack = new Stack<>();\n public void push(int val) { stack.push(val); minStack.push(Math.min(val, minStack.isEmpty() ? val : minStack.peek())); }\n public void pop() { stack.pop(); minStack.pop(); }\n public int top() { return stack.peek(); }\n public int getMin() { return minStack.peek(); }\n}", "solution_cpp": "class MinStack {\n stack st, minSt;\npublic:\n void push(int val) { st.push(val); minSt.push(min(val, minSt.empty() ? val : minSt.top())); }\n void pop() { st.pop(); minSt.pop(); }\n int top() { return st.top(); }\n int getMin() { return minSt.top(); }\n};", "test_cases": ["push(-2), push(0), push(-3) -> getMin() returns -3"], "key_points": ["辅助栈记录最小值", "O(1)时间获取最小值"], "tags": ["stack", "medium", "Google", "Microsoft"]} {"problem_id": "algo_00739", "original_id": "lru-cache", "title": "LRU缓存", "category": "design", "difficulty": "hard", "companies": ["Google", "Amazon"], "description": "设计和实现一个 LRU(最近最少使用)缓存机制。", "solution_python": "class LRUCache:\n def __init__(self, capacity):\n self.capacity = capacity\n self.cache = {}\n self.order = []\n def get(self, key):\n if key not in self.cache: return -1\n self.order.remove(key); self.order.append(key)\n return self.cache[key]\n def put(self, key, value):\n if key in self.cache:\n self.order.remove(key)\n elif len(self.cache) >= self.capacity:\n del self.cache[self.order.pop(0)]\n self.cache[key] = value; self.order.append(key)", "solution_java": "class LRUCache {\n int capacity;\n LinkedHashMap cache = new LinkedHashMap<>();\n public LRUCache(int cap) { capacity = cap; }\n public int get(int key) { return cache.containsKey(key) ? cache.remove(key) : -1; }\n public void put(int key, int val) {\n if (cache.containsKey(key)) cache.remove(key);\n else if (cache.size() >= capacity) cache.remove(cache.keySet().iterator().next());\n cache.put(key, val);\n }\n}", "solution_cpp": "class LRUCache {\n int cap;\n list> dll;\n unordered_map>::iterator> cache;\npublic:\n LRUCache(int capacity) : cap(capacity) {}\n int get(int key) {\n auto it = cache.find(key);\n if (it == cache.end()) return -1;\n dll.splice(dll.end(), dll, it->second);\n return it->second->second;\n }\n void put(int key, int value) {\n auto it = cache.find(key);\n if (it != cache.end()) dll.erase(it->second);\n else if (cache.size() >= cap) { cache.erase(dll.front().first); dll.pop_front(); }\n dll.push_back({key, value});\n cache[key] = --dll.end();\n }\n};", "test_cases": ["put(1,1), put(2,2), get(1) -> 1"], "key_points": ["HashMap + 双向链表", "O(1)时间操作"], "tags": ["design", "hard", "Google", "Amazon"]} {"problem_id": "algo_00740", "original_id": "num-islands", "title": "岛屿数量", "category": "graph", "difficulty": "medium", "companies": ["Google", "Facebook"], "description": "给你一个由 '1'(陆地)和 '0'(水)组成的二维网格,请你计算网格中岛屿的数量。岛屿总是被水包围,且只能由水平或垂直方向相邻的陆地连接形成。", "solution_python": "def numIslands(grid):\n if not grid: return 0\n rows, cols = len(grid), len(grid[0])\n count = 0\n def dfs(r, c):\n if r < 0 or r >= rows or c < 0 or c >= cols or grid[r][c] != '1': return\n grid[r][c] = '0'\n dfs(r+1, c); dfs(r-1, c); dfs(r, c+1); dfs(r, c-1)\n for r in range(rows):\n for c in range(cols):\n if grid[r][c] == '1': count += 1; dfs(r, c)\n return count", "solution_java": "public int numIslands(char[][] grid) {\n if (grid.length == 0) return 0;\n int count = 0;\n for (int i = 0; i < grid.length; i++)\n for (int j = 0; j < grid[0].length; j++)\n if (grid[i][j] == '1') { count++; dfs(grid, i, j); }\n return count;\n}\nprivate void dfs(char[][] grid, int r, int c) {\n if (r < 0 || r >= grid.length || c < 0 || c >= grid[0].length || grid[r][c] != '1') return;\n grid[r][c] = '0';\n dfs(grid, r+1, c); dfs(grid, r-1, c); dfs(grid, r, c+1); dfs(grid, r, c-1);\n}", "solution_cpp": "int numIslands(vector>& grid) {\n if (grid.empty()) return 0;\n int count = 0;\n for (int i = 0; i < grid.size(); i++)\n for (int j = 0; j < grid[0].size(); j++)\n if (grid[i][j] == '1') { count++; dfs(grid, i, j); }\n return count;\n}\nvoid dfs(vector>& grid, int r, int c) {\n if (r < 0 || r >= grid.size() || c < 0 || c >= grid[0].size() || grid[r][c] != '1') return;\n grid[r][c] = '0';\n dfs(grid, r+1, c); dfs(grid, r-1, c); dfs(grid, r, c+1); dfs(grid, r, c-1);\n}", "test_cases": ["grid=[[1,1,1,1,0],[1,1,0,1,0],[1,1,0,0,0],[0,0,0,0,0]] -> 1"], "key_points": ["DFS/BFS遍历", "访问后标记为0避免重复"], "tags": ["graph", "medium", "Google", "Facebook"]} {"problem_id": "algo_00741", "original_id": "two-sum", "title": "两数之和", "category": "array", "difficulty": "easy", "companies": ["Amazon", "Google"], "description": "给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那两个整数,并返回他们的数组下标。", "solution_python": "def twoSum(nums, target):\n hashmap = {}\n for i, num in enumerate(nums):\n complement = target - num\n if complement in hashmap:\n return [hashmap[complement], i]\n hashmap[num] = i\n return []", "solution_java": "public int[] twoSum(int[] nums, int target) {\n Map map = new HashMap<>();\n for (int i = 0; i < nums.length; i++) {\n int complement = target - nums[i];\n if (map.containsKey(complement)) return new int[]{map.get(complement), i};\n map.put(nums[i], i);\n }\n return new int[]{};\n}", "solution_cpp": "vector twoSum(vector& nums, int target) {\n unordered_map m;\n for (int i = 0; i < nums.size(); i++) {\n if (m.count(target - nums[i])) return {m[target - nums[i]], i};\n m[nums[i]] = i;\n }\n return {};\n}", "test_cases": ["nums=[2,7,11,15], target=9 -> [0,1]", "nums=[3,2,4], target=6 -> [1,2]"], "key_points": ["哈希表一次遍历", "空间换时间"], "tags": ["array", "easy", "Amazon", "Google"]} {"problem_id": "algo_00742", "original_id": "merge-sorted", "title": "合并两个有序数组", "category": "array", "difficulty": "easy", "companies": ["Microsoft", "Uber"], "description": "给你两个按非递减顺序排列的整数数组 nums1 和 nums2,另有两个整数 m 和 n,分别表示 nums1 和 nums2 中的元素数目。请你合并 nums2 到 nums1 中。", "solution_python": "def merge(nums1, m, nums2, n):\n p1, p2, p = m-1, n-1, m+n-1\n while p1 >= 0 and p2 >= 0:\n if nums1[p1] > nums2[p2]: nums1[p] = nums1[p1]; p1 -= 1\n else: nums1[p] = nums2[p2]; p2 -= 1\n p -= 1\n while p2 >= 0: nums1[p] = nums2[p2]; p2 -= 1; p -= 1", "solution_java": "public void merge(int[] nums1, int m, int[] nums2, int n) {\n int p1 = m-1, p2 = n-1, p = m+n-1;\n while (p1 >= 0 && p2 >= 0) {\n nums1[p--] = nums1[p1] > nums2[p2] ? nums1[p1--] : nums2[p2--];\n }\n while (p2 >= 0) nums1[p--] = nums2[p2--];\n}", "solution_cpp": "void merge(vector& nums1, int m, vector& nums2, int n) {\n int p1 = m-1, p2 = n-1, p = m+n-1;\n while (p1 >= 0 && p2 >= 0) nums1[p--] = nums1[p1] > nums2[p2] ? nums1[p1--] : nums2[p2--];\n while (p2 >= 0) nums1[p--] = nums2[p2--];\n}", "test_cases": ["nums1=[1,2,3], m=3, nums2=[2,5,6], n=3 -> [1,2,2,3,5,6]", "nums1=[], m=0, nums2=[1], n=1 -> [1]"], "key_points": ["从后往前合并", "三指针技巧"], "tags": ["array", "easy", "Microsoft", "Uber"]} {"problem_id": "algo_00743", "original_id": "max-subarray", "title": "最大子数组和", "category": "array", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "给你一个整数数组 nums ,请你找出一个具有最大和的连续子数组,返回其最大和。", "solution_python": "def maxSubArray(nums):\n max_sum = current = nums[0]\n for num in nums[1:]:\n current = max(num, current + num)\n max_sum = max(max_sum, current)\n return max_sum", "solution_java": "public int maxSubArray(int[] nums) {\n int maxSum = nums[0], curr = nums[0];\n for (int i = 1; i < nums.length; i++) {\n curr = Math.max(nums[i], curr + nums[i]);\n maxSum = Math.max(maxSum, curr);\n }\n return maxSum;\n}", "solution_cpp": "int maxSubArray(vector& nums) {\n int maxSum = nums[0], curr = nums[0];\n for (int i = 1; i < nums.size(); i++) {\n curr = max(nums[i], curr + nums[i]);\n maxSum = max(maxSum, curr);\n }\n return maxSum;\n}", "test_cases": ["nums=[-2,1,-3,4,-1,2,1,-5,4] -> 6", "nums=[1] -> 1"], "key_points": ["Kadane算法", "动态规划基础题"], "tags": ["array", "medium", "Google", "Microsoft"]} {"problem_id": "algo_00744", "original_id": "valid-parentheses", "title": "有效的括号", "category": "string", "difficulty": "easy", "companies": ["Google", "Uber"], "description": "给定一个只包括 '(',')','{','}','[',']' 的字符串 s,判断字符串是否有效。", "solution_python": "def isValid(s):\n stack = []\n mapping = {')': '(', ']': '[', '}': '{'}\n for c in s:\n if c in mapping:\n if not stack or stack[-1] != mapping[c]: return False\n stack.pop()\n else: stack.append(c)\n return not stack", "solution_java": "public boolean isValid(String s) {\n Stack stack = new Stack<>();\n Map map = Map.of(')', '(', ']', '[', '}', '{');\n for (char c : s.toCharArray()) {\n if (map.containsValue(c)) stack.push(c);\n else if (!stack.isEmpty() && stack.pop() != map.get(c)) return false;\n }\n return stack.isEmpty();\n}", "solution_cpp": "bool isValid(string s) {\n stack st;\n unordered_map m = {{')','('},{']','['},{'}','{'}};\n for (char c : s) {\n if (m.find(c) == m.end()) st.push(c);\n else if (st.empty() || st.top() != m[c]) return false;\n else st.pop();\n }\n return st.empty();\n}", "test_cases": ["s=\"()\" -> true", "s=\"()[]{}\" -> true", "s=\"(]\" -> false"], "key_points": ["栈匹配法", "注意空栈边界"], "tags": ["string", "easy", "Google", "Uber"]} {"problem_id": "algo_00745", "original_id": "longest-palindrome", "title": "最长回文子串", "category": "string", "difficulty": "medium", "companies": ["Google", "Amazon"], "description": "给你一个字符串 s,找到 s 中最长的回文子串。", "solution_python": "def longestPalindrome(s):\n def expand(l, r):\n while l >= 0 and r < len(s) and s[l] == s[r]: l -= 1; r += 1\n return l + 1, r - 1\n start = end = 0\n for i in range(len(s)):\n l1, r1 = expand(i, i)\n l2, r2 = expand(i, i + 1)\n if r1 - l1 > end - start: start, end = l1, r1\n if r2 - l2 > end - start: start, end = l2, r2\n return s[start:end+1]", "solution_java": "public String longestPalindrome(String s) {\n int start = 0, end = 0;\n for (int i = 0; i < s.length(); i++) {\n int len1 = expand(s, i, i), len2 = expand(s, i, i+1);\n int len = Math.max(len1, len2);\n if (len > end - start) { start = i - (len-1)/2; end = i + len/2; }\n }\n return s.substring(start, end + 1);\n}\nprivate int expand(String s, int l, int r) {\n while (l >= 0 && r < s.length() && s.charAt(l) == s.charAt(r)) { l--; r++; }\n return r - l - 1;\n}", "solution_cpp": "string longestPalindrome(string s) {\n int start = 0, end = 0;\n for (int i = 0; i < s.size(); i++) {\n int len1 = expand(s, i, i), len2 = expand(s, i, i+1);\n if (max(len1, len2) > end - start) { start = i - (max(len1,len2)-1)/2; end = i + max(len1,len2)/2; }\n }\n return s.substr(start, end - start + 1);\n}", "test_cases": ["s=\"babad\" -> bab或aba", "s=\"cbbd\" -> bb"], "key_points": ["中心扩展法", "处理奇偶长度"], "tags": ["string", "medium", "Google", "Amazon"]} {"problem_id": "algo_00746", "original_id": "reverse-list", "title": "反转链表", "category": "linkedlist", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "给你单链表的头节点 head,请你反转链表,并返回反转后的链表。", "solution_python": "def reverseList(head):\n prev = None\n curr = head\n while curr:\n nxt = curr.next\n curr.next = prev\n prev = curr\n curr = nxt\n return prev", "solution_java": "public ListNode reverseList(ListNode head) {\n ListNode prev = null, curr = head;\n while (curr != null) {\n ListNode next = curr.next;\n curr.next = prev;\n prev = curr;\n curr = next;\n }\n return prev;\n}", "solution_cpp": "ListNode* reverseList(ListNode* head) {\n ListNode* prev = nullptr, *curr = head;\n while (curr) {\n ListNode* next = curr->next;\n curr->next = prev;\n prev = curr;\n curr = next;\n }\n return prev;\n}", "test_cases": ["head=[1,2,3,4,5] -> [5,4,3,2,1]", "head=[1,2] -> [2,1]"], "key_points": ["迭代法 O(1)空间", "递归法 O(n)空间"], "tags": ["linkedlist", "medium", "Google", "Microsoft"]} {"problem_id": "algo_00747", "original_id": "middle-node", "title": "链表的中间结点", "category": "linkedlist", "difficulty": "easy", "companies": ["Amazon", "Facebook"], "description": "给你单链表的头节点 head,请你找出并返回链表的中间结点。如果有两个中间结点,则返回第二个中间结点。", "solution_python": "def middleNode(head):\n slow = fast = head\n while fast and fast.next:\n slow = slow.next\n fast = fast.next.next\n return slow", "solution_java": "public ListNode middleNode(ListNode head) {\n ListNode slow = head, fast = head;\n while (fast != null && fast.next != null) {\n slow = slow.next;\n fast = fast.next.next;\n }\n return slow;\n}", "solution_cpp": "ListNode* middleNode(ListNode* head) {\n ListNode* slow = head, *fast = head;\n while (fast && fast->next) { slow = slow->next; fast = fast->next->next; }\n return slow;\n}", "test_cases": ["head=[1,2,3,4,5] -> 3", "head=[1,2,3,4,5,6] -> 4"], "key_points": ["快慢指针", "O(n)时间O(1)空间"], "tags": ["linkedlist", "easy", "Amazon", "Facebook"]} {"problem_id": "algo_00748", "original_id": "max-depth", "title": "二叉树的最大深度", "category": "tree", "difficulty": "easy", "companies": ["Microsoft", "Apple"], "description": "给定一个二叉树 root,返回其最大深度。", "solution_python": "def maxDepth(root):\n if not root: return 0\n return max(maxDepth(root.left), maxDepth(root.right)) + 1", "solution_java": "public int maxDepth(TreeNode root) {\n if (root == null) return 0;\n return Math.max(maxDepth(root.left), maxDepth(root.right)) + 1;\n}", "solution_cpp": "int maxDepth(TreeNode* root) {\n if (!root) return 0;\n return max(maxDepth(root->left), maxDepth(root->right)) + 1;\n}", "test_cases": ["root=[3,9,20,null,null,15,7] -> 3", "root=[1,null,2] -> 2"], "key_points": ["DFS递归", "层序遍历也可"], "tags": ["tree", "easy", "Microsoft", "Apple"]} {"problem_id": "algo_00749", "original_id": "inorder-traversal", "title": "二叉树的中序遍历", "category": "tree", "difficulty": "easy", "companies": ["Google", "Microsoft"], "description": "给定一个二叉树的根节点 root,返回它的中序遍历结果。", "solution_python": "def inorderTraversal(root):\n result = []\n def dfs(node):\n if node:\n dfs(node.left)\n result.append(node.val)\n dfs(node.right)\n dfs(root)\n return result", "solution_java": "public List inorderTraversal(TreeNode root) {\n List res = new ArrayList<>();\n dfs(root, res);\n return res;\n}\nprivate void dfs(TreeNode node, List res) {\n if (node == null) return;\n dfs(node.left, res); res.add(node.val); dfs(node.right, res);\n}", "solution_cpp": "vector inorderTraversal(TreeNode* root) {\n vector res;\n dfs(root, res);\n return res;\n}\nvoid dfs(TreeNode* node, vector& res) {\n if (!node) return;\n dfs(node->left, res); res.push_back(node->val); dfs(node->right, res);\n}", "test_cases": ["root=[1,null,2,3] -> [1,3,2]", "root=[] -> []"], "key_points": ["左-根-右顺序", "递归最简洁"], "tags": ["tree", "easy", "Google", "Microsoft"]} {"problem_id": "algo_00750", "original_id": "binary-search", "title": "二分查找", "category": "binarysearch", "difficulty": "easy", "companies": ["Google", "Amazon"], "description": "给定一个 n 个元素有序的(升序)整型数组 nums 和一个目标值 target,写一个函数搜索 nums 中的 target,如果目标值存在返回下标,否则返回 -1。", "solution_python": "def search(nums, target):\n left, right = 0, len(nums) - 1\n while left <= right:\n mid = (left + right) // 2\n if nums[mid] == target: return mid\n elif nums[mid] < target: left = mid + 1\n else: right = mid - 1\n return -1", "solution_java": "public int search(int[] nums, int target) {\n int left = 0, right = nums.length - 1;\n while (left <= right) {\n int mid = left + (right - left) / 2;\n if (nums[mid] == target) return mid;\n else if (nums[mid] < target) left = mid + 1;\n else right = mid - 1;\n }\n return -1;\n}", "solution_cpp": "int search(vector& nums, int target) {\n int left = 0, right = nums.size() - 1;\n while (left <= right) {\n int mid = left + (right - left) / 2;\n if (nums[mid] == target) return mid;\n else if (nums[mid] < target) left = mid + 1;\n else right = mid - 1;\n }\n return -1;\n}", "test_cases": ["nums=[-1,0,3,5,9,12], target=9 -> 4", "nums=[-1,0,3,5,9,12], target=2 -> -1"], "key_points": ["标准模板", "注意防溢出写法"], "tags": ["binarysearch", "easy", "Google", "Amazon"]} {"problem_id": "algo_00751", "original_id": "climbing-stairs", "title": "爬楼梯", "category": "dp", "difficulty": "easy", "companies": ["Amazon", "Google"], "description": "假设你正在爬楼梯。需要 n 阶你才能到达楼顶。每次你可以爬 1 或 2 个台阶。你有多少种不同的方法可以爬到楼顶?", "solution_python": "def climbStairs(n):\n if n <= 2: return n\n a, b = 1, 2\n for _ in range(3, n+1):\n a, b = b, a + b\n return b", "solution_java": "public int climbStairs(int n) {\n if (n <= 2) return n;\n int a = 1, b = 2;\n for (int i = 3; i <= n; i++) { int temp = a + b; a = b; b = temp; }\n return b;\n}", "solution_cpp": "int climbStairs(int n) {\n if (n <= 2) return n;\n int a = 1, b = 2;\n for (int i = 3; i <= n; i++) { int temp = a + b; a = b; b = temp; }\n return b;\n}", "test_cases": ["n=2 -> 2", "n=3 -> 3", "n=5 -> 8"], "key_points": ["斐波那契数列", "滚动数组优化空间"], "tags": ["dp", "easy", "Amazon", "Google"]} {"problem_id": "algo_00752", "original_id": "coin-change", "title": "零钱兑换", "category": "dp", "difficulty": "medium", "companies": ["Google", "Amazon"], "description": "给你一个整数数组 coins 表示不同面额的硬币,以及一个整数 amount 表示总金额。计算并返回可以凑成总金额所需的最少的硬币个数。如果没有任何一种硬币组合能组成总金额,返回 -1。", "solution_python": "def coinChange(coins, amount):\n dp = [float('inf')] * (amount + 1)\n dp[0] = 0\n for coin in coins:\n for x in range(coin, amount + 1):\n dp[x] = min(dp[x], dp[x - coin] + 1)\n return dp[amount] if dp[amount] != float('inf') else -1", "solution_java": "public int coinChange(int[] coins, int amount) {\n int[] dp = new int[amount + 1];\n Arrays.fill(dp, amount + 1);\n dp[0] = 0;\n for (int coin : coins) {\n for (int x = coin; x <= amount; x++) {\n dp[x] = Math.min(dp[x], dp[x - coin] + 1);\n }\n }\n return dp[amount] > amount ? -1 : dp[amount];\n}", "solution_cpp": "int coinChange(vector& coins, int amount) {\n vector dp(amount + 1, amount + 1);\n dp[0] = 0;\n for (int coin : coins) {\n for (int x = coin; x <= amount; x++) {\n dp[x] = min(dp[x], dp[x - coin] + 1);\n }\n }\n return dp[amount] > amount ? -1 : dp[amount];\n}", "test_cases": ["coins=[1,2,5], amount=11 -> 3", "coins=[2], amount=3 -> -1"], "key_points": ["完全背包问题", "dp[x] = min(dp[x-coin]+1)"], "tags": ["dp", "medium", "Google", "Amazon"]} {"problem_id": "algo_00753", "original_id": "subsets", "title": "子集", "category": "backtracking", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "给你一个整数数组 nums ,数组中的元素 互不相同 。返回该数组所有可能的子集(幂集)。", "solution_python": "def subsets(nums):\n result = []\n def backtrack(start, path):\n result.append(path[:])\n for i in range(start, len(nums)):\n path.append(nums[i])\n backtrack(i + 1, path)\n path.pop()\n backtrack(0, [])\n return result", "solution_java": "public List> subsets(int[] nums) {\n List> result = new ArrayList<>();\n backtrack(nums, 0, new ArrayList<>(), result);\n return result;\n}\nprivate void backtrack(int[] nums, int start, List path, List> result) {\n result.add(new ArrayList<>(path));\n for (int i = start; i < nums.length; i++) {\n path.add(nums[i]);\n backtrack(nums, i + 1, path, result);\n path.remove(path.size() - 1);\n }\n}", "solution_cpp": "vector> subsets(vector& nums) {\n vector> result;\n vector path;\n backtrack(nums, 0, path, result);\n return result;\n}\nvoid backtrack(vector& nums, int start, vector& path, vector>& result) {\n result.push_back(path);\n for (int i = start; i < nums.size(); i++) {\n path.push_back(nums[i]);\n backtrack(nums, i + 1, path, result);\n path.pop_back();\n }\n}", "test_cases": ["nums=[1,2,3] -> [[],[1],[2],[1,2],[3],[1,3],[2,3],[1,2,3]]"], "key_points": ["选或不选", "DFS遍历子集树"], "tags": ["backtracking", "medium", "Google", "Microsoft"]} {"problem_id": "algo_00754", "original_id": "permutations", "title": "全排列", "category": "backtracking", "difficulty": "medium", "companies": ["Google", "Facebook"], "description": "给定一个不含重复数字的数组 nums,返回其所有可能的全排列。", "solution_python": "def permute(nums):\n result = []\n def backtrack(path, used):\n if len(path) == len(nums):\n result.append(path[:])\n return\n for i in range(len(nums)):\n if used[i]: continue\n used[i] = True\n path.append(nums[i])\n backtrack(path, used)\n path.pop()\n used[i] = False\n backtrack([], [False]*len(nums))\n return result", "solution_java": "public List> permute(int[] nums) {\n List> result = new ArrayList<>();\n boolean[] used = new boolean[nums.length];\n backtrack(nums, used, new ArrayList<>(), result);\n return result;\n}\nprivate void backtrack(int[] nums, boolean[] used, List path, List> result) {\n if (path.size() == nums.length) { result.add(new ArrayList<>(path)); return; }\n for (int i = 0; i < nums.length; i++) {\n if (used[i]) continue;\n used[i] = true;\n path.add(nums[i]);\n backtrack(nums, used, path, result);\n path.remove(path.size() - 1);\n used[i] = false;\n }\n}", "solution_cpp": "vector> permute(vector& nums) {\n vector> result;\n vector used(nums.size(), false);\n vector path;\n backtrack(nums, used, path, result);\n return result;\n}\nvoid backtrack(vector& nums, vector& used, vector& path, vector>& result) {\n if (path.size() == nums.size()) { result.push_back(path); return; }\n for (int i = 0; i < nums.size(); i++) {\n if (used[i]) continue;\n used[i] = true;\n path.push_back(nums[i]);\n backtrack(nums, used, path, result);\n path.pop_back();\n used[i] = false;\n }\n}", "test_cases": ["nums=[1,2,3] -> [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]"], "key_points": ["标记已使用元素", "回溯经典模板"], "tags": ["backtracking", "medium", "Google", "Facebook"]} {"problem_id": "algo_00755", "original_id": "top-k-frequent", "title": "前K个高频元素", "category": "heap", "difficulty": "medium", "companies": ["Amazon", "Facebook"], "description": "给你一个整数数组 nums 和一个整数 k,请你返回其中出现频率前 k 高的元素。", "solution_python": "import heapq\nfrom collections import Counter\ndef topKFrequent(nums, k):\n count = Counter(nums)\n heap = []\n for num, freq in count.items():\n heapq.heappush(heap, (freq, num))\n if len(heap) > k: heapq.heappop(heap)\n return [num for freq, num in heap]", "solution_java": "public int[] topKFrequent(int[] nums, int k) {\n Map count = new HashMap<>();\n for (int n : nums) count.put(n, count.getOrDefault(n, 0) + 1);\n PriorityQueue> heap = \n new PriorityQueue<>((a, b) -> a.getValue() - b.getValue());\n for (Map.Entry e : count.entrySet()) {\n heap.offer(e);\n if (heap.size() > k) heap.poll();\n }\n int[] res = new int[k];\n for (int i = k - 1; i >= 0; i--) res[i] = heap.poll().getKey();\n return res;\n}", "solution_cpp": "vector topKFrequent(vector& nums, int k) {\n unordered_map count;\n for (int n : nums) count[n]++;\n priority_queue, vector>, greater>> heap;\n for (auto& [num, freq] : count) {\n heap.push({freq, num});\n if (heap.size() > k) heap.pop();\n }\n vector res;\n while (!heap.empty()) { res.push_back(heap.top().second); heap.pop(); }\n reverse(res.begin(), res.end());\n return res;\n}", "test_cases": ["nums=[1,1,1,2,2,3], k=2 -> [1,2]", "nums=[1], k=1 -> [1]"], "key_points": ["小顶堆保持大小k", "时间复杂度O(nlogk)"], "tags": ["heap", "medium", "Amazon", "Facebook"]} {"problem_id": "algo_00756", "original_id": "3sum", "title": "三数之和", "category": "two-pointers", "difficulty": "medium", "companies": ["Google", "Amazon"], "description": "给你一个整数数组 nums,判断是否存在三元组满足和为0,返回所有不重复的三元组。", "solution_python": "def threeSum(nums):\n nums.sort()\n result = []\n for i in range(len(nums) - 2):\n if i > 0 and nums[i] == nums[i-1]: continue\n left, right = i + 1, len(nums) - 1\n while left < right:\n total = nums[i] + nums[left] + nums[right]\n if total < 0: left += 1\n elif total > 0: right -= 1\n else:\n result.append([nums[i], nums[left], nums[right]])\n while left < right and nums[left] == nums[left+1]: left += 1\n while left < right and nums[right] == nums[right-1]: right -= 1\n left += 1; right -= 1\n return result", "solution_java": "public List> threeSum(int[] nums) {\n Arrays.sort(nums);\n List> result = new ArrayList<>();\n for (int i = 0; i < nums.length - 2; i++) {\n if (i > 0 && nums[i] == nums[i-1]) continue;\n int left = i + 1, right = nums.length - 1;\n while (left < right) {\n int total = nums[i] + nums[left] + nums[right];\n if (total < 0) left++;\n else if (total > 0) right--;\n else {\n result.add(Arrays.asList(nums[i], nums[left], nums[right]));\n while (left < right && nums[left] == nums[left+1]) left++;\n while (left < right && nums[right] == nums[right-1]) right--;\n left++; right--;\n }\n }\n }\n return result;\n}", "solution_cpp": "vector> threeSum(vector& nums) {\n sort(nums.begin(), nums.end());\n vector> result;\n for (int i = 0; i < nums.size() - 2; i++) {\n if (i > 0 && nums[i] == nums[i-1]) continue;\n int left = i + 1, right = nums.size() - 1;\n while (left < right) {\n int total = nums[i] + nums[left] + nums[right];\n if (total < 0) left++;\n else if (total > 0) right--;\n else {\n result.push_back({nums[i], nums[left], nums[right]});\n while (left < right && nums[left] == nums[left+1]) left++;\n while (left < right && nums[right] == nums[right-1]) right--;\n left++; right--;\n }\n }\n }\n return result;\n}", "test_cases": ["nums=[-1,0,1,2,-1,-4] -> [[-1,-1,2],[-1,0,1]]"], "key_points": ["排序+双指针", "去重是关键"], "tags": ["two-pointers", "medium", "Google", "Amazon"]} {"problem_id": "algo_00757", "original_id": "container-water", "title": "盛最多水的容器", "category": "two-pointers", "difficulty": "medium", "companies": ["Google", "Uber"], "description": "给定一个长度为 n 的整数数组 height,找出其中的两条线,使得它们与 x 轴共同构成的容器可以容纳最多的水。", "solution_python": "def maxArea(height):\n left, right = 0, len(height) - 1\n max_area = 0\n while left < right:\n h = min(height[left], height[right])\n max_area = max(max_area, h * (right - left))\n if height[left] < height[right]: left += 1\n else: right -= 1\n return max_area", "solution_java": "public int maxArea(int[] height) {\n int left = 0, right = height.length - 1, maxArea = 0;\n while (left < right) {\n int h = Math.min(height[left], height[right]);\n maxArea = Math.max(maxArea, h * (right - left));\n if (height[left] < height[right]) left++;\n else right--;\n }\n return maxArea;\n}", "solution_cpp": "int maxArea(vector& height) {\n int left = 0, right = height.size() - 1, maxArea = 0;\n while (left < right) {\n int h = min(height[left], height[right]);\n maxArea = max(maxArea, h * (right - left));\n if (height[left] < height[right]) left++;\n else right--;\n }\n return maxArea;\n}", "test_cases": ["height=[1,8,6,2,5,4,8,3,7] -> 49"], "key_points": ["移动短边指针", "面积=min(h1,h2)*width"], "tags": ["two-pointers", "medium", "Google", "Uber"]} {"problem_id": "algo_00758", "original_id": "min-stack", "title": "最小栈", "category": "stack", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "设计一个支持 push,pop,top 操作,并能在常数时间内检索到最小元素的栈。", "solution_python": "class MinStack:\n def __init__(self):\n self.stack = []\n self.min_stack = []\n def push(self, val):\n self.stack.append(val)\n self.min_stack.append(min(val, self.min_stack[-1] if self.min_stack else val))\n def pop(self):\n self.stack.pop(); self.min_stack.pop()\n def top(self): return self.stack[-1]\n def getMin(self): return self.min_stack[-1]", "solution_java": "class MinStack {\n Stack stack = new Stack<>();\n Stack minStack = new Stack<>();\n public void push(int val) { stack.push(val); minStack.push(Math.min(val, minStack.isEmpty() ? val : minStack.peek())); }\n public void pop() { stack.pop(); minStack.pop(); }\n public int top() { return stack.peek(); }\n public int getMin() { return minStack.peek(); }\n}", "solution_cpp": "class MinStack {\n stack st, minSt;\npublic:\n void push(int val) { st.push(val); minSt.push(min(val, minSt.empty() ? val : minSt.top())); }\n void pop() { st.pop(); minSt.pop(); }\n int top() { return st.top(); }\n int getMin() { return minSt.top(); }\n};", "test_cases": ["push(-2), push(0), push(-3) -> getMin() returns -3"], "key_points": ["辅助栈记录最小值", "O(1)时间获取最小值"], "tags": ["stack", "medium", "Google", "Microsoft"]} {"problem_id": "algo_00759", "original_id": "lru-cache", "title": "LRU缓存", "category": "design", "difficulty": "hard", "companies": ["Google", "Amazon"], "description": "设计和实现一个 LRU(最近最少使用)缓存机制。", "solution_python": "class LRUCache:\n def __init__(self, capacity):\n self.capacity = capacity\n self.cache = {}\n self.order = []\n def get(self, key):\n if key not in self.cache: return -1\n self.order.remove(key); self.order.append(key)\n return self.cache[key]\n def put(self, key, value):\n if key in self.cache:\n self.order.remove(key)\n elif len(self.cache) >= self.capacity:\n del self.cache[self.order.pop(0)]\n self.cache[key] = value; self.order.append(key)", "solution_java": "class LRUCache {\n int capacity;\n LinkedHashMap cache = new LinkedHashMap<>();\n public LRUCache(int cap) { capacity = cap; }\n public int get(int key) { return cache.containsKey(key) ? cache.remove(key) : -1; }\n public void put(int key, int val) {\n if (cache.containsKey(key)) cache.remove(key);\n else if (cache.size() >= capacity) cache.remove(cache.keySet().iterator().next());\n cache.put(key, val);\n }\n}", "solution_cpp": "class LRUCache {\n int cap;\n list> dll;\n unordered_map>::iterator> cache;\npublic:\n LRUCache(int capacity) : cap(capacity) {}\n int get(int key) {\n auto it = cache.find(key);\n if (it == cache.end()) return -1;\n dll.splice(dll.end(), dll, it->second);\n return it->second->second;\n }\n void put(int key, int value) {\n auto it = cache.find(key);\n if (it != cache.end()) dll.erase(it->second);\n else if (cache.size() >= cap) { cache.erase(dll.front().first); dll.pop_front(); }\n dll.push_back({key, value});\n cache[key] = --dll.end();\n }\n};", "test_cases": ["put(1,1), put(2,2), get(1) -> 1"], "key_points": ["HashMap + 双向链表", "O(1)时间操作"], "tags": ["design", "hard", "Google", "Amazon"]} {"problem_id": "algo_00760", "original_id": "num-islands", "title": "岛屿数量", "category": "graph", "difficulty": "medium", "companies": ["Google", "Facebook"], "description": "给你一个由 '1'(陆地)和 '0'(水)组成的二维网格,请你计算网格中岛屿的数量。岛屿总是被水包围,且只能由水平或垂直方向相邻的陆地连接形成。", "solution_python": "def numIslands(grid):\n if not grid: return 0\n rows, cols = len(grid), len(grid[0])\n count = 0\n def dfs(r, c):\n if r < 0 or r >= rows or c < 0 or c >= cols or grid[r][c] != '1': return\n grid[r][c] = '0'\n dfs(r+1, c); dfs(r-1, c); dfs(r, c+1); dfs(r, c-1)\n for r in range(rows):\n for c in range(cols):\n if grid[r][c] == '1': count += 1; dfs(r, c)\n return count", "solution_java": "public int numIslands(char[][] grid) {\n if (grid.length == 0) return 0;\n int count = 0;\n for (int i = 0; i < grid.length; i++)\n for (int j = 0; j < grid[0].length; j++)\n if (grid[i][j] == '1') { count++; dfs(grid, i, j); }\n return count;\n}\nprivate void dfs(char[][] grid, int r, int c) {\n if (r < 0 || r >= grid.length || c < 0 || c >= grid[0].length || grid[r][c] != '1') return;\n grid[r][c] = '0';\n dfs(grid, r+1, c); dfs(grid, r-1, c); dfs(grid, r, c+1); dfs(grid, r, c-1);\n}", "solution_cpp": "int numIslands(vector>& grid) {\n if (grid.empty()) return 0;\n int count = 0;\n for (int i = 0; i < grid.size(); i++)\n for (int j = 0; j < grid[0].size(); j++)\n if (grid[i][j] == '1') { count++; dfs(grid, i, j); }\n return count;\n}\nvoid dfs(vector>& grid, int r, int c) {\n if (r < 0 || r >= grid.size() || c < 0 || c >= grid[0].size() || grid[r][c] != '1') return;\n grid[r][c] = '0';\n dfs(grid, r+1, c); dfs(grid, r-1, c); dfs(grid, r, c+1); dfs(grid, r, c-1);\n}", "test_cases": ["grid=[[1,1,1,1,0],[1,1,0,1,0],[1,1,0,0,0],[0,0,0,0,0]] -> 1"], "key_points": ["DFS/BFS遍历", "访问后标记为0避免重复"], "tags": ["graph", "medium", "Google", "Facebook"]} {"problem_id": "algo_00761", "original_id": "two-sum", "title": "两数之和", "category": "array", "difficulty": "easy", "companies": ["Amazon", "Google"], "description": "给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那两个整数,并返回他们的数组下标。", "solution_python": "def twoSum(nums, target):\n hashmap = {}\n for i, num in enumerate(nums):\n complement = target - num\n if complement in hashmap:\n return [hashmap[complement], i]\n hashmap[num] = i\n return []", "solution_java": "public int[] twoSum(int[] nums, int target) {\n Map map = new HashMap<>();\n for (int i = 0; i < nums.length; i++) {\n int complement = target - nums[i];\n if (map.containsKey(complement)) return new int[]{map.get(complement), i};\n map.put(nums[i], i);\n }\n return new int[]{};\n}", "solution_cpp": "vector twoSum(vector& nums, int target) {\n unordered_map m;\n for (int i = 0; i < nums.size(); i++) {\n if (m.count(target - nums[i])) return {m[target - nums[i]], i};\n m[nums[i]] = i;\n }\n return {};\n}", "test_cases": ["nums=[2,7,11,15], target=9 -> [0,1]", "nums=[3,2,4], target=6 -> [1,2]"], "key_points": ["哈希表一次遍历", "空间换时间"], "tags": ["array", "easy", "Amazon", "Google"]} {"problem_id": "algo_00762", "original_id": "merge-sorted", "title": "合并两个有序数组", "category": "array", "difficulty": "easy", "companies": ["Microsoft", "Uber"], "description": "给你两个按非递减顺序排列的整数数组 nums1 和 nums2,另有两个整数 m 和 n,分别表示 nums1 和 nums2 中的元素数目。请你合并 nums2 到 nums1 中。", "solution_python": "def merge(nums1, m, nums2, n):\n p1, p2, p = m-1, n-1, m+n-1\n while p1 >= 0 and p2 >= 0:\n if nums1[p1] > nums2[p2]: nums1[p] = nums1[p1]; p1 -= 1\n else: nums1[p] = nums2[p2]; p2 -= 1\n p -= 1\n while p2 >= 0: nums1[p] = nums2[p2]; p2 -= 1; p -= 1", "solution_java": "public void merge(int[] nums1, int m, int[] nums2, int n) {\n int p1 = m-1, p2 = n-1, p = m+n-1;\n while (p1 >= 0 && p2 >= 0) {\n nums1[p--] = nums1[p1] > nums2[p2] ? nums1[p1--] : nums2[p2--];\n }\n while (p2 >= 0) nums1[p--] = nums2[p2--];\n}", "solution_cpp": "void merge(vector& nums1, int m, vector& nums2, int n) {\n int p1 = m-1, p2 = n-1, p = m+n-1;\n while (p1 >= 0 && p2 >= 0) nums1[p--] = nums1[p1] > nums2[p2] ? nums1[p1--] : nums2[p2--];\n while (p2 >= 0) nums1[p--] = nums2[p2--];\n}", "test_cases": ["nums1=[1,2,3], m=3, nums2=[2,5,6], n=3 -> [1,2,2,3,5,6]", "nums1=[], m=0, nums2=[1], n=1 -> [1]"], "key_points": ["从后往前合并", "三指针技巧"], "tags": ["array", "easy", "Microsoft", "Uber"]} {"problem_id": "algo_00763", "original_id": "max-subarray", "title": "最大子数组和", "category": "array", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "给你一个整数数组 nums ,请你找出一个具有最大和的连续子数组,返回其最大和。", "solution_python": "def maxSubArray(nums):\n max_sum = current = nums[0]\n for num in nums[1:]:\n current = max(num, current + num)\n max_sum = max(max_sum, current)\n return max_sum", "solution_java": "public int maxSubArray(int[] nums) {\n int maxSum = nums[0], curr = nums[0];\n for (int i = 1; i < nums.length; i++) {\n curr = Math.max(nums[i], curr + nums[i]);\n maxSum = Math.max(maxSum, curr);\n }\n return maxSum;\n}", "solution_cpp": "int maxSubArray(vector& nums) {\n int maxSum = nums[0], curr = nums[0];\n for (int i = 1; i < nums.size(); i++) {\n curr = max(nums[i], curr + nums[i]);\n maxSum = max(maxSum, curr);\n }\n return maxSum;\n}", "test_cases": ["nums=[-2,1,-3,4,-1,2,1,-5,4] -> 6", "nums=[1] -> 1"], "key_points": ["Kadane算法", "动态规划基础题"], "tags": ["array", "medium", "Google", "Microsoft"]} {"problem_id": "algo_00764", "original_id": "valid-parentheses", "title": "有效的括号", "category": "string", "difficulty": "easy", "companies": ["Google", "Uber"], "description": "给定一个只包括 '(',')','{','}','[',']' 的字符串 s,判断字符串是否有效。", "solution_python": "def isValid(s):\n stack = []\n mapping = {')': '(', ']': '[', '}': '{'}\n for c in s:\n if c in mapping:\n if not stack or stack[-1] != mapping[c]: return False\n stack.pop()\n else: stack.append(c)\n return not stack", "solution_java": "public boolean isValid(String s) {\n Stack stack = new Stack<>();\n Map map = Map.of(')', '(', ']', '[', '}', '{');\n for (char c : s.toCharArray()) {\n if (map.containsValue(c)) stack.push(c);\n else if (!stack.isEmpty() && stack.pop() != map.get(c)) return false;\n }\n return stack.isEmpty();\n}", "solution_cpp": "bool isValid(string s) {\n stack st;\n unordered_map m = {{')','('},{']','['},{'}','{'}};\n for (char c : s) {\n if (m.find(c) == m.end()) st.push(c);\n else if (st.empty() || st.top() != m[c]) return false;\n else st.pop();\n }\n return st.empty();\n}", "test_cases": ["s=\"()\" -> true", "s=\"()[]{}\" -> true", "s=\"(]\" -> false"], "key_points": ["栈匹配法", "注意空栈边界"], "tags": ["string", "easy", "Google", "Uber"]} {"problem_id": "algo_00765", "original_id": "longest-palindrome", "title": "最长回文子串", "category": "string", "difficulty": "medium", "companies": ["Google", "Amazon"], "description": "给你一个字符串 s,找到 s 中最长的回文子串。", "solution_python": "def longestPalindrome(s):\n def expand(l, r):\n while l >= 0 and r < len(s) and s[l] == s[r]: l -= 1; r += 1\n return l + 1, r - 1\n start = end = 0\n for i in range(len(s)):\n l1, r1 = expand(i, i)\n l2, r2 = expand(i, i + 1)\n if r1 - l1 > end - start: start, end = l1, r1\n if r2 - l2 > end - start: start, end = l2, r2\n return s[start:end+1]", "solution_java": "public String longestPalindrome(String s) {\n int start = 0, end = 0;\n for (int i = 0; i < s.length(); i++) {\n int len1 = expand(s, i, i), len2 = expand(s, i, i+1);\n int len = Math.max(len1, len2);\n if (len > end - start) { start = i - (len-1)/2; end = i + len/2; }\n }\n return s.substring(start, end + 1);\n}\nprivate int expand(String s, int l, int r) {\n while (l >= 0 && r < s.length() && s.charAt(l) == s.charAt(r)) { l--; r++; }\n return r - l - 1;\n}", "solution_cpp": "string longestPalindrome(string s) {\n int start = 0, end = 0;\n for (int i = 0; i < s.size(); i++) {\n int len1 = expand(s, i, i), len2 = expand(s, i, i+1);\n if (max(len1, len2) > end - start) { start = i - (max(len1,len2)-1)/2; end = i + max(len1,len2)/2; }\n }\n return s.substr(start, end - start + 1);\n}", "test_cases": ["s=\"babad\" -> bab或aba", "s=\"cbbd\" -> bb"], "key_points": ["中心扩展法", "处理奇偶长度"], "tags": ["string", "medium", "Google", "Amazon"]} {"problem_id": "algo_00766", "original_id": "reverse-list", "title": "反转链表", "category": "linkedlist", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "给你单链表的头节点 head,请你反转链表,并返回反转后的链表。", "solution_python": "def reverseList(head):\n prev = None\n curr = head\n while curr:\n nxt = curr.next\n curr.next = prev\n prev = curr\n curr = nxt\n return prev", "solution_java": "public ListNode reverseList(ListNode head) {\n ListNode prev = null, curr = head;\n while (curr != null) {\n ListNode next = curr.next;\n curr.next = prev;\n prev = curr;\n curr = next;\n }\n return prev;\n}", "solution_cpp": "ListNode* reverseList(ListNode* head) {\n ListNode* prev = nullptr, *curr = head;\n while (curr) {\n ListNode* next = curr->next;\n curr->next = prev;\n prev = curr;\n curr = next;\n }\n return prev;\n}", "test_cases": ["head=[1,2,3,4,5] -> [5,4,3,2,1]", "head=[1,2] -> [2,1]"], "key_points": ["迭代法 O(1)空间", "递归法 O(n)空间"], "tags": ["linkedlist", "medium", "Google", "Microsoft"]} {"problem_id": "algo_00767", "original_id": "middle-node", "title": "链表的中间结点", "category": "linkedlist", "difficulty": "easy", "companies": ["Amazon", "Facebook"], "description": "给你单链表的头节点 head,请你找出并返回链表的中间结点。如果有两个中间结点,则返回第二个中间结点。", "solution_python": "def middleNode(head):\n slow = fast = head\n while fast and fast.next:\n slow = slow.next\n fast = fast.next.next\n return slow", "solution_java": "public ListNode middleNode(ListNode head) {\n ListNode slow = head, fast = head;\n while (fast != null && fast.next != null) {\n slow = slow.next;\n fast = fast.next.next;\n }\n return slow;\n}", "solution_cpp": "ListNode* middleNode(ListNode* head) {\n ListNode* slow = head, *fast = head;\n while (fast && fast->next) { slow = slow->next; fast = fast->next->next; }\n return slow;\n}", "test_cases": ["head=[1,2,3,4,5] -> 3", "head=[1,2,3,4,5,6] -> 4"], "key_points": ["快慢指针", "O(n)时间O(1)空间"], "tags": ["linkedlist", "easy", "Amazon", "Facebook"]} {"problem_id": "algo_00768", "original_id": "max-depth", "title": "二叉树的最大深度", "category": "tree", "difficulty": "easy", "companies": ["Microsoft", "Apple"], "description": "给定一个二叉树 root,返回其最大深度。", "solution_python": "def maxDepth(root):\n if not root: return 0\n return max(maxDepth(root.left), maxDepth(root.right)) + 1", "solution_java": "public int maxDepth(TreeNode root) {\n if (root == null) return 0;\n return Math.max(maxDepth(root.left), maxDepth(root.right)) + 1;\n}", "solution_cpp": "int maxDepth(TreeNode* root) {\n if (!root) return 0;\n return max(maxDepth(root->left), maxDepth(root->right)) + 1;\n}", "test_cases": ["root=[3,9,20,null,null,15,7] -> 3", "root=[1,null,2] -> 2"], "key_points": ["DFS递归", "层序遍历也可"], "tags": ["tree", "easy", "Microsoft", "Apple"]} {"problem_id": "algo_00769", "original_id": "inorder-traversal", "title": "二叉树的中序遍历", "category": "tree", "difficulty": "easy", "companies": ["Google", "Microsoft"], "description": "给定一个二叉树的根节点 root,返回它的中序遍历结果。", "solution_python": "def inorderTraversal(root):\n result = []\n def dfs(node):\n if node:\n dfs(node.left)\n result.append(node.val)\n dfs(node.right)\n dfs(root)\n return result", "solution_java": "public List inorderTraversal(TreeNode root) {\n List res = new ArrayList<>();\n dfs(root, res);\n return res;\n}\nprivate void dfs(TreeNode node, List res) {\n if (node == null) return;\n dfs(node.left, res); res.add(node.val); dfs(node.right, res);\n}", "solution_cpp": "vector inorderTraversal(TreeNode* root) {\n vector res;\n dfs(root, res);\n return res;\n}\nvoid dfs(TreeNode* node, vector& res) {\n if (!node) return;\n dfs(node->left, res); res.push_back(node->val); dfs(node->right, res);\n}", "test_cases": ["root=[1,null,2,3] -> [1,3,2]", "root=[] -> []"], "key_points": ["左-根-右顺序", "递归最简洁"], "tags": ["tree", "easy", "Google", "Microsoft"]} {"problem_id": "algo_00770", "original_id": "binary-search", "title": "二分查找", "category": "binarysearch", "difficulty": "easy", "companies": ["Google", "Amazon"], "description": "给定一个 n 个元素有序的(升序)整型数组 nums 和一个目标值 target,写一个函数搜索 nums 中的 target,如果目标值存在返回下标,否则返回 -1。", "solution_python": "def search(nums, target):\n left, right = 0, len(nums) - 1\n while left <= right:\n mid = (left + right) // 2\n if nums[mid] == target: return mid\n elif nums[mid] < target: left = mid + 1\n else: right = mid - 1\n return -1", "solution_java": "public int search(int[] nums, int target) {\n int left = 0, right = nums.length - 1;\n while (left <= right) {\n int mid = left + (right - left) / 2;\n if (nums[mid] == target) return mid;\n else if (nums[mid] < target) left = mid + 1;\n else right = mid - 1;\n }\n return -1;\n}", "solution_cpp": "int search(vector& nums, int target) {\n int left = 0, right = nums.size() - 1;\n while (left <= right) {\n int mid = left + (right - left) / 2;\n if (nums[mid] == target) return mid;\n else if (nums[mid] < target) left = mid + 1;\n else right = mid - 1;\n }\n return -1;\n}", "test_cases": ["nums=[-1,0,3,5,9,12], target=9 -> 4", "nums=[-1,0,3,5,9,12], target=2 -> -1"], "key_points": ["标准模板", "注意防溢出写法"], "tags": ["binarysearch", "easy", "Google", "Amazon"]} {"problem_id": "algo_00771", "original_id": "climbing-stairs", "title": "爬楼梯", "category": "dp", "difficulty": "easy", "companies": ["Amazon", "Google"], "description": "假设你正在爬楼梯。需要 n 阶你才能到达楼顶。每次你可以爬 1 或 2 个台阶。你有多少种不同的方法可以爬到楼顶?", "solution_python": "def climbStairs(n):\n if n <= 2: return n\n a, b = 1, 2\n for _ in range(3, n+1):\n a, b = b, a + b\n return b", "solution_java": "public int climbStairs(int n) {\n if (n <= 2) return n;\n int a = 1, b = 2;\n for (int i = 3; i <= n; i++) { int temp = a + b; a = b; b = temp; }\n return b;\n}", "solution_cpp": "int climbStairs(int n) {\n if (n <= 2) return n;\n int a = 1, b = 2;\n for (int i = 3; i <= n; i++) { int temp = a + b; a = b; b = temp; }\n return b;\n}", "test_cases": ["n=2 -> 2", "n=3 -> 3", "n=5 -> 8"], "key_points": ["斐波那契数列", "滚动数组优化空间"], "tags": ["dp", "easy", "Amazon", "Google"]} {"problem_id": "algo_00772", "original_id": "coin-change", "title": "零钱兑换", "category": "dp", "difficulty": "medium", "companies": ["Google", "Amazon"], "description": "给你一个整数数组 coins 表示不同面额的硬币,以及一个整数 amount 表示总金额。计算并返回可以凑成总金额所需的最少的硬币个数。如果没有任何一种硬币组合能组成总金额,返回 -1。", "solution_python": "def coinChange(coins, amount):\n dp = [float('inf')] * (amount + 1)\n dp[0] = 0\n for coin in coins:\n for x in range(coin, amount + 1):\n dp[x] = min(dp[x], dp[x - coin] + 1)\n return dp[amount] if dp[amount] != float('inf') else -1", "solution_java": "public int coinChange(int[] coins, int amount) {\n int[] dp = new int[amount + 1];\n Arrays.fill(dp, amount + 1);\n dp[0] = 0;\n for (int coin : coins) {\n for (int x = coin; x <= amount; x++) {\n dp[x] = Math.min(dp[x], dp[x - coin] + 1);\n }\n }\n return dp[amount] > amount ? -1 : dp[amount];\n}", "solution_cpp": "int coinChange(vector& coins, int amount) {\n vector dp(amount + 1, amount + 1);\n dp[0] = 0;\n for (int coin : coins) {\n for (int x = coin; x <= amount; x++) {\n dp[x] = min(dp[x], dp[x - coin] + 1);\n }\n }\n return dp[amount] > amount ? -1 : dp[amount];\n}", "test_cases": ["coins=[1,2,5], amount=11 -> 3", "coins=[2], amount=3 -> -1"], "key_points": ["完全背包问题", "dp[x] = min(dp[x-coin]+1)"], "tags": ["dp", "medium", "Google", "Amazon"]} {"problem_id": "algo_00773", "original_id": "subsets", "title": "子集", "category": "backtracking", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "给你一个整数数组 nums ,数组中的元素 互不相同 。返回该数组所有可能的子集(幂集)。", "solution_python": "def subsets(nums):\n result = []\n def backtrack(start, path):\n result.append(path[:])\n for i in range(start, len(nums)):\n path.append(nums[i])\n backtrack(i + 1, path)\n path.pop()\n backtrack(0, [])\n return result", "solution_java": "public List> subsets(int[] nums) {\n List> result = new ArrayList<>();\n backtrack(nums, 0, new ArrayList<>(), result);\n return result;\n}\nprivate void backtrack(int[] nums, int start, List path, List> result) {\n result.add(new ArrayList<>(path));\n for (int i = start; i < nums.length; i++) {\n path.add(nums[i]);\n backtrack(nums, i + 1, path, result);\n path.remove(path.size() - 1);\n }\n}", "solution_cpp": "vector> subsets(vector& nums) {\n vector> result;\n vector path;\n backtrack(nums, 0, path, result);\n return result;\n}\nvoid backtrack(vector& nums, int start, vector& path, vector>& result) {\n result.push_back(path);\n for (int i = start; i < nums.size(); i++) {\n path.push_back(nums[i]);\n backtrack(nums, i + 1, path, result);\n path.pop_back();\n }\n}", "test_cases": ["nums=[1,2,3] -> [[],[1],[2],[1,2],[3],[1,3],[2,3],[1,2,3]]"], "key_points": ["选或不选", "DFS遍历子集树"], "tags": ["backtracking", "medium", "Google", "Microsoft"]} {"problem_id": "algo_00774", "original_id": "permutations", "title": "全排列", "category": "backtracking", "difficulty": "medium", "companies": ["Google", "Facebook"], "description": "给定一个不含重复数字的数组 nums,返回其所有可能的全排列。", "solution_python": "def permute(nums):\n result = []\n def backtrack(path, used):\n if len(path) == len(nums):\n result.append(path[:])\n return\n for i in range(len(nums)):\n if used[i]: continue\n used[i] = True\n path.append(nums[i])\n backtrack(path, used)\n path.pop()\n used[i] = False\n backtrack([], [False]*len(nums))\n return result", "solution_java": "public List> permute(int[] nums) {\n List> result = new ArrayList<>();\n boolean[] used = new boolean[nums.length];\n backtrack(nums, used, new ArrayList<>(), result);\n return result;\n}\nprivate void backtrack(int[] nums, boolean[] used, List path, List> result) {\n if (path.size() == nums.length) { result.add(new ArrayList<>(path)); return; }\n for (int i = 0; i < nums.length; i++) {\n if (used[i]) continue;\n used[i] = true;\n path.add(nums[i]);\n backtrack(nums, used, path, result);\n path.remove(path.size() - 1);\n used[i] = false;\n }\n}", "solution_cpp": "vector> permute(vector& nums) {\n vector> result;\n vector used(nums.size(), false);\n vector path;\n backtrack(nums, used, path, result);\n return result;\n}\nvoid backtrack(vector& nums, vector& used, vector& path, vector>& result) {\n if (path.size() == nums.size()) { result.push_back(path); return; }\n for (int i = 0; i < nums.size(); i++) {\n if (used[i]) continue;\n used[i] = true;\n path.push_back(nums[i]);\n backtrack(nums, used, path, result);\n path.pop_back();\n used[i] = false;\n }\n}", "test_cases": ["nums=[1,2,3] -> [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]"], "key_points": ["标记已使用元素", "回溯经典模板"], "tags": ["backtracking", "medium", "Google", "Facebook"]} {"problem_id": "algo_00775", "original_id": "top-k-frequent", "title": "前K个高频元素", "category": "heap", "difficulty": "medium", "companies": ["Amazon", "Facebook"], "description": "给你一个整数数组 nums 和一个整数 k,请你返回其中出现频率前 k 高的元素。", "solution_python": "import heapq\nfrom collections import Counter\ndef topKFrequent(nums, k):\n count = Counter(nums)\n heap = []\n for num, freq in count.items():\n heapq.heappush(heap, (freq, num))\n if len(heap) > k: heapq.heappop(heap)\n return [num for freq, num in heap]", "solution_java": "public int[] topKFrequent(int[] nums, int k) {\n Map count = new HashMap<>();\n for (int n : nums) count.put(n, count.getOrDefault(n, 0) + 1);\n PriorityQueue> heap = \n new PriorityQueue<>((a, b) -> a.getValue() - b.getValue());\n for (Map.Entry e : count.entrySet()) {\n heap.offer(e);\n if (heap.size() > k) heap.poll();\n }\n int[] res = new int[k];\n for (int i = k - 1; i >= 0; i--) res[i] = heap.poll().getKey();\n return res;\n}", "solution_cpp": "vector topKFrequent(vector& nums, int k) {\n unordered_map count;\n for (int n : nums) count[n]++;\n priority_queue, vector>, greater>> heap;\n for (auto& [num, freq] : count) {\n heap.push({freq, num});\n if (heap.size() > k) heap.pop();\n }\n vector res;\n while (!heap.empty()) { res.push_back(heap.top().second); heap.pop(); }\n reverse(res.begin(), res.end());\n return res;\n}", "test_cases": ["nums=[1,1,1,2,2,3], k=2 -> [1,2]", "nums=[1], k=1 -> [1]"], "key_points": ["小顶堆保持大小k", "时间复杂度O(nlogk)"], "tags": ["heap", "medium", "Amazon", "Facebook"]} {"problem_id": "algo_00776", "original_id": "3sum", "title": "三数之和", "category": "two-pointers", "difficulty": "medium", "companies": ["Google", "Amazon"], "description": "给你一个整数数组 nums,判断是否存在三元组满足和为0,返回所有不重复的三元组。", "solution_python": "def threeSum(nums):\n nums.sort()\n result = []\n for i in range(len(nums) - 2):\n if i > 0 and nums[i] == nums[i-1]: continue\n left, right = i + 1, len(nums) - 1\n while left < right:\n total = nums[i] + nums[left] + nums[right]\n if total < 0: left += 1\n elif total > 0: right -= 1\n else:\n result.append([nums[i], nums[left], nums[right]])\n while left < right and nums[left] == nums[left+1]: left += 1\n while left < right and nums[right] == nums[right-1]: right -= 1\n left += 1; right -= 1\n return result", "solution_java": "public List> threeSum(int[] nums) {\n Arrays.sort(nums);\n List> result = new ArrayList<>();\n for (int i = 0; i < nums.length - 2; i++) {\n if (i > 0 && nums[i] == nums[i-1]) continue;\n int left = i + 1, right = nums.length - 1;\n while (left < right) {\n int total = nums[i] + nums[left] + nums[right];\n if (total < 0) left++;\n else if (total > 0) right--;\n else {\n result.add(Arrays.asList(nums[i], nums[left], nums[right]));\n while (left < right && nums[left] == nums[left+1]) left++;\n while (left < right && nums[right] == nums[right-1]) right--;\n left++; right--;\n }\n }\n }\n return result;\n}", "solution_cpp": "vector> threeSum(vector& nums) {\n sort(nums.begin(), nums.end());\n vector> result;\n for (int i = 0; i < nums.size() - 2; i++) {\n if (i > 0 && nums[i] == nums[i-1]) continue;\n int left = i + 1, right = nums.size() - 1;\n while (left < right) {\n int total = nums[i] + nums[left] + nums[right];\n if (total < 0) left++;\n else if (total > 0) right--;\n else {\n result.push_back({nums[i], nums[left], nums[right]});\n while (left < right && nums[left] == nums[left+1]) left++;\n while (left < right && nums[right] == nums[right-1]) right--;\n left++; right--;\n }\n }\n }\n return result;\n}", "test_cases": ["nums=[-1,0,1,2,-1,-4] -> [[-1,-1,2],[-1,0,1]]"], "key_points": ["排序+双指针", "去重是关键"], "tags": ["two-pointers", "medium", "Google", "Amazon"]} {"problem_id": "algo_00777", "original_id": "container-water", "title": "盛最多水的容器", "category": "two-pointers", "difficulty": "medium", "companies": ["Google", "Uber"], "description": "给定一个长度为 n 的整数数组 height,找出其中的两条线,使得它们与 x 轴共同构成的容器可以容纳最多的水。", "solution_python": "def maxArea(height):\n left, right = 0, len(height) - 1\n max_area = 0\n while left < right:\n h = min(height[left], height[right])\n max_area = max(max_area, h * (right - left))\n if height[left] < height[right]: left += 1\n else: right -= 1\n return max_area", "solution_java": "public int maxArea(int[] height) {\n int left = 0, right = height.length - 1, maxArea = 0;\n while (left < right) {\n int h = Math.min(height[left], height[right]);\n maxArea = Math.max(maxArea, h * (right - left));\n if (height[left] < height[right]) left++;\n else right--;\n }\n return maxArea;\n}", "solution_cpp": "int maxArea(vector& height) {\n int left = 0, right = height.size() - 1, maxArea = 0;\n while (left < right) {\n int h = min(height[left], height[right]);\n maxArea = max(maxArea, h * (right - left));\n if (height[left] < height[right]) left++;\n else right--;\n }\n return maxArea;\n}", "test_cases": ["height=[1,8,6,2,5,4,8,3,7] -> 49"], "key_points": ["移动短边指针", "面积=min(h1,h2)*width"], "tags": ["two-pointers", "medium", "Google", "Uber"]} {"problem_id": "algo_00778", "original_id": "min-stack", "title": "最小栈", "category": "stack", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "设计一个支持 push,pop,top 操作,并能在常数时间内检索到最小元素的栈。", "solution_python": "class MinStack:\n def __init__(self):\n self.stack = []\n self.min_stack = []\n def push(self, val):\n self.stack.append(val)\n self.min_stack.append(min(val, self.min_stack[-1] if self.min_stack else val))\n def pop(self):\n self.stack.pop(); self.min_stack.pop()\n def top(self): return self.stack[-1]\n def getMin(self): return self.min_stack[-1]", "solution_java": "class MinStack {\n Stack stack = new Stack<>();\n Stack minStack = new Stack<>();\n public void push(int val) { stack.push(val); minStack.push(Math.min(val, minStack.isEmpty() ? val : minStack.peek())); }\n public void pop() { stack.pop(); minStack.pop(); }\n public int top() { return stack.peek(); }\n public int getMin() { return minStack.peek(); }\n}", "solution_cpp": "class MinStack {\n stack st, minSt;\npublic:\n void push(int val) { st.push(val); minSt.push(min(val, minSt.empty() ? val : minSt.top())); }\n void pop() { st.pop(); minSt.pop(); }\n int top() { return st.top(); }\n int getMin() { return minSt.top(); }\n};", "test_cases": ["push(-2), push(0), push(-3) -> getMin() returns -3"], "key_points": ["辅助栈记录最小值", "O(1)时间获取最小值"], "tags": ["stack", "medium", "Google", "Microsoft"]} {"problem_id": "algo_00779", "original_id": "lru-cache", "title": "LRU缓存", "category": "design", "difficulty": "hard", "companies": ["Google", "Amazon"], "description": "设计和实现一个 LRU(最近最少使用)缓存机制。", "solution_python": "class LRUCache:\n def __init__(self, capacity):\n self.capacity = capacity\n self.cache = {}\n self.order = []\n def get(self, key):\n if key not in self.cache: return -1\n self.order.remove(key); self.order.append(key)\n return self.cache[key]\n def put(self, key, value):\n if key in self.cache:\n self.order.remove(key)\n elif len(self.cache) >= self.capacity:\n del self.cache[self.order.pop(0)]\n self.cache[key] = value; self.order.append(key)", "solution_java": "class LRUCache {\n int capacity;\n LinkedHashMap cache = new LinkedHashMap<>();\n public LRUCache(int cap) { capacity = cap; }\n public int get(int key) { return cache.containsKey(key) ? cache.remove(key) : -1; }\n public void put(int key, int val) {\n if (cache.containsKey(key)) cache.remove(key);\n else if (cache.size() >= capacity) cache.remove(cache.keySet().iterator().next());\n cache.put(key, val);\n }\n}", "solution_cpp": "class LRUCache {\n int cap;\n list> dll;\n unordered_map>::iterator> cache;\npublic:\n LRUCache(int capacity) : cap(capacity) {}\n int get(int key) {\n auto it = cache.find(key);\n if (it == cache.end()) return -1;\n dll.splice(dll.end(), dll, it->second);\n return it->second->second;\n }\n void put(int key, int value) {\n auto it = cache.find(key);\n if (it != cache.end()) dll.erase(it->second);\n else if (cache.size() >= cap) { cache.erase(dll.front().first); dll.pop_front(); }\n dll.push_back({key, value});\n cache[key] = --dll.end();\n }\n};", "test_cases": ["put(1,1), put(2,2), get(1) -> 1"], "key_points": ["HashMap + 双向链表", "O(1)时间操作"], "tags": ["design", "hard", "Google", "Amazon"]} {"problem_id": "algo_00780", "original_id": "num-islands", "title": "岛屿数量", "category": "graph", "difficulty": "medium", "companies": ["Google", "Facebook"], "description": "给你一个由 '1'(陆地)和 '0'(水)组成的二维网格,请你计算网格中岛屿的数量。岛屿总是被水包围,且只能由水平或垂直方向相邻的陆地连接形成。", "solution_python": "def numIslands(grid):\n if not grid: return 0\n rows, cols = len(grid), len(grid[0])\n count = 0\n def dfs(r, c):\n if r < 0 or r >= rows or c < 0 or c >= cols or grid[r][c] != '1': return\n grid[r][c] = '0'\n dfs(r+1, c); dfs(r-1, c); dfs(r, c+1); dfs(r, c-1)\n for r in range(rows):\n for c in range(cols):\n if grid[r][c] == '1': count += 1; dfs(r, c)\n return count", "solution_java": "public int numIslands(char[][] grid) {\n if (grid.length == 0) return 0;\n int count = 0;\n for (int i = 0; i < grid.length; i++)\n for (int j = 0; j < grid[0].length; j++)\n if (grid[i][j] == '1') { count++; dfs(grid, i, j); }\n return count;\n}\nprivate void dfs(char[][] grid, int r, int c) {\n if (r < 0 || r >= grid.length || c < 0 || c >= grid[0].length || grid[r][c] != '1') return;\n grid[r][c] = '0';\n dfs(grid, r+1, c); dfs(grid, r-1, c); dfs(grid, r, c+1); dfs(grid, r, c-1);\n}", "solution_cpp": "int numIslands(vector>& grid) {\n if (grid.empty()) return 0;\n int count = 0;\n for (int i = 0; i < grid.size(); i++)\n for (int j = 0; j < grid[0].size(); j++)\n if (grid[i][j] == '1') { count++; dfs(grid, i, j); }\n return count;\n}\nvoid dfs(vector>& grid, int r, int c) {\n if (r < 0 || r >= grid.size() || c < 0 || c >= grid[0].size() || grid[r][c] != '1') return;\n grid[r][c] = '0';\n dfs(grid, r+1, c); dfs(grid, r-1, c); dfs(grid, r, c+1); dfs(grid, r, c-1);\n}", "test_cases": ["grid=[[1,1,1,1,0],[1,1,0,1,0],[1,1,0,0,0],[0,0,0,0,0]] -> 1"], "key_points": ["DFS/BFS遍历", "访问后标记为0避免重复"], "tags": ["graph", "medium", "Google", "Facebook"]} {"problem_id": "algo_00781", "original_id": "two-sum", "title": "两数之和", "category": "array", "difficulty": "easy", "companies": ["Amazon", "Google"], "description": "给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那两个整数,并返回他们的数组下标。", "solution_python": "def twoSum(nums, target):\n hashmap = {}\n for i, num in enumerate(nums):\n complement = target - num\n if complement in hashmap:\n return [hashmap[complement], i]\n hashmap[num] = i\n return []", "solution_java": "public int[] twoSum(int[] nums, int target) {\n Map map = new HashMap<>();\n for (int i = 0; i < nums.length; i++) {\n int complement = target - nums[i];\n if (map.containsKey(complement)) return new int[]{map.get(complement), i};\n map.put(nums[i], i);\n }\n return new int[]{};\n}", "solution_cpp": "vector twoSum(vector& nums, int target) {\n unordered_map m;\n for (int i = 0; i < nums.size(); i++) {\n if (m.count(target - nums[i])) return {m[target - nums[i]], i};\n m[nums[i]] = i;\n }\n return {};\n}", "test_cases": ["nums=[2,7,11,15], target=9 -> [0,1]", "nums=[3,2,4], target=6 -> [1,2]"], "key_points": ["哈希表一次遍历", "空间换时间"], "tags": ["array", "easy", "Amazon", "Google"]} {"problem_id": "algo_00782", "original_id": "merge-sorted", "title": "合并两个有序数组", "category": "array", "difficulty": "easy", "companies": ["Microsoft", "Uber"], "description": "给你两个按非递减顺序排列的整数数组 nums1 和 nums2,另有两个整数 m 和 n,分别表示 nums1 和 nums2 中的元素数目。请你合并 nums2 到 nums1 中。", "solution_python": "def merge(nums1, m, nums2, n):\n p1, p2, p = m-1, n-1, m+n-1\n while p1 >= 0 and p2 >= 0:\n if nums1[p1] > nums2[p2]: nums1[p] = nums1[p1]; p1 -= 1\n else: nums1[p] = nums2[p2]; p2 -= 1\n p -= 1\n while p2 >= 0: nums1[p] = nums2[p2]; p2 -= 1; p -= 1", "solution_java": "public void merge(int[] nums1, int m, int[] nums2, int n) {\n int p1 = m-1, p2 = n-1, p = m+n-1;\n while (p1 >= 0 && p2 >= 0) {\n nums1[p--] = nums1[p1] > nums2[p2] ? nums1[p1--] : nums2[p2--];\n }\n while (p2 >= 0) nums1[p--] = nums2[p2--];\n}", "solution_cpp": "void merge(vector& nums1, int m, vector& nums2, int n) {\n int p1 = m-1, p2 = n-1, p = m+n-1;\n while (p1 >= 0 && p2 >= 0) nums1[p--] = nums1[p1] > nums2[p2] ? nums1[p1--] : nums2[p2--];\n while (p2 >= 0) nums1[p--] = nums2[p2--];\n}", "test_cases": ["nums1=[1,2,3], m=3, nums2=[2,5,6], n=3 -> [1,2,2,3,5,6]", "nums1=[], m=0, nums2=[1], n=1 -> [1]"], "key_points": ["从后往前合并", "三指针技巧"], "tags": ["array", "easy", "Microsoft", "Uber"]} {"problem_id": "algo_00783", "original_id": "max-subarray", "title": "最大子数组和", "category": "array", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "给你一个整数数组 nums ,请你找出一个具有最大和的连续子数组,返回其最大和。", "solution_python": "def maxSubArray(nums):\n max_sum = current = nums[0]\n for num in nums[1:]:\n current = max(num, current + num)\n max_sum = max(max_sum, current)\n return max_sum", "solution_java": "public int maxSubArray(int[] nums) {\n int maxSum = nums[0], curr = nums[0];\n for (int i = 1; i < nums.length; i++) {\n curr = Math.max(nums[i], curr + nums[i]);\n maxSum = Math.max(maxSum, curr);\n }\n return maxSum;\n}", "solution_cpp": "int maxSubArray(vector& nums) {\n int maxSum = nums[0], curr = nums[0];\n for (int i = 1; i < nums.size(); i++) {\n curr = max(nums[i], curr + nums[i]);\n maxSum = max(maxSum, curr);\n }\n return maxSum;\n}", "test_cases": ["nums=[-2,1,-3,4,-1,2,1,-5,4] -> 6", "nums=[1] -> 1"], "key_points": ["Kadane算法", "动态规划基础题"], "tags": ["array", "medium", "Google", "Microsoft"]} {"problem_id": "algo_00784", "original_id": "valid-parentheses", "title": "有效的括号", "category": "string", "difficulty": "easy", "companies": ["Google", "Uber"], "description": "给定一个只包括 '(',')','{','}','[',']' 的字符串 s,判断字符串是否有效。", "solution_python": "def isValid(s):\n stack = []\n mapping = {')': '(', ']': '[', '}': '{'}\n for c in s:\n if c in mapping:\n if not stack or stack[-1] != mapping[c]: return False\n stack.pop()\n else: stack.append(c)\n return not stack", "solution_java": "public boolean isValid(String s) {\n Stack stack = new Stack<>();\n Map map = Map.of(')', '(', ']', '[', '}', '{');\n for (char c : s.toCharArray()) {\n if (map.containsValue(c)) stack.push(c);\n else if (!stack.isEmpty() && stack.pop() != map.get(c)) return false;\n }\n return stack.isEmpty();\n}", "solution_cpp": "bool isValid(string s) {\n stack st;\n unordered_map m = {{')','('},{']','['},{'}','{'}};\n for (char c : s) {\n if (m.find(c) == m.end()) st.push(c);\n else if (st.empty() || st.top() != m[c]) return false;\n else st.pop();\n }\n return st.empty();\n}", "test_cases": ["s=\"()\" -> true", "s=\"()[]{}\" -> true", "s=\"(]\" -> false"], "key_points": ["栈匹配法", "注意空栈边界"], "tags": ["string", "easy", "Google", "Uber"]} {"problem_id": "algo_00785", "original_id": "longest-palindrome", "title": "最长回文子串", "category": "string", "difficulty": "medium", "companies": ["Google", "Amazon"], "description": "给你一个字符串 s,找到 s 中最长的回文子串。", "solution_python": "def longestPalindrome(s):\n def expand(l, r):\n while l >= 0 and r < len(s) and s[l] == s[r]: l -= 1; r += 1\n return l + 1, r - 1\n start = end = 0\n for i in range(len(s)):\n l1, r1 = expand(i, i)\n l2, r2 = expand(i, i + 1)\n if r1 - l1 > end - start: start, end = l1, r1\n if r2 - l2 > end - start: start, end = l2, r2\n return s[start:end+1]", "solution_java": "public String longestPalindrome(String s) {\n int start = 0, end = 0;\n for (int i = 0; i < s.length(); i++) {\n int len1 = expand(s, i, i), len2 = expand(s, i, i+1);\n int len = Math.max(len1, len2);\n if (len > end - start) { start = i - (len-1)/2; end = i + len/2; }\n }\n return s.substring(start, end + 1);\n}\nprivate int expand(String s, int l, int r) {\n while (l >= 0 && r < s.length() && s.charAt(l) == s.charAt(r)) { l--; r++; }\n return r - l - 1;\n}", "solution_cpp": "string longestPalindrome(string s) {\n int start = 0, end = 0;\n for (int i = 0; i < s.size(); i++) {\n int len1 = expand(s, i, i), len2 = expand(s, i, i+1);\n if (max(len1, len2) > end - start) { start = i - (max(len1,len2)-1)/2; end = i + max(len1,len2)/2; }\n }\n return s.substr(start, end - start + 1);\n}", "test_cases": ["s=\"babad\" -> bab或aba", "s=\"cbbd\" -> bb"], "key_points": ["中心扩展法", "处理奇偶长度"], "tags": ["string", "medium", "Google", "Amazon"]} {"problem_id": "algo_00786", "original_id": "reverse-list", "title": "反转链表", "category": "linkedlist", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "给你单链表的头节点 head,请你反转链表,并返回反转后的链表。", "solution_python": "def reverseList(head):\n prev = None\n curr = head\n while curr:\n nxt = curr.next\n curr.next = prev\n prev = curr\n curr = nxt\n return prev", "solution_java": "public ListNode reverseList(ListNode head) {\n ListNode prev = null, curr = head;\n while (curr != null) {\n ListNode next = curr.next;\n curr.next = prev;\n prev = curr;\n curr = next;\n }\n return prev;\n}", "solution_cpp": "ListNode* reverseList(ListNode* head) {\n ListNode* prev = nullptr, *curr = head;\n while (curr) {\n ListNode* next = curr->next;\n curr->next = prev;\n prev = curr;\n curr = next;\n }\n return prev;\n}", "test_cases": ["head=[1,2,3,4,5] -> [5,4,3,2,1]", "head=[1,2] -> [2,1]"], "key_points": ["迭代法 O(1)空间", "递归法 O(n)空间"], "tags": ["linkedlist", "medium", "Google", "Microsoft"]} {"problem_id": "algo_00787", "original_id": "middle-node", "title": "链表的中间结点", "category": "linkedlist", "difficulty": "easy", "companies": ["Amazon", "Facebook"], "description": "给你单链表的头节点 head,请你找出并返回链表的中间结点。如果有两个中间结点,则返回第二个中间结点。", "solution_python": "def middleNode(head):\n slow = fast = head\n while fast and fast.next:\n slow = slow.next\n fast = fast.next.next\n return slow", "solution_java": "public ListNode middleNode(ListNode head) {\n ListNode slow = head, fast = head;\n while (fast != null && fast.next != null) {\n slow = slow.next;\n fast = fast.next.next;\n }\n return slow;\n}", "solution_cpp": "ListNode* middleNode(ListNode* head) {\n ListNode* slow = head, *fast = head;\n while (fast && fast->next) { slow = slow->next; fast = fast->next->next; }\n return slow;\n}", "test_cases": ["head=[1,2,3,4,5] -> 3", "head=[1,2,3,4,5,6] -> 4"], "key_points": ["快慢指针", "O(n)时间O(1)空间"], "tags": ["linkedlist", "easy", "Amazon", "Facebook"]} {"problem_id": "algo_00788", "original_id": "max-depth", "title": "二叉树的最大深度", "category": "tree", "difficulty": "easy", "companies": ["Microsoft", "Apple"], "description": "给定一个二叉树 root,返回其最大深度。", "solution_python": "def maxDepth(root):\n if not root: return 0\n return max(maxDepth(root.left), maxDepth(root.right)) + 1", "solution_java": "public int maxDepth(TreeNode root) {\n if (root == null) return 0;\n return Math.max(maxDepth(root.left), maxDepth(root.right)) + 1;\n}", "solution_cpp": "int maxDepth(TreeNode* root) {\n if (!root) return 0;\n return max(maxDepth(root->left), maxDepth(root->right)) + 1;\n}", "test_cases": ["root=[3,9,20,null,null,15,7] -> 3", "root=[1,null,2] -> 2"], "key_points": ["DFS递归", "层序遍历也可"], "tags": ["tree", "easy", "Microsoft", "Apple"]} {"problem_id": "algo_00789", "original_id": "inorder-traversal", "title": "二叉树的中序遍历", "category": "tree", "difficulty": "easy", "companies": ["Google", "Microsoft"], "description": "给定一个二叉树的根节点 root,返回它的中序遍历结果。", "solution_python": "def inorderTraversal(root):\n result = []\n def dfs(node):\n if node:\n dfs(node.left)\n result.append(node.val)\n dfs(node.right)\n dfs(root)\n return result", "solution_java": "public List inorderTraversal(TreeNode root) {\n List res = new ArrayList<>();\n dfs(root, res);\n return res;\n}\nprivate void dfs(TreeNode node, List res) {\n if (node == null) return;\n dfs(node.left, res); res.add(node.val); dfs(node.right, res);\n}", "solution_cpp": "vector inorderTraversal(TreeNode* root) {\n vector res;\n dfs(root, res);\n return res;\n}\nvoid dfs(TreeNode* node, vector& res) {\n if (!node) return;\n dfs(node->left, res); res.push_back(node->val); dfs(node->right, res);\n}", "test_cases": ["root=[1,null,2,3] -> [1,3,2]", "root=[] -> []"], "key_points": ["左-根-右顺序", "递归最简洁"], "tags": ["tree", "easy", "Google", "Microsoft"]} {"problem_id": "algo_00790", "original_id": "binary-search", "title": "二分查找", "category": "binarysearch", "difficulty": "easy", "companies": ["Google", "Amazon"], "description": "给定一个 n 个元素有序的(升序)整型数组 nums 和一个目标值 target,写一个函数搜索 nums 中的 target,如果目标值存在返回下标,否则返回 -1。", "solution_python": "def search(nums, target):\n left, right = 0, len(nums) - 1\n while left <= right:\n mid = (left + right) // 2\n if nums[mid] == target: return mid\n elif nums[mid] < target: left = mid + 1\n else: right = mid - 1\n return -1", "solution_java": "public int search(int[] nums, int target) {\n int left = 0, right = nums.length - 1;\n while (left <= right) {\n int mid = left + (right - left) / 2;\n if (nums[mid] == target) return mid;\n else if (nums[mid] < target) left = mid + 1;\n else right = mid - 1;\n }\n return -1;\n}", "solution_cpp": "int search(vector& nums, int target) {\n int left = 0, right = nums.size() - 1;\n while (left <= right) {\n int mid = left + (right - left) / 2;\n if (nums[mid] == target) return mid;\n else if (nums[mid] < target) left = mid + 1;\n else right = mid - 1;\n }\n return -1;\n}", "test_cases": ["nums=[-1,0,3,5,9,12], target=9 -> 4", "nums=[-1,0,3,5,9,12], target=2 -> -1"], "key_points": ["标准模板", "注意防溢出写法"], "tags": ["binarysearch", "easy", "Google", "Amazon"]} {"problem_id": "algo_00791", "original_id": "climbing-stairs", "title": "爬楼梯", "category": "dp", "difficulty": "easy", "companies": ["Amazon", "Google"], "description": "假设你正在爬楼梯。需要 n 阶你才能到达楼顶。每次你可以爬 1 或 2 个台阶。你有多少种不同的方法可以爬到楼顶?", "solution_python": "def climbStairs(n):\n if n <= 2: return n\n a, b = 1, 2\n for _ in range(3, n+1):\n a, b = b, a + b\n return b", "solution_java": "public int climbStairs(int n) {\n if (n <= 2) return n;\n int a = 1, b = 2;\n for (int i = 3; i <= n; i++) { int temp = a + b; a = b; b = temp; }\n return b;\n}", "solution_cpp": "int climbStairs(int n) {\n if (n <= 2) return n;\n int a = 1, b = 2;\n for (int i = 3; i <= n; i++) { int temp = a + b; a = b; b = temp; }\n return b;\n}", "test_cases": ["n=2 -> 2", "n=3 -> 3", "n=5 -> 8"], "key_points": ["斐波那契数列", "滚动数组优化空间"], "tags": ["dp", "easy", "Amazon", "Google"]} {"problem_id": "algo_00792", "original_id": "coin-change", "title": "零钱兑换", "category": "dp", "difficulty": "medium", "companies": ["Google", "Amazon"], "description": "给你一个整数数组 coins 表示不同面额的硬币,以及一个整数 amount 表示总金额。计算并返回可以凑成总金额所需的最少的硬币个数。如果没有任何一种硬币组合能组成总金额,返回 -1。", "solution_python": "def coinChange(coins, amount):\n dp = [float('inf')] * (amount + 1)\n dp[0] = 0\n for coin in coins:\n for x in range(coin, amount + 1):\n dp[x] = min(dp[x], dp[x - coin] + 1)\n return dp[amount] if dp[amount] != float('inf') else -1", "solution_java": "public int coinChange(int[] coins, int amount) {\n int[] dp = new int[amount + 1];\n Arrays.fill(dp, amount + 1);\n dp[0] = 0;\n for (int coin : coins) {\n for (int x = coin; x <= amount; x++) {\n dp[x] = Math.min(dp[x], dp[x - coin] + 1);\n }\n }\n return dp[amount] > amount ? -1 : dp[amount];\n}", "solution_cpp": "int coinChange(vector& coins, int amount) {\n vector dp(amount + 1, amount + 1);\n dp[0] = 0;\n for (int coin : coins) {\n for (int x = coin; x <= amount; x++) {\n dp[x] = min(dp[x], dp[x - coin] + 1);\n }\n }\n return dp[amount] > amount ? -1 : dp[amount];\n}", "test_cases": ["coins=[1,2,5], amount=11 -> 3", "coins=[2], amount=3 -> -1"], "key_points": ["完全背包问题", "dp[x] = min(dp[x-coin]+1)"], "tags": ["dp", "medium", "Google", "Amazon"]} {"problem_id": "algo_00793", "original_id": "subsets", "title": "子集", "category": "backtracking", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "给你一个整数数组 nums ,数组中的元素 互不相同 。返回该数组所有可能的子集(幂集)。", "solution_python": "def subsets(nums):\n result = []\n def backtrack(start, path):\n result.append(path[:])\n for i in range(start, len(nums)):\n path.append(nums[i])\n backtrack(i + 1, path)\n path.pop()\n backtrack(0, [])\n return result", "solution_java": "public List> subsets(int[] nums) {\n List> result = new ArrayList<>();\n backtrack(nums, 0, new ArrayList<>(), result);\n return result;\n}\nprivate void backtrack(int[] nums, int start, List path, List> result) {\n result.add(new ArrayList<>(path));\n for (int i = start; i < nums.length; i++) {\n path.add(nums[i]);\n backtrack(nums, i + 1, path, result);\n path.remove(path.size() - 1);\n }\n}", "solution_cpp": "vector> subsets(vector& nums) {\n vector> result;\n vector path;\n backtrack(nums, 0, path, result);\n return result;\n}\nvoid backtrack(vector& nums, int start, vector& path, vector>& result) {\n result.push_back(path);\n for (int i = start; i < nums.size(); i++) {\n path.push_back(nums[i]);\n backtrack(nums, i + 1, path, result);\n path.pop_back();\n }\n}", "test_cases": ["nums=[1,2,3] -> [[],[1],[2],[1,2],[3],[1,3],[2,3],[1,2,3]]"], "key_points": ["选或不选", "DFS遍历子集树"], "tags": ["backtracking", "medium", "Google", "Microsoft"]} {"problem_id": "algo_00794", "original_id": "permutations", "title": "全排列", "category": "backtracking", "difficulty": "medium", "companies": ["Google", "Facebook"], "description": "给定一个不含重复数字的数组 nums,返回其所有可能的全排列。", "solution_python": "def permute(nums):\n result = []\n def backtrack(path, used):\n if len(path) == len(nums):\n result.append(path[:])\n return\n for i in range(len(nums)):\n if used[i]: continue\n used[i] = True\n path.append(nums[i])\n backtrack(path, used)\n path.pop()\n used[i] = False\n backtrack([], [False]*len(nums))\n return result", "solution_java": "public List> permute(int[] nums) {\n List> result = new ArrayList<>();\n boolean[] used = new boolean[nums.length];\n backtrack(nums, used, new ArrayList<>(), result);\n return result;\n}\nprivate void backtrack(int[] nums, boolean[] used, List path, List> result) {\n if (path.size() == nums.length) { result.add(new ArrayList<>(path)); return; }\n for (int i = 0; i < nums.length; i++) {\n if (used[i]) continue;\n used[i] = true;\n path.add(nums[i]);\n backtrack(nums, used, path, result);\n path.remove(path.size() - 1);\n used[i] = false;\n }\n}", "solution_cpp": "vector> permute(vector& nums) {\n vector> result;\n vector used(nums.size(), false);\n vector path;\n backtrack(nums, used, path, result);\n return result;\n}\nvoid backtrack(vector& nums, vector& used, vector& path, vector>& result) {\n if (path.size() == nums.size()) { result.push_back(path); return; }\n for (int i = 0; i < nums.size(); i++) {\n if (used[i]) continue;\n used[i] = true;\n path.push_back(nums[i]);\n backtrack(nums, used, path, result);\n path.pop_back();\n used[i] = false;\n }\n}", "test_cases": ["nums=[1,2,3] -> [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]"], "key_points": ["标记已使用元素", "回溯经典模板"], "tags": ["backtracking", "medium", "Google", "Facebook"]} {"problem_id": "algo_00795", "original_id": "top-k-frequent", "title": "前K个高频元素", "category": "heap", "difficulty": "medium", "companies": ["Amazon", "Facebook"], "description": "给你一个整数数组 nums 和一个整数 k,请你返回其中出现频率前 k 高的元素。", "solution_python": "import heapq\nfrom collections import Counter\ndef topKFrequent(nums, k):\n count = Counter(nums)\n heap = []\n for num, freq in count.items():\n heapq.heappush(heap, (freq, num))\n if len(heap) > k: heapq.heappop(heap)\n return [num for freq, num in heap]", "solution_java": "public int[] topKFrequent(int[] nums, int k) {\n Map count = new HashMap<>();\n for (int n : nums) count.put(n, count.getOrDefault(n, 0) + 1);\n PriorityQueue> heap = \n new PriorityQueue<>((a, b) -> a.getValue() - b.getValue());\n for (Map.Entry e : count.entrySet()) {\n heap.offer(e);\n if (heap.size() > k) heap.poll();\n }\n int[] res = new int[k];\n for (int i = k - 1; i >= 0; i--) res[i] = heap.poll().getKey();\n return res;\n}", "solution_cpp": "vector topKFrequent(vector& nums, int k) {\n unordered_map count;\n for (int n : nums) count[n]++;\n priority_queue, vector>, greater>> heap;\n for (auto& [num, freq] : count) {\n heap.push({freq, num});\n if (heap.size() > k) heap.pop();\n }\n vector res;\n while (!heap.empty()) { res.push_back(heap.top().second); heap.pop(); }\n reverse(res.begin(), res.end());\n return res;\n}", "test_cases": ["nums=[1,1,1,2,2,3], k=2 -> [1,2]", "nums=[1], k=1 -> [1]"], "key_points": ["小顶堆保持大小k", "时间复杂度O(nlogk)"], "tags": ["heap", "medium", "Amazon", "Facebook"]} {"problem_id": "algo_00796", "original_id": "3sum", "title": "三数之和", "category": "two-pointers", "difficulty": "medium", "companies": ["Google", "Amazon"], "description": "给你一个整数数组 nums,判断是否存在三元组满足和为0,返回所有不重复的三元组。", "solution_python": "def threeSum(nums):\n nums.sort()\n result = []\n for i in range(len(nums) - 2):\n if i > 0 and nums[i] == nums[i-1]: continue\n left, right = i + 1, len(nums) - 1\n while left < right:\n total = nums[i] + nums[left] + nums[right]\n if total < 0: left += 1\n elif total > 0: right -= 1\n else:\n result.append([nums[i], nums[left], nums[right]])\n while left < right and nums[left] == nums[left+1]: left += 1\n while left < right and nums[right] == nums[right-1]: right -= 1\n left += 1; right -= 1\n return result", "solution_java": "public List> threeSum(int[] nums) {\n Arrays.sort(nums);\n List> result = new ArrayList<>();\n for (int i = 0; i < nums.length - 2; i++) {\n if (i > 0 && nums[i] == nums[i-1]) continue;\n int left = i + 1, right = nums.length - 1;\n while (left < right) {\n int total = nums[i] + nums[left] + nums[right];\n if (total < 0) left++;\n else if (total > 0) right--;\n else {\n result.add(Arrays.asList(nums[i], nums[left], nums[right]));\n while (left < right && nums[left] == nums[left+1]) left++;\n while (left < right && nums[right] == nums[right-1]) right--;\n left++; right--;\n }\n }\n }\n return result;\n}", "solution_cpp": "vector> threeSum(vector& nums) {\n sort(nums.begin(), nums.end());\n vector> result;\n for (int i = 0; i < nums.size() - 2; i++) {\n if (i > 0 && nums[i] == nums[i-1]) continue;\n int left = i + 1, right = nums.size() - 1;\n while (left < right) {\n int total = nums[i] + nums[left] + nums[right];\n if (total < 0) left++;\n else if (total > 0) right--;\n else {\n result.push_back({nums[i], nums[left], nums[right]});\n while (left < right && nums[left] == nums[left+1]) left++;\n while (left < right && nums[right] == nums[right-1]) right--;\n left++; right--;\n }\n }\n }\n return result;\n}", "test_cases": ["nums=[-1,0,1,2,-1,-4] -> [[-1,-1,2],[-1,0,1]]"], "key_points": ["排序+双指针", "去重是关键"], "tags": ["two-pointers", "medium", "Google", "Amazon"]} {"problem_id": "algo_00797", "original_id": "container-water", "title": "盛最多水的容器", "category": "two-pointers", "difficulty": "medium", "companies": ["Google", "Uber"], "description": "给定一个长度为 n 的整数数组 height,找出其中的两条线,使得它们与 x 轴共同构成的容器可以容纳最多的水。", "solution_python": "def maxArea(height):\n left, right = 0, len(height) - 1\n max_area = 0\n while left < right:\n h = min(height[left], height[right])\n max_area = max(max_area, h * (right - left))\n if height[left] < height[right]: left += 1\n else: right -= 1\n return max_area", "solution_java": "public int maxArea(int[] height) {\n int left = 0, right = height.length - 1, maxArea = 0;\n while (left < right) {\n int h = Math.min(height[left], height[right]);\n maxArea = Math.max(maxArea, h * (right - left));\n if (height[left] < height[right]) left++;\n else right--;\n }\n return maxArea;\n}", "solution_cpp": "int maxArea(vector& height) {\n int left = 0, right = height.size() - 1, maxArea = 0;\n while (left < right) {\n int h = min(height[left], height[right]);\n maxArea = max(maxArea, h * (right - left));\n if (height[left] < height[right]) left++;\n else right--;\n }\n return maxArea;\n}", "test_cases": ["height=[1,8,6,2,5,4,8,3,7] -> 49"], "key_points": ["移动短边指针", "面积=min(h1,h2)*width"], "tags": ["two-pointers", "medium", "Google", "Uber"]} {"problem_id": "algo_00798", "original_id": "min-stack", "title": "最小栈", "category": "stack", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "设计一个支持 push,pop,top 操作,并能在常数时间内检索到最小元素的栈。", "solution_python": "class MinStack:\n def __init__(self):\n self.stack = []\n self.min_stack = []\n def push(self, val):\n self.stack.append(val)\n self.min_stack.append(min(val, self.min_stack[-1] if self.min_stack else val))\n def pop(self):\n self.stack.pop(); self.min_stack.pop()\n def top(self): return self.stack[-1]\n def getMin(self): return self.min_stack[-1]", "solution_java": "class MinStack {\n Stack stack = new Stack<>();\n Stack minStack = new Stack<>();\n public void push(int val) { stack.push(val); minStack.push(Math.min(val, minStack.isEmpty() ? val : minStack.peek())); }\n public void pop() { stack.pop(); minStack.pop(); }\n public int top() { return stack.peek(); }\n public int getMin() { return minStack.peek(); }\n}", "solution_cpp": "class MinStack {\n stack st, minSt;\npublic:\n void push(int val) { st.push(val); minSt.push(min(val, minSt.empty() ? val : minSt.top())); }\n void pop() { st.pop(); minSt.pop(); }\n int top() { return st.top(); }\n int getMin() { return minSt.top(); }\n};", "test_cases": ["push(-2), push(0), push(-3) -> getMin() returns -3"], "key_points": ["辅助栈记录最小值", "O(1)时间获取最小值"], "tags": ["stack", "medium", "Google", "Microsoft"]} {"problem_id": "algo_00799", "original_id": "lru-cache", "title": "LRU缓存", "category": "design", "difficulty": "hard", "companies": ["Google", "Amazon"], "description": "设计和实现一个 LRU(最近最少使用)缓存机制。", "solution_python": "class LRUCache:\n def __init__(self, capacity):\n self.capacity = capacity\n self.cache = {}\n self.order = []\n def get(self, key):\n if key not in self.cache: return -1\n self.order.remove(key); self.order.append(key)\n return self.cache[key]\n def put(self, key, value):\n if key in self.cache:\n self.order.remove(key)\n elif len(self.cache) >= self.capacity:\n del self.cache[self.order.pop(0)]\n self.cache[key] = value; self.order.append(key)", "solution_java": "class LRUCache {\n int capacity;\n LinkedHashMap cache = new LinkedHashMap<>();\n public LRUCache(int cap) { capacity = cap; }\n public int get(int key) { return cache.containsKey(key) ? cache.remove(key) : -1; }\n public void put(int key, int val) {\n if (cache.containsKey(key)) cache.remove(key);\n else if (cache.size() >= capacity) cache.remove(cache.keySet().iterator().next());\n cache.put(key, val);\n }\n}", "solution_cpp": "class LRUCache {\n int cap;\n list> dll;\n unordered_map>::iterator> cache;\npublic:\n LRUCache(int capacity) : cap(capacity) {}\n int get(int key) {\n auto it = cache.find(key);\n if (it == cache.end()) return -1;\n dll.splice(dll.end(), dll, it->second);\n return it->second->second;\n }\n void put(int key, int value) {\n auto it = cache.find(key);\n if (it != cache.end()) dll.erase(it->second);\n else if (cache.size() >= cap) { cache.erase(dll.front().first); dll.pop_front(); }\n dll.push_back({key, value});\n cache[key] = --dll.end();\n }\n};", "test_cases": ["put(1,1), put(2,2), get(1) -> 1"], "key_points": ["HashMap + 双向链表", "O(1)时间操作"], "tags": ["design", "hard", "Google", "Amazon"]} {"problem_id": "algo_00800", "original_id": "num-islands", "title": "岛屿数量", "category": "graph", "difficulty": "medium", "companies": ["Google", "Facebook"], "description": "给你一个由 '1'(陆地)和 '0'(水)组成的二维网格,请你计算网格中岛屿的数量。岛屿总是被水包围,且只能由水平或垂直方向相邻的陆地连接形成。", "solution_python": "def numIslands(grid):\n if not grid: return 0\n rows, cols = len(grid), len(grid[0])\n count = 0\n def dfs(r, c):\n if r < 0 or r >= rows or c < 0 or c >= cols or grid[r][c] != '1': return\n grid[r][c] = '0'\n dfs(r+1, c); dfs(r-1, c); dfs(r, c+1); dfs(r, c-1)\n for r in range(rows):\n for c in range(cols):\n if grid[r][c] == '1': count += 1; dfs(r, c)\n return count", "solution_java": "public int numIslands(char[][] grid) {\n if (grid.length == 0) return 0;\n int count = 0;\n for (int i = 0; i < grid.length; i++)\n for (int j = 0; j < grid[0].length; j++)\n if (grid[i][j] == '1') { count++; dfs(grid, i, j); }\n return count;\n}\nprivate void dfs(char[][] grid, int r, int c) {\n if (r < 0 || r >= grid.length || c < 0 || c >= grid[0].length || grid[r][c] != '1') return;\n grid[r][c] = '0';\n dfs(grid, r+1, c); dfs(grid, r-1, c); dfs(grid, r, c+1); dfs(grid, r, c-1);\n}", "solution_cpp": "int numIslands(vector>& grid) {\n if (grid.empty()) return 0;\n int count = 0;\n for (int i = 0; i < grid.size(); i++)\n for (int j = 0; j < grid[0].size(); j++)\n if (grid[i][j] == '1') { count++; dfs(grid, i, j); }\n return count;\n}\nvoid dfs(vector>& grid, int r, int c) {\n if (r < 0 || r >= grid.size() || c < 0 || c >= grid[0].size() || grid[r][c] != '1') return;\n grid[r][c] = '0';\n dfs(grid, r+1, c); dfs(grid, r-1, c); dfs(grid, r, c+1); dfs(grid, r, c-1);\n}", "test_cases": ["grid=[[1,1,1,1,0],[1,1,0,1,0],[1,1,0,0,0],[0,0,0,0,0]] -> 1"], "key_points": ["DFS/BFS遍历", "访问后标记为0避免重复"], "tags": ["graph", "medium", "Google", "Facebook"]} {"problem_id": "algo_00801", "original_id": "two-sum", "title": "两数之和", "category": "array", "difficulty": "easy", "companies": ["Amazon", "Google"], "description": "给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那两个整数,并返回他们的数组下标。", "solution_python": "def twoSum(nums, target):\n hashmap = {}\n for i, num in enumerate(nums):\n complement = target - num\n if complement in hashmap:\n return [hashmap[complement], i]\n hashmap[num] = i\n return []", "solution_java": "public int[] twoSum(int[] nums, int target) {\n Map map = new HashMap<>();\n for (int i = 0; i < nums.length; i++) {\n int complement = target - nums[i];\n if (map.containsKey(complement)) return new int[]{map.get(complement), i};\n map.put(nums[i], i);\n }\n return new int[]{};\n}", "solution_cpp": "vector twoSum(vector& nums, int target) {\n unordered_map m;\n for (int i = 0; i < nums.size(); i++) {\n if (m.count(target - nums[i])) return {m[target - nums[i]], i};\n m[nums[i]] = i;\n }\n return {};\n}", "test_cases": ["nums=[2,7,11,15], target=9 -> [0,1]", "nums=[3,2,4], target=6 -> [1,2]"], "key_points": ["哈希表一次遍历", "空间换时间"], "tags": ["array", "easy", "Amazon", "Google"]} {"problem_id": "algo_00802", "original_id": "merge-sorted", "title": "合并两个有序数组", "category": "array", "difficulty": "easy", "companies": ["Microsoft", "Uber"], "description": "给你两个按非递减顺序排列的整数数组 nums1 和 nums2,另有两个整数 m 和 n,分别表示 nums1 和 nums2 中的元素数目。请你合并 nums2 到 nums1 中。", "solution_python": "def merge(nums1, m, nums2, n):\n p1, p2, p = m-1, n-1, m+n-1\n while p1 >= 0 and p2 >= 0:\n if nums1[p1] > nums2[p2]: nums1[p] = nums1[p1]; p1 -= 1\n else: nums1[p] = nums2[p2]; p2 -= 1\n p -= 1\n while p2 >= 0: nums1[p] = nums2[p2]; p2 -= 1; p -= 1", "solution_java": "public void merge(int[] nums1, int m, int[] nums2, int n) {\n int p1 = m-1, p2 = n-1, p = m+n-1;\n while (p1 >= 0 && p2 >= 0) {\n nums1[p--] = nums1[p1] > nums2[p2] ? nums1[p1--] : nums2[p2--];\n }\n while (p2 >= 0) nums1[p--] = nums2[p2--];\n}", "solution_cpp": "void merge(vector& nums1, int m, vector& nums2, int n) {\n int p1 = m-1, p2 = n-1, p = m+n-1;\n while (p1 >= 0 && p2 >= 0) nums1[p--] = nums1[p1] > nums2[p2] ? nums1[p1--] : nums2[p2--];\n while (p2 >= 0) nums1[p--] = nums2[p2--];\n}", "test_cases": ["nums1=[1,2,3], m=3, nums2=[2,5,6], n=3 -> [1,2,2,3,5,6]", "nums1=[], m=0, nums2=[1], n=1 -> [1]"], "key_points": ["从后往前合并", "三指针技巧"], "tags": ["array", "easy", "Microsoft", "Uber"]} {"problem_id": "algo_00803", "original_id": "max-subarray", "title": "最大子数组和", "category": "array", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "给你一个整数数组 nums ,请你找出一个具有最大和的连续子数组,返回其最大和。", "solution_python": "def maxSubArray(nums):\n max_sum = current = nums[0]\n for num in nums[1:]:\n current = max(num, current + num)\n max_sum = max(max_sum, current)\n return max_sum", "solution_java": "public int maxSubArray(int[] nums) {\n int maxSum = nums[0], curr = nums[0];\n for (int i = 1; i < nums.length; i++) {\n curr = Math.max(nums[i], curr + nums[i]);\n maxSum = Math.max(maxSum, curr);\n }\n return maxSum;\n}", "solution_cpp": "int maxSubArray(vector& nums) {\n int maxSum = nums[0], curr = nums[0];\n for (int i = 1; i < nums.size(); i++) {\n curr = max(nums[i], curr + nums[i]);\n maxSum = max(maxSum, curr);\n }\n return maxSum;\n}", "test_cases": ["nums=[-2,1,-3,4,-1,2,1,-5,4] -> 6", "nums=[1] -> 1"], "key_points": ["Kadane算法", "动态规划基础题"], "tags": ["array", "medium", "Google", "Microsoft"]} {"problem_id": "algo_00804", "original_id": "valid-parentheses", "title": "有效的括号", "category": "string", "difficulty": "easy", "companies": ["Google", "Uber"], "description": "给定一个只包括 '(',')','{','}','[',']' 的字符串 s,判断字符串是否有效。", "solution_python": "def isValid(s):\n stack = []\n mapping = {')': '(', ']': '[', '}': '{'}\n for c in s:\n if c in mapping:\n if not stack or stack[-1] != mapping[c]: return False\n stack.pop()\n else: stack.append(c)\n return not stack", "solution_java": "public boolean isValid(String s) {\n Stack stack = new Stack<>();\n Map map = Map.of(')', '(', ']', '[', '}', '{');\n for (char c : s.toCharArray()) {\n if (map.containsValue(c)) stack.push(c);\n else if (!stack.isEmpty() && stack.pop() != map.get(c)) return false;\n }\n return stack.isEmpty();\n}", "solution_cpp": "bool isValid(string s) {\n stack st;\n unordered_map m = {{')','('},{']','['},{'}','{'}};\n for (char c : s) {\n if (m.find(c) == m.end()) st.push(c);\n else if (st.empty() || st.top() != m[c]) return false;\n else st.pop();\n }\n return st.empty();\n}", "test_cases": ["s=\"()\" -> true", "s=\"()[]{}\" -> true", "s=\"(]\" -> false"], "key_points": ["栈匹配法", "注意空栈边界"], "tags": ["string", "easy", "Google", "Uber"]} {"problem_id": "algo_00805", "original_id": "longest-palindrome", "title": "最长回文子串", "category": "string", "difficulty": "medium", "companies": ["Google", "Amazon"], "description": "给你一个字符串 s,找到 s 中最长的回文子串。", "solution_python": "def longestPalindrome(s):\n def expand(l, r):\n while l >= 0 and r < len(s) and s[l] == s[r]: l -= 1; r += 1\n return l + 1, r - 1\n start = end = 0\n for i in range(len(s)):\n l1, r1 = expand(i, i)\n l2, r2 = expand(i, i + 1)\n if r1 - l1 > end - start: start, end = l1, r1\n if r2 - l2 > end - start: start, end = l2, r2\n return s[start:end+1]", "solution_java": "public String longestPalindrome(String s) {\n int start = 0, end = 0;\n for (int i = 0; i < s.length(); i++) {\n int len1 = expand(s, i, i), len2 = expand(s, i, i+1);\n int len = Math.max(len1, len2);\n if (len > end - start) { start = i - (len-1)/2; end = i + len/2; }\n }\n return s.substring(start, end + 1);\n}\nprivate int expand(String s, int l, int r) {\n while (l >= 0 && r < s.length() && s.charAt(l) == s.charAt(r)) { l--; r++; }\n return r - l - 1;\n}", "solution_cpp": "string longestPalindrome(string s) {\n int start = 0, end = 0;\n for (int i = 0; i < s.size(); i++) {\n int len1 = expand(s, i, i), len2 = expand(s, i, i+1);\n if (max(len1, len2) > end - start) { start = i - (max(len1,len2)-1)/2; end = i + max(len1,len2)/2; }\n }\n return s.substr(start, end - start + 1);\n}", "test_cases": ["s=\"babad\" -> bab或aba", "s=\"cbbd\" -> bb"], "key_points": ["中心扩展法", "处理奇偶长度"], "tags": ["string", "medium", "Google", "Amazon"]} {"problem_id": "algo_00806", "original_id": "reverse-list", "title": "反转链表", "category": "linkedlist", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "给你单链表的头节点 head,请你反转链表,并返回反转后的链表。", "solution_python": "def reverseList(head):\n prev = None\n curr = head\n while curr:\n nxt = curr.next\n curr.next = prev\n prev = curr\n curr = nxt\n return prev", "solution_java": "public ListNode reverseList(ListNode head) {\n ListNode prev = null, curr = head;\n while (curr != null) {\n ListNode next = curr.next;\n curr.next = prev;\n prev = curr;\n curr = next;\n }\n return prev;\n}", "solution_cpp": "ListNode* reverseList(ListNode* head) {\n ListNode* prev = nullptr, *curr = head;\n while (curr) {\n ListNode* next = curr->next;\n curr->next = prev;\n prev = curr;\n curr = next;\n }\n return prev;\n}", "test_cases": ["head=[1,2,3,4,5] -> [5,4,3,2,1]", "head=[1,2] -> [2,1]"], "key_points": ["迭代法 O(1)空间", "递归法 O(n)空间"], "tags": ["linkedlist", "medium", "Google", "Microsoft"]} {"problem_id": "algo_00807", "original_id": "middle-node", "title": "链表的中间结点", "category": "linkedlist", "difficulty": "easy", "companies": ["Amazon", "Facebook"], "description": "给你单链表的头节点 head,请你找出并返回链表的中间结点。如果有两个中间结点,则返回第二个中间结点。", "solution_python": "def middleNode(head):\n slow = fast = head\n while fast and fast.next:\n slow = slow.next\n fast = fast.next.next\n return slow", "solution_java": "public ListNode middleNode(ListNode head) {\n ListNode slow = head, fast = head;\n while (fast != null && fast.next != null) {\n slow = slow.next;\n fast = fast.next.next;\n }\n return slow;\n}", "solution_cpp": "ListNode* middleNode(ListNode* head) {\n ListNode* slow = head, *fast = head;\n while (fast && fast->next) { slow = slow->next; fast = fast->next->next; }\n return slow;\n}", "test_cases": ["head=[1,2,3,4,5] -> 3", "head=[1,2,3,4,5,6] -> 4"], "key_points": ["快慢指针", "O(n)时间O(1)空间"], "tags": ["linkedlist", "easy", "Amazon", "Facebook"]} {"problem_id": "algo_00808", "original_id": "max-depth", "title": "二叉树的最大深度", "category": "tree", "difficulty": "easy", "companies": ["Microsoft", "Apple"], "description": "给定一个二叉树 root,返回其最大深度。", "solution_python": "def maxDepth(root):\n if not root: return 0\n return max(maxDepth(root.left), maxDepth(root.right)) + 1", "solution_java": "public int maxDepth(TreeNode root) {\n if (root == null) return 0;\n return Math.max(maxDepth(root.left), maxDepth(root.right)) + 1;\n}", "solution_cpp": "int maxDepth(TreeNode* root) {\n if (!root) return 0;\n return max(maxDepth(root->left), maxDepth(root->right)) + 1;\n}", "test_cases": ["root=[3,9,20,null,null,15,7] -> 3", "root=[1,null,2] -> 2"], "key_points": ["DFS递归", "层序遍历也可"], "tags": ["tree", "easy", "Microsoft", "Apple"]} {"problem_id": "algo_00809", "original_id": "inorder-traversal", "title": "二叉树的中序遍历", "category": "tree", "difficulty": "easy", "companies": ["Google", "Microsoft"], "description": "给定一个二叉树的根节点 root,返回它的中序遍历结果。", "solution_python": "def inorderTraversal(root):\n result = []\n def dfs(node):\n if node:\n dfs(node.left)\n result.append(node.val)\n dfs(node.right)\n dfs(root)\n return result", "solution_java": "public List inorderTraversal(TreeNode root) {\n List res = new ArrayList<>();\n dfs(root, res);\n return res;\n}\nprivate void dfs(TreeNode node, List res) {\n if (node == null) return;\n dfs(node.left, res); res.add(node.val); dfs(node.right, res);\n}", "solution_cpp": "vector inorderTraversal(TreeNode* root) {\n vector res;\n dfs(root, res);\n return res;\n}\nvoid dfs(TreeNode* node, vector& res) {\n if (!node) return;\n dfs(node->left, res); res.push_back(node->val); dfs(node->right, res);\n}", "test_cases": ["root=[1,null,2,3] -> [1,3,2]", "root=[] -> []"], "key_points": ["左-根-右顺序", "递归最简洁"], "tags": ["tree", "easy", "Google", "Microsoft"]} {"problem_id": "algo_00810", "original_id": "binary-search", "title": "二分查找", "category": "binarysearch", "difficulty": "easy", "companies": ["Google", "Amazon"], "description": "给定一个 n 个元素有序的(升序)整型数组 nums 和一个目标值 target,写一个函数搜索 nums 中的 target,如果目标值存在返回下标,否则返回 -1。", "solution_python": "def search(nums, target):\n left, right = 0, len(nums) - 1\n while left <= right:\n mid = (left + right) // 2\n if nums[mid] == target: return mid\n elif nums[mid] < target: left = mid + 1\n else: right = mid - 1\n return -1", "solution_java": "public int search(int[] nums, int target) {\n int left = 0, right = nums.length - 1;\n while (left <= right) {\n int mid = left + (right - left) / 2;\n if (nums[mid] == target) return mid;\n else if (nums[mid] < target) left = mid + 1;\n else right = mid - 1;\n }\n return -1;\n}", "solution_cpp": "int search(vector& nums, int target) {\n int left = 0, right = nums.size() - 1;\n while (left <= right) {\n int mid = left + (right - left) / 2;\n if (nums[mid] == target) return mid;\n else if (nums[mid] < target) left = mid + 1;\n else right = mid - 1;\n }\n return -1;\n}", "test_cases": ["nums=[-1,0,3,5,9,12], target=9 -> 4", "nums=[-1,0,3,5,9,12], target=2 -> -1"], "key_points": ["标准模板", "注意防溢出写法"], "tags": ["binarysearch", "easy", "Google", "Amazon"]} {"problem_id": "algo_00811", "original_id": "climbing-stairs", "title": "爬楼梯", "category": "dp", "difficulty": "easy", "companies": ["Amazon", "Google"], "description": "假设你正在爬楼梯。需要 n 阶你才能到达楼顶。每次你可以爬 1 或 2 个台阶。你有多少种不同的方法可以爬到楼顶?", "solution_python": "def climbStairs(n):\n if n <= 2: return n\n a, b = 1, 2\n for _ in range(3, n+1):\n a, b = b, a + b\n return b", "solution_java": "public int climbStairs(int n) {\n if (n <= 2) return n;\n int a = 1, b = 2;\n for (int i = 3; i <= n; i++) { int temp = a + b; a = b; b = temp; }\n return b;\n}", "solution_cpp": "int climbStairs(int n) {\n if (n <= 2) return n;\n int a = 1, b = 2;\n for (int i = 3; i <= n; i++) { int temp = a + b; a = b; b = temp; }\n return b;\n}", "test_cases": ["n=2 -> 2", "n=3 -> 3", "n=5 -> 8"], "key_points": ["斐波那契数列", "滚动数组优化空间"], "tags": ["dp", "easy", "Amazon", "Google"]} {"problem_id": "algo_00812", "original_id": "coin-change", "title": "零钱兑换", "category": "dp", "difficulty": "medium", "companies": ["Google", "Amazon"], "description": "给你一个整数数组 coins 表示不同面额的硬币,以及一个整数 amount 表示总金额。计算并返回可以凑成总金额所需的最少的硬币个数。如果没有任何一种硬币组合能组成总金额,返回 -1。", "solution_python": "def coinChange(coins, amount):\n dp = [float('inf')] * (amount + 1)\n dp[0] = 0\n for coin in coins:\n for x in range(coin, amount + 1):\n dp[x] = min(dp[x], dp[x - coin] + 1)\n return dp[amount] if dp[amount] != float('inf') else -1", "solution_java": "public int coinChange(int[] coins, int amount) {\n int[] dp = new int[amount + 1];\n Arrays.fill(dp, amount + 1);\n dp[0] = 0;\n for (int coin : coins) {\n for (int x = coin; x <= amount; x++) {\n dp[x] = Math.min(dp[x], dp[x - coin] + 1);\n }\n }\n return dp[amount] > amount ? -1 : dp[amount];\n}", "solution_cpp": "int coinChange(vector& coins, int amount) {\n vector dp(amount + 1, amount + 1);\n dp[0] = 0;\n for (int coin : coins) {\n for (int x = coin; x <= amount; x++) {\n dp[x] = min(dp[x], dp[x - coin] + 1);\n }\n }\n return dp[amount] > amount ? -1 : dp[amount];\n}", "test_cases": ["coins=[1,2,5], amount=11 -> 3", "coins=[2], amount=3 -> -1"], "key_points": ["完全背包问题", "dp[x] = min(dp[x-coin]+1)"], "tags": ["dp", "medium", "Google", "Amazon"]} {"problem_id": "algo_00813", "original_id": "subsets", "title": "子集", "category": "backtracking", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "给你一个整数数组 nums ,数组中的元素 互不相同 。返回该数组所有可能的子集(幂集)。", "solution_python": "def subsets(nums):\n result = []\n def backtrack(start, path):\n result.append(path[:])\n for i in range(start, len(nums)):\n path.append(nums[i])\n backtrack(i + 1, path)\n path.pop()\n backtrack(0, [])\n return result", "solution_java": "public List> subsets(int[] nums) {\n List> result = new ArrayList<>();\n backtrack(nums, 0, new ArrayList<>(), result);\n return result;\n}\nprivate void backtrack(int[] nums, int start, List path, List> result) {\n result.add(new ArrayList<>(path));\n for (int i = start; i < nums.length; i++) {\n path.add(nums[i]);\n backtrack(nums, i + 1, path, result);\n path.remove(path.size() - 1);\n }\n}", "solution_cpp": "vector> subsets(vector& nums) {\n vector> result;\n vector path;\n backtrack(nums, 0, path, result);\n return result;\n}\nvoid backtrack(vector& nums, int start, vector& path, vector>& result) {\n result.push_back(path);\n for (int i = start; i < nums.size(); i++) {\n path.push_back(nums[i]);\n backtrack(nums, i + 1, path, result);\n path.pop_back();\n }\n}", "test_cases": ["nums=[1,2,3] -> [[],[1],[2],[1,2],[3],[1,3],[2,3],[1,2,3]]"], "key_points": ["选或不选", "DFS遍历子集树"], "tags": ["backtracking", "medium", "Google", "Microsoft"]} {"problem_id": "algo_00814", "original_id": "permutations", "title": "全排列", "category": "backtracking", "difficulty": "medium", "companies": ["Google", "Facebook"], "description": "给定一个不含重复数字的数组 nums,返回其所有可能的全排列。", "solution_python": "def permute(nums):\n result = []\n def backtrack(path, used):\n if len(path) == len(nums):\n result.append(path[:])\n return\n for i in range(len(nums)):\n if used[i]: continue\n used[i] = True\n path.append(nums[i])\n backtrack(path, used)\n path.pop()\n used[i] = False\n backtrack([], [False]*len(nums))\n return result", "solution_java": "public List> permute(int[] nums) {\n List> result = new ArrayList<>();\n boolean[] used = new boolean[nums.length];\n backtrack(nums, used, new ArrayList<>(), result);\n return result;\n}\nprivate void backtrack(int[] nums, boolean[] used, List path, List> result) {\n if (path.size() == nums.length) { result.add(new ArrayList<>(path)); return; }\n for (int i = 0; i < nums.length; i++) {\n if (used[i]) continue;\n used[i] = true;\n path.add(nums[i]);\n backtrack(nums, used, path, result);\n path.remove(path.size() - 1);\n used[i] = false;\n }\n}", "solution_cpp": "vector> permute(vector& nums) {\n vector> result;\n vector used(nums.size(), false);\n vector path;\n backtrack(nums, used, path, result);\n return result;\n}\nvoid backtrack(vector& nums, vector& used, vector& path, vector>& result) {\n if (path.size() == nums.size()) { result.push_back(path); return; }\n for (int i = 0; i < nums.size(); i++) {\n if (used[i]) continue;\n used[i] = true;\n path.push_back(nums[i]);\n backtrack(nums, used, path, result);\n path.pop_back();\n used[i] = false;\n }\n}", "test_cases": ["nums=[1,2,3] -> [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]"], "key_points": ["标记已使用元素", "回溯经典模板"], "tags": ["backtracking", "medium", "Google", "Facebook"]} {"problem_id": "algo_00815", "original_id": "top-k-frequent", "title": "前K个高频元素", "category": "heap", "difficulty": "medium", "companies": ["Amazon", "Facebook"], "description": "给你一个整数数组 nums 和一个整数 k,请你返回其中出现频率前 k 高的元素。", "solution_python": "import heapq\nfrom collections import Counter\ndef topKFrequent(nums, k):\n count = Counter(nums)\n heap = []\n for num, freq in count.items():\n heapq.heappush(heap, (freq, num))\n if len(heap) > k: heapq.heappop(heap)\n return [num for freq, num in heap]", "solution_java": "public int[] topKFrequent(int[] nums, int k) {\n Map count = new HashMap<>();\n for (int n : nums) count.put(n, count.getOrDefault(n, 0) + 1);\n PriorityQueue> heap = \n new PriorityQueue<>((a, b) -> a.getValue() - b.getValue());\n for (Map.Entry e : count.entrySet()) {\n heap.offer(e);\n if (heap.size() > k) heap.poll();\n }\n int[] res = new int[k];\n for (int i = k - 1; i >= 0; i--) res[i] = heap.poll().getKey();\n return res;\n}", "solution_cpp": "vector topKFrequent(vector& nums, int k) {\n unordered_map count;\n for (int n : nums) count[n]++;\n priority_queue, vector>, greater>> heap;\n for (auto& [num, freq] : count) {\n heap.push({freq, num});\n if (heap.size() > k) heap.pop();\n }\n vector res;\n while (!heap.empty()) { res.push_back(heap.top().second); heap.pop(); }\n reverse(res.begin(), res.end());\n return res;\n}", "test_cases": ["nums=[1,1,1,2,2,3], k=2 -> [1,2]", "nums=[1], k=1 -> [1]"], "key_points": ["小顶堆保持大小k", "时间复杂度O(nlogk)"], "tags": ["heap", "medium", "Amazon", "Facebook"]} {"problem_id": "algo_00816", "original_id": "3sum", "title": "三数之和", "category": "two-pointers", "difficulty": "medium", "companies": ["Google", "Amazon"], "description": "给你一个整数数组 nums,判断是否存在三元组满足和为0,返回所有不重复的三元组。", "solution_python": "def threeSum(nums):\n nums.sort()\n result = []\n for i in range(len(nums) - 2):\n if i > 0 and nums[i] == nums[i-1]: continue\n left, right = i + 1, len(nums) - 1\n while left < right:\n total = nums[i] + nums[left] + nums[right]\n if total < 0: left += 1\n elif total > 0: right -= 1\n else:\n result.append([nums[i], nums[left], nums[right]])\n while left < right and nums[left] == nums[left+1]: left += 1\n while left < right and nums[right] == nums[right-1]: right -= 1\n left += 1; right -= 1\n return result", "solution_java": "public List> threeSum(int[] nums) {\n Arrays.sort(nums);\n List> result = new ArrayList<>();\n for (int i = 0; i < nums.length - 2; i++) {\n if (i > 0 && nums[i] == nums[i-1]) continue;\n int left = i + 1, right = nums.length - 1;\n while (left < right) {\n int total = nums[i] + nums[left] + nums[right];\n if (total < 0) left++;\n else if (total > 0) right--;\n else {\n result.add(Arrays.asList(nums[i], nums[left], nums[right]));\n while (left < right && nums[left] == nums[left+1]) left++;\n while (left < right && nums[right] == nums[right-1]) right--;\n left++; right--;\n }\n }\n }\n return result;\n}", "solution_cpp": "vector> threeSum(vector& nums) {\n sort(nums.begin(), nums.end());\n vector> result;\n for (int i = 0; i < nums.size() - 2; i++) {\n if (i > 0 && nums[i] == nums[i-1]) continue;\n int left = i + 1, right = nums.size() - 1;\n while (left < right) {\n int total = nums[i] + nums[left] + nums[right];\n if (total < 0) left++;\n else if (total > 0) right--;\n else {\n result.push_back({nums[i], nums[left], nums[right]});\n while (left < right && nums[left] == nums[left+1]) left++;\n while (left < right && nums[right] == nums[right-1]) right--;\n left++; right--;\n }\n }\n }\n return result;\n}", "test_cases": ["nums=[-1,0,1,2,-1,-4] -> [[-1,-1,2],[-1,0,1]]"], "key_points": ["排序+双指针", "去重是关键"], "tags": ["two-pointers", "medium", "Google", "Amazon"]} {"problem_id": "algo_00817", "original_id": "container-water", "title": "盛最多水的容器", "category": "two-pointers", "difficulty": "medium", "companies": ["Google", "Uber"], "description": "给定一个长度为 n 的整数数组 height,找出其中的两条线,使得它们与 x 轴共同构成的容器可以容纳最多的水。", "solution_python": "def maxArea(height):\n left, right = 0, len(height) - 1\n max_area = 0\n while left < right:\n h = min(height[left], height[right])\n max_area = max(max_area, h * (right - left))\n if height[left] < height[right]: left += 1\n else: right -= 1\n return max_area", "solution_java": "public int maxArea(int[] height) {\n int left = 0, right = height.length - 1, maxArea = 0;\n while (left < right) {\n int h = Math.min(height[left], height[right]);\n maxArea = Math.max(maxArea, h * (right - left));\n if (height[left] < height[right]) left++;\n else right--;\n }\n return maxArea;\n}", "solution_cpp": "int maxArea(vector& height) {\n int left = 0, right = height.size() - 1, maxArea = 0;\n while (left < right) {\n int h = min(height[left], height[right]);\n maxArea = max(maxArea, h * (right - left));\n if (height[left] < height[right]) left++;\n else right--;\n }\n return maxArea;\n}", "test_cases": ["height=[1,8,6,2,5,4,8,3,7] -> 49"], "key_points": ["移动短边指针", "面积=min(h1,h2)*width"], "tags": ["two-pointers", "medium", "Google", "Uber"]} {"problem_id": "algo_00818", "original_id": "min-stack", "title": "最小栈", "category": "stack", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "设计一个支持 push,pop,top 操作,并能在常数时间内检索到最小元素的栈。", "solution_python": "class MinStack:\n def __init__(self):\n self.stack = []\n self.min_stack = []\n def push(self, val):\n self.stack.append(val)\n self.min_stack.append(min(val, self.min_stack[-1] if self.min_stack else val))\n def pop(self):\n self.stack.pop(); self.min_stack.pop()\n def top(self): return self.stack[-1]\n def getMin(self): return self.min_stack[-1]", "solution_java": "class MinStack {\n Stack stack = new Stack<>();\n Stack minStack = new Stack<>();\n public void push(int val) { stack.push(val); minStack.push(Math.min(val, minStack.isEmpty() ? val : minStack.peek())); }\n public void pop() { stack.pop(); minStack.pop(); }\n public int top() { return stack.peek(); }\n public int getMin() { return minStack.peek(); }\n}", "solution_cpp": "class MinStack {\n stack st, minSt;\npublic:\n void push(int val) { st.push(val); minSt.push(min(val, minSt.empty() ? val : minSt.top())); }\n void pop() { st.pop(); minSt.pop(); }\n int top() { return st.top(); }\n int getMin() { return minSt.top(); }\n};", "test_cases": ["push(-2), push(0), push(-3) -> getMin() returns -3"], "key_points": ["辅助栈记录最小值", "O(1)时间获取最小值"], "tags": ["stack", "medium", "Google", "Microsoft"]} {"problem_id": "algo_00819", "original_id": "lru-cache", "title": "LRU缓存", "category": "design", "difficulty": "hard", "companies": ["Google", "Amazon"], "description": "设计和实现一个 LRU(最近最少使用)缓存机制。", "solution_python": "class LRUCache:\n def __init__(self, capacity):\n self.capacity = capacity\n self.cache = {}\n self.order = []\n def get(self, key):\n if key not in self.cache: return -1\n self.order.remove(key); self.order.append(key)\n return self.cache[key]\n def put(self, key, value):\n if key in self.cache:\n self.order.remove(key)\n elif len(self.cache) >= self.capacity:\n del self.cache[self.order.pop(0)]\n self.cache[key] = value; self.order.append(key)", "solution_java": "class LRUCache {\n int capacity;\n LinkedHashMap cache = new LinkedHashMap<>();\n public LRUCache(int cap) { capacity = cap; }\n public int get(int key) { return cache.containsKey(key) ? cache.remove(key) : -1; }\n public void put(int key, int val) {\n if (cache.containsKey(key)) cache.remove(key);\n else if (cache.size() >= capacity) cache.remove(cache.keySet().iterator().next());\n cache.put(key, val);\n }\n}", "solution_cpp": "class LRUCache {\n int cap;\n list> dll;\n unordered_map>::iterator> cache;\npublic:\n LRUCache(int capacity) : cap(capacity) {}\n int get(int key) {\n auto it = cache.find(key);\n if (it == cache.end()) return -1;\n dll.splice(dll.end(), dll, it->second);\n return it->second->second;\n }\n void put(int key, int value) {\n auto it = cache.find(key);\n if (it != cache.end()) dll.erase(it->second);\n else if (cache.size() >= cap) { cache.erase(dll.front().first); dll.pop_front(); }\n dll.push_back({key, value});\n cache[key] = --dll.end();\n }\n};", "test_cases": ["put(1,1), put(2,2), get(1) -> 1"], "key_points": ["HashMap + 双向链表", "O(1)时间操作"], "tags": ["design", "hard", "Google", "Amazon"]} {"problem_id": "algo_00820", "original_id": "num-islands", "title": "岛屿数量", "category": "graph", "difficulty": "medium", "companies": ["Google", "Facebook"], "description": "给你一个由 '1'(陆地)和 '0'(水)组成的二维网格,请你计算网格中岛屿的数量。岛屿总是被水包围,且只能由水平或垂直方向相邻的陆地连接形成。", "solution_python": "def numIslands(grid):\n if not grid: return 0\n rows, cols = len(grid), len(grid[0])\n count = 0\n def dfs(r, c):\n if r < 0 or r >= rows or c < 0 or c >= cols or grid[r][c] != '1': return\n grid[r][c] = '0'\n dfs(r+1, c); dfs(r-1, c); dfs(r, c+1); dfs(r, c-1)\n for r in range(rows):\n for c in range(cols):\n if grid[r][c] == '1': count += 1; dfs(r, c)\n return count", "solution_java": "public int numIslands(char[][] grid) {\n if (grid.length == 0) return 0;\n int count = 0;\n for (int i = 0; i < grid.length; i++)\n for (int j = 0; j < grid[0].length; j++)\n if (grid[i][j] == '1') { count++; dfs(grid, i, j); }\n return count;\n}\nprivate void dfs(char[][] grid, int r, int c) {\n if (r < 0 || r >= grid.length || c < 0 || c >= grid[0].length || grid[r][c] != '1') return;\n grid[r][c] = '0';\n dfs(grid, r+1, c); dfs(grid, r-1, c); dfs(grid, r, c+1); dfs(grid, r, c-1);\n}", "solution_cpp": "int numIslands(vector>& grid) {\n if (grid.empty()) return 0;\n int count = 0;\n for (int i = 0; i < grid.size(); i++)\n for (int j = 0; j < grid[0].size(); j++)\n if (grid[i][j] == '1') { count++; dfs(grid, i, j); }\n return count;\n}\nvoid dfs(vector>& grid, int r, int c) {\n if (r < 0 || r >= grid.size() || c < 0 || c >= grid[0].size() || grid[r][c] != '1') return;\n grid[r][c] = '0';\n dfs(grid, r+1, c); dfs(grid, r-1, c); dfs(grid, r, c+1); dfs(grid, r, c-1);\n}", "test_cases": ["grid=[[1,1,1,1,0],[1,1,0,1,0],[1,1,0,0,0],[0,0,0,0,0]] -> 1"], "key_points": ["DFS/BFS遍历", "访问后标记为0避免重复"], "tags": ["graph", "medium", "Google", "Facebook"]} {"problem_id": "algo_00821", "original_id": "two-sum", "title": "两数之和", "category": "array", "difficulty": "easy", "companies": ["Amazon", "Google"], "description": "给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那两个整数,并返回他们的数组下标。", "solution_python": "def twoSum(nums, target):\n hashmap = {}\n for i, num in enumerate(nums):\n complement = target - num\n if complement in hashmap:\n return [hashmap[complement], i]\n hashmap[num] = i\n return []", "solution_java": "public int[] twoSum(int[] nums, int target) {\n Map map = new HashMap<>();\n for (int i = 0; i < nums.length; i++) {\n int complement = target - nums[i];\n if (map.containsKey(complement)) return new int[]{map.get(complement), i};\n map.put(nums[i], i);\n }\n return new int[]{};\n}", "solution_cpp": "vector twoSum(vector& nums, int target) {\n unordered_map m;\n for (int i = 0; i < nums.size(); i++) {\n if (m.count(target - nums[i])) return {m[target - nums[i]], i};\n m[nums[i]] = i;\n }\n return {};\n}", "test_cases": ["nums=[2,7,11,15], target=9 -> [0,1]", "nums=[3,2,4], target=6 -> [1,2]"], "key_points": ["哈希表一次遍历", "空间换时间"], "tags": ["array", "easy", "Amazon", "Google"]} {"problem_id": "algo_00822", "original_id": "merge-sorted", "title": "合并两个有序数组", "category": "array", "difficulty": "easy", "companies": ["Microsoft", "Uber"], "description": "给你两个按非递减顺序排列的整数数组 nums1 和 nums2,另有两个整数 m 和 n,分别表示 nums1 和 nums2 中的元素数目。请你合并 nums2 到 nums1 中。", "solution_python": "def merge(nums1, m, nums2, n):\n p1, p2, p = m-1, n-1, m+n-1\n while p1 >= 0 and p2 >= 0:\n if nums1[p1] > nums2[p2]: nums1[p] = nums1[p1]; p1 -= 1\n else: nums1[p] = nums2[p2]; p2 -= 1\n p -= 1\n while p2 >= 0: nums1[p] = nums2[p2]; p2 -= 1; p -= 1", "solution_java": "public void merge(int[] nums1, int m, int[] nums2, int n) {\n int p1 = m-1, p2 = n-1, p = m+n-1;\n while (p1 >= 0 && p2 >= 0) {\n nums1[p--] = nums1[p1] > nums2[p2] ? nums1[p1--] : nums2[p2--];\n }\n while (p2 >= 0) nums1[p--] = nums2[p2--];\n}", "solution_cpp": "void merge(vector& nums1, int m, vector& nums2, int n) {\n int p1 = m-1, p2 = n-1, p = m+n-1;\n while (p1 >= 0 && p2 >= 0) nums1[p--] = nums1[p1] > nums2[p2] ? nums1[p1--] : nums2[p2--];\n while (p2 >= 0) nums1[p--] = nums2[p2--];\n}", "test_cases": ["nums1=[1,2,3], m=3, nums2=[2,5,6], n=3 -> [1,2,2,3,5,6]", "nums1=[], m=0, nums2=[1], n=1 -> [1]"], "key_points": ["从后往前合并", "三指针技巧"], "tags": ["array", "easy", "Microsoft", "Uber"]} {"problem_id": "algo_00823", "original_id": "max-subarray", "title": "最大子数组和", "category": "array", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "给你一个整数数组 nums ,请你找出一个具有最大和的连续子数组,返回其最大和。", "solution_python": "def maxSubArray(nums):\n max_sum = current = nums[0]\n for num in nums[1:]:\n current = max(num, current + num)\n max_sum = max(max_sum, current)\n return max_sum", "solution_java": "public int maxSubArray(int[] nums) {\n int maxSum = nums[0], curr = nums[0];\n for (int i = 1; i < nums.length; i++) {\n curr = Math.max(nums[i], curr + nums[i]);\n maxSum = Math.max(maxSum, curr);\n }\n return maxSum;\n}", "solution_cpp": "int maxSubArray(vector& nums) {\n int maxSum = nums[0], curr = nums[0];\n for (int i = 1; i < nums.size(); i++) {\n curr = max(nums[i], curr + nums[i]);\n maxSum = max(maxSum, curr);\n }\n return maxSum;\n}", "test_cases": ["nums=[-2,1,-3,4,-1,2,1,-5,4] -> 6", "nums=[1] -> 1"], "key_points": ["Kadane算法", "动态规划基础题"], "tags": ["array", "medium", "Google", "Microsoft"]} {"problem_id": "algo_00824", "original_id": "valid-parentheses", "title": "有效的括号", "category": "string", "difficulty": "easy", "companies": ["Google", "Uber"], "description": "给定一个只包括 '(',')','{','}','[',']' 的字符串 s,判断字符串是否有效。", "solution_python": "def isValid(s):\n stack = []\n mapping = {')': '(', ']': '[', '}': '{'}\n for c in s:\n if c in mapping:\n if not stack or stack[-1] != mapping[c]: return False\n stack.pop()\n else: stack.append(c)\n return not stack", "solution_java": "public boolean isValid(String s) {\n Stack stack = new Stack<>();\n Map map = Map.of(')', '(', ']', '[', '}', '{');\n for (char c : s.toCharArray()) {\n if (map.containsValue(c)) stack.push(c);\n else if (!stack.isEmpty() && stack.pop() != map.get(c)) return false;\n }\n return stack.isEmpty();\n}", "solution_cpp": "bool isValid(string s) {\n stack st;\n unordered_map m = {{')','('},{']','['},{'}','{'}};\n for (char c : s) {\n if (m.find(c) == m.end()) st.push(c);\n else if (st.empty() || st.top() != m[c]) return false;\n else st.pop();\n }\n return st.empty();\n}", "test_cases": ["s=\"()\" -> true", "s=\"()[]{}\" -> true", "s=\"(]\" -> false"], "key_points": ["栈匹配法", "注意空栈边界"], "tags": ["string", "easy", "Google", "Uber"]} {"problem_id": "algo_00825", "original_id": "longest-palindrome", "title": "最长回文子串", "category": "string", "difficulty": "medium", "companies": ["Google", "Amazon"], "description": "给你一个字符串 s,找到 s 中最长的回文子串。", "solution_python": "def longestPalindrome(s):\n def expand(l, r):\n while l >= 0 and r < len(s) and s[l] == s[r]: l -= 1; r += 1\n return l + 1, r - 1\n start = end = 0\n for i in range(len(s)):\n l1, r1 = expand(i, i)\n l2, r2 = expand(i, i + 1)\n if r1 - l1 > end - start: start, end = l1, r1\n if r2 - l2 > end - start: start, end = l2, r2\n return s[start:end+1]", "solution_java": "public String longestPalindrome(String s) {\n int start = 0, end = 0;\n for (int i = 0; i < s.length(); i++) {\n int len1 = expand(s, i, i), len2 = expand(s, i, i+1);\n int len = Math.max(len1, len2);\n if (len > end - start) { start = i - (len-1)/2; end = i + len/2; }\n }\n return s.substring(start, end + 1);\n}\nprivate int expand(String s, int l, int r) {\n while (l >= 0 && r < s.length() && s.charAt(l) == s.charAt(r)) { l--; r++; }\n return r - l - 1;\n}", "solution_cpp": "string longestPalindrome(string s) {\n int start = 0, end = 0;\n for (int i = 0; i < s.size(); i++) {\n int len1 = expand(s, i, i), len2 = expand(s, i, i+1);\n if (max(len1, len2) > end - start) { start = i - (max(len1,len2)-1)/2; end = i + max(len1,len2)/2; }\n }\n return s.substr(start, end - start + 1);\n}", "test_cases": ["s=\"babad\" -> bab或aba", "s=\"cbbd\" -> bb"], "key_points": ["中心扩展法", "处理奇偶长度"], "tags": ["string", "medium", "Google", "Amazon"]} {"problem_id": "algo_00826", "original_id": "reverse-list", "title": "反转链表", "category": "linkedlist", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "给你单链表的头节点 head,请你反转链表,并返回反转后的链表。", "solution_python": "def reverseList(head):\n prev = None\n curr = head\n while curr:\n nxt = curr.next\n curr.next = prev\n prev = curr\n curr = nxt\n return prev", "solution_java": "public ListNode reverseList(ListNode head) {\n ListNode prev = null, curr = head;\n while (curr != null) {\n ListNode next = curr.next;\n curr.next = prev;\n prev = curr;\n curr = next;\n }\n return prev;\n}", "solution_cpp": "ListNode* reverseList(ListNode* head) {\n ListNode* prev = nullptr, *curr = head;\n while (curr) {\n ListNode* next = curr->next;\n curr->next = prev;\n prev = curr;\n curr = next;\n }\n return prev;\n}", "test_cases": ["head=[1,2,3,4,5] -> [5,4,3,2,1]", "head=[1,2] -> [2,1]"], "key_points": ["迭代法 O(1)空间", "递归法 O(n)空间"], "tags": ["linkedlist", "medium", "Google", "Microsoft"]} {"problem_id": "algo_00827", "original_id": "middle-node", "title": "链表的中间结点", "category": "linkedlist", "difficulty": "easy", "companies": ["Amazon", "Facebook"], "description": "给你单链表的头节点 head,请你找出并返回链表的中间结点。如果有两个中间结点,则返回第二个中间结点。", "solution_python": "def middleNode(head):\n slow = fast = head\n while fast and fast.next:\n slow = slow.next\n fast = fast.next.next\n return slow", "solution_java": "public ListNode middleNode(ListNode head) {\n ListNode slow = head, fast = head;\n while (fast != null && fast.next != null) {\n slow = slow.next;\n fast = fast.next.next;\n }\n return slow;\n}", "solution_cpp": "ListNode* middleNode(ListNode* head) {\n ListNode* slow = head, *fast = head;\n while (fast && fast->next) { slow = slow->next; fast = fast->next->next; }\n return slow;\n}", "test_cases": ["head=[1,2,3,4,5] -> 3", "head=[1,2,3,4,5,6] -> 4"], "key_points": ["快慢指针", "O(n)时间O(1)空间"], "tags": ["linkedlist", "easy", "Amazon", "Facebook"]} {"problem_id": "algo_00828", "original_id": "max-depth", "title": "二叉树的最大深度", "category": "tree", "difficulty": "easy", "companies": ["Microsoft", "Apple"], "description": "给定一个二叉树 root,返回其最大深度。", "solution_python": "def maxDepth(root):\n if not root: return 0\n return max(maxDepth(root.left), maxDepth(root.right)) + 1", "solution_java": "public int maxDepth(TreeNode root) {\n if (root == null) return 0;\n return Math.max(maxDepth(root.left), maxDepth(root.right)) + 1;\n}", "solution_cpp": "int maxDepth(TreeNode* root) {\n if (!root) return 0;\n return max(maxDepth(root->left), maxDepth(root->right)) + 1;\n}", "test_cases": ["root=[3,9,20,null,null,15,7] -> 3", "root=[1,null,2] -> 2"], "key_points": ["DFS递归", "层序遍历也可"], "tags": ["tree", "easy", "Microsoft", "Apple"]} {"problem_id": "algo_00829", "original_id": "inorder-traversal", "title": "二叉树的中序遍历", "category": "tree", "difficulty": "easy", "companies": ["Google", "Microsoft"], "description": "给定一个二叉树的根节点 root,返回它的中序遍历结果。", "solution_python": "def inorderTraversal(root):\n result = []\n def dfs(node):\n if node:\n dfs(node.left)\n result.append(node.val)\n dfs(node.right)\n dfs(root)\n return result", "solution_java": "public List inorderTraversal(TreeNode root) {\n List res = new ArrayList<>();\n dfs(root, res);\n return res;\n}\nprivate void dfs(TreeNode node, List res) {\n if (node == null) return;\n dfs(node.left, res); res.add(node.val); dfs(node.right, res);\n}", "solution_cpp": "vector inorderTraversal(TreeNode* root) {\n vector res;\n dfs(root, res);\n return res;\n}\nvoid dfs(TreeNode* node, vector& res) {\n if (!node) return;\n dfs(node->left, res); res.push_back(node->val); dfs(node->right, res);\n}", "test_cases": ["root=[1,null,2,3] -> [1,3,2]", "root=[] -> []"], "key_points": ["左-根-右顺序", "递归最简洁"], "tags": ["tree", "easy", "Google", "Microsoft"]} {"problem_id": "algo_00830", "original_id": "binary-search", "title": "二分查找", "category": "binarysearch", "difficulty": "easy", "companies": ["Google", "Amazon"], "description": "给定一个 n 个元素有序的(升序)整型数组 nums 和一个目标值 target,写一个函数搜索 nums 中的 target,如果目标值存在返回下标,否则返回 -1。", "solution_python": "def search(nums, target):\n left, right = 0, len(nums) - 1\n while left <= right:\n mid = (left + right) // 2\n if nums[mid] == target: return mid\n elif nums[mid] < target: left = mid + 1\n else: right = mid - 1\n return -1", "solution_java": "public int search(int[] nums, int target) {\n int left = 0, right = nums.length - 1;\n while (left <= right) {\n int mid = left + (right - left) / 2;\n if (nums[mid] == target) return mid;\n else if (nums[mid] < target) left = mid + 1;\n else right = mid - 1;\n }\n return -1;\n}", "solution_cpp": "int search(vector& nums, int target) {\n int left = 0, right = nums.size() - 1;\n while (left <= right) {\n int mid = left + (right - left) / 2;\n if (nums[mid] == target) return mid;\n else if (nums[mid] < target) left = mid + 1;\n else right = mid - 1;\n }\n return -1;\n}", "test_cases": ["nums=[-1,0,3,5,9,12], target=9 -> 4", "nums=[-1,0,3,5,9,12], target=2 -> -1"], "key_points": ["标准模板", "注意防溢出写法"], "tags": ["binarysearch", "easy", "Google", "Amazon"]} {"problem_id": "algo_00831", "original_id": "climbing-stairs", "title": "爬楼梯", "category": "dp", "difficulty": "easy", "companies": ["Amazon", "Google"], "description": "假设你正在爬楼梯。需要 n 阶你才能到达楼顶。每次你可以爬 1 或 2 个台阶。你有多少种不同的方法可以爬到楼顶?", "solution_python": "def climbStairs(n):\n if n <= 2: return n\n a, b = 1, 2\n for _ in range(3, n+1):\n a, b = b, a + b\n return b", "solution_java": "public int climbStairs(int n) {\n if (n <= 2) return n;\n int a = 1, b = 2;\n for (int i = 3; i <= n; i++) { int temp = a + b; a = b; b = temp; }\n return b;\n}", "solution_cpp": "int climbStairs(int n) {\n if (n <= 2) return n;\n int a = 1, b = 2;\n for (int i = 3; i <= n; i++) { int temp = a + b; a = b; b = temp; }\n return b;\n}", "test_cases": ["n=2 -> 2", "n=3 -> 3", "n=5 -> 8"], "key_points": ["斐波那契数列", "滚动数组优化空间"], "tags": ["dp", "easy", "Amazon", "Google"]} {"problem_id": "algo_00832", "original_id": "coin-change", "title": "零钱兑换", "category": "dp", "difficulty": "medium", "companies": ["Google", "Amazon"], "description": "给你一个整数数组 coins 表示不同面额的硬币,以及一个整数 amount 表示总金额。计算并返回可以凑成总金额所需的最少的硬币个数。如果没有任何一种硬币组合能组成总金额,返回 -1。", "solution_python": "def coinChange(coins, amount):\n dp = [float('inf')] * (amount + 1)\n dp[0] = 0\n for coin in coins:\n for x in range(coin, amount + 1):\n dp[x] = min(dp[x], dp[x - coin] + 1)\n return dp[amount] if dp[amount] != float('inf') else -1", "solution_java": "public int coinChange(int[] coins, int amount) {\n int[] dp = new int[amount + 1];\n Arrays.fill(dp, amount + 1);\n dp[0] = 0;\n for (int coin : coins) {\n for (int x = coin; x <= amount; x++) {\n dp[x] = Math.min(dp[x], dp[x - coin] + 1);\n }\n }\n return dp[amount] > amount ? -1 : dp[amount];\n}", "solution_cpp": "int coinChange(vector& coins, int amount) {\n vector dp(amount + 1, amount + 1);\n dp[0] = 0;\n for (int coin : coins) {\n for (int x = coin; x <= amount; x++) {\n dp[x] = min(dp[x], dp[x - coin] + 1);\n }\n }\n return dp[amount] > amount ? -1 : dp[amount];\n}", "test_cases": ["coins=[1,2,5], amount=11 -> 3", "coins=[2], amount=3 -> -1"], "key_points": ["完全背包问题", "dp[x] = min(dp[x-coin]+1)"], "tags": ["dp", "medium", "Google", "Amazon"]} {"problem_id": "algo_00833", "original_id": "subsets", "title": "子集", "category": "backtracking", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "给你一个整数数组 nums ,数组中的元素 互不相同 。返回该数组所有可能的子集(幂集)。", "solution_python": "def subsets(nums):\n result = []\n def backtrack(start, path):\n result.append(path[:])\n for i in range(start, len(nums)):\n path.append(nums[i])\n backtrack(i + 1, path)\n path.pop()\n backtrack(0, [])\n return result", "solution_java": "public List> subsets(int[] nums) {\n List> result = new ArrayList<>();\n backtrack(nums, 0, new ArrayList<>(), result);\n return result;\n}\nprivate void backtrack(int[] nums, int start, List path, List> result) {\n result.add(new ArrayList<>(path));\n for (int i = start; i < nums.length; i++) {\n path.add(nums[i]);\n backtrack(nums, i + 1, path, result);\n path.remove(path.size() - 1);\n }\n}", "solution_cpp": "vector> subsets(vector& nums) {\n vector> result;\n vector path;\n backtrack(nums, 0, path, result);\n return result;\n}\nvoid backtrack(vector& nums, int start, vector& path, vector>& result) {\n result.push_back(path);\n for (int i = start; i < nums.size(); i++) {\n path.push_back(nums[i]);\n backtrack(nums, i + 1, path, result);\n path.pop_back();\n }\n}", "test_cases": ["nums=[1,2,3] -> [[],[1],[2],[1,2],[3],[1,3],[2,3],[1,2,3]]"], "key_points": ["选或不选", "DFS遍历子集树"], "tags": ["backtracking", "medium", "Google", "Microsoft"]} {"problem_id": "algo_00834", "original_id": "permutations", "title": "全排列", "category": "backtracking", "difficulty": "medium", "companies": ["Google", "Facebook"], "description": "给定一个不含重复数字的数组 nums,返回其所有可能的全排列。", "solution_python": "def permute(nums):\n result = []\n def backtrack(path, used):\n if len(path) == len(nums):\n result.append(path[:])\n return\n for i in range(len(nums)):\n if used[i]: continue\n used[i] = True\n path.append(nums[i])\n backtrack(path, used)\n path.pop()\n used[i] = False\n backtrack([], [False]*len(nums))\n return result", "solution_java": "public List> permute(int[] nums) {\n List> result = new ArrayList<>();\n boolean[] used = new boolean[nums.length];\n backtrack(nums, used, new ArrayList<>(), result);\n return result;\n}\nprivate void backtrack(int[] nums, boolean[] used, List path, List> result) {\n if (path.size() == nums.length) { result.add(new ArrayList<>(path)); return; }\n for (int i = 0; i < nums.length; i++) {\n if (used[i]) continue;\n used[i] = true;\n path.add(nums[i]);\n backtrack(nums, used, path, result);\n path.remove(path.size() - 1);\n used[i] = false;\n }\n}", "solution_cpp": "vector> permute(vector& nums) {\n vector> result;\n vector used(nums.size(), false);\n vector path;\n backtrack(nums, used, path, result);\n return result;\n}\nvoid backtrack(vector& nums, vector& used, vector& path, vector>& result) {\n if (path.size() == nums.size()) { result.push_back(path); return; }\n for (int i = 0; i < nums.size(); i++) {\n if (used[i]) continue;\n used[i] = true;\n path.push_back(nums[i]);\n backtrack(nums, used, path, result);\n path.pop_back();\n used[i] = false;\n }\n}", "test_cases": ["nums=[1,2,3] -> [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]"], "key_points": ["标记已使用元素", "回溯经典模板"], "tags": ["backtracking", "medium", "Google", "Facebook"]} {"problem_id": "algo_00835", "original_id": "top-k-frequent", "title": "前K个高频元素", "category": "heap", "difficulty": "medium", "companies": ["Amazon", "Facebook"], "description": "给你一个整数数组 nums 和一个整数 k,请你返回其中出现频率前 k 高的元素。", "solution_python": "import heapq\nfrom collections import Counter\ndef topKFrequent(nums, k):\n count = Counter(nums)\n heap = []\n for num, freq in count.items():\n heapq.heappush(heap, (freq, num))\n if len(heap) > k: heapq.heappop(heap)\n return [num for freq, num in heap]", "solution_java": "public int[] topKFrequent(int[] nums, int k) {\n Map count = new HashMap<>();\n for (int n : nums) count.put(n, count.getOrDefault(n, 0) + 1);\n PriorityQueue> heap = \n new PriorityQueue<>((a, b) -> a.getValue() - b.getValue());\n for (Map.Entry e : count.entrySet()) {\n heap.offer(e);\n if (heap.size() > k) heap.poll();\n }\n int[] res = new int[k];\n for (int i = k - 1; i >= 0; i--) res[i] = heap.poll().getKey();\n return res;\n}", "solution_cpp": "vector topKFrequent(vector& nums, int k) {\n unordered_map count;\n for (int n : nums) count[n]++;\n priority_queue, vector>, greater>> heap;\n for (auto& [num, freq] : count) {\n heap.push({freq, num});\n if (heap.size() > k) heap.pop();\n }\n vector res;\n while (!heap.empty()) { res.push_back(heap.top().second); heap.pop(); }\n reverse(res.begin(), res.end());\n return res;\n}", "test_cases": ["nums=[1,1,1,2,2,3], k=2 -> [1,2]", "nums=[1], k=1 -> [1]"], "key_points": ["小顶堆保持大小k", "时间复杂度O(nlogk)"], "tags": ["heap", "medium", "Amazon", "Facebook"]} {"problem_id": "algo_00836", "original_id": "3sum", "title": "三数之和", "category": "two-pointers", "difficulty": "medium", "companies": ["Google", "Amazon"], "description": "给你一个整数数组 nums,判断是否存在三元组满足和为0,返回所有不重复的三元组。", "solution_python": "def threeSum(nums):\n nums.sort()\n result = []\n for i in range(len(nums) - 2):\n if i > 0 and nums[i] == nums[i-1]: continue\n left, right = i + 1, len(nums) - 1\n while left < right:\n total = nums[i] + nums[left] + nums[right]\n if total < 0: left += 1\n elif total > 0: right -= 1\n else:\n result.append([nums[i], nums[left], nums[right]])\n while left < right and nums[left] == nums[left+1]: left += 1\n while left < right and nums[right] == nums[right-1]: right -= 1\n left += 1; right -= 1\n return result", "solution_java": "public List> threeSum(int[] nums) {\n Arrays.sort(nums);\n List> result = new ArrayList<>();\n for (int i = 0; i < nums.length - 2; i++) {\n if (i > 0 && nums[i] == nums[i-1]) continue;\n int left = i + 1, right = nums.length - 1;\n while (left < right) {\n int total = nums[i] + nums[left] + nums[right];\n if (total < 0) left++;\n else if (total > 0) right--;\n else {\n result.add(Arrays.asList(nums[i], nums[left], nums[right]));\n while (left < right && nums[left] == nums[left+1]) left++;\n while (left < right && nums[right] == nums[right-1]) right--;\n left++; right--;\n }\n }\n }\n return result;\n}", "solution_cpp": "vector> threeSum(vector& nums) {\n sort(nums.begin(), nums.end());\n vector> result;\n for (int i = 0; i < nums.size() - 2; i++) {\n if (i > 0 && nums[i] == nums[i-1]) continue;\n int left = i + 1, right = nums.size() - 1;\n while (left < right) {\n int total = nums[i] + nums[left] + nums[right];\n if (total < 0) left++;\n else if (total > 0) right--;\n else {\n result.push_back({nums[i], nums[left], nums[right]});\n while (left < right && nums[left] == nums[left+1]) left++;\n while (left < right && nums[right] == nums[right-1]) right--;\n left++; right--;\n }\n }\n }\n return result;\n}", "test_cases": ["nums=[-1,0,1,2,-1,-4] -> [[-1,-1,2],[-1,0,1]]"], "key_points": ["排序+双指针", "去重是关键"], "tags": ["two-pointers", "medium", "Google", "Amazon"]} {"problem_id": "algo_00837", "original_id": "container-water", "title": "盛最多水的容器", "category": "two-pointers", "difficulty": "medium", "companies": ["Google", "Uber"], "description": "给定一个长度为 n 的整数数组 height,找出其中的两条线,使得它们与 x 轴共同构成的容器可以容纳最多的水。", "solution_python": "def maxArea(height):\n left, right = 0, len(height) - 1\n max_area = 0\n while left < right:\n h = min(height[left], height[right])\n max_area = max(max_area, h * (right - left))\n if height[left] < height[right]: left += 1\n else: right -= 1\n return max_area", "solution_java": "public int maxArea(int[] height) {\n int left = 0, right = height.length - 1, maxArea = 0;\n while (left < right) {\n int h = Math.min(height[left], height[right]);\n maxArea = Math.max(maxArea, h * (right - left));\n if (height[left] < height[right]) left++;\n else right--;\n }\n return maxArea;\n}", "solution_cpp": "int maxArea(vector& height) {\n int left = 0, right = height.size() - 1, maxArea = 0;\n while (left < right) {\n int h = min(height[left], height[right]);\n maxArea = max(maxArea, h * (right - left));\n if (height[left] < height[right]) left++;\n else right--;\n }\n return maxArea;\n}", "test_cases": ["height=[1,8,6,2,5,4,8,3,7] -> 49"], "key_points": ["移动短边指针", "面积=min(h1,h2)*width"], "tags": ["two-pointers", "medium", "Google", "Uber"]} {"problem_id": "algo_00838", "original_id": "min-stack", "title": "最小栈", "category": "stack", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "设计一个支持 push,pop,top 操作,并能在常数时间内检索到最小元素的栈。", "solution_python": "class MinStack:\n def __init__(self):\n self.stack = []\n self.min_stack = []\n def push(self, val):\n self.stack.append(val)\n self.min_stack.append(min(val, self.min_stack[-1] if self.min_stack else val))\n def pop(self):\n self.stack.pop(); self.min_stack.pop()\n def top(self): return self.stack[-1]\n def getMin(self): return self.min_stack[-1]", "solution_java": "class MinStack {\n Stack stack = new Stack<>();\n Stack minStack = new Stack<>();\n public void push(int val) { stack.push(val); minStack.push(Math.min(val, minStack.isEmpty() ? val : minStack.peek())); }\n public void pop() { stack.pop(); minStack.pop(); }\n public int top() { return stack.peek(); }\n public int getMin() { return minStack.peek(); }\n}", "solution_cpp": "class MinStack {\n stack st, minSt;\npublic:\n void push(int val) { st.push(val); minSt.push(min(val, minSt.empty() ? val : minSt.top())); }\n void pop() { st.pop(); minSt.pop(); }\n int top() { return st.top(); }\n int getMin() { return minSt.top(); }\n};", "test_cases": ["push(-2), push(0), push(-3) -> getMin() returns -3"], "key_points": ["辅助栈记录最小值", "O(1)时间获取最小值"], "tags": ["stack", "medium", "Google", "Microsoft"]} {"problem_id": "algo_00839", "original_id": "lru-cache", "title": "LRU缓存", "category": "design", "difficulty": "hard", "companies": ["Google", "Amazon"], "description": "设计和实现一个 LRU(最近最少使用)缓存机制。", "solution_python": "class LRUCache:\n def __init__(self, capacity):\n self.capacity = capacity\n self.cache = {}\n self.order = []\n def get(self, key):\n if key not in self.cache: return -1\n self.order.remove(key); self.order.append(key)\n return self.cache[key]\n def put(self, key, value):\n if key in self.cache:\n self.order.remove(key)\n elif len(self.cache) >= self.capacity:\n del self.cache[self.order.pop(0)]\n self.cache[key] = value; self.order.append(key)", "solution_java": "class LRUCache {\n int capacity;\n LinkedHashMap cache = new LinkedHashMap<>();\n public LRUCache(int cap) { capacity = cap; }\n public int get(int key) { return cache.containsKey(key) ? cache.remove(key) : -1; }\n public void put(int key, int val) {\n if (cache.containsKey(key)) cache.remove(key);\n else if (cache.size() >= capacity) cache.remove(cache.keySet().iterator().next());\n cache.put(key, val);\n }\n}", "solution_cpp": "class LRUCache {\n int cap;\n list> dll;\n unordered_map>::iterator> cache;\npublic:\n LRUCache(int capacity) : cap(capacity) {}\n int get(int key) {\n auto it = cache.find(key);\n if (it == cache.end()) return -1;\n dll.splice(dll.end(), dll, it->second);\n return it->second->second;\n }\n void put(int key, int value) {\n auto it = cache.find(key);\n if (it != cache.end()) dll.erase(it->second);\n else if (cache.size() >= cap) { cache.erase(dll.front().first); dll.pop_front(); }\n dll.push_back({key, value});\n cache[key] = --dll.end();\n }\n};", "test_cases": ["put(1,1), put(2,2), get(1) -> 1"], "key_points": ["HashMap + 双向链表", "O(1)时间操作"], "tags": ["design", "hard", "Google", "Amazon"]} {"problem_id": "algo_00840", "original_id": "num-islands", "title": "岛屿数量", "category": "graph", "difficulty": "medium", "companies": ["Google", "Facebook"], "description": "给你一个由 '1'(陆地)和 '0'(水)组成的二维网格,请你计算网格中岛屿的数量。岛屿总是被水包围,且只能由水平或垂直方向相邻的陆地连接形成。", "solution_python": "def numIslands(grid):\n if not grid: return 0\n rows, cols = len(grid), len(grid[0])\n count = 0\n def dfs(r, c):\n if r < 0 or r >= rows or c < 0 or c >= cols or grid[r][c] != '1': return\n grid[r][c] = '0'\n dfs(r+1, c); dfs(r-1, c); dfs(r, c+1); dfs(r, c-1)\n for r in range(rows):\n for c in range(cols):\n if grid[r][c] == '1': count += 1; dfs(r, c)\n return count", "solution_java": "public int numIslands(char[][] grid) {\n if (grid.length == 0) return 0;\n int count = 0;\n for (int i = 0; i < grid.length; i++)\n for (int j = 0; j < grid[0].length; j++)\n if (grid[i][j] == '1') { count++; dfs(grid, i, j); }\n return count;\n}\nprivate void dfs(char[][] grid, int r, int c) {\n if (r < 0 || r >= grid.length || c < 0 || c >= grid[0].length || grid[r][c] != '1') return;\n grid[r][c] = '0';\n dfs(grid, r+1, c); dfs(grid, r-1, c); dfs(grid, r, c+1); dfs(grid, r, c-1);\n}", "solution_cpp": "int numIslands(vector>& grid) {\n if (grid.empty()) return 0;\n int count = 0;\n for (int i = 0; i < grid.size(); i++)\n for (int j = 0; j < grid[0].size(); j++)\n if (grid[i][j] == '1') { count++; dfs(grid, i, j); }\n return count;\n}\nvoid dfs(vector>& grid, int r, int c) {\n if (r < 0 || r >= grid.size() || c < 0 || c >= grid[0].size() || grid[r][c] != '1') return;\n grid[r][c] = '0';\n dfs(grid, r+1, c); dfs(grid, r-1, c); dfs(grid, r, c+1); dfs(grid, r, c-1);\n}", "test_cases": ["grid=[[1,1,1,1,0],[1,1,0,1,0],[1,1,0,0,0],[0,0,0,0,0]] -> 1"], "key_points": ["DFS/BFS遍历", "访问后标记为0避免重复"], "tags": ["graph", "medium", "Google", "Facebook"]} {"problem_id": "algo_00841", "original_id": "two-sum", "title": "两数之和", "category": "array", "difficulty": "easy", "companies": ["Amazon", "Google"], "description": "给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那两个整数,并返回他们的数组下标。", "solution_python": "def twoSum(nums, target):\n hashmap = {}\n for i, num in enumerate(nums):\n complement = target - num\n if complement in hashmap:\n return [hashmap[complement], i]\n hashmap[num] = i\n return []", "solution_java": "public int[] twoSum(int[] nums, int target) {\n Map map = new HashMap<>();\n for (int i = 0; i < nums.length; i++) {\n int complement = target - nums[i];\n if (map.containsKey(complement)) return new int[]{map.get(complement), i};\n map.put(nums[i], i);\n }\n return new int[]{};\n}", "solution_cpp": "vector twoSum(vector& nums, int target) {\n unordered_map m;\n for (int i = 0; i < nums.size(); i++) {\n if (m.count(target - nums[i])) return {m[target - nums[i]], i};\n m[nums[i]] = i;\n }\n return {};\n}", "test_cases": ["nums=[2,7,11,15], target=9 -> [0,1]", "nums=[3,2,4], target=6 -> [1,2]"], "key_points": ["哈希表一次遍历", "空间换时间"], "tags": ["array", "easy", "Amazon", "Google"]} {"problem_id": "algo_00842", "original_id": "merge-sorted", "title": "合并两个有序数组", "category": "array", "difficulty": "easy", "companies": ["Microsoft", "Uber"], "description": "给你两个按非递减顺序排列的整数数组 nums1 和 nums2,另有两个整数 m 和 n,分别表示 nums1 和 nums2 中的元素数目。请你合并 nums2 到 nums1 中。", "solution_python": "def merge(nums1, m, nums2, n):\n p1, p2, p = m-1, n-1, m+n-1\n while p1 >= 0 and p2 >= 0:\n if nums1[p1] > nums2[p2]: nums1[p] = nums1[p1]; p1 -= 1\n else: nums1[p] = nums2[p2]; p2 -= 1\n p -= 1\n while p2 >= 0: nums1[p] = nums2[p2]; p2 -= 1; p -= 1", "solution_java": "public void merge(int[] nums1, int m, int[] nums2, int n) {\n int p1 = m-1, p2 = n-1, p = m+n-1;\n while (p1 >= 0 && p2 >= 0) {\n nums1[p--] = nums1[p1] > nums2[p2] ? nums1[p1--] : nums2[p2--];\n }\n while (p2 >= 0) nums1[p--] = nums2[p2--];\n}", "solution_cpp": "void merge(vector& nums1, int m, vector& nums2, int n) {\n int p1 = m-1, p2 = n-1, p = m+n-1;\n while (p1 >= 0 && p2 >= 0) nums1[p--] = nums1[p1] > nums2[p2] ? nums1[p1--] : nums2[p2--];\n while (p2 >= 0) nums1[p--] = nums2[p2--];\n}", "test_cases": ["nums1=[1,2,3], m=3, nums2=[2,5,6], n=3 -> [1,2,2,3,5,6]", "nums1=[], m=0, nums2=[1], n=1 -> [1]"], "key_points": ["从后往前合并", "三指针技巧"], "tags": ["array", "easy", "Microsoft", "Uber"]} {"problem_id": "algo_00843", "original_id": "max-subarray", "title": "最大子数组和", "category": "array", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "给你一个整数数组 nums ,请你找出一个具有最大和的连续子数组,返回其最大和。", "solution_python": "def maxSubArray(nums):\n max_sum = current = nums[0]\n for num in nums[1:]:\n current = max(num, current + num)\n max_sum = max(max_sum, current)\n return max_sum", "solution_java": "public int maxSubArray(int[] nums) {\n int maxSum = nums[0], curr = nums[0];\n for (int i = 1; i < nums.length; i++) {\n curr = Math.max(nums[i], curr + nums[i]);\n maxSum = Math.max(maxSum, curr);\n }\n return maxSum;\n}", "solution_cpp": "int maxSubArray(vector& nums) {\n int maxSum = nums[0], curr = nums[0];\n for (int i = 1; i < nums.size(); i++) {\n curr = max(nums[i], curr + nums[i]);\n maxSum = max(maxSum, curr);\n }\n return maxSum;\n}", "test_cases": ["nums=[-2,1,-3,4,-1,2,1,-5,4] -> 6", "nums=[1] -> 1"], "key_points": ["Kadane算法", "动态规划基础题"], "tags": ["array", "medium", "Google", "Microsoft"]} {"problem_id": "algo_00844", "original_id": "valid-parentheses", "title": "有效的括号", "category": "string", "difficulty": "easy", "companies": ["Google", "Uber"], "description": "给定一个只包括 '(',')','{','}','[',']' 的字符串 s,判断字符串是否有效。", "solution_python": "def isValid(s):\n stack = []\n mapping = {')': '(', ']': '[', '}': '{'}\n for c in s:\n if c in mapping:\n if not stack or stack[-1] != mapping[c]: return False\n stack.pop()\n else: stack.append(c)\n return not stack", "solution_java": "public boolean isValid(String s) {\n Stack stack = new Stack<>();\n Map map = Map.of(')', '(', ']', '[', '}', '{');\n for (char c : s.toCharArray()) {\n if (map.containsValue(c)) stack.push(c);\n else if (!stack.isEmpty() && stack.pop() != map.get(c)) return false;\n }\n return stack.isEmpty();\n}", "solution_cpp": "bool isValid(string s) {\n stack st;\n unordered_map m = {{')','('},{']','['},{'}','{'}};\n for (char c : s) {\n if (m.find(c) == m.end()) st.push(c);\n else if (st.empty() || st.top() != m[c]) return false;\n else st.pop();\n }\n return st.empty();\n}", "test_cases": ["s=\"()\" -> true", "s=\"()[]{}\" -> true", "s=\"(]\" -> false"], "key_points": ["栈匹配法", "注意空栈边界"], "tags": ["string", "easy", "Google", "Uber"]} {"problem_id": "algo_00845", "original_id": "longest-palindrome", "title": "最长回文子串", "category": "string", "difficulty": "medium", "companies": ["Google", "Amazon"], "description": "给你一个字符串 s,找到 s 中最长的回文子串。", "solution_python": "def longestPalindrome(s):\n def expand(l, r):\n while l >= 0 and r < len(s) and s[l] == s[r]: l -= 1; r += 1\n return l + 1, r - 1\n start = end = 0\n for i in range(len(s)):\n l1, r1 = expand(i, i)\n l2, r2 = expand(i, i + 1)\n if r1 - l1 > end - start: start, end = l1, r1\n if r2 - l2 > end - start: start, end = l2, r2\n return s[start:end+1]", "solution_java": "public String longestPalindrome(String s) {\n int start = 0, end = 0;\n for (int i = 0; i < s.length(); i++) {\n int len1 = expand(s, i, i), len2 = expand(s, i, i+1);\n int len = Math.max(len1, len2);\n if (len > end - start) { start = i - (len-1)/2; end = i + len/2; }\n }\n return s.substring(start, end + 1);\n}\nprivate int expand(String s, int l, int r) {\n while (l >= 0 && r < s.length() && s.charAt(l) == s.charAt(r)) { l--; r++; }\n return r - l - 1;\n}", "solution_cpp": "string longestPalindrome(string s) {\n int start = 0, end = 0;\n for (int i = 0; i < s.size(); i++) {\n int len1 = expand(s, i, i), len2 = expand(s, i, i+1);\n if (max(len1, len2) > end - start) { start = i - (max(len1,len2)-1)/2; end = i + max(len1,len2)/2; }\n }\n return s.substr(start, end - start + 1);\n}", "test_cases": ["s=\"babad\" -> bab或aba", "s=\"cbbd\" -> bb"], "key_points": ["中心扩展法", "处理奇偶长度"], "tags": ["string", "medium", "Google", "Amazon"]} {"problem_id": "algo_00846", "original_id": "reverse-list", "title": "反转链表", "category": "linkedlist", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "给你单链表的头节点 head,请你反转链表,并返回反转后的链表。", "solution_python": "def reverseList(head):\n prev = None\n curr = head\n while curr:\n nxt = curr.next\n curr.next = prev\n prev = curr\n curr = nxt\n return prev", "solution_java": "public ListNode reverseList(ListNode head) {\n ListNode prev = null, curr = head;\n while (curr != null) {\n ListNode next = curr.next;\n curr.next = prev;\n prev = curr;\n curr = next;\n }\n return prev;\n}", "solution_cpp": "ListNode* reverseList(ListNode* head) {\n ListNode* prev = nullptr, *curr = head;\n while (curr) {\n ListNode* next = curr->next;\n curr->next = prev;\n prev = curr;\n curr = next;\n }\n return prev;\n}", "test_cases": ["head=[1,2,3,4,5] -> [5,4,3,2,1]", "head=[1,2] -> [2,1]"], "key_points": ["迭代法 O(1)空间", "递归法 O(n)空间"], "tags": ["linkedlist", "medium", "Google", "Microsoft"]} {"problem_id": "algo_00847", "original_id": "middle-node", "title": "链表的中间结点", "category": "linkedlist", "difficulty": "easy", "companies": ["Amazon", "Facebook"], "description": "给你单链表的头节点 head,请你找出并返回链表的中间结点。如果有两个中间结点,则返回第二个中间结点。", "solution_python": "def middleNode(head):\n slow = fast = head\n while fast and fast.next:\n slow = slow.next\n fast = fast.next.next\n return slow", "solution_java": "public ListNode middleNode(ListNode head) {\n ListNode slow = head, fast = head;\n while (fast != null && fast.next != null) {\n slow = slow.next;\n fast = fast.next.next;\n }\n return slow;\n}", "solution_cpp": "ListNode* middleNode(ListNode* head) {\n ListNode* slow = head, *fast = head;\n while (fast && fast->next) { slow = slow->next; fast = fast->next->next; }\n return slow;\n}", "test_cases": ["head=[1,2,3,4,5] -> 3", "head=[1,2,3,4,5,6] -> 4"], "key_points": ["快慢指针", "O(n)时间O(1)空间"], "tags": ["linkedlist", "easy", "Amazon", "Facebook"]} {"problem_id": "algo_00848", "original_id": "max-depth", "title": "二叉树的最大深度", "category": "tree", "difficulty": "easy", "companies": ["Microsoft", "Apple"], "description": "给定一个二叉树 root,返回其最大深度。", "solution_python": "def maxDepth(root):\n if not root: return 0\n return max(maxDepth(root.left), maxDepth(root.right)) + 1", "solution_java": "public int maxDepth(TreeNode root) {\n if (root == null) return 0;\n return Math.max(maxDepth(root.left), maxDepth(root.right)) + 1;\n}", "solution_cpp": "int maxDepth(TreeNode* root) {\n if (!root) return 0;\n return max(maxDepth(root->left), maxDepth(root->right)) + 1;\n}", "test_cases": ["root=[3,9,20,null,null,15,7] -> 3", "root=[1,null,2] -> 2"], "key_points": ["DFS递归", "层序遍历也可"], "tags": ["tree", "easy", "Microsoft", "Apple"]} {"problem_id": "algo_00849", "original_id": "inorder-traversal", "title": "二叉树的中序遍历", "category": "tree", "difficulty": "easy", "companies": ["Google", "Microsoft"], "description": "给定一个二叉树的根节点 root,返回它的中序遍历结果。", "solution_python": "def inorderTraversal(root):\n result = []\n def dfs(node):\n if node:\n dfs(node.left)\n result.append(node.val)\n dfs(node.right)\n dfs(root)\n return result", "solution_java": "public List inorderTraversal(TreeNode root) {\n List res = new ArrayList<>();\n dfs(root, res);\n return res;\n}\nprivate void dfs(TreeNode node, List res) {\n if (node == null) return;\n dfs(node.left, res); res.add(node.val); dfs(node.right, res);\n}", "solution_cpp": "vector inorderTraversal(TreeNode* root) {\n vector res;\n dfs(root, res);\n return res;\n}\nvoid dfs(TreeNode* node, vector& res) {\n if (!node) return;\n dfs(node->left, res); res.push_back(node->val); dfs(node->right, res);\n}", "test_cases": ["root=[1,null,2,3] -> [1,3,2]", "root=[] -> []"], "key_points": ["左-根-右顺序", "递归最简洁"], "tags": ["tree", "easy", "Google", "Microsoft"]} {"problem_id": "algo_00850", "original_id": "binary-search", "title": "二分查找", "category": "binarysearch", "difficulty": "easy", "companies": ["Google", "Amazon"], "description": "给定一个 n 个元素有序的(升序)整型数组 nums 和一个目标值 target,写一个函数搜索 nums 中的 target,如果目标值存在返回下标,否则返回 -1。", "solution_python": "def search(nums, target):\n left, right = 0, len(nums) - 1\n while left <= right:\n mid = (left + right) // 2\n if nums[mid] == target: return mid\n elif nums[mid] < target: left = mid + 1\n else: right = mid - 1\n return -1", "solution_java": "public int search(int[] nums, int target) {\n int left = 0, right = nums.length - 1;\n while (left <= right) {\n int mid = left + (right - left) / 2;\n if (nums[mid] == target) return mid;\n else if (nums[mid] < target) left = mid + 1;\n else right = mid - 1;\n }\n return -1;\n}", "solution_cpp": "int search(vector& nums, int target) {\n int left = 0, right = nums.size() - 1;\n while (left <= right) {\n int mid = left + (right - left) / 2;\n if (nums[mid] == target) return mid;\n else if (nums[mid] < target) left = mid + 1;\n else right = mid - 1;\n }\n return -1;\n}", "test_cases": ["nums=[-1,0,3,5,9,12], target=9 -> 4", "nums=[-1,0,3,5,9,12], target=2 -> -1"], "key_points": ["标准模板", "注意防溢出写法"], "tags": ["binarysearch", "easy", "Google", "Amazon"]} {"problem_id": "algo_00851", "original_id": "climbing-stairs", "title": "爬楼梯", "category": "dp", "difficulty": "easy", "companies": ["Amazon", "Google"], "description": "假设你正在爬楼梯。需要 n 阶你才能到达楼顶。每次你可以爬 1 或 2 个台阶。你有多少种不同的方法可以爬到楼顶?", "solution_python": "def climbStairs(n):\n if n <= 2: return n\n a, b = 1, 2\n for _ in range(3, n+1):\n a, b = b, a + b\n return b", "solution_java": "public int climbStairs(int n) {\n if (n <= 2) return n;\n int a = 1, b = 2;\n for (int i = 3; i <= n; i++) { int temp = a + b; a = b; b = temp; }\n return b;\n}", "solution_cpp": "int climbStairs(int n) {\n if (n <= 2) return n;\n int a = 1, b = 2;\n for (int i = 3; i <= n; i++) { int temp = a + b; a = b; b = temp; }\n return b;\n}", "test_cases": ["n=2 -> 2", "n=3 -> 3", "n=5 -> 8"], "key_points": ["斐波那契数列", "滚动数组优化空间"], "tags": ["dp", "easy", "Amazon", "Google"]} {"problem_id": "algo_00852", "original_id": "coin-change", "title": "零钱兑换", "category": "dp", "difficulty": "medium", "companies": ["Google", "Amazon"], "description": "给你一个整数数组 coins 表示不同面额的硬币,以及一个整数 amount 表示总金额。计算并返回可以凑成总金额所需的最少的硬币个数。如果没有任何一种硬币组合能组成总金额,返回 -1。", "solution_python": "def coinChange(coins, amount):\n dp = [float('inf')] * (amount + 1)\n dp[0] = 0\n for coin in coins:\n for x in range(coin, amount + 1):\n dp[x] = min(dp[x], dp[x - coin] + 1)\n return dp[amount] if dp[amount] != float('inf') else -1", "solution_java": "public int coinChange(int[] coins, int amount) {\n int[] dp = new int[amount + 1];\n Arrays.fill(dp, amount + 1);\n dp[0] = 0;\n for (int coin : coins) {\n for (int x = coin; x <= amount; x++) {\n dp[x] = Math.min(dp[x], dp[x - coin] + 1);\n }\n }\n return dp[amount] > amount ? -1 : dp[amount];\n}", "solution_cpp": "int coinChange(vector& coins, int amount) {\n vector dp(amount + 1, amount + 1);\n dp[0] = 0;\n for (int coin : coins) {\n for (int x = coin; x <= amount; x++) {\n dp[x] = min(dp[x], dp[x - coin] + 1);\n }\n }\n return dp[amount] > amount ? -1 : dp[amount];\n}", "test_cases": ["coins=[1,2,5], amount=11 -> 3", "coins=[2], amount=3 -> -1"], "key_points": ["完全背包问题", "dp[x] = min(dp[x-coin]+1)"], "tags": ["dp", "medium", "Google", "Amazon"]} {"problem_id": "algo_00853", "original_id": "subsets", "title": "子集", "category": "backtracking", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "给你一个整数数组 nums ,数组中的元素 互不相同 。返回该数组所有可能的子集(幂集)。", "solution_python": "def subsets(nums):\n result = []\n def backtrack(start, path):\n result.append(path[:])\n for i in range(start, len(nums)):\n path.append(nums[i])\n backtrack(i + 1, path)\n path.pop()\n backtrack(0, [])\n return result", "solution_java": "public List> subsets(int[] nums) {\n List> result = new ArrayList<>();\n backtrack(nums, 0, new ArrayList<>(), result);\n return result;\n}\nprivate void backtrack(int[] nums, int start, List path, List> result) {\n result.add(new ArrayList<>(path));\n for (int i = start; i < nums.length; i++) {\n path.add(nums[i]);\n backtrack(nums, i + 1, path, result);\n path.remove(path.size() - 1);\n }\n}", "solution_cpp": "vector> subsets(vector& nums) {\n vector> result;\n vector path;\n backtrack(nums, 0, path, result);\n return result;\n}\nvoid backtrack(vector& nums, int start, vector& path, vector>& result) {\n result.push_back(path);\n for (int i = start; i < nums.size(); i++) {\n path.push_back(nums[i]);\n backtrack(nums, i + 1, path, result);\n path.pop_back();\n }\n}", "test_cases": ["nums=[1,2,3] -> [[],[1],[2],[1,2],[3],[1,3],[2,3],[1,2,3]]"], "key_points": ["选或不选", "DFS遍历子集树"], "tags": ["backtracking", "medium", "Google", "Microsoft"]} {"problem_id": "algo_00854", "original_id": "permutations", "title": "全排列", "category": "backtracking", "difficulty": "medium", "companies": ["Google", "Facebook"], "description": "给定一个不含重复数字的数组 nums,返回其所有可能的全排列。", "solution_python": "def permute(nums):\n result = []\n def backtrack(path, used):\n if len(path) == len(nums):\n result.append(path[:])\n return\n for i in range(len(nums)):\n if used[i]: continue\n used[i] = True\n path.append(nums[i])\n backtrack(path, used)\n path.pop()\n used[i] = False\n backtrack([], [False]*len(nums))\n return result", "solution_java": "public List> permute(int[] nums) {\n List> result = new ArrayList<>();\n boolean[] used = new boolean[nums.length];\n backtrack(nums, used, new ArrayList<>(), result);\n return result;\n}\nprivate void backtrack(int[] nums, boolean[] used, List path, List> result) {\n if (path.size() == nums.length) { result.add(new ArrayList<>(path)); return; }\n for (int i = 0; i < nums.length; i++) {\n if (used[i]) continue;\n used[i] = true;\n path.add(nums[i]);\n backtrack(nums, used, path, result);\n path.remove(path.size() - 1);\n used[i] = false;\n }\n}", "solution_cpp": "vector> permute(vector& nums) {\n vector> result;\n vector used(nums.size(), false);\n vector path;\n backtrack(nums, used, path, result);\n return result;\n}\nvoid backtrack(vector& nums, vector& used, vector& path, vector>& result) {\n if (path.size() == nums.size()) { result.push_back(path); return; }\n for (int i = 0; i < nums.size(); i++) {\n if (used[i]) continue;\n used[i] = true;\n path.push_back(nums[i]);\n backtrack(nums, used, path, result);\n path.pop_back();\n used[i] = false;\n }\n}", "test_cases": ["nums=[1,2,3] -> [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]"], "key_points": ["标记已使用元素", "回溯经典模板"], "tags": ["backtracking", "medium", "Google", "Facebook"]} {"problem_id": "algo_00855", "original_id": "top-k-frequent", "title": "前K个高频元素", "category": "heap", "difficulty": "medium", "companies": ["Amazon", "Facebook"], "description": "给你一个整数数组 nums 和一个整数 k,请你返回其中出现频率前 k 高的元素。", "solution_python": "import heapq\nfrom collections import Counter\ndef topKFrequent(nums, k):\n count = Counter(nums)\n heap = []\n for num, freq in count.items():\n heapq.heappush(heap, (freq, num))\n if len(heap) > k: heapq.heappop(heap)\n return [num for freq, num in heap]", "solution_java": "public int[] topKFrequent(int[] nums, int k) {\n Map count = new HashMap<>();\n for (int n : nums) count.put(n, count.getOrDefault(n, 0) + 1);\n PriorityQueue> heap = \n new PriorityQueue<>((a, b) -> a.getValue() - b.getValue());\n for (Map.Entry e : count.entrySet()) {\n heap.offer(e);\n if (heap.size() > k) heap.poll();\n }\n int[] res = new int[k];\n for (int i = k - 1; i >= 0; i--) res[i] = heap.poll().getKey();\n return res;\n}", "solution_cpp": "vector topKFrequent(vector& nums, int k) {\n unordered_map count;\n for (int n : nums) count[n]++;\n priority_queue, vector>, greater>> heap;\n for (auto& [num, freq] : count) {\n heap.push({freq, num});\n if (heap.size() > k) heap.pop();\n }\n vector res;\n while (!heap.empty()) { res.push_back(heap.top().second); heap.pop(); }\n reverse(res.begin(), res.end());\n return res;\n}", "test_cases": ["nums=[1,1,1,2,2,3], k=2 -> [1,2]", "nums=[1], k=1 -> [1]"], "key_points": ["小顶堆保持大小k", "时间复杂度O(nlogk)"], "tags": ["heap", "medium", "Amazon", "Facebook"]} {"problem_id": "algo_00856", "original_id": "3sum", "title": "三数之和", "category": "two-pointers", "difficulty": "medium", "companies": ["Google", "Amazon"], "description": "给你一个整数数组 nums,判断是否存在三元组满足和为0,返回所有不重复的三元组。", "solution_python": "def threeSum(nums):\n nums.sort()\n result = []\n for i in range(len(nums) - 2):\n if i > 0 and nums[i] == nums[i-1]: continue\n left, right = i + 1, len(nums) - 1\n while left < right:\n total = nums[i] + nums[left] + nums[right]\n if total < 0: left += 1\n elif total > 0: right -= 1\n else:\n result.append([nums[i], nums[left], nums[right]])\n while left < right and nums[left] == nums[left+1]: left += 1\n while left < right and nums[right] == nums[right-1]: right -= 1\n left += 1; right -= 1\n return result", "solution_java": "public List> threeSum(int[] nums) {\n Arrays.sort(nums);\n List> result = new ArrayList<>();\n for (int i = 0; i < nums.length - 2; i++) {\n if (i > 0 && nums[i] == nums[i-1]) continue;\n int left = i + 1, right = nums.length - 1;\n while (left < right) {\n int total = nums[i] + nums[left] + nums[right];\n if (total < 0) left++;\n else if (total > 0) right--;\n else {\n result.add(Arrays.asList(nums[i], nums[left], nums[right]));\n while (left < right && nums[left] == nums[left+1]) left++;\n while (left < right && nums[right] == nums[right-1]) right--;\n left++; right--;\n }\n }\n }\n return result;\n}", "solution_cpp": "vector> threeSum(vector& nums) {\n sort(nums.begin(), nums.end());\n vector> result;\n for (int i = 0; i < nums.size() - 2; i++) {\n if (i > 0 && nums[i] == nums[i-1]) continue;\n int left = i + 1, right = nums.size() - 1;\n while (left < right) {\n int total = nums[i] + nums[left] + nums[right];\n if (total < 0) left++;\n else if (total > 0) right--;\n else {\n result.push_back({nums[i], nums[left], nums[right]});\n while (left < right && nums[left] == nums[left+1]) left++;\n while (left < right && nums[right] == nums[right-1]) right--;\n left++; right--;\n }\n }\n }\n return result;\n}", "test_cases": ["nums=[-1,0,1,2,-1,-4] -> [[-1,-1,2],[-1,0,1]]"], "key_points": ["排序+双指针", "去重是关键"], "tags": ["two-pointers", "medium", "Google", "Amazon"]} {"problem_id": "algo_00857", "original_id": "container-water", "title": "盛最多水的容器", "category": "two-pointers", "difficulty": "medium", "companies": ["Google", "Uber"], "description": "给定一个长度为 n 的整数数组 height,找出其中的两条线,使得它们与 x 轴共同构成的容器可以容纳最多的水。", "solution_python": "def maxArea(height):\n left, right = 0, len(height) - 1\n max_area = 0\n while left < right:\n h = min(height[left], height[right])\n max_area = max(max_area, h * (right - left))\n if height[left] < height[right]: left += 1\n else: right -= 1\n return max_area", "solution_java": "public int maxArea(int[] height) {\n int left = 0, right = height.length - 1, maxArea = 0;\n while (left < right) {\n int h = Math.min(height[left], height[right]);\n maxArea = Math.max(maxArea, h * (right - left));\n if (height[left] < height[right]) left++;\n else right--;\n }\n return maxArea;\n}", "solution_cpp": "int maxArea(vector& height) {\n int left = 0, right = height.size() - 1, maxArea = 0;\n while (left < right) {\n int h = min(height[left], height[right]);\n maxArea = max(maxArea, h * (right - left));\n if (height[left] < height[right]) left++;\n else right--;\n }\n return maxArea;\n}", "test_cases": ["height=[1,8,6,2,5,4,8,3,7] -> 49"], "key_points": ["移动短边指针", "面积=min(h1,h2)*width"], "tags": ["two-pointers", "medium", "Google", "Uber"]} {"problem_id": "algo_00858", "original_id": "min-stack", "title": "最小栈", "category": "stack", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "设计一个支持 push,pop,top 操作,并能在常数时间内检索到最小元素的栈。", "solution_python": "class MinStack:\n def __init__(self):\n self.stack = []\n self.min_stack = []\n def push(self, val):\n self.stack.append(val)\n self.min_stack.append(min(val, self.min_stack[-1] if self.min_stack else val))\n def pop(self):\n self.stack.pop(); self.min_stack.pop()\n def top(self): return self.stack[-1]\n def getMin(self): return self.min_stack[-1]", "solution_java": "class MinStack {\n Stack stack = new Stack<>();\n Stack minStack = new Stack<>();\n public void push(int val) { stack.push(val); minStack.push(Math.min(val, minStack.isEmpty() ? val : minStack.peek())); }\n public void pop() { stack.pop(); minStack.pop(); }\n public int top() { return stack.peek(); }\n public int getMin() { return minStack.peek(); }\n}", "solution_cpp": "class MinStack {\n stack st, minSt;\npublic:\n void push(int val) { st.push(val); minSt.push(min(val, minSt.empty() ? val : minSt.top())); }\n void pop() { st.pop(); minSt.pop(); }\n int top() { return st.top(); }\n int getMin() { return minSt.top(); }\n};", "test_cases": ["push(-2), push(0), push(-3) -> getMin() returns -3"], "key_points": ["辅助栈记录最小值", "O(1)时间获取最小值"], "tags": ["stack", "medium", "Google", "Microsoft"]} {"problem_id": "algo_00859", "original_id": "lru-cache", "title": "LRU缓存", "category": "design", "difficulty": "hard", "companies": ["Google", "Amazon"], "description": "设计和实现一个 LRU(最近最少使用)缓存机制。", "solution_python": "class LRUCache:\n def __init__(self, capacity):\n self.capacity = capacity\n self.cache = {}\n self.order = []\n def get(self, key):\n if key not in self.cache: return -1\n self.order.remove(key); self.order.append(key)\n return self.cache[key]\n def put(self, key, value):\n if key in self.cache:\n self.order.remove(key)\n elif len(self.cache) >= self.capacity:\n del self.cache[self.order.pop(0)]\n self.cache[key] = value; self.order.append(key)", "solution_java": "class LRUCache {\n int capacity;\n LinkedHashMap cache = new LinkedHashMap<>();\n public LRUCache(int cap) { capacity = cap; }\n public int get(int key) { return cache.containsKey(key) ? cache.remove(key) : -1; }\n public void put(int key, int val) {\n if (cache.containsKey(key)) cache.remove(key);\n else if (cache.size() >= capacity) cache.remove(cache.keySet().iterator().next());\n cache.put(key, val);\n }\n}", "solution_cpp": "class LRUCache {\n int cap;\n list> dll;\n unordered_map>::iterator> cache;\npublic:\n LRUCache(int capacity) : cap(capacity) {}\n int get(int key) {\n auto it = cache.find(key);\n if (it == cache.end()) return -1;\n dll.splice(dll.end(), dll, it->second);\n return it->second->second;\n }\n void put(int key, int value) {\n auto it = cache.find(key);\n if (it != cache.end()) dll.erase(it->second);\n else if (cache.size() >= cap) { cache.erase(dll.front().first); dll.pop_front(); }\n dll.push_back({key, value});\n cache[key] = --dll.end();\n }\n};", "test_cases": ["put(1,1), put(2,2), get(1) -> 1"], "key_points": ["HashMap + 双向链表", "O(1)时间操作"], "tags": ["design", "hard", "Google", "Amazon"]} {"problem_id": "algo_00860", "original_id": "num-islands", "title": "岛屿数量", "category": "graph", "difficulty": "medium", "companies": ["Google", "Facebook"], "description": "给你一个由 '1'(陆地)和 '0'(水)组成的二维网格,请你计算网格中岛屿的数量。岛屿总是被水包围,且只能由水平或垂直方向相邻的陆地连接形成。", "solution_python": "def numIslands(grid):\n if not grid: return 0\n rows, cols = len(grid), len(grid[0])\n count = 0\n def dfs(r, c):\n if r < 0 or r >= rows or c < 0 or c >= cols or grid[r][c] != '1': return\n grid[r][c] = '0'\n dfs(r+1, c); dfs(r-1, c); dfs(r, c+1); dfs(r, c-1)\n for r in range(rows):\n for c in range(cols):\n if grid[r][c] == '1': count += 1; dfs(r, c)\n return count", "solution_java": "public int numIslands(char[][] grid) {\n if (grid.length == 0) return 0;\n int count = 0;\n for (int i = 0; i < grid.length; i++)\n for (int j = 0; j < grid[0].length; j++)\n if (grid[i][j] == '1') { count++; dfs(grid, i, j); }\n return count;\n}\nprivate void dfs(char[][] grid, int r, int c) {\n if (r < 0 || r >= grid.length || c < 0 || c >= grid[0].length || grid[r][c] != '1') return;\n grid[r][c] = '0';\n dfs(grid, r+1, c); dfs(grid, r-1, c); dfs(grid, r, c+1); dfs(grid, r, c-1);\n}", "solution_cpp": "int numIslands(vector>& grid) {\n if (grid.empty()) return 0;\n int count = 0;\n for (int i = 0; i < grid.size(); i++)\n for (int j = 0; j < grid[0].size(); j++)\n if (grid[i][j] == '1') { count++; dfs(grid, i, j); }\n return count;\n}\nvoid dfs(vector>& grid, int r, int c) {\n if (r < 0 || r >= grid.size() || c < 0 || c >= grid[0].size() || grid[r][c] != '1') return;\n grid[r][c] = '0';\n dfs(grid, r+1, c); dfs(grid, r-1, c); dfs(grid, r, c+1); dfs(grid, r, c-1);\n}", "test_cases": ["grid=[[1,1,1,1,0],[1,1,0,1,0],[1,1,0,0,0],[0,0,0,0,0]] -> 1"], "key_points": ["DFS/BFS遍历", "访问后标记为0避免重复"], "tags": ["graph", "medium", "Google", "Facebook"]} {"problem_id": "algo_00861", "original_id": "two-sum", "title": "两数之和", "category": "array", "difficulty": "easy", "companies": ["Amazon", "Google"], "description": "给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那两个整数,并返回他们的数组下标。", "solution_python": "def twoSum(nums, target):\n hashmap = {}\n for i, num in enumerate(nums):\n complement = target - num\n if complement in hashmap:\n return [hashmap[complement], i]\n hashmap[num] = i\n return []", "solution_java": "public int[] twoSum(int[] nums, int target) {\n Map map = new HashMap<>();\n for (int i = 0; i < nums.length; i++) {\n int complement = target - nums[i];\n if (map.containsKey(complement)) return new int[]{map.get(complement), i};\n map.put(nums[i], i);\n }\n return new int[]{};\n}", "solution_cpp": "vector twoSum(vector& nums, int target) {\n unordered_map m;\n for (int i = 0; i < nums.size(); i++) {\n if (m.count(target - nums[i])) return {m[target - nums[i]], i};\n m[nums[i]] = i;\n }\n return {};\n}", "test_cases": ["nums=[2,7,11,15], target=9 -> [0,1]", "nums=[3,2,4], target=6 -> [1,2]"], "key_points": ["哈希表一次遍历", "空间换时间"], "tags": ["array", "easy", "Amazon", "Google"]} {"problem_id": "algo_00862", "original_id": "merge-sorted", "title": "合并两个有序数组", "category": "array", "difficulty": "easy", "companies": ["Microsoft", "Uber"], "description": "给你两个按非递减顺序排列的整数数组 nums1 和 nums2,另有两个整数 m 和 n,分别表示 nums1 和 nums2 中的元素数目。请你合并 nums2 到 nums1 中。", "solution_python": "def merge(nums1, m, nums2, n):\n p1, p2, p = m-1, n-1, m+n-1\n while p1 >= 0 and p2 >= 0:\n if nums1[p1] > nums2[p2]: nums1[p] = nums1[p1]; p1 -= 1\n else: nums1[p] = nums2[p2]; p2 -= 1\n p -= 1\n while p2 >= 0: nums1[p] = nums2[p2]; p2 -= 1; p -= 1", "solution_java": "public void merge(int[] nums1, int m, int[] nums2, int n) {\n int p1 = m-1, p2 = n-1, p = m+n-1;\n while (p1 >= 0 && p2 >= 0) {\n nums1[p--] = nums1[p1] > nums2[p2] ? nums1[p1--] : nums2[p2--];\n }\n while (p2 >= 0) nums1[p--] = nums2[p2--];\n}", "solution_cpp": "void merge(vector& nums1, int m, vector& nums2, int n) {\n int p1 = m-1, p2 = n-1, p = m+n-1;\n while (p1 >= 0 && p2 >= 0) nums1[p--] = nums1[p1] > nums2[p2] ? nums1[p1--] : nums2[p2--];\n while (p2 >= 0) nums1[p--] = nums2[p2--];\n}", "test_cases": ["nums1=[1,2,3], m=3, nums2=[2,5,6], n=3 -> [1,2,2,3,5,6]", "nums1=[], m=0, nums2=[1], n=1 -> [1]"], "key_points": ["从后往前合并", "三指针技巧"], "tags": ["array", "easy", "Microsoft", "Uber"]} {"problem_id": "algo_00863", "original_id": "max-subarray", "title": "最大子数组和", "category": "array", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "给你一个整数数组 nums ,请你找出一个具有最大和的连续子数组,返回其最大和。", "solution_python": "def maxSubArray(nums):\n max_sum = current = nums[0]\n for num in nums[1:]:\n current = max(num, current + num)\n max_sum = max(max_sum, current)\n return max_sum", "solution_java": "public int maxSubArray(int[] nums) {\n int maxSum = nums[0], curr = nums[0];\n for (int i = 1; i < nums.length; i++) {\n curr = Math.max(nums[i], curr + nums[i]);\n maxSum = Math.max(maxSum, curr);\n }\n return maxSum;\n}", "solution_cpp": "int maxSubArray(vector& nums) {\n int maxSum = nums[0], curr = nums[0];\n for (int i = 1; i < nums.size(); i++) {\n curr = max(nums[i], curr + nums[i]);\n maxSum = max(maxSum, curr);\n }\n return maxSum;\n}", "test_cases": ["nums=[-2,1,-3,4,-1,2,1,-5,4] -> 6", "nums=[1] -> 1"], "key_points": ["Kadane算法", "动态规划基础题"], "tags": ["array", "medium", "Google", "Microsoft"]} {"problem_id": "algo_00864", "original_id": "valid-parentheses", "title": "有效的括号", "category": "string", "difficulty": "easy", "companies": ["Google", "Uber"], "description": "给定一个只包括 '(',')','{','}','[',']' 的字符串 s,判断字符串是否有效。", "solution_python": "def isValid(s):\n stack = []\n mapping = {')': '(', ']': '[', '}': '{'}\n for c in s:\n if c in mapping:\n if not stack or stack[-1] != mapping[c]: return False\n stack.pop()\n else: stack.append(c)\n return not stack", "solution_java": "public boolean isValid(String s) {\n Stack stack = new Stack<>();\n Map map = Map.of(')', '(', ']', '[', '}', '{');\n for (char c : s.toCharArray()) {\n if (map.containsValue(c)) stack.push(c);\n else if (!stack.isEmpty() && stack.pop() != map.get(c)) return false;\n }\n return stack.isEmpty();\n}", "solution_cpp": "bool isValid(string s) {\n stack st;\n unordered_map m = {{')','('},{']','['},{'}','{'}};\n for (char c : s) {\n if (m.find(c) == m.end()) st.push(c);\n else if (st.empty() || st.top() != m[c]) return false;\n else st.pop();\n }\n return st.empty();\n}", "test_cases": ["s=\"()\" -> true", "s=\"()[]{}\" -> true", "s=\"(]\" -> false"], "key_points": ["栈匹配法", "注意空栈边界"], "tags": ["string", "easy", "Google", "Uber"]} {"problem_id": "algo_00865", "original_id": "longest-palindrome", "title": "最长回文子串", "category": "string", "difficulty": "medium", "companies": ["Google", "Amazon"], "description": "给你一个字符串 s,找到 s 中最长的回文子串。", "solution_python": "def longestPalindrome(s):\n def expand(l, r):\n while l >= 0 and r < len(s) and s[l] == s[r]: l -= 1; r += 1\n return l + 1, r - 1\n start = end = 0\n for i in range(len(s)):\n l1, r1 = expand(i, i)\n l2, r2 = expand(i, i + 1)\n if r1 - l1 > end - start: start, end = l1, r1\n if r2 - l2 > end - start: start, end = l2, r2\n return s[start:end+1]", "solution_java": "public String longestPalindrome(String s) {\n int start = 0, end = 0;\n for (int i = 0; i < s.length(); i++) {\n int len1 = expand(s, i, i), len2 = expand(s, i, i+1);\n int len = Math.max(len1, len2);\n if (len > end - start) { start = i - (len-1)/2; end = i + len/2; }\n }\n return s.substring(start, end + 1);\n}\nprivate int expand(String s, int l, int r) {\n while (l >= 0 && r < s.length() && s.charAt(l) == s.charAt(r)) { l--; r++; }\n return r - l - 1;\n}", "solution_cpp": "string longestPalindrome(string s) {\n int start = 0, end = 0;\n for (int i = 0; i < s.size(); i++) {\n int len1 = expand(s, i, i), len2 = expand(s, i, i+1);\n if (max(len1, len2) > end - start) { start = i - (max(len1,len2)-1)/2; end = i + max(len1,len2)/2; }\n }\n return s.substr(start, end - start + 1);\n}", "test_cases": ["s=\"babad\" -> bab或aba", "s=\"cbbd\" -> bb"], "key_points": ["中心扩展法", "处理奇偶长度"], "tags": ["string", "medium", "Google", "Amazon"]} {"problem_id": "algo_00866", "original_id": "reverse-list", "title": "反转链表", "category": "linkedlist", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "给你单链表的头节点 head,请你反转链表,并返回反转后的链表。", "solution_python": "def reverseList(head):\n prev = None\n curr = head\n while curr:\n nxt = curr.next\n curr.next = prev\n prev = curr\n curr = nxt\n return prev", "solution_java": "public ListNode reverseList(ListNode head) {\n ListNode prev = null, curr = head;\n while (curr != null) {\n ListNode next = curr.next;\n curr.next = prev;\n prev = curr;\n curr = next;\n }\n return prev;\n}", "solution_cpp": "ListNode* reverseList(ListNode* head) {\n ListNode* prev = nullptr, *curr = head;\n while (curr) {\n ListNode* next = curr->next;\n curr->next = prev;\n prev = curr;\n curr = next;\n }\n return prev;\n}", "test_cases": ["head=[1,2,3,4,5] -> [5,4,3,2,1]", "head=[1,2] -> [2,1]"], "key_points": ["迭代法 O(1)空间", "递归法 O(n)空间"], "tags": ["linkedlist", "medium", "Google", "Microsoft"]} {"problem_id": "algo_00867", "original_id": "middle-node", "title": "链表的中间结点", "category": "linkedlist", "difficulty": "easy", "companies": ["Amazon", "Facebook"], "description": "给你单链表的头节点 head,请你找出并返回链表的中间结点。如果有两个中间结点,则返回第二个中间结点。", "solution_python": "def middleNode(head):\n slow = fast = head\n while fast and fast.next:\n slow = slow.next\n fast = fast.next.next\n return slow", "solution_java": "public ListNode middleNode(ListNode head) {\n ListNode slow = head, fast = head;\n while (fast != null && fast.next != null) {\n slow = slow.next;\n fast = fast.next.next;\n }\n return slow;\n}", "solution_cpp": "ListNode* middleNode(ListNode* head) {\n ListNode* slow = head, *fast = head;\n while (fast && fast->next) { slow = slow->next; fast = fast->next->next; }\n return slow;\n}", "test_cases": ["head=[1,2,3,4,5] -> 3", "head=[1,2,3,4,5,6] -> 4"], "key_points": ["快慢指针", "O(n)时间O(1)空间"], "tags": ["linkedlist", "easy", "Amazon", "Facebook"]} {"problem_id": "algo_00868", "original_id": "max-depth", "title": "二叉树的最大深度", "category": "tree", "difficulty": "easy", "companies": ["Microsoft", "Apple"], "description": "给定一个二叉树 root,返回其最大深度。", "solution_python": "def maxDepth(root):\n if not root: return 0\n return max(maxDepth(root.left), maxDepth(root.right)) + 1", "solution_java": "public int maxDepth(TreeNode root) {\n if (root == null) return 0;\n return Math.max(maxDepth(root.left), maxDepth(root.right)) + 1;\n}", "solution_cpp": "int maxDepth(TreeNode* root) {\n if (!root) return 0;\n return max(maxDepth(root->left), maxDepth(root->right)) + 1;\n}", "test_cases": ["root=[3,9,20,null,null,15,7] -> 3", "root=[1,null,2] -> 2"], "key_points": ["DFS递归", "层序遍历也可"], "tags": ["tree", "easy", "Microsoft", "Apple"]} {"problem_id": "algo_00869", "original_id": "inorder-traversal", "title": "二叉树的中序遍历", "category": "tree", "difficulty": "easy", "companies": ["Google", "Microsoft"], "description": "给定一个二叉树的根节点 root,返回它的中序遍历结果。", "solution_python": "def inorderTraversal(root):\n result = []\n def dfs(node):\n if node:\n dfs(node.left)\n result.append(node.val)\n dfs(node.right)\n dfs(root)\n return result", "solution_java": "public List inorderTraversal(TreeNode root) {\n List res = new ArrayList<>();\n dfs(root, res);\n return res;\n}\nprivate void dfs(TreeNode node, List res) {\n if (node == null) return;\n dfs(node.left, res); res.add(node.val); dfs(node.right, res);\n}", "solution_cpp": "vector inorderTraversal(TreeNode* root) {\n vector res;\n dfs(root, res);\n return res;\n}\nvoid dfs(TreeNode* node, vector& res) {\n if (!node) return;\n dfs(node->left, res); res.push_back(node->val); dfs(node->right, res);\n}", "test_cases": ["root=[1,null,2,3] -> [1,3,2]", "root=[] -> []"], "key_points": ["左-根-右顺序", "递归最简洁"], "tags": ["tree", "easy", "Google", "Microsoft"]} {"problem_id": "algo_00870", "original_id": "binary-search", "title": "二分查找", "category": "binarysearch", "difficulty": "easy", "companies": ["Google", "Amazon"], "description": "给定一个 n 个元素有序的(升序)整型数组 nums 和一个目标值 target,写一个函数搜索 nums 中的 target,如果目标值存在返回下标,否则返回 -1。", "solution_python": "def search(nums, target):\n left, right = 0, len(nums) - 1\n while left <= right:\n mid = (left + right) // 2\n if nums[mid] == target: return mid\n elif nums[mid] < target: left = mid + 1\n else: right = mid - 1\n return -1", "solution_java": "public int search(int[] nums, int target) {\n int left = 0, right = nums.length - 1;\n while (left <= right) {\n int mid = left + (right - left) / 2;\n if (nums[mid] == target) return mid;\n else if (nums[mid] < target) left = mid + 1;\n else right = mid - 1;\n }\n return -1;\n}", "solution_cpp": "int search(vector& nums, int target) {\n int left = 0, right = nums.size() - 1;\n while (left <= right) {\n int mid = left + (right - left) / 2;\n if (nums[mid] == target) return mid;\n else if (nums[mid] < target) left = mid + 1;\n else right = mid - 1;\n }\n return -1;\n}", "test_cases": ["nums=[-1,0,3,5,9,12], target=9 -> 4", "nums=[-1,0,3,5,9,12], target=2 -> -1"], "key_points": ["标准模板", "注意防溢出写法"], "tags": ["binarysearch", "easy", "Google", "Amazon"]} {"problem_id": "algo_00871", "original_id": "climbing-stairs", "title": "爬楼梯", "category": "dp", "difficulty": "easy", "companies": ["Amazon", "Google"], "description": "假设你正在爬楼梯。需要 n 阶你才能到达楼顶。每次你可以爬 1 或 2 个台阶。你有多少种不同的方法可以爬到楼顶?", "solution_python": "def climbStairs(n):\n if n <= 2: return n\n a, b = 1, 2\n for _ in range(3, n+1):\n a, b = b, a + b\n return b", "solution_java": "public int climbStairs(int n) {\n if (n <= 2) return n;\n int a = 1, b = 2;\n for (int i = 3; i <= n; i++) { int temp = a + b; a = b; b = temp; }\n return b;\n}", "solution_cpp": "int climbStairs(int n) {\n if (n <= 2) return n;\n int a = 1, b = 2;\n for (int i = 3; i <= n; i++) { int temp = a + b; a = b; b = temp; }\n return b;\n}", "test_cases": ["n=2 -> 2", "n=3 -> 3", "n=5 -> 8"], "key_points": ["斐波那契数列", "滚动数组优化空间"], "tags": ["dp", "easy", "Amazon", "Google"]} {"problem_id": "algo_00872", "original_id": "coin-change", "title": "零钱兑换", "category": "dp", "difficulty": "medium", "companies": ["Google", "Amazon"], "description": "给你一个整数数组 coins 表示不同面额的硬币,以及一个整数 amount 表示总金额。计算并返回可以凑成总金额所需的最少的硬币个数。如果没有任何一种硬币组合能组成总金额,返回 -1。", "solution_python": "def coinChange(coins, amount):\n dp = [float('inf')] * (amount + 1)\n dp[0] = 0\n for coin in coins:\n for x in range(coin, amount + 1):\n dp[x] = min(dp[x], dp[x - coin] + 1)\n return dp[amount] if dp[amount] != float('inf') else -1", "solution_java": "public int coinChange(int[] coins, int amount) {\n int[] dp = new int[amount + 1];\n Arrays.fill(dp, amount + 1);\n dp[0] = 0;\n for (int coin : coins) {\n for (int x = coin; x <= amount; x++) {\n dp[x] = Math.min(dp[x], dp[x - coin] + 1);\n }\n }\n return dp[amount] > amount ? -1 : dp[amount];\n}", "solution_cpp": "int coinChange(vector& coins, int amount) {\n vector dp(amount + 1, amount + 1);\n dp[0] = 0;\n for (int coin : coins) {\n for (int x = coin; x <= amount; x++) {\n dp[x] = min(dp[x], dp[x - coin] + 1);\n }\n }\n return dp[amount] > amount ? -1 : dp[amount];\n}", "test_cases": ["coins=[1,2,5], amount=11 -> 3", "coins=[2], amount=3 -> -1"], "key_points": ["完全背包问题", "dp[x] = min(dp[x-coin]+1)"], "tags": ["dp", "medium", "Google", "Amazon"]} {"problem_id": "algo_00873", "original_id": "subsets", "title": "子集", "category": "backtracking", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "给你一个整数数组 nums ,数组中的元素 互不相同 。返回该数组所有可能的子集(幂集)。", "solution_python": "def subsets(nums):\n result = []\n def backtrack(start, path):\n result.append(path[:])\n for i in range(start, len(nums)):\n path.append(nums[i])\n backtrack(i + 1, path)\n path.pop()\n backtrack(0, [])\n return result", "solution_java": "public List> subsets(int[] nums) {\n List> result = new ArrayList<>();\n backtrack(nums, 0, new ArrayList<>(), result);\n return result;\n}\nprivate void backtrack(int[] nums, int start, List path, List> result) {\n result.add(new ArrayList<>(path));\n for (int i = start; i < nums.length; i++) {\n path.add(nums[i]);\n backtrack(nums, i + 1, path, result);\n path.remove(path.size() - 1);\n }\n}", "solution_cpp": "vector> subsets(vector& nums) {\n vector> result;\n vector path;\n backtrack(nums, 0, path, result);\n return result;\n}\nvoid backtrack(vector& nums, int start, vector& path, vector>& result) {\n result.push_back(path);\n for (int i = start; i < nums.size(); i++) {\n path.push_back(nums[i]);\n backtrack(nums, i + 1, path, result);\n path.pop_back();\n }\n}", "test_cases": ["nums=[1,2,3] -> [[],[1],[2],[1,2],[3],[1,3],[2,3],[1,2,3]]"], "key_points": ["选或不选", "DFS遍历子集树"], "tags": ["backtracking", "medium", "Google", "Microsoft"]} {"problem_id": "algo_00874", "original_id": "permutations", "title": "全排列", "category": "backtracking", "difficulty": "medium", "companies": ["Google", "Facebook"], "description": "给定一个不含重复数字的数组 nums,返回其所有可能的全排列。", "solution_python": "def permute(nums):\n result = []\n def backtrack(path, used):\n if len(path) == len(nums):\n result.append(path[:])\n return\n for i in range(len(nums)):\n if used[i]: continue\n used[i] = True\n path.append(nums[i])\n backtrack(path, used)\n path.pop()\n used[i] = False\n backtrack([], [False]*len(nums))\n return result", "solution_java": "public List> permute(int[] nums) {\n List> result = new ArrayList<>();\n boolean[] used = new boolean[nums.length];\n backtrack(nums, used, new ArrayList<>(), result);\n return result;\n}\nprivate void backtrack(int[] nums, boolean[] used, List path, List> result) {\n if (path.size() == nums.length) { result.add(new ArrayList<>(path)); return; }\n for (int i = 0; i < nums.length; i++) {\n if (used[i]) continue;\n used[i] = true;\n path.add(nums[i]);\n backtrack(nums, used, path, result);\n path.remove(path.size() - 1);\n used[i] = false;\n }\n}", "solution_cpp": "vector> permute(vector& nums) {\n vector> result;\n vector used(nums.size(), false);\n vector path;\n backtrack(nums, used, path, result);\n return result;\n}\nvoid backtrack(vector& nums, vector& used, vector& path, vector>& result) {\n if (path.size() == nums.size()) { result.push_back(path); return; }\n for (int i = 0; i < nums.size(); i++) {\n if (used[i]) continue;\n used[i] = true;\n path.push_back(nums[i]);\n backtrack(nums, used, path, result);\n path.pop_back();\n used[i] = false;\n }\n}", "test_cases": ["nums=[1,2,3] -> [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]"], "key_points": ["标记已使用元素", "回溯经典模板"], "tags": ["backtracking", "medium", "Google", "Facebook"]} {"problem_id": "algo_00875", "original_id": "top-k-frequent", "title": "前K个高频元素", "category": "heap", "difficulty": "medium", "companies": ["Amazon", "Facebook"], "description": "给你一个整数数组 nums 和一个整数 k,请你返回其中出现频率前 k 高的元素。", "solution_python": "import heapq\nfrom collections import Counter\ndef topKFrequent(nums, k):\n count = Counter(nums)\n heap = []\n for num, freq in count.items():\n heapq.heappush(heap, (freq, num))\n if len(heap) > k: heapq.heappop(heap)\n return [num for freq, num in heap]", "solution_java": "public int[] topKFrequent(int[] nums, int k) {\n Map count = new HashMap<>();\n for (int n : nums) count.put(n, count.getOrDefault(n, 0) + 1);\n PriorityQueue> heap = \n new PriorityQueue<>((a, b) -> a.getValue() - b.getValue());\n for (Map.Entry e : count.entrySet()) {\n heap.offer(e);\n if (heap.size() > k) heap.poll();\n }\n int[] res = new int[k];\n for (int i = k - 1; i >= 0; i--) res[i] = heap.poll().getKey();\n return res;\n}", "solution_cpp": "vector topKFrequent(vector& nums, int k) {\n unordered_map count;\n for (int n : nums) count[n]++;\n priority_queue, vector>, greater>> heap;\n for (auto& [num, freq] : count) {\n heap.push({freq, num});\n if (heap.size() > k) heap.pop();\n }\n vector res;\n while (!heap.empty()) { res.push_back(heap.top().second); heap.pop(); }\n reverse(res.begin(), res.end());\n return res;\n}", "test_cases": ["nums=[1,1,1,2,2,3], k=2 -> [1,2]", "nums=[1], k=1 -> [1]"], "key_points": ["小顶堆保持大小k", "时间复杂度O(nlogk)"], "tags": ["heap", "medium", "Amazon", "Facebook"]} {"problem_id": "algo_00876", "original_id": "3sum", "title": "三数之和", "category": "two-pointers", "difficulty": "medium", "companies": ["Google", "Amazon"], "description": "给你一个整数数组 nums,判断是否存在三元组满足和为0,返回所有不重复的三元组。", "solution_python": "def threeSum(nums):\n nums.sort()\n result = []\n for i in range(len(nums) - 2):\n if i > 0 and nums[i] == nums[i-1]: continue\n left, right = i + 1, len(nums) - 1\n while left < right:\n total = nums[i] + nums[left] + nums[right]\n if total < 0: left += 1\n elif total > 0: right -= 1\n else:\n result.append([nums[i], nums[left], nums[right]])\n while left < right and nums[left] == nums[left+1]: left += 1\n while left < right and nums[right] == nums[right-1]: right -= 1\n left += 1; right -= 1\n return result", "solution_java": "public List> threeSum(int[] nums) {\n Arrays.sort(nums);\n List> result = new ArrayList<>();\n for (int i = 0; i < nums.length - 2; i++) {\n if (i > 0 && nums[i] == nums[i-1]) continue;\n int left = i + 1, right = nums.length - 1;\n while (left < right) {\n int total = nums[i] + nums[left] + nums[right];\n if (total < 0) left++;\n else if (total > 0) right--;\n else {\n result.add(Arrays.asList(nums[i], nums[left], nums[right]));\n while (left < right && nums[left] == nums[left+1]) left++;\n while (left < right && nums[right] == nums[right-1]) right--;\n left++; right--;\n }\n }\n }\n return result;\n}", "solution_cpp": "vector> threeSum(vector& nums) {\n sort(nums.begin(), nums.end());\n vector> result;\n for (int i = 0; i < nums.size() - 2; i++) {\n if (i > 0 && nums[i] == nums[i-1]) continue;\n int left = i + 1, right = nums.size() - 1;\n while (left < right) {\n int total = nums[i] + nums[left] + nums[right];\n if (total < 0) left++;\n else if (total > 0) right--;\n else {\n result.push_back({nums[i], nums[left], nums[right]});\n while (left < right && nums[left] == nums[left+1]) left++;\n while (left < right && nums[right] == nums[right-1]) right--;\n left++; right--;\n }\n }\n }\n return result;\n}", "test_cases": ["nums=[-1,0,1,2,-1,-4] -> [[-1,-1,2],[-1,0,1]]"], "key_points": ["排序+双指针", "去重是关键"], "tags": ["two-pointers", "medium", "Google", "Amazon"]} {"problem_id": "algo_00877", "original_id": "container-water", "title": "盛最多水的容器", "category": "two-pointers", "difficulty": "medium", "companies": ["Google", "Uber"], "description": "给定一个长度为 n 的整数数组 height,找出其中的两条线,使得它们与 x 轴共同构成的容器可以容纳最多的水。", "solution_python": "def maxArea(height):\n left, right = 0, len(height) - 1\n max_area = 0\n while left < right:\n h = min(height[left], height[right])\n max_area = max(max_area, h * (right - left))\n if height[left] < height[right]: left += 1\n else: right -= 1\n return max_area", "solution_java": "public int maxArea(int[] height) {\n int left = 0, right = height.length - 1, maxArea = 0;\n while (left < right) {\n int h = Math.min(height[left], height[right]);\n maxArea = Math.max(maxArea, h * (right - left));\n if (height[left] < height[right]) left++;\n else right--;\n }\n return maxArea;\n}", "solution_cpp": "int maxArea(vector& height) {\n int left = 0, right = height.size() - 1, maxArea = 0;\n while (left < right) {\n int h = min(height[left], height[right]);\n maxArea = max(maxArea, h * (right - left));\n if (height[left] < height[right]) left++;\n else right--;\n }\n return maxArea;\n}", "test_cases": ["height=[1,8,6,2,5,4,8,3,7] -> 49"], "key_points": ["移动短边指针", "面积=min(h1,h2)*width"], "tags": ["two-pointers", "medium", "Google", "Uber"]} {"problem_id": "algo_00878", "original_id": "min-stack", "title": "最小栈", "category": "stack", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "设计一个支持 push,pop,top 操作,并能在常数时间内检索到最小元素的栈。", "solution_python": "class MinStack:\n def __init__(self):\n self.stack = []\n self.min_stack = []\n def push(self, val):\n self.stack.append(val)\n self.min_stack.append(min(val, self.min_stack[-1] if self.min_stack else val))\n def pop(self):\n self.stack.pop(); self.min_stack.pop()\n def top(self): return self.stack[-1]\n def getMin(self): return self.min_stack[-1]", "solution_java": "class MinStack {\n Stack stack = new Stack<>();\n Stack minStack = new Stack<>();\n public void push(int val) { stack.push(val); minStack.push(Math.min(val, minStack.isEmpty() ? val : minStack.peek())); }\n public void pop() { stack.pop(); minStack.pop(); }\n public int top() { return stack.peek(); }\n public int getMin() { return minStack.peek(); }\n}", "solution_cpp": "class MinStack {\n stack st, minSt;\npublic:\n void push(int val) { st.push(val); minSt.push(min(val, minSt.empty() ? val : minSt.top())); }\n void pop() { st.pop(); minSt.pop(); }\n int top() { return st.top(); }\n int getMin() { return minSt.top(); }\n};", "test_cases": ["push(-2), push(0), push(-3) -> getMin() returns -3"], "key_points": ["辅助栈记录最小值", "O(1)时间获取最小值"], "tags": ["stack", "medium", "Google", "Microsoft"]} {"problem_id": "algo_00879", "original_id": "lru-cache", "title": "LRU缓存", "category": "design", "difficulty": "hard", "companies": ["Google", "Amazon"], "description": "设计和实现一个 LRU(最近最少使用)缓存机制。", "solution_python": "class LRUCache:\n def __init__(self, capacity):\n self.capacity = capacity\n self.cache = {}\n self.order = []\n def get(self, key):\n if key not in self.cache: return -1\n self.order.remove(key); self.order.append(key)\n return self.cache[key]\n def put(self, key, value):\n if key in self.cache:\n self.order.remove(key)\n elif len(self.cache) >= self.capacity:\n del self.cache[self.order.pop(0)]\n self.cache[key] = value; self.order.append(key)", "solution_java": "class LRUCache {\n int capacity;\n LinkedHashMap cache = new LinkedHashMap<>();\n public LRUCache(int cap) { capacity = cap; }\n public int get(int key) { return cache.containsKey(key) ? cache.remove(key) : -1; }\n public void put(int key, int val) {\n if (cache.containsKey(key)) cache.remove(key);\n else if (cache.size() >= capacity) cache.remove(cache.keySet().iterator().next());\n cache.put(key, val);\n }\n}", "solution_cpp": "class LRUCache {\n int cap;\n list> dll;\n unordered_map>::iterator> cache;\npublic:\n LRUCache(int capacity) : cap(capacity) {}\n int get(int key) {\n auto it = cache.find(key);\n if (it == cache.end()) return -1;\n dll.splice(dll.end(), dll, it->second);\n return it->second->second;\n }\n void put(int key, int value) {\n auto it = cache.find(key);\n if (it != cache.end()) dll.erase(it->second);\n else if (cache.size() >= cap) { cache.erase(dll.front().first); dll.pop_front(); }\n dll.push_back({key, value});\n cache[key] = --dll.end();\n }\n};", "test_cases": ["put(1,1), put(2,2), get(1) -> 1"], "key_points": ["HashMap + 双向链表", "O(1)时间操作"], "tags": ["design", "hard", "Google", "Amazon"]} {"problem_id": "algo_00880", "original_id": "num-islands", "title": "岛屿数量", "category": "graph", "difficulty": "medium", "companies": ["Google", "Facebook"], "description": "给你一个由 '1'(陆地)和 '0'(水)组成的二维网格,请你计算网格中岛屿的数量。岛屿总是被水包围,且只能由水平或垂直方向相邻的陆地连接形成。", "solution_python": "def numIslands(grid):\n if not grid: return 0\n rows, cols = len(grid), len(grid[0])\n count = 0\n def dfs(r, c):\n if r < 0 or r >= rows or c < 0 or c >= cols or grid[r][c] != '1': return\n grid[r][c] = '0'\n dfs(r+1, c); dfs(r-1, c); dfs(r, c+1); dfs(r, c-1)\n for r in range(rows):\n for c in range(cols):\n if grid[r][c] == '1': count += 1; dfs(r, c)\n return count", "solution_java": "public int numIslands(char[][] grid) {\n if (grid.length == 0) return 0;\n int count = 0;\n for (int i = 0; i < grid.length; i++)\n for (int j = 0; j < grid[0].length; j++)\n if (grid[i][j] == '1') { count++; dfs(grid, i, j); }\n return count;\n}\nprivate void dfs(char[][] grid, int r, int c) {\n if (r < 0 || r >= grid.length || c < 0 || c >= grid[0].length || grid[r][c] != '1') return;\n grid[r][c] = '0';\n dfs(grid, r+1, c); dfs(grid, r-1, c); dfs(grid, r, c+1); dfs(grid, r, c-1);\n}", "solution_cpp": "int numIslands(vector>& grid) {\n if (grid.empty()) return 0;\n int count = 0;\n for (int i = 0; i < grid.size(); i++)\n for (int j = 0; j < grid[0].size(); j++)\n if (grid[i][j] == '1') { count++; dfs(grid, i, j); }\n return count;\n}\nvoid dfs(vector>& grid, int r, int c) {\n if (r < 0 || r >= grid.size() || c < 0 || c >= grid[0].size() || grid[r][c] != '1') return;\n grid[r][c] = '0';\n dfs(grid, r+1, c); dfs(grid, r-1, c); dfs(grid, r, c+1); dfs(grid, r, c-1);\n}", "test_cases": ["grid=[[1,1,1,1,0],[1,1,0,1,0],[1,1,0,0,0],[0,0,0,0,0]] -> 1"], "key_points": ["DFS/BFS遍历", "访问后标记为0避免重复"], "tags": ["graph", "medium", "Google", "Facebook"]} {"problem_id": "algo_00881", "original_id": "two-sum", "title": "两数之和", "category": "array", "difficulty": "easy", "companies": ["Amazon", "Google"], "description": "给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那两个整数,并返回他们的数组下标。", "solution_python": "def twoSum(nums, target):\n hashmap = {}\n for i, num in enumerate(nums):\n complement = target - num\n if complement in hashmap:\n return [hashmap[complement], i]\n hashmap[num] = i\n return []", "solution_java": "public int[] twoSum(int[] nums, int target) {\n Map map = new HashMap<>();\n for (int i = 0; i < nums.length; i++) {\n int complement = target - nums[i];\n if (map.containsKey(complement)) return new int[]{map.get(complement), i};\n map.put(nums[i], i);\n }\n return new int[]{};\n}", "solution_cpp": "vector twoSum(vector& nums, int target) {\n unordered_map m;\n for (int i = 0; i < nums.size(); i++) {\n if (m.count(target - nums[i])) return {m[target - nums[i]], i};\n m[nums[i]] = i;\n }\n return {};\n}", "test_cases": ["nums=[2,7,11,15], target=9 -> [0,1]", "nums=[3,2,4], target=6 -> [1,2]"], "key_points": ["哈希表一次遍历", "空间换时间"], "tags": ["array", "easy", "Amazon", "Google"]} {"problem_id": "algo_00882", "original_id": "merge-sorted", "title": "合并两个有序数组", "category": "array", "difficulty": "easy", "companies": ["Microsoft", "Uber"], "description": "给你两个按非递减顺序排列的整数数组 nums1 和 nums2,另有两个整数 m 和 n,分别表示 nums1 和 nums2 中的元素数目。请你合并 nums2 到 nums1 中。", "solution_python": "def merge(nums1, m, nums2, n):\n p1, p2, p = m-1, n-1, m+n-1\n while p1 >= 0 and p2 >= 0:\n if nums1[p1] > nums2[p2]: nums1[p] = nums1[p1]; p1 -= 1\n else: nums1[p] = nums2[p2]; p2 -= 1\n p -= 1\n while p2 >= 0: nums1[p] = nums2[p2]; p2 -= 1; p -= 1", "solution_java": "public void merge(int[] nums1, int m, int[] nums2, int n) {\n int p1 = m-1, p2 = n-1, p = m+n-1;\n while (p1 >= 0 && p2 >= 0) {\n nums1[p--] = nums1[p1] > nums2[p2] ? nums1[p1--] : nums2[p2--];\n }\n while (p2 >= 0) nums1[p--] = nums2[p2--];\n}", "solution_cpp": "void merge(vector& nums1, int m, vector& nums2, int n) {\n int p1 = m-1, p2 = n-1, p = m+n-1;\n while (p1 >= 0 && p2 >= 0) nums1[p--] = nums1[p1] > nums2[p2] ? nums1[p1--] : nums2[p2--];\n while (p2 >= 0) nums1[p--] = nums2[p2--];\n}", "test_cases": ["nums1=[1,2,3], m=3, nums2=[2,5,6], n=3 -> [1,2,2,3,5,6]", "nums1=[], m=0, nums2=[1], n=1 -> [1]"], "key_points": ["从后往前合并", "三指针技巧"], "tags": ["array", "easy", "Microsoft", "Uber"]} {"problem_id": "algo_00883", "original_id": "max-subarray", "title": "最大子数组和", "category": "array", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "给你一个整数数组 nums ,请你找出一个具有最大和的连续子数组,返回其最大和。", "solution_python": "def maxSubArray(nums):\n max_sum = current = nums[0]\n for num in nums[1:]:\n current = max(num, current + num)\n max_sum = max(max_sum, current)\n return max_sum", "solution_java": "public int maxSubArray(int[] nums) {\n int maxSum = nums[0], curr = nums[0];\n for (int i = 1; i < nums.length; i++) {\n curr = Math.max(nums[i], curr + nums[i]);\n maxSum = Math.max(maxSum, curr);\n }\n return maxSum;\n}", "solution_cpp": "int maxSubArray(vector& nums) {\n int maxSum = nums[0], curr = nums[0];\n for (int i = 1; i < nums.size(); i++) {\n curr = max(nums[i], curr + nums[i]);\n maxSum = max(maxSum, curr);\n }\n return maxSum;\n}", "test_cases": ["nums=[-2,1,-3,4,-1,2,1,-5,4] -> 6", "nums=[1] -> 1"], "key_points": ["Kadane算法", "动态规划基础题"], "tags": ["array", "medium", "Google", "Microsoft"]} {"problem_id": "algo_00884", "original_id": "valid-parentheses", "title": "有效的括号", "category": "string", "difficulty": "easy", "companies": ["Google", "Uber"], "description": "给定一个只包括 '(',')','{','}','[',']' 的字符串 s,判断字符串是否有效。", "solution_python": "def isValid(s):\n stack = []\n mapping = {')': '(', ']': '[', '}': '{'}\n for c in s:\n if c in mapping:\n if not stack or stack[-1] != mapping[c]: return False\n stack.pop()\n else: stack.append(c)\n return not stack", "solution_java": "public boolean isValid(String s) {\n Stack stack = new Stack<>();\n Map map = Map.of(')', '(', ']', '[', '}', '{');\n for (char c : s.toCharArray()) {\n if (map.containsValue(c)) stack.push(c);\n else if (!stack.isEmpty() && stack.pop() != map.get(c)) return false;\n }\n return stack.isEmpty();\n}", "solution_cpp": "bool isValid(string s) {\n stack st;\n unordered_map m = {{')','('},{']','['},{'}','{'}};\n for (char c : s) {\n if (m.find(c) == m.end()) st.push(c);\n else if (st.empty() || st.top() != m[c]) return false;\n else st.pop();\n }\n return st.empty();\n}", "test_cases": ["s=\"()\" -> true", "s=\"()[]{}\" -> true", "s=\"(]\" -> false"], "key_points": ["栈匹配法", "注意空栈边界"], "tags": ["string", "easy", "Google", "Uber"]} {"problem_id": "algo_00885", "original_id": "longest-palindrome", "title": "最长回文子串", "category": "string", "difficulty": "medium", "companies": ["Google", "Amazon"], "description": "给你一个字符串 s,找到 s 中最长的回文子串。", "solution_python": "def longestPalindrome(s):\n def expand(l, r):\n while l >= 0 and r < len(s) and s[l] == s[r]: l -= 1; r += 1\n return l + 1, r - 1\n start = end = 0\n for i in range(len(s)):\n l1, r1 = expand(i, i)\n l2, r2 = expand(i, i + 1)\n if r1 - l1 > end - start: start, end = l1, r1\n if r2 - l2 > end - start: start, end = l2, r2\n return s[start:end+1]", "solution_java": "public String longestPalindrome(String s) {\n int start = 0, end = 0;\n for (int i = 0; i < s.length(); i++) {\n int len1 = expand(s, i, i), len2 = expand(s, i, i+1);\n int len = Math.max(len1, len2);\n if (len > end - start) { start = i - (len-1)/2; end = i + len/2; }\n }\n return s.substring(start, end + 1);\n}\nprivate int expand(String s, int l, int r) {\n while (l >= 0 && r < s.length() && s.charAt(l) == s.charAt(r)) { l--; r++; }\n return r - l - 1;\n}", "solution_cpp": "string longestPalindrome(string s) {\n int start = 0, end = 0;\n for (int i = 0; i < s.size(); i++) {\n int len1 = expand(s, i, i), len2 = expand(s, i, i+1);\n if (max(len1, len2) > end - start) { start = i - (max(len1,len2)-1)/2; end = i + max(len1,len2)/2; }\n }\n return s.substr(start, end - start + 1);\n}", "test_cases": ["s=\"babad\" -> bab或aba", "s=\"cbbd\" -> bb"], "key_points": ["中心扩展法", "处理奇偶长度"], "tags": ["string", "medium", "Google", "Amazon"]} {"problem_id": "algo_00886", "original_id": "reverse-list", "title": "反转链表", "category": "linkedlist", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "给你单链表的头节点 head,请你反转链表,并返回反转后的链表。", "solution_python": "def reverseList(head):\n prev = None\n curr = head\n while curr:\n nxt = curr.next\n curr.next = prev\n prev = curr\n curr = nxt\n return prev", "solution_java": "public ListNode reverseList(ListNode head) {\n ListNode prev = null, curr = head;\n while (curr != null) {\n ListNode next = curr.next;\n curr.next = prev;\n prev = curr;\n curr = next;\n }\n return prev;\n}", "solution_cpp": "ListNode* reverseList(ListNode* head) {\n ListNode* prev = nullptr, *curr = head;\n while (curr) {\n ListNode* next = curr->next;\n curr->next = prev;\n prev = curr;\n curr = next;\n }\n return prev;\n}", "test_cases": ["head=[1,2,3,4,5] -> [5,4,3,2,1]", "head=[1,2] -> [2,1]"], "key_points": ["迭代法 O(1)空间", "递归法 O(n)空间"], "tags": ["linkedlist", "medium", "Google", "Microsoft"]} {"problem_id": "algo_00887", "original_id": "middle-node", "title": "链表的中间结点", "category": "linkedlist", "difficulty": "easy", "companies": ["Amazon", "Facebook"], "description": "给你单链表的头节点 head,请你找出并返回链表的中间结点。如果有两个中间结点,则返回第二个中间结点。", "solution_python": "def middleNode(head):\n slow = fast = head\n while fast and fast.next:\n slow = slow.next\n fast = fast.next.next\n return slow", "solution_java": "public ListNode middleNode(ListNode head) {\n ListNode slow = head, fast = head;\n while (fast != null && fast.next != null) {\n slow = slow.next;\n fast = fast.next.next;\n }\n return slow;\n}", "solution_cpp": "ListNode* middleNode(ListNode* head) {\n ListNode* slow = head, *fast = head;\n while (fast && fast->next) { slow = slow->next; fast = fast->next->next; }\n return slow;\n}", "test_cases": ["head=[1,2,3,4,5] -> 3", "head=[1,2,3,4,5,6] -> 4"], "key_points": ["快慢指针", "O(n)时间O(1)空间"], "tags": ["linkedlist", "easy", "Amazon", "Facebook"]} {"problem_id": "algo_00888", "original_id": "max-depth", "title": "二叉树的最大深度", "category": "tree", "difficulty": "easy", "companies": ["Microsoft", "Apple"], "description": "给定一个二叉树 root,返回其最大深度。", "solution_python": "def maxDepth(root):\n if not root: return 0\n return max(maxDepth(root.left), maxDepth(root.right)) + 1", "solution_java": "public int maxDepth(TreeNode root) {\n if (root == null) return 0;\n return Math.max(maxDepth(root.left), maxDepth(root.right)) + 1;\n}", "solution_cpp": "int maxDepth(TreeNode* root) {\n if (!root) return 0;\n return max(maxDepth(root->left), maxDepth(root->right)) + 1;\n}", "test_cases": ["root=[3,9,20,null,null,15,7] -> 3", "root=[1,null,2] -> 2"], "key_points": ["DFS递归", "层序遍历也可"], "tags": ["tree", "easy", "Microsoft", "Apple"]} {"problem_id": "algo_00889", "original_id": "inorder-traversal", "title": "二叉树的中序遍历", "category": "tree", "difficulty": "easy", "companies": ["Google", "Microsoft"], "description": "给定一个二叉树的根节点 root,返回它的中序遍历结果。", "solution_python": "def inorderTraversal(root):\n result = []\n def dfs(node):\n if node:\n dfs(node.left)\n result.append(node.val)\n dfs(node.right)\n dfs(root)\n return result", "solution_java": "public List inorderTraversal(TreeNode root) {\n List res = new ArrayList<>();\n dfs(root, res);\n return res;\n}\nprivate void dfs(TreeNode node, List res) {\n if (node == null) return;\n dfs(node.left, res); res.add(node.val); dfs(node.right, res);\n}", "solution_cpp": "vector inorderTraversal(TreeNode* root) {\n vector res;\n dfs(root, res);\n return res;\n}\nvoid dfs(TreeNode* node, vector& res) {\n if (!node) return;\n dfs(node->left, res); res.push_back(node->val); dfs(node->right, res);\n}", "test_cases": ["root=[1,null,2,3] -> [1,3,2]", "root=[] -> []"], "key_points": ["左-根-右顺序", "递归最简洁"], "tags": ["tree", "easy", "Google", "Microsoft"]} {"problem_id": "algo_00890", "original_id": "binary-search", "title": "二分查找", "category": "binarysearch", "difficulty": "easy", "companies": ["Google", "Amazon"], "description": "给定一个 n 个元素有序的(升序)整型数组 nums 和一个目标值 target,写一个函数搜索 nums 中的 target,如果目标值存在返回下标,否则返回 -1。", "solution_python": "def search(nums, target):\n left, right = 0, len(nums) - 1\n while left <= right:\n mid = (left + right) // 2\n if nums[mid] == target: return mid\n elif nums[mid] < target: left = mid + 1\n else: right = mid - 1\n return -1", "solution_java": "public int search(int[] nums, int target) {\n int left = 0, right = nums.length - 1;\n while (left <= right) {\n int mid = left + (right - left) / 2;\n if (nums[mid] == target) return mid;\n else if (nums[mid] < target) left = mid + 1;\n else right = mid - 1;\n }\n return -1;\n}", "solution_cpp": "int search(vector& nums, int target) {\n int left = 0, right = nums.size() - 1;\n while (left <= right) {\n int mid = left + (right - left) / 2;\n if (nums[mid] == target) return mid;\n else if (nums[mid] < target) left = mid + 1;\n else right = mid - 1;\n }\n return -1;\n}", "test_cases": ["nums=[-1,0,3,5,9,12], target=9 -> 4", "nums=[-1,0,3,5,9,12], target=2 -> -1"], "key_points": ["标准模板", "注意防溢出写法"], "tags": ["binarysearch", "easy", "Google", "Amazon"]} {"problem_id": "algo_00891", "original_id": "climbing-stairs", "title": "爬楼梯", "category": "dp", "difficulty": "easy", "companies": ["Amazon", "Google"], "description": "假设你正在爬楼梯。需要 n 阶你才能到达楼顶。每次你可以爬 1 或 2 个台阶。你有多少种不同的方法可以爬到楼顶?", "solution_python": "def climbStairs(n):\n if n <= 2: return n\n a, b = 1, 2\n for _ in range(3, n+1):\n a, b = b, a + b\n return b", "solution_java": "public int climbStairs(int n) {\n if (n <= 2) return n;\n int a = 1, b = 2;\n for (int i = 3; i <= n; i++) { int temp = a + b; a = b; b = temp; }\n return b;\n}", "solution_cpp": "int climbStairs(int n) {\n if (n <= 2) return n;\n int a = 1, b = 2;\n for (int i = 3; i <= n; i++) { int temp = a + b; a = b; b = temp; }\n return b;\n}", "test_cases": ["n=2 -> 2", "n=3 -> 3", "n=5 -> 8"], "key_points": ["斐波那契数列", "滚动数组优化空间"], "tags": ["dp", "easy", "Amazon", "Google"]} {"problem_id": "algo_00892", "original_id": "coin-change", "title": "零钱兑换", "category": "dp", "difficulty": "medium", "companies": ["Google", "Amazon"], "description": "给你一个整数数组 coins 表示不同面额的硬币,以及一个整数 amount 表示总金额。计算并返回可以凑成总金额所需的最少的硬币个数。如果没有任何一种硬币组合能组成总金额,返回 -1。", "solution_python": "def coinChange(coins, amount):\n dp = [float('inf')] * (amount + 1)\n dp[0] = 0\n for coin in coins:\n for x in range(coin, amount + 1):\n dp[x] = min(dp[x], dp[x - coin] + 1)\n return dp[amount] if dp[amount] != float('inf') else -1", "solution_java": "public int coinChange(int[] coins, int amount) {\n int[] dp = new int[amount + 1];\n Arrays.fill(dp, amount + 1);\n dp[0] = 0;\n for (int coin : coins) {\n for (int x = coin; x <= amount; x++) {\n dp[x] = Math.min(dp[x], dp[x - coin] + 1);\n }\n }\n return dp[amount] > amount ? -1 : dp[amount];\n}", "solution_cpp": "int coinChange(vector& coins, int amount) {\n vector dp(amount + 1, amount + 1);\n dp[0] = 0;\n for (int coin : coins) {\n for (int x = coin; x <= amount; x++) {\n dp[x] = min(dp[x], dp[x - coin] + 1);\n }\n }\n return dp[amount] > amount ? -1 : dp[amount];\n}", "test_cases": ["coins=[1,2,5], amount=11 -> 3", "coins=[2], amount=3 -> -1"], "key_points": ["完全背包问题", "dp[x] = min(dp[x-coin]+1)"], "tags": ["dp", "medium", "Google", "Amazon"]} {"problem_id": "algo_00893", "original_id": "subsets", "title": "子集", "category": "backtracking", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "给你一个整数数组 nums ,数组中的元素 互不相同 。返回该数组所有可能的子集(幂集)。", "solution_python": "def subsets(nums):\n result = []\n def backtrack(start, path):\n result.append(path[:])\n for i in range(start, len(nums)):\n path.append(nums[i])\n backtrack(i + 1, path)\n path.pop()\n backtrack(0, [])\n return result", "solution_java": "public List> subsets(int[] nums) {\n List> result = new ArrayList<>();\n backtrack(nums, 0, new ArrayList<>(), result);\n return result;\n}\nprivate void backtrack(int[] nums, int start, List path, List> result) {\n result.add(new ArrayList<>(path));\n for (int i = start; i < nums.length; i++) {\n path.add(nums[i]);\n backtrack(nums, i + 1, path, result);\n path.remove(path.size() - 1);\n }\n}", "solution_cpp": "vector> subsets(vector& nums) {\n vector> result;\n vector path;\n backtrack(nums, 0, path, result);\n return result;\n}\nvoid backtrack(vector& nums, int start, vector& path, vector>& result) {\n result.push_back(path);\n for (int i = start; i < nums.size(); i++) {\n path.push_back(nums[i]);\n backtrack(nums, i + 1, path, result);\n path.pop_back();\n }\n}", "test_cases": ["nums=[1,2,3] -> [[],[1],[2],[1,2],[3],[1,3],[2,3],[1,2,3]]"], "key_points": ["选或不选", "DFS遍历子集树"], "tags": ["backtracking", "medium", "Google", "Microsoft"]} {"problem_id": "algo_00894", "original_id": "permutations", "title": "全排列", "category": "backtracking", "difficulty": "medium", "companies": ["Google", "Facebook"], "description": "给定一个不含重复数字的数组 nums,返回其所有可能的全排列。", "solution_python": "def permute(nums):\n result = []\n def backtrack(path, used):\n if len(path) == len(nums):\n result.append(path[:])\n return\n for i in range(len(nums)):\n if used[i]: continue\n used[i] = True\n path.append(nums[i])\n backtrack(path, used)\n path.pop()\n used[i] = False\n backtrack([], [False]*len(nums))\n return result", "solution_java": "public List> permute(int[] nums) {\n List> result = new ArrayList<>();\n boolean[] used = new boolean[nums.length];\n backtrack(nums, used, new ArrayList<>(), result);\n return result;\n}\nprivate void backtrack(int[] nums, boolean[] used, List path, List> result) {\n if (path.size() == nums.length) { result.add(new ArrayList<>(path)); return; }\n for (int i = 0; i < nums.length; i++) {\n if (used[i]) continue;\n used[i] = true;\n path.add(nums[i]);\n backtrack(nums, used, path, result);\n path.remove(path.size() - 1);\n used[i] = false;\n }\n}", "solution_cpp": "vector> permute(vector& nums) {\n vector> result;\n vector used(nums.size(), false);\n vector path;\n backtrack(nums, used, path, result);\n return result;\n}\nvoid backtrack(vector& nums, vector& used, vector& path, vector>& result) {\n if (path.size() == nums.size()) { result.push_back(path); return; }\n for (int i = 0; i < nums.size(); i++) {\n if (used[i]) continue;\n used[i] = true;\n path.push_back(nums[i]);\n backtrack(nums, used, path, result);\n path.pop_back();\n used[i] = false;\n }\n}", "test_cases": ["nums=[1,2,3] -> [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]"], "key_points": ["标记已使用元素", "回溯经典模板"], "tags": ["backtracking", "medium", "Google", "Facebook"]} {"problem_id": "algo_00895", "original_id": "top-k-frequent", "title": "前K个高频元素", "category": "heap", "difficulty": "medium", "companies": ["Amazon", "Facebook"], "description": "给你一个整数数组 nums 和一个整数 k,请你返回其中出现频率前 k 高的元素。", "solution_python": "import heapq\nfrom collections import Counter\ndef topKFrequent(nums, k):\n count = Counter(nums)\n heap = []\n for num, freq in count.items():\n heapq.heappush(heap, (freq, num))\n if len(heap) > k: heapq.heappop(heap)\n return [num for freq, num in heap]", "solution_java": "public int[] topKFrequent(int[] nums, int k) {\n Map count = new HashMap<>();\n for (int n : nums) count.put(n, count.getOrDefault(n, 0) + 1);\n PriorityQueue> heap = \n new PriorityQueue<>((a, b) -> a.getValue() - b.getValue());\n for (Map.Entry e : count.entrySet()) {\n heap.offer(e);\n if (heap.size() > k) heap.poll();\n }\n int[] res = new int[k];\n for (int i = k - 1; i >= 0; i--) res[i] = heap.poll().getKey();\n return res;\n}", "solution_cpp": "vector topKFrequent(vector& nums, int k) {\n unordered_map count;\n for (int n : nums) count[n]++;\n priority_queue, vector>, greater>> heap;\n for (auto& [num, freq] : count) {\n heap.push({freq, num});\n if (heap.size() > k) heap.pop();\n }\n vector res;\n while (!heap.empty()) { res.push_back(heap.top().second); heap.pop(); }\n reverse(res.begin(), res.end());\n return res;\n}", "test_cases": ["nums=[1,1,1,2,2,3], k=2 -> [1,2]", "nums=[1], k=1 -> [1]"], "key_points": ["小顶堆保持大小k", "时间复杂度O(nlogk)"], "tags": ["heap", "medium", "Amazon", "Facebook"]} {"problem_id": "algo_00896", "original_id": "3sum", "title": "三数之和", "category": "two-pointers", "difficulty": "medium", "companies": ["Google", "Amazon"], "description": "给你一个整数数组 nums,判断是否存在三元组满足和为0,返回所有不重复的三元组。", "solution_python": "def threeSum(nums):\n nums.sort()\n result = []\n for i in range(len(nums) - 2):\n if i > 0 and nums[i] == nums[i-1]: continue\n left, right = i + 1, len(nums) - 1\n while left < right:\n total = nums[i] + nums[left] + nums[right]\n if total < 0: left += 1\n elif total > 0: right -= 1\n else:\n result.append([nums[i], nums[left], nums[right]])\n while left < right and nums[left] == nums[left+1]: left += 1\n while left < right and nums[right] == nums[right-1]: right -= 1\n left += 1; right -= 1\n return result", "solution_java": "public List> threeSum(int[] nums) {\n Arrays.sort(nums);\n List> result = new ArrayList<>();\n for (int i = 0; i < nums.length - 2; i++) {\n if (i > 0 && nums[i] == nums[i-1]) continue;\n int left = i + 1, right = nums.length - 1;\n while (left < right) {\n int total = nums[i] + nums[left] + nums[right];\n if (total < 0) left++;\n else if (total > 0) right--;\n else {\n result.add(Arrays.asList(nums[i], nums[left], nums[right]));\n while (left < right && nums[left] == nums[left+1]) left++;\n while (left < right && nums[right] == nums[right-1]) right--;\n left++; right--;\n }\n }\n }\n return result;\n}", "solution_cpp": "vector> threeSum(vector& nums) {\n sort(nums.begin(), nums.end());\n vector> result;\n for (int i = 0; i < nums.size() - 2; i++) {\n if (i > 0 && nums[i] == nums[i-1]) continue;\n int left = i + 1, right = nums.size() - 1;\n while (left < right) {\n int total = nums[i] + nums[left] + nums[right];\n if (total < 0) left++;\n else if (total > 0) right--;\n else {\n result.push_back({nums[i], nums[left], nums[right]});\n while (left < right && nums[left] == nums[left+1]) left++;\n while (left < right && nums[right] == nums[right-1]) right--;\n left++; right--;\n }\n }\n }\n return result;\n}", "test_cases": ["nums=[-1,0,1,2,-1,-4] -> [[-1,-1,2],[-1,0,1]]"], "key_points": ["排序+双指针", "去重是关键"], "tags": ["two-pointers", "medium", "Google", "Amazon"]} {"problem_id": "algo_00897", "original_id": "container-water", "title": "盛最多水的容器", "category": "two-pointers", "difficulty": "medium", "companies": ["Google", "Uber"], "description": "给定一个长度为 n 的整数数组 height,找出其中的两条线,使得它们与 x 轴共同构成的容器可以容纳最多的水。", "solution_python": "def maxArea(height):\n left, right = 0, len(height) - 1\n max_area = 0\n while left < right:\n h = min(height[left], height[right])\n max_area = max(max_area, h * (right - left))\n if height[left] < height[right]: left += 1\n else: right -= 1\n return max_area", "solution_java": "public int maxArea(int[] height) {\n int left = 0, right = height.length - 1, maxArea = 0;\n while (left < right) {\n int h = Math.min(height[left], height[right]);\n maxArea = Math.max(maxArea, h * (right - left));\n if (height[left] < height[right]) left++;\n else right--;\n }\n return maxArea;\n}", "solution_cpp": "int maxArea(vector& height) {\n int left = 0, right = height.size() - 1, maxArea = 0;\n while (left < right) {\n int h = min(height[left], height[right]);\n maxArea = max(maxArea, h * (right - left));\n if (height[left] < height[right]) left++;\n else right--;\n }\n return maxArea;\n}", "test_cases": ["height=[1,8,6,2,5,4,8,3,7] -> 49"], "key_points": ["移动短边指针", "面积=min(h1,h2)*width"], "tags": ["two-pointers", "medium", "Google", "Uber"]} {"problem_id": "algo_00898", "original_id": "min-stack", "title": "最小栈", "category": "stack", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "设计一个支持 push,pop,top 操作,并能在常数时间内检索到最小元素的栈。", "solution_python": "class MinStack:\n def __init__(self):\n self.stack = []\n self.min_stack = []\n def push(self, val):\n self.stack.append(val)\n self.min_stack.append(min(val, self.min_stack[-1] if self.min_stack else val))\n def pop(self):\n self.stack.pop(); self.min_stack.pop()\n def top(self): return self.stack[-1]\n def getMin(self): return self.min_stack[-1]", "solution_java": "class MinStack {\n Stack stack = new Stack<>();\n Stack minStack = new Stack<>();\n public void push(int val) { stack.push(val); minStack.push(Math.min(val, minStack.isEmpty() ? val : minStack.peek())); }\n public void pop() { stack.pop(); minStack.pop(); }\n public int top() { return stack.peek(); }\n public int getMin() { return minStack.peek(); }\n}", "solution_cpp": "class MinStack {\n stack st, minSt;\npublic:\n void push(int val) { st.push(val); minSt.push(min(val, minSt.empty() ? val : minSt.top())); }\n void pop() { st.pop(); minSt.pop(); }\n int top() { return st.top(); }\n int getMin() { return minSt.top(); }\n};", "test_cases": ["push(-2), push(0), push(-3) -> getMin() returns -3"], "key_points": ["辅助栈记录最小值", "O(1)时间获取最小值"], "tags": ["stack", "medium", "Google", "Microsoft"]} {"problem_id": "algo_00899", "original_id": "lru-cache", "title": "LRU缓存", "category": "design", "difficulty": "hard", "companies": ["Google", "Amazon"], "description": "设计和实现一个 LRU(最近最少使用)缓存机制。", "solution_python": "class LRUCache:\n def __init__(self, capacity):\n self.capacity = capacity\n self.cache = {}\n self.order = []\n def get(self, key):\n if key not in self.cache: return -1\n self.order.remove(key); self.order.append(key)\n return self.cache[key]\n def put(self, key, value):\n if key in self.cache:\n self.order.remove(key)\n elif len(self.cache) >= self.capacity:\n del self.cache[self.order.pop(0)]\n self.cache[key] = value; self.order.append(key)", "solution_java": "class LRUCache {\n int capacity;\n LinkedHashMap cache = new LinkedHashMap<>();\n public LRUCache(int cap) { capacity = cap; }\n public int get(int key) { return cache.containsKey(key) ? cache.remove(key) : -1; }\n public void put(int key, int val) {\n if (cache.containsKey(key)) cache.remove(key);\n else if (cache.size() >= capacity) cache.remove(cache.keySet().iterator().next());\n cache.put(key, val);\n }\n}", "solution_cpp": "class LRUCache {\n int cap;\n list> dll;\n unordered_map>::iterator> cache;\npublic:\n LRUCache(int capacity) : cap(capacity) {}\n int get(int key) {\n auto it = cache.find(key);\n if (it == cache.end()) return -1;\n dll.splice(dll.end(), dll, it->second);\n return it->second->second;\n }\n void put(int key, int value) {\n auto it = cache.find(key);\n if (it != cache.end()) dll.erase(it->second);\n else if (cache.size() >= cap) { cache.erase(dll.front().first); dll.pop_front(); }\n dll.push_back({key, value});\n cache[key] = --dll.end();\n }\n};", "test_cases": ["put(1,1), put(2,2), get(1) -> 1"], "key_points": ["HashMap + 双向链表", "O(1)时间操作"], "tags": ["design", "hard", "Google", "Amazon"]} {"problem_id": "algo_00900", "original_id": "num-islands", "title": "岛屿数量", "category": "graph", "difficulty": "medium", "companies": ["Google", "Facebook"], "description": "给你一个由 '1'(陆地)和 '0'(水)组成的二维网格,请你计算网格中岛屿的数量。岛屿总是被水包围,且只能由水平或垂直方向相邻的陆地连接形成。", "solution_python": "def numIslands(grid):\n if not grid: return 0\n rows, cols = len(grid), len(grid[0])\n count = 0\n def dfs(r, c):\n if r < 0 or r >= rows or c < 0 or c >= cols or grid[r][c] != '1': return\n grid[r][c] = '0'\n dfs(r+1, c); dfs(r-1, c); dfs(r, c+1); dfs(r, c-1)\n for r in range(rows):\n for c in range(cols):\n if grid[r][c] == '1': count += 1; dfs(r, c)\n return count", "solution_java": "public int numIslands(char[][] grid) {\n if (grid.length == 0) return 0;\n int count = 0;\n for (int i = 0; i < grid.length; i++)\n for (int j = 0; j < grid[0].length; j++)\n if (grid[i][j] == '1') { count++; dfs(grid, i, j); }\n return count;\n}\nprivate void dfs(char[][] grid, int r, int c) {\n if (r < 0 || r >= grid.length || c < 0 || c >= grid[0].length || grid[r][c] != '1') return;\n grid[r][c] = '0';\n dfs(grid, r+1, c); dfs(grid, r-1, c); dfs(grid, r, c+1); dfs(grid, r, c-1);\n}", "solution_cpp": "int numIslands(vector>& grid) {\n if (grid.empty()) return 0;\n int count = 0;\n for (int i = 0; i < grid.size(); i++)\n for (int j = 0; j < grid[0].size(); j++)\n if (grid[i][j] == '1') { count++; dfs(grid, i, j); }\n return count;\n}\nvoid dfs(vector>& grid, int r, int c) {\n if (r < 0 || r >= grid.size() || c < 0 || c >= grid[0].size() || grid[r][c] != '1') return;\n grid[r][c] = '0';\n dfs(grid, r+1, c); dfs(grid, r-1, c); dfs(grid, r, c+1); dfs(grid, r, c-1);\n}", "test_cases": ["grid=[[1,1,1,1,0],[1,1,0,1,0],[1,1,0,0,0],[0,0,0,0,0]] -> 1"], "key_points": ["DFS/BFS遍历", "访问后标记为0避免重复"], "tags": ["graph", "medium", "Google", "Facebook"]} {"problem_id": "algo_00901", "original_id": "two-sum", "title": "两数之和", "category": "array", "difficulty": "easy", "companies": ["Amazon", "Google"], "description": "给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那两个整数,并返回他们的数组下标。", "solution_python": "def twoSum(nums, target):\n hashmap = {}\n for i, num in enumerate(nums):\n complement = target - num\n if complement in hashmap:\n return [hashmap[complement], i]\n hashmap[num] = i\n return []", "solution_java": "public int[] twoSum(int[] nums, int target) {\n Map map = new HashMap<>();\n for (int i = 0; i < nums.length; i++) {\n int complement = target - nums[i];\n if (map.containsKey(complement)) return new int[]{map.get(complement), i};\n map.put(nums[i], i);\n }\n return new int[]{};\n}", "solution_cpp": "vector twoSum(vector& nums, int target) {\n unordered_map m;\n for (int i = 0; i < nums.size(); i++) {\n if (m.count(target - nums[i])) return {m[target - nums[i]], i};\n m[nums[i]] = i;\n }\n return {};\n}", "test_cases": ["nums=[2,7,11,15], target=9 -> [0,1]", "nums=[3,2,4], target=6 -> [1,2]"], "key_points": ["哈希表一次遍历", "空间换时间"], "tags": ["array", "easy", "Amazon", "Google"]} {"problem_id": "algo_00902", "original_id": "merge-sorted", "title": "合并两个有序数组", "category": "array", "difficulty": "easy", "companies": ["Microsoft", "Uber"], "description": "给你两个按非递减顺序排列的整数数组 nums1 和 nums2,另有两个整数 m 和 n,分别表示 nums1 和 nums2 中的元素数目。请你合并 nums2 到 nums1 中。", "solution_python": "def merge(nums1, m, nums2, n):\n p1, p2, p = m-1, n-1, m+n-1\n while p1 >= 0 and p2 >= 0:\n if nums1[p1] > nums2[p2]: nums1[p] = nums1[p1]; p1 -= 1\n else: nums1[p] = nums2[p2]; p2 -= 1\n p -= 1\n while p2 >= 0: nums1[p] = nums2[p2]; p2 -= 1; p -= 1", "solution_java": "public void merge(int[] nums1, int m, int[] nums2, int n) {\n int p1 = m-1, p2 = n-1, p = m+n-1;\n while (p1 >= 0 && p2 >= 0) {\n nums1[p--] = nums1[p1] > nums2[p2] ? nums1[p1--] : nums2[p2--];\n }\n while (p2 >= 0) nums1[p--] = nums2[p2--];\n}", "solution_cpp": "void merge(vector& nums1, int m, vector& nums2, int n) {\n int p1 = m-1, p2 = n-1, p = m+n-1;\n while (p1 >= 0 && p2 >= 0) nums1[p--] = nums1[p1] > nums2[p2] ? nums1[p1--] : nums2[p2--];\n while (p2 >= 0) nums1[p--] = nums2[p2--];\n}", "test_cases": ["nums1=[1,2,3], m=3, nums2=[2,5,6], n=3 -> [1,2,2,3,5,6]", "nums1=[], m=0, nums2=[1], n=1 -> [1]"], "key_points": ["从后往前合并", "三指针技巧"], "tags": ["array", "easy", "Microsoft", "Uber"]} {"problem_id": "algo_00903", "original_id": "max-subarray", "title": "最大子数组和", "category": "array", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "给你一个整数数组 nums ,请你找出一个具有最大和的连续子数组,返回其最大和。", "solution_python": "def maxSubArray(nums):\n max_sum = current = nums[0]\n for num in nums[1:]:\n current = max(num, current + num)\n max_sum = max(max_sum, current)\n return max_sum", "solution_java": "public int maxSubArray(int[] nums) {\n int maxSum = nums[0], curr = nums[0];\n for (int i = 1; i < nums.length; i++) {\n curr = Math.max(nums[i], curr + nums[i]);\n maxSum = Math.max(maxSum, curr);\n }\n return maxSum;\n}", "solution_cpp": "int maxSubArray(vector& nums) {\n int maxSum = nums[0], curr = nums[0];\n for (int i = 1; i < nums.size(); i++) {\n curr = max(nums[i], curr + nums[i]);\n maxSum = max(maxSum, curr);\n }\n return maxSum;\n}", "test_cases": ["nums=[-2,1,-3,4,-1,2,1,-5,4] -> 6", "nums=[1] -> 1"], "key_points": ["Kadane算法", "动态规划基础题"], "tags": ["array", "medium", "Google", "Microsoft"]} {"problem_id": "algo_00904", "original_id": "valid-parentheses", "title": "有效的括号", "category": "string", "difficulty": "easy", "companies": ["Google", "Uber"], "description": "给定一个只包括 '(',')','{','}','[',']' 的字符串 s,判断字符串是否有效。", "solution_python": "def isValid(s):\n stack = []\n mapping = {')': '(', ']': '[', '}': '{'}\n for c in s:\n if c in mapping:\n if not stack or stack[-1] != mapping[c]: return False\n stack.pop()\n else: stack.append(c)\n return not stack", "solution_java": "public boolean isValid(String s) {\n Stack stack = new Stack<>();\n Map map = Map.of(')', '(', ']', '[', '}', '{');\n for (char c : s.toCharArray()) {\n if (map.containsValue(c)) stack.push(c);\n else if (!stack.isEmpty() && stack.pop() != map.get(c)) return false;\n }\n return stack.isEmpty();\n}", "solution_cpp": "bool isValid(string s) {\n stack st;\n unordered_map m = {{')','('},{']','['},{'}','{'}};\n for (char c : s) {\n if (m.find(c) == m.end()) st.push(c);\n else if (st.empty() || st.top() != m[c]) return false;\n else st.pop();\n }\n return st.empty();\n}", "test_cases": ["s=\"()\" -> true", "s=\"()[]{}\" -> true", "s=\"(]\" -> false"], "key_points": ["栈匹配法", "注意空栈边界"], "tags": ["string", "easy", "Google", "Uber"]} {"problem_id": "algo_00905", "original_id": "longest-palindrome", "title": "最长回文子串", "category": "string", "difficulty": "medium", "companies": ["Google", "Amazon"], "description": "给你一个字符串 s,找到 s 中最长的回文子串。", "solution_python": "def longestPalindrome(s):\n def expand(l, r):\n while l >= 0 and r < len(s) and s[l] == s[r]: l -= 1; r += 1\n return l + 1, r - 1\n start = end = 0\n for i in range(len(s)):\n l1, r1 = expand(i, i)\n l2, r2 = expand(i, i + 1)\n if r1 - l1 > end - start: start, end = l1, r1\n if r2 - l2 > end - start: start, end = l2, r2\n return s[start:end+1]", "solution_java": "public String longestPalindrome(String s) {\n int start = 0, end = 0;\n for (int i = 0; i < s.length(); i++) {\n int len1 = expand(s, i, i), len2 = expand(s, i, i+1);\n int len = Math.max(len1, len2);\n if (len > end - start) { start = i - (len-1)/2; end = i + len/2; }\n }\n return s.substring(start, end + 1);\n}\nprivate int expand(String s, int l, int r) {\n while (l >= 0 && r < s.length() && s.charAt(l) == s.charAt(r)) { l--; r++; }\n return r - l - 1;\n}", "solution_cpp": "string longestPalindrome(string s) {\n int start = 0, end = 0;\n for (int i = 0; i < s.size(); i++) {\n int len1 = expand(s, i, i), len2 = expand(s, i, i+1);\n if (max(len1, len2) > end - start) { start = i - (max(len1,len2)-1)/2; end = i + max(len1,len2)/2; }\n }\n return s.substr(start, end - start + 1);\n}", "test_cases": ["s=\"babad\" -> bab或aba", "s=\"cbbd\" -> bb"], "key_points": ["中心扩展法", "处理奇偶长度"], "tags": ["string", "medium", "Google", "Amazon"]} {"problem_id": "algo_00906", "original_id": "reverse-list", "title": "反转链表", "category": "linkedlist", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "给你单链表的头节点 head,请你反转链表,并返回反转后的链表。", "solution_python": "def reverseList(head):\n prev = None\n curr = head\n while curr:\n nxt = curr.next\n curr.next = prev\n prev = curr\n curr = nxt\n return prev", "solution_java": "public ListNode reverseList(ListNode head) {\n ListNode prev = null, curr = head;\n while (curr != null) {\n ListNode next = curr.next;\n curr.next = prev;\n prev = curr;\n curr = next;\n }\n return prev;\n}", "solution_cpp": "ListNode* reverseList(ListNode* head) {\n ListNode* prev = nullptr, *curr = head;\n while (curr) {\n ListNode* next = curr->next;\n curr->next = prev;\n prev = curr;\n curr = next;\n }\n return prev;\n}", "test_cases": ["head=[1,2,3,4,5] -> [5,4,3,2,1]", "head=[1,2] -> [2,1]"], "key_points": ["迭代法 O(1)空间", "递归法 O(n)空间"], "tags": ["linkedlist", "medium", "Google", "Microsoft"]} {"problem_id": "algo_00907", "original_id": "middle-node", "title": "链表的中间结点", "category": "linkedlist", "difficulty": "easy", "companies": ["Amazon", "Facebook"], "description": "给你单链表的头节点 head,请你找出并返回链表的中间结点。如果有两个中间结点,则返回第二个中间结点。", "solution_python": "def middleNode(head):\n slow = fast = head\n while fast and fast.next:\n slow = slow.next\n fast = fast.next.next\n return slow", "solution_java": "public ListNode middleNode(ListNode head) {\n ListNode slow = head, fast = head;\n while (fast != null && fast.next != null) {\n slow = slow.next;\n fast = fast.next.next;\n }\n return slow;\n}", "solution_cpp": "ListNode* middleNode(ListNode* head) {\n ListNode* slow = head, *fast = head;\n while (fast && fast->next) { slow = slow->next; fast = fast->next->next; }\n return slow;\n}", "test_cases": ["head=[1,2,3,4,5] -> 3", "head=[1,2,3,4,5,6] -> 4"], "key_points": ["快慢指针", "O(n)时间O(1)空间"], "tags": ["linkedlist", "easy", "Amazon", "Facebook"]} {"problem_id": "algo_00908", "original_id": "max-depth", "title": "二叉树的最大深度", "category": "tree", "difficulty": "easy", "companies": ["Microsoft", "Apple"], "description": "给定一个二叉树 root,返回其最大深度。", "solution_python": "def maxDepth(root):\n if not root: return 0\n return max(maxDepth(root.left), maxDepth(root.right)) + 1", "solution_java": "public int maxDepth(TreeNode root) {\n if (root == null) return 0;\n return Math.max(maxDepth(root.left), maxDepth(root.right)) + 1;\n}", "solution_cpp": "int maxDepth(TreeNode* root) {\n if (!root) return 0;\n return max(maxDepth(root->left), maxDepth(root->right)) + 1;\n}", "test_cases": ["root=[3,9,20,null,null,15,7] -> 3", "root=[1,null,2] -> 2"], "key_points": ["DFS递归", "层序遍历也可"], "tags": ["tree", "easy", "Microsoft", "Apple"]} {"problem_id": "algo_00909", "original_id": "inorder-traversal", "title": "二叉树的中序遍历", "category": "tree", "difficulty": "easy", "companies": ["Google", "Microsoft"], "description": "给定一个二叉树的根节点 root,返回它的中序遍历结果。", "solution_python": "def inorderTraversal(root):\n result = []\n def dfs(node):\n if node:\n dfs(node.left)\n result.append(node.val)\n dfs(node.right)\n dfs(root)\n return result", "solution_java": "public List inorderTraversal(TreeNode root) {\n List res = new ArrayList<>();\n dfs(root, res);\n return res;\n}\nprivate void dfs(TreeNode node, List res) {\n if (node == null) return;\n dfs(node.left, res); res.add(node.val); dfs(node.right, res);\n}", "solution_cpp": "vector inorderTraversal(TreeNode* root) {\n vector res;\n dfs(root, res);\n return res;\n}\nvoid dfs(TreeNode* node, vector& res) {\n if (!node) return;\n dfs(node->left, res); res.push_back(node->val); dfs(node->right, res);\n}", "test_cases": ["root=[1,null,2,3] -> [1,3,2]", "root=[] -> []"], "key_points": ["左-根-右顺序", "递归最简洁"], "tags": ["tree", "easy", "Google", "Microsoft"]} {"problem_id": "algo_00910", "original_id": "binary-search", "title": "二分查找", "category": "binarysearch", "difficulty": "easy", "companies": ["Google", "Amazon"], "description": "给定一个 n 个元素有序的(升序)整型数组 nums 和一个目标值 target,写一个函数搜索 nums 中的 target,如果目标值存在返回下标,否则返回 -1。", "solution_python": "def search(nums, target):\n left, right = 0, len(nums) - 1\n while left <= right:\n mid = (left + right) // 2\n if nums[mid] == target: return mid\n elif nums[mid] < target: left = mid + 1\n else: right = mid - 1\n return -1", "solution_java": "public int search(int[] nums, int target) {\n int left = 0, right = nums.length - 1;\n while (left <= right) {\n int mid = left + (right - left) / 2;\n if (nums[mid] == target) return mid;\n else if (nums[mid] < target) left = mid + 1;\n else right = mid - 1;\n }\n return -1;\n}", "solution_cpp": "int search(vector& nums, int target) {\n int left = 0, right = nums.size() - 1;\n while (left <= right) {\n int mid = left + (right - left) / 2;\n if (nums[mid] == target) return mid;\n else if (nums[mid] < target) left = mid + 1;\n else right = mid - 1;\n }\n return -1;\n}", "test_cases": ["nums=[-1,0,3,5,9,12], target=9 -> 4", "nums=[-1,0,3,5,9,12], target=2 -> -1"], "key_points": ["标准模板", "注意防溢出写法"], "tags": ["binarysearch", "easy", "Google", "Amazon"]} {"problem_id": "algo_00911", "original_id": "climbing-stairs", "title": "爬楼梯", "category": "dp", "difficulty": "easy", "companies": ["Amazon", "Google"], "description": "假设你正在爬楼梯。需要 n 阶你才能到达楼顶。每次你可以爬 1 或 2 个台阶。你有多少种不同的方法可以爬到楼顶?", "solution_python": "def climbStairs(n):\n if n <= 2: return n\n a, b = 1, 2\n for _ in range(3, n+1):\n a, b = b, a + b\n return b", "solution_java": "public int climbStairs(int n) {\n if (n <= 2) return n;\n int a = 1, b = 2;\n for (int i = 3; i <= n; i++) { int temp = a + b; a = b; b = temp; }\n return b;\n}", "solution_cpp": "int climbStairs(int n) {\n if (n <= 2) return n;\n int a = 1, b = 2;\n for (int i = 3; i <= n; i++) { int temp = a + b; a = b; b = temp; }\n return b;\n}", "test_cases": ["n=2 -> 2", "n=3 -> 3", "n=5 -> 8"], "key_points": ["斐波那契数列", "滚动数组优化空间"], "tags": ["dp", "easy", "Amazon", "Google"]} {"problem_id": "algo_00912", "original_id": "coin-change", "title": "零钱兑换", "category": "dp", "difficulty": "medium", "companies": ["Google", "Amazon"], "description": "给你一个整数数组 coins 表示不同面额的硬币,以及一个整数 amount 表示总金额。计算并返回可以凑成总金额所需的最少的硬币个数。如果没有任何一种硬币组合能组成总金额,返回 -1。", "solution_python": "def coinChange(coins, amount):\n dp = [float('inf')] * (amount + 1)\n dp[0] = 0\n for coin in coins:\n for x in range(coin, amount + 1):\n dp[x] = min(dp[x], dp[x - coin] + 1)\n return dp[amount] if dp[amount] != float('inf') else -1", "solution_java": "public int coinChange(int[] coins, int amount) {\n int[] dp = new int[amount + 1];\n Arrays.fill(dp, amount + 1);\n dp[0] = 0;\n for (int coin : coins) {\n for (int x = coin; x <= amount; x++) {\n dp[x] = Math.min(dp[x], dp[x - coin] + 1);\n }\n }\n return dp[amount] > amount ? -1 : dp[amount];\n}", "solution_cpp": "int coinChange(vector& coins, int amount) {\n vector dp(amount + 1, amount + 1);\n dp[0] = 0;\n for (int coin : coins) {\n for (int x = coin; x <= amount; x++) {\n dp[x] = min(dp[x], dp[x - coin] + 1);\n }\n }\n return dp[amount] > amount ? -1 : dp[amount];\n}", "test_cases": ["coins=[1,2,5], amount=11 -> 3", "coins=[2], amount=3 -> -1"], "key_points": ["完全背包问题", "dp[x] = min(dp[x-coin]+1)"], "tags": ["dp", "medium", "Google", "Amazon"]} {"problem_id": "algo_00913", "original_id": "subsets", "title": "子集", "category": "backtracking", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "给你一个整数数组 nums ,数组中的元素 互不相同 。返回该数组所有可能的子集(幂集)。", "solution_python": "def subsets(nums):\n result = []\n def backtrack(start, path):\n result.append(path[:])\n for i in range(start, len(nums)):\n path.append(nums[i])\n backtrack(i + 1, path)\n path.pop()\n backtrack(0, [])\n return result", "solution_java": "public List> subsets(int[] nums) {\n List> result = new ArrayList<>();\n backtrack(nums, 0, new ArrayList<>(), result);\n return result;\n}\nprivate void backtrack(int[] nums, int start, List path, List> result) {\n result.add(new ArrayList<>(path));\n for (int i = start; i < nums.length; i++) {\n path.add(nums[i]);\n backtrack(nums, i + 1, path, result);\n path.remove(path.size() - 1);\n }\n}", "solution_cpp": "vector> subsets(vector& nums) {\n vector> result;\n vector path;\n backtrack(nums, 0, path, result);\n return result;\n}\nvoid backtrack(vector& nums, int start, vector& path, vector>& result) {\n result.push_back(path);\n for (int i = start; i < nums.size(); i++) {\n path.push_back(nums[i]);\n backtrack(nums, i + 1, path, result);\n path.pop_back();\n }\n}", "test_cases": ["nums=[1,2,3] -> [[],[1],[2],[1,2],[3],[1,3],[2,3],[1,2,3]]"], "key_points": ["选或不选", "DFS遍历子集树"], "tags": ["backtracking", "medium", "Google", "Microsoft"]} {"problem_id": "algo_00914", "original_id": "permutations", "title": "全排列", "category": "backtracking", "difficulty": "medium", "companies": ["Google", "Facebook"], "description": "给定一个不含重复数字的数组 nums,返回其所有可能的全排列。", "solution_python": "def permute(nums):\n result = []\n def backtrack(path, used):\n if len(path) == len(nums):\n result.append(path[:])\n return\n for i in range(len(nums)):\n if used[i]: continue\n used[i] = True\n path.append(nums[i])\n backtrack(path, used)\n path.pop()\n used[i] = False\n backtrack([], [False]*len(nums))\n return result", "solution_java": "public List> permute(int[] nums) {\n List> result = new ArrayList<>();\n boolean[] used = new boolean[nums.length];\n backtrack(nums, used, new ArrayList<>(), result);\n return result;\n}\nprivate void backtrack(int[] nums, boolean[] used, List path, List> result) {\n if (path.size() == nums.length) { result.add(new ArrayList<>(path)); return; }\n for (int i = 0; i < nums.length; i++) {\n if (used[i]) continue;\n used[i] = true;\n path.add(nums[i]);\n backtrack(nums, used, path, result);\n path.remove(path.size() - 1);\n used[i] = false;\n }\n}", "solution_cpp": "vector> permute(vector& nums) {\n vector> result;\n vector used(nums.size(), false);\n vector path;\n backtrack(nums, used, path, result);\n return result;\n}\nvoid backtrack(vector& nums, vector& used, vector& path, vector>& result) {\n if (path.size() == nums.size()) { result.push_back(path); return; }\n for (int i = 0; i < nums.size(); i++) {\n if (used[i]) continue;\n used[i] = true;\n path.push_back(nums[i]);\n backtrack(nums, used, path, result);\n path.pop_back();\n used[i] = false;\n }\n}", "test_cases": ["nums=[1,2,3] -> [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]"], "key_points": ["标记已使用元素", "回溯经典模板"], "tags": ["backtracking", "medium", "Google", "Facebook"]} {"problem_id": "algo_00915", "original_id": "top-k-frequent", "title": "前K个高频元素", "category": "heap", "difficulty": "medium", "companies": ["Amazon", "Facebook"], "description": "给你一个整数数组 nums 和一个整数 k,请你返回其中出现频率前 k 高的元素。", "solution_python": "import heapq\nfrom collections import Counter\ndef topKFrequent(nums, k):\n count = Counter(nums)\n heap = []\n for num, freq in count.items():\n heapq.heappush(heap, (freq, num))\n if len(heap) > k: heapq.heappop(heap)\n return [num for freq, num in heap]", "solution_java": "public int[] topKFrequent(int[] nums, int k) {\n Map count = new HashMap<>();\n for (int n : nums) count.put(n, count.getOrDefault(n, 0) + 1);\n PriorityQueue> heap = \n new PriorityQueue<>((a, b) -> a.getValue() - b.getValue());\n for (Map.Entry e : count.entrySet()) {\n heap.offer(e);\n if (heap.size() > k) heap.poll();\n }\n int[] res = new int[k];\n for (int i = k - 1; i >= 0; i--) res[i] = heap.poll().getKey();\n return res;\n}", "solution_cpp": "vector topKFrequent(vector& nums, int k) {\n unordered_map count;\n for (int n : nums) count[n]++;\n priority_queue, vector>, greater>> heap;\n for (auto& [num, freq] : count) {\n heap.push({freq, num});\n if (heap.size() > k) heap.pop();\n }\n vector res;\n while (!heap.empty()) { res.push_back(heap.top().second); heap.pop(); }\n reverse(res.begin(), res.end());\n return res;\n}", "test_cases": ["nums=[1,1,1,2,2,3], k=2 -> [1,2]", "nums=[1], k=1 -> [1]"], "key_points": ["小顶堆保持大小k", "时间复杂度O(nlogk)"], "tags": ["heap", "medium", "Amazon", "Facebook"]} {"problem_id": "algo_00916", "original_id": "3sum", "title": "三数之和", "category": "two-pointers", "difficulty": "medium", "companies": ["Google", "Amazon"], "description": "给你一个整数数组 nums,判断是否存在三元组满足和为0,返回所有不重复的三元组。", "solution_python": "def threeSum(nums):\n nums.sort()\n result = []\n for i in range(len(nums) - 2):\n if i > 0 and nums[i] == nums[i-1]: continue\n left, right = i + 1, len(nums) - 1\n while left < right:\n total = nums[i] + nums[left] + nums[right]\n if total < 0: left += 1\n elif total > 0: right -= 1\n else:\n result.append([nums[i], nums[left], nums[right]])\n while left < right and nums[left] == nums[left+1]: left += 1\n while left < right and nums[right] == nums[right-1]: right -= 1\n left += 1; right -= 1\n return result", "solution_java": "public List> threeSum(int[] nums) {\n Arrays.sort(nums);\n List> result = new ArrayList<>();\n for (int i = 0; i < nums.length - 2; i++) {\n if (i > 0 && nums[i] == nums[i-1]) continue;\n int left = i + 1, right = nums.length - 1;\n while (left < right) {\n int total = nums[i] + nums[left] + nums[right];\n if (total < 0) left++;\n else if (total > 0) right--;\n else {\n result.add(Arrays.asList(nums[i], nums[left], nums[right]));\n while (left < right && nums[left] == nums[left+1]) left++;\n while (left < right && nums[right] == nums[right-1]) right--;\n left++; right--;\n }\n }\n }\n return result;\n}", "solution_cpp": "vector> threeSum(vector& nums) {\n sort(nums.begin(), nums.end());\n vector> result;\n for (int i = 0; i < nums.size() - 2; i++) {\n if (i > 0 && nums[i] == nums[i-1]) continue;\n int left = i + 1, right = nums.size() - 1;\n while (left < right) {\n int total = nums[i] + nums[left] + nums[right];\n if (total < 0) left++;\n else if (total > 0) right--;\n else {\n result.push_back({nums[i], nums[left], nums[right]});\n while (left < right && nums[left] == nums[left+1]) left++;\n while (left < right && nums[right] == nums[right-1]) right--;\n left++; right--;\n }\n }\n }\n return result;\n}", "test_cases": ["nums=[-1,0,1,2,-1,-4] -> [[-1,-1,2],[-1,0,1]]"], "key_points": ["排序+双指针", "去重是关键"], "tags": ["two-pointers", "medium", "Google", "Amazon"]} {"problem_id": "algo_00917", "original_id": "container-water", "title": "盛最多水的容器", "category": "two-pointers", "difficulty": "medium", "companies": ["Google", "Uber"], "description": "给定一个长度为 n 的整数数组 height,找出其中的两条线,使得它们与 x 轴共同构成的容器可以容纳最多的水。", "solution_python": "def maxArea(height):\n left, right = 0, len(height) - 1\n max_area = 0\n while left < right:\n h = min(height[left], height[right])\n max_area = max(max_area, h * (right - left))\n if height[left] < height[right]: left += 1\n else: right -= 1\n return max_area", "solution_java": "public int maxArea(int[] height) {\n int left = 0, right = height.length - 1, maxArea = 0;\n while (left < right) {\n int h = Math.min(height[left], height[right]);\n maxArea = Math.max(maxArea, h * (right - left));\n if (height[left] < height[right]) left++;\n else right--;\n }\n return maxArea;\n}", "solution_cpp": "int maxArea(vector& height) {\n int left = 0, right = height.size() - 1, maxArea = 0;\n while (left < right) {\n int h = min(height[left], height[right]);\n maxArea = max(maxArea, h * (right - left));\n if (height[left] < height[right]) left++;\n else right--;\n }\n return maxArea;\n}", "test_cases": ["height=[1,8,6,2,5,4,8,3,7] -> 49"], "key_points": ["移动短边指针", "面积=min(h1,h2)*width"], "tags": ["two-pointers", "medium", "Google", "Uber"]} {"problem_id": "algo_00918", "original_id": "min-stack", "title": "最小栈", "category": "stack", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "设计一个支持 push,pop,top 操作,并能在常数时间内检索到最小元素的栈。", "solution_python": "class MinStack:\n def __init__(self):\n self.stack = []\n self.min_stack = []\n def push(self, val):\n self.stack.append(val)\n self.min_stack.append(min(val, self.min_stack[-1] if self.min_stack else val))\n def pop(self):\n self.stack.pop(); self.min_stack.pop()\n def top(self): return self.stack[-1]\n def getMin(self): return self.min_stack[-1]", "solution_java": "class MinStack {\n Stack stack = new Stack<>();\n Stack minStack = new Stack<>();\n public void push(int val) { stack.push(val); minStack.push(Math.min(val, minStack.isEmpty() ? val : minStack.peek())); }\n public void pop() { stack.pop(); minStack.pop(); }\n public int top() { return stack.peek(); }\n public int getMin() { return minStack.peek(); }\n}", "solution_cpp": "class MinStack {\n stack st, minSt;\npublic:\n void push(int val) { st.push(val); minSt.push(min(val, minSt.empty() ? val : minSt.top())); }\n void pop() { st.pop(); minSt.pop(); }\n int top() { return st.top(); }\n int getMin() { return minSt.top(); }\n};", "test_cases": ["push(-2), push(0), push(-3) -> getMin() returns -3"], "key_points": ["辅助栈记录最小值", "O(1)时间获取最小值"], "tags": ["stack", "medium", "Google", "Microsoft"]} {"problem_id": "algo_00919", "original_id": "lru-cache", "title": "LRU缓存", "category": "design", "difficulty": "hard", "companies": ["Google", "Amazon"], "description": "设计和实现一个 LRU(最近最少使用)缓存机制。", "solution_python": "class LRUCache:\n def __init__(self, capacity):\n self.capacity = capacity\n self.cache = {}\n self.order = []\n def get(self, key):\n if key not in self.cache: return -1\n self.order.remove(key); self.order.append(key)\n return self.cache[key]\n def put(self, key, value):\n if key in self.cache:\n self.order.remove(key)\n elif len(self.cache) >= self.capacity:\n del self.cache[self.order.pop(0)]\n self.cache[key] = value; self.order.append(key)", "solution_java": "class LRUCache {\n int capacity;\n LinkedHashMap cache = new LinkedHashMap<>();\n public LRUCache(int cap) { capacity = cap; }\n public int get(int key) { return cache.containsKey(key) ? cache.remove(key) : -1; }\n public void put(int key, int val) {\n if (cache.containsKey(key)) cache.remove(key);\n else if (cache.size() >= capacity) cache.remove(cache.keySet().iterator().next());\n cache.put(key, val);\n }\n}", "solution_cpp": "class LRUCache {\n int cap;\n list> dll;\n unordered_map>::iterator> cache;\npublic:\n LRUCache(int capacity) : cap(capacity) {}\n int get(int key) {\n auto it = cache.find(key);\n if (it == cache.end()) return -1;\n dll.splice(dll.end(), dll, it->second);\n return it->second->second;\n }\n void put(int key, int value) {\n auto it = cache.find(key);\n if (it != cache.end()) dll.erase(it->second);\n else if (cache.size() >= cap) { cache.erase(dll.front().first); dll.pop_front(); }\n dll.push_back({key, value});\n cache[key] = --dll.end();\n }\n};", "test_cases": ["put(1,1), put(2,2), get(1) -> 1"], "key_points": ["HashMap + 双向链表", "O(1)时间操作"], "tags": ["design", "hard", "Google", "Amazon"]} {"problem_id": "algo_00920", "original_id": "num-islands", "title": "岛屿数量", "category": "graph", "difficulty": "medium", "companies": ["Google", "Facebook"], "description": "给你一个由 '1'(陆地)和 '0'(水)组成的二维网格,请你计算网格中岛屿的数量。岛屿总是被水包围,且只能由水平或垂直方向相邻的陆地连接形成。", "solution_python": "def numIslands(grid):\n if not grid: return 0\n rows, cols = len(grid), len(grid[0])\n count = 0\n def dfs(r, c):\n if r < 0 or r >= rows or c < 0 or c >= cols or grid[r][c] != '1': return\n grid[r][c] = '0'\n dfs(r+1, c); dfs(r-1, c); dfs(r, c+1); dfs(r, c-1)\n for r in range(rows):\n for c in range(cols):\n if grid[r][c] == '1': count += 1; dfs(r, c)\n return count", "solution_java": "public int numIslands(char[][] grid) {\n if (grid.length == 0) return 0;\n int count = 0;\n for (int i = 0; i < grid.length; i++)\n for (int j = 0; j < grid[0].length; j++)\n if (grid[i][j] == '1') { count++; dfs(grid, i, j); }\n return count;\n}\nprivate void dfs(char[][] grid, int r, int c) {\n if (r < 0 || r >= grid.length || c < 0 || c >= grid[0].length || grid[r][c] != '1') return;\n grid[r][c] = '0';\n dfs(grid, r+1, c); dfs(grid, r-1, c); dfs(grid, r, c+1); dfs(grid, r, c-1);\n}", "solution_cpp": "int numIslands(vector>& grid) {\n if (grid.empty()) return 0;\n int count = 0;\n for (int i = 0; i < grid.size(); i++)\n for (int j = 0; j < grid[0].size(); j++)\n if (grid[i][j] == '1') { count++; dfs(grid, i, j); }\n return count;\n}\nvoid dfs(vector>& grid, int r, int c) {\n if (r < 0 || r >= grid.size() || c < 0 || c >= grid[0].size() || grid[r][c] != '1') return;\n grid[r][c] = '0';\n dfs(grid, r+1, c); dfs(grid, r-1, c); dfs(grid, r, c+1); dfs(grid, r, c-1);\n}", "test_cases": ["grid=[[1,1,1,1,0],[1,1,0,1,0],[1,1,0,0,0],[0,0,0,0,0]] -> 1"], "key_points": ["DFS/BFS遍历", "访问后标记为0避免重复"], "tags": ["graph", "medium", "Google", "Facebook"]} {"problem_id": "algo_00921", "original_id": "two-sum", "title": "两数之和", "category": "array", "difficulty": "easy", "companies": ["Amazon", "Google"], "description": "给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那两个整数,并返回他们的数组下标。", "solution_python": "def twoSum(nums, target):\n hashmap = {}\n for i, num in enumerate(nums):\n complement = target - num\n if complement in hashmap:\n return [hashmap[complement], i]\n hashmap[num] = i\n return []", "solution_java": "public int[] twoSum(int[] nums, int target) {\n Map map = new HashMap<>();\n for (int i = 0; i < nums.length; i++) {\n int complement = target - nums[i];\n if (map.containsKey(complement)) return new int[]{map.get(complement), i};\n map.put(nums[i], i);\n }\n return new int[]{};\n}", "solution_cpp": "vector twoSum(vector& nums, int target) {\n unordered_map m;\n for (int i = 0; i < nums.size(); i++) {\n if (m.count(target - nums[i])) return {m[target - nums[i]], i};\n m[nums[i]] = i;\n }\n return {};\n}", "test_cases": ["nums=[2,7,11,15], target=9 -> [0,1]", "nums=[3,2,4], target=6 -> [1,2]"], "key_points": ["哈希表一次遍历", "空间换时间"], "tags": ["array", "easy", "Amazon", "Google"]} {"problem_id": "algo_00922", "original_id": "merge-sorted", "title": "合并两个有序数组", "category": "array", "difficulty": "easy", "companies": ["Microsoft", "Uber"], "description": "给你两个按非递减顺序排列的整数数组 nums1 和 nums2,另有两个整数 m 和 n,分别表示 nums1 和 nums2 中的元素数目。请你合并 nums2 到 nums1 中。", "solution_python": "def merge(nums1, m, nums2, n):\n p1, p2, p = m-1, n-1, m+n-1\n while p1 >= 0 and p2 >= 0:\n if nums1[p1] > nums2[p2]: nums1[p] = nums1[p1]; p1 -= 1\n else: nums1[p] = nums2[p2]; p2 -= 1\n p -= 1\n while p2 >= 0: nums1[p] = nums2[p2]; p2 -= 1; p -= 1", "solution_java": "public void merge(int[] nums1, int m, int[] nums2, int n) {\n int p1 = m-1, p2 = n-1, p = m+n-1;\n while (p1 >= 0 && p2 >= 0) {\n nums1[p--] = nums1[p1] > nums2[p2] ? nums1[p1--] : nums2[p2--];\n }\n while (p2 >= 0) nums1[p--] = nums2[p2--];\n}", "solution_cpp": "void merge(vector& nums1, int m, vector& nums2, int n) {\n int p1 = m-1, p2 = n-1, p = m+n-1;\n while (p1 >= 0 && p2 >= 0) nums1[p--] = nums1[p1] > nums2[p2] ? nums1[p1--] : nums2[p2--];\n while (p2 >= 0) nums1[p--] = nums2[p2--];\n}", "test_cases": ["nums1=[1,2,3], m=3, nums2=[2,5,6], n=3 -> [1,2,2,3,5,6]", "nums1=[], m=0, nums2=[1], n=1 -> [1]"], "key_points": ["从后往前合并", "三指针技巧"], "tags": ["array", "easy", "Microsoft", "Uber"]} {"problem_id": "algo_00923", "original_id": "max-subarray", "title": "最大子数组和", "category": "array", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "给你一个整数数组 nums ,请你找出一个具有最大和的连续子数组,返回其最大和。", "solution_python": "def maxSubArray(nums):\n max_sum = current = nums[0]\n for num in nums[1:]:\n current = max(num, current + num)\n max_sum = max(max_sum, current)\n return max_sum", "solution_java": "public int maxSubArray(int[] nums) {\n int maxSum = nums[0], curr = nums[0];\n for (int i = 1; i < nums.length; i++) {\n curr = Math.max(nums[i], curr + nums[i]);\n maxSum = Math.max(maxSum, curr);\n }\n return maxSum;\n}", "solution_cpp": "int maxSubArray(vector& nums) {\n int maxSum = nums[0], curr = nums[0];\n for (int i = 1; i < nums.size(); i++) {\n curr = max(nums[i], curr + nums[i]);\n maxSum = max(maxSum, curr);\n }\n return maxSum;\n}", "test_cases": ["nums=[-2,1,-3,4,-1,2,1,-5,4] -> 6", "nums=[1] -> 1"], "key_points": ["Kadane算法", "动态规划基础题"], "tags": ["array", "medium", "Google", "Microsoft"]} {"problem_id": "algo_00924", "original_id": "valid-parentheses", "title": "有效的括号", "category": "string", "difficulty": "easy", "companies": ["Google", "Uber"], "description": "给定一个只包括 '(',')','{','}','[',']' 的字符串 s,判断字符串是否有效。", "solution_python": "def isValid(s):\n stack = []\n mapping = {')': '(', ']': '[', '}': '{'}\n for c in s:\n if c in mapping:\n if not stack or stack[-1] != mapping[c]: return False\n stack.pop()\n else: stack.append(c)\n return not stack", "solution_java": "public boolean isValid(String s) {\n Stack stack = new Stack<>();\n Map map = Map.of(')', '(', ']', '[', '}', '{');\n for (char c : s.toCharArray()) {\n if (map.containsValue(c)) stack.push(c);\n else if (!stack.isEmpty() && stack.pop() != map.get(c)) return false;\n }\n return stack.isEmpty();\n}", "solution_cpp": "bool isValid(string s) {\n stack st;\n unordered_map m = {{')','('},{']','['},{'}','{'}};\n for (char c : s) {\n if (m.find(c) == m.end()) st.push(c);\n else if (st.empty() || st.top() != m[c]) return false;\n else st.pop();\n }\n return st.empty();\n}", "test_cases": ["s=\"()\" -> true", "s=\"()[]{}\" -> true", "s=\"(]\" -> false"], "key_points": ["栈匹配法", "注意空栈边界"], "tags": ["string", "easy", "Google", "Uber"]} {"problem_id": "algo_00925", "original_id": "longest-palindrome", "title": "最长回文子串", "category": "string", "difficulty": "medium", "companies": ["Google", "Amazon"], "description": "给你一个字符串 s,找到 s 中最长的回文子串。", "solution_python": "def longestPalindrome(s):\n def expand(l, r):\n while l >= 0 and r < len(s) and s[l] == s[r]: l -= 1; r += 1\n return l + 1, r - 1\n start = end = 0\n for i in range(len(s)):\n l1, r1 = expand(i, i)\n l2, r2 = expand(i, i + 1)\n if r1 - l1 > end - start: start, end = l1, r1\n if r2 - l2 > end - start: start, end = l2, r2\n return s[start:end+1]", "solution_java": "public String longestPalindrome(String s) {\n int start = 0, end = 0;\n for (int i = 0; i < s.length(); i++) {\n int len1 = expand(s, i, i), len2 = expand(s, i, i+1);\n int len = Math.max(len1, len2);\n if (len > end - start) { start = i - (len-1)/2; end = i + len/2; }\n }\n return s.substring(start, end + 1);\n}\nprivate int expand(String s, int l, int r) {\n while (l >= 0 && r < s.length() && s.charAt(l) == s.charAt(r)) { l--; r++; }\n return r - l - 1;\n}", "solution_cpp": "string longestPalindrome(string s) {\n int start = 0, end = 0;\n for (int i = 0; i < s.size(); i++) {\n int len1 = expand(s, i, i), len2 = expand(s, i, i+1);\n if (max(len1, len2) > end - start) { start = i - (max(len1,len2)-1)/2; end = i + max(len1,len2)/2; }\n }\n return s.substr(start, end - start + 1);\n}", "test_cases": ["s=\"babad\" -> bab或aba", "s=\"cbbd\" -> bb"], "key_points": ["中心扩展法", "处理奇偶长度"], "tags": ["string", "medium", "Google", "Amazon"]} {"problem_id": "algo_00926", "original_id": "reverse-list", "title": "反转链表", "category": "linkedlist", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "给你单链表的头节点 head,请你反转链表,并返回反转后的链表。", "solution_python": "def reverseList(head):\n prev = None\n curr = head\n while curr:\n nxt = curr.next\n curr.next = prev\n prev = curr\n curr = nxt\n return prev", "solution_java": "public ListNode reverseList(ListNode head) {\n ListNode prev = null, curr = head;\n while (curr != null) {\n ListNode next = curr.next;\n curr.next = prev;\n prev = curr;\n curr = next;\n }\n return prev;\n}", "solution_cpp": "ListNode* reverseList(ListNode* head) {\n ListNode* prev = nullptr, *curr = head;\n while (curr) {\n ListNode* next = curr->next;\n curr->next = prev;\n prev = curr;\n curr = next;\n }\n return prev;\n}", "test_cases": ["head=[1,2,3,4,5] -> [5,4,3,2,1]", "head=[1,2] -> [2,1]"], "key_points": ["迭代法 O(1)空间", "递归法 O(n)空间"], "tags": ["linkedlist", "medium", "Google", "Microsoft"]} {"problem_id": "algo_00927", "original_id": "middle-node", "title": "链表的中间结点", "category": "linkedlist", "difficulty": "easy", "companies": ["Amazon", "Facebook"], "description": "给你单链表的头节点 head,请你找出并返回链表的中间结点。如果有两个中间结点,则返回第二个中间结点。", "solution_python": "def middleNode(head):\n slow = fast = head\n while fast and fast.next:\n slow = slow.next\n fast = fast.next.next\n return slow", "solution_java": "public ListNode middleNode(ListNode head) {\n ListNode slow = head, fast = head;\n while (fast != null && fast.next != null) {\n slow = slow.next;\n fast = fast.next.next;\n }\n return slow;\n}", "solution_cpp": "ListNode* middleNode(ListNode* head) {\n ListNode* slow = head, *fast = head;\n while (fast && fast->next) { slow = slow->next; fast = fast->next->next; }\n return slow;\n}", "test_cases": ["head=[1,2,3,4,5] -> 3", "head=[1,2,3,4,5,6] -> 4"], "key_points": ["快慢指针", "O(n)时间O(1)空间"], "tags": ["linkedlist", "easy", "Amazon", "Facebook"]} {"problem_id": "algo_00928", "original_id": "max-depth", "title": "二叉树的最大深度", "category": "tree", "difficulty": "easy", "companies": ["Microsoft", "Apple"], "description": "给定一个二叉树 root,返回其最大深度。", "solution_python": "def maxDepth(root):\n if not root: return 0\n return max(maxDepth(root.left), maxDepth(root.right)) + 1", "solution_java": "public int maxDepth(TreeNode root) {\n if (root == null) return 0;\n return Math.max(maxDepth(root.left), maxDepth(root.right)) + 1;\n}", "solution_cpp": "int maxDepth(TreeNode* root) {\n if (!root) return 0;\n return max(maxDepth(root->left), maxDepth(root->right)) + 1;\n}", "test_cases": ["root=[3,9,20,null,null,15,7] -> 3", "root=[1,null,2] -> 2"], "key_points": ["DFS递归", "层序遍历也可"], "tags": ["tree", "easy", "Microsoft", "Apple"]} {"problem_id": "algo_00929", "original_id": "inorder-traversal", "title": "二叉树的中序遍历", "category": "tree", "difficulty": "easy", "companies": ["Google", "Microsoft"], "description": "给定一个二叉树的根节点 root,返回它的中序遍历结果。", "solution_python": "def inorderTraversal(root):\n result = []\n def dfs(node):\n if node:\n dfs(node.left)\n result.append(node.val)\n dfs(node.right)\n dfs(root)\n return result", "solution_java": "public List inorderTraversal(TreeNode root) {\n List res = new ArrayList<>();\n dfs(root, res);\n return res;\n}\nprivate void dfs(TreeNode node, List res) {\n if (node == null) return;\n dfs(node.left, res); res.add(node.val); dfs(node.right, res);\n}", "solution_cpp": "vector inorderTraversal(TreeNode* root) {\n vector res;\n dfs(root, res);\n return res;\n}\nvoid dfs(TreeNode* node, vector& res) {\n if (!node) return;\n dfs(node->left, res); res.push_back(node->val); dfs(node->right, res);\n}", "test_cases": ["root=[1,null,2,3] -> [1,3,2]", "root=[] -> []"], "key_points": ["左-根-右顺序", "递归最简洁"], "tags": ["tree", "easy", "Google", "Microsoft"]} {"problem_id": "algo_00930", "original_id": "binary-search", "title": "二分查找", "category": "binarysearch", "difficulty": "easy", "companies": ["Google", "Amazon"], "description": "给定一个 n 个元素有序的(升序)整型数组 nums 和一个目标值 target,写一个函数搜索 nums 中的 target,如果目标值存在返回下标,否则返回 -1。", "solution_python": "def search(nums, target):\n left, right = 0, len(nums) - 1\n while left <= right:\n mid = (left + right) // 2\n if nums[mid] == target: return mid\n elif nums[mid] < target: left = mid + 1\n else: right = mid - 1\n return -1", "solution_java": "public int search(int[] nums, int target) {\n int left = 0, right = nums.length - 1;\n while (left <= right) {\n int mid = left + (right - left) / 2;\n if (nums[mid] == target) return mid;\n else if (nums[mid] < target) left = mid + 1;\n else right = mid - 1;\n }\n return -1;\n}", "solution_cpp": "int search(vector& nums, int target) {\n int left = 0, right = nums.size() - 1;\n while (left <= right) {\n int mid = left + (right - left) / 2;\n if (nums[mid] == target) return mid;\n else if (nums[mid] < target) left = mid + 1;\n else right = mid - 1;\n }\n return -1;\n}", "test_cases": ["nums=[-1,0,3,5,9,12], target=9 -> 4", "nums=[-1,0,3,5,9,12], target=2 -> -1"], "key_points": ["标准模板", "注意防溢出写法"], "tags": ["binarysearch", "easy", "Google", "Amazon"]} {"problem_id": "algo_00931", "original_id": "climbing-stairs", "title": "爬楼梯", "category": "dp", "difficulty": "easy", "companies": ["Amazon", "Google"], "description": "假设你正在爬楼梯。需要 n 阶你才能到达楼顶。每次你可以爬 1 或 2 个台阶。你有多少种不同的方法可以爬到楼顶?", "solution_python": "def climbStairs(n):\n if n <= 2: return n\n a, b = 1, 2\n for _ in range(3, n+1):\n a, b = b, a + b\n return b", "solution_java": "public int climbStairs(int n) {\n if (n <= 2) return n;\n int a = 1, b = 2;\n for (int i = 3; i <= n; i++) { int temp = a + b; a = b; b = temp; }\n return b;\n}", "solution_cpp": "int climbStairs(int n) {\n if (n <= 2) return n;\n int a = 1, b = 2;\n for (int i = 3; i <= n; i++) { int temp = a + b; a = b; b = temp; }\n return b;\n}", "test_cases": ["n=2 -> 2", "n=3 -> 3", "n=5 -> 8"], "key_points": ["斐波那契数列", "滚动数组优化空间"], "tags": ["dp", "easy", "Amazon", "Google"]} {"problem_id": "algo_00932", "original_id": "coin-change", "title": "零钱兑换", "category": "dp", "difficulty": "medium", "companies": ["Google", "Amazon"], "description": "给你一个整数数组 coins 表示不同面额的硬币,以及一个整数 amount 表示总金额。计算并返回可以凑成总金额所需的最少的硬币个数。如果没有任何一种硬币组合能组成总金额,返回 -1。", "solution_python": "def coinChange(coins, amount):\n dp = [float('inf')] * (amount + 1)\n dp[0] = 0\n for coin in coins:\n for x in range(coin, amount + 1):\n dp[x] = min(dp[x], dp[x - coin] + 1)\n return dp[amount] if dp[amount] != float('inf') else -1", "solution_java": "public int coinChange(int[] coins, int amount) {\n int[] dp = new int[amount + 1];\n Arrays.fill(dp, amount + 1);\n dp[0] = 0;\n for (int coin : coins) {\n for (int x = coin; x <= amount; x++) {\n dp[x] = Math.min(dp[x], dp[x - coin] + 1);\n }\n }\n return dp[amount] > amount ? -1 : dp[amount];\n}", "solution_cpp": "int coinChange(vector& coins, int amount) {\n vector dp(amount + 1, amount + 1);\n dp[0] = 0;\n for (int coin : coins) {\n for (int x = coin; x <= amount; x++) {\n dp[x] = min(dp[x], dp[x - coin] + 1);\n }\n }\n return dp[amount] > amount ? -1 : dp[amount];\n}", "test_cases": ["coins=[1,2,5], amount=11 -> 3", "coins=[2], amount=3 -> -1"], "key_points": ["完全背包问题", "dp[x] = min(dp[x-coin]+1)"], "tags": ["dp", "medium", "Google", "Amazon"]} {"problem_id": "algo_00933", "original_id": "subsets", "title": "子集", "category": "backtracking", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "给你一个整数数组 nums ,数组中的元素 互不相同 。返回该数组所有可能的子集(幂集)。", "solution_python": "def subsets(nums):\n result = []\n def backtrack(start, path):\n result.append(path[:])\n for i in range(start, len(nums)):\n path.append(nums[i])\n backtrack(i + 1, path)\n path.pop()\n backtrack(0, [])\n return result", "solution_java": "public List> subsets(int[] nums) {\n List> result = new ArrayList<>();\n backtrack(nums, 0, new ArrayList<>(), result);\n return result;\n}\nprivate void backtrack(int[] nums, int start, List path, List> result) {\n result.add(new ArrayList<>(path));\n for (int i = start; i < nums.length; i++) {\n path.add(nums[i]);\n backtrack(nums, i + 1, path, result);\n path.remove(path.size() - 1);\n }\n}", "solution_cpp": "vector> subsets(vector& nums) {\n vector> result;\n vector path;\n backtrack(nums, 0, path, result);\n return result;\n}\nvoid backtrack(vector& nums, int start, vector& path, vector>& result) {\n result.push_back(path);\n for (int i = start; i < nums.size(); i++) {\n path.push_back(nums[i]);\n backtrack(nums, i + 1, path, result);\n path.pop_back();\n }\n}", "test_cases": ["nums=[1,2,3] -> [[],[1],[2],[1,2],[3],[1,3],[2,3],[1,2,3]]"], "key_points": ["选或不选", "DFS遍历子集树"], "tags": ["backtracking", "medium", "Google", "Microsoft"]} {"problem_id": "algo_00934", "original_id": "permutations", "title": "全排列", "category": "backtracking", "difficulty": "medium", "companies": ["Google", "Facebook"], "description": "给定一个不含重复数字的数组 nums,返回其所有可能的全排列。", "solution_python": "def permute(nums):\n result = []\n def backtrack(path, used):\n if len(path) == len(nums):\n result.append(path[:])\n return\n for i in range(len(nums)):\n if used[i]: continue\n used[i] = True\n path.append(nums[i])\n backtrack(path, used)\n path.pop()\n used[i] = False\n backtrack([], [False]*len(nums))\n return result", "solution_java": "public List> permute(int[] nums) {\n List> result = new ArrayList<>();\n boolean[] used = new boolean[nums.length];\n backtrack(nums, used, new ArrayList<>(), result);\n return result;\n}\nprivate void backtrack(int[] nums, boolean[] used, List path, List> result) {\n if (path.size() == nums.length) { result.add(new ArrayList<>(path)); return; }\n for (int i = 0; i < nums.length; i++) {\n if (used[i]) continue;\n used[i] = true;\n path.add(nums[i]);\n backtrack(nums, used, path, result);\n path.remove(path.size() - 1);\n used[i] = false;\n }\n}", "solution_cpp": "vector> permute(vector& nums) {\n vector> result;\n vector used(nums.size(), false);\n vector path;\n backtrack(nums, used, path, result);\n return result;\n}\nvoid backtrack(vector& nums, vector& used, vector& path, vector>& result) {\n if (path.size() == nums.size()) { result.push_back(path); return; }\n for (int i = 0; i < nums.size(); i++) {\n if (used[i]) continue;\n used[i] = true;\n path.push_back(nums[i]);\n backtrack(nums, used, path, result);\n path.pop_back();\n used[i] = false;\n }\n}", "test_cases": ["nums=[1,2,3] -> [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]"], "key_points": ["标记已使用元素", "回溯经典模板"], "tags": ["backtracking", "medium", "Google", "Facebook"]} {"problem_id": "algo_00935", "original_id": "top-k-frequent", "title": "前K个高频元素", "category": "heap", "difficulty": "medium", "companies": ["Amazon", "Facebook"], "description": "给你一个整数数组 nums 和一个整数 k,请你返回其中出现频率前 k 高的元素。", "solution_python": "import heapq\nfrom collections import Counter\ndef topKFrequent(nums, k):\n count = Counter(nums)\n heap = []\n for num, freq in count.items():\n heapq.heappush(heap, (freq, num))\n if len(heap) > k: heapq.heappop(heap)\n return [num for freq, num in heap]", "solution_java": "public int[] topKFrequent(int[] nums, int k) {\n Map count = new HashMap<>();\n for (int n : nums) count.put(n, count.getOrDefault(n, 0) + 1);\n PriorityQueue> heap = \n new PriorityQueue<>((a, b) -> a.getValue() - b.getValue());\n for (Map.Entry e : count.entrySet()) {\n heap.offer(e);\n if (heap.size() > k) heap.poll();\n }\n int[] res = new int[k];\n for (int i = k - 1; i >= 0; i--) res[i] = heap.poll().getKey();\n return res;\n}", "solution_cpp": "vector topKFrequent(vector& nums, int k) {\n unordered_map count;\n for (int n : nums) count[n]++;\n priority_queue, vector>, greater>> heap;\n for (auto& [num, freq] : count) {\n heap.push({freq, num});\n if (heap.size() > k) heap.pop();\n }\n vector res;\n while (!heap.empty()) { res.push_back(heap.top().second); heap.pop(); }\n reverse(res.begin(), res.end());\n return res;\n}", "test_cases": ["nums=[1,1,1,2,2,3], k=2 -> [1,2]", "nums=[1], k=1 -> [1]"], "key_points": ["小顶堆保持大小k", "时间复杂度O(nlogk)"], "tags": ["heap", "medium", "Amazon", "Facebook"]} {"problem_id": "algo_00936", "original_id": "3sum", "title": "三数之和", "category": "two-pointers", "difficulty": "medium", "companies": ["Google", "Amazon"], "description": "给你一个整数数组 nums,判断是否存在三元组满足和为0,返回所有不重复的三元组。", "solution_python": "def threeSum(nums):\n nums.sort()\n result = []\n for i in range(len(nums) - 2):\n if i > 0 and nums[i] == nums[i-1]: continue\n left, right = i + 1, len(nums) - 1\n while left < right:\n total = nums[i] + nums[left] + nums[right]\n if total < 0: left += 1\n elif total > 0: right -= 1\n else:\n result.append([nums[i], nums[left], nums[right]])\n while left < right and nums[left] == nums[left+1]: left += 1\n while left < right and nums[right] == nums[right-1]: right -= 1\n left += 1; right -= 1\n return result", "solution_java": "public List> threeSum(int[] nums) {\n Arrays.sort(nums);\n List> result = new ArrayList<>();\n for (int i = 0; i < nums.length - 2; i++) {\n if (i > 0 && nums[i] == nums[i-1]) continue;\n int left = i + 1, right = nums.length - 1;\n while (left < right) {\n int total = nums[i] + nums[left] + nums[right];\n if (total < 0) left++;\n else if (total > 0) right--;\n else {\n result.add(Arrays.asList(nums[i], nums[left], nums[right]));\n while (left < right && nums[left] == nums[left+1]) left++;\n while (left < right && nums[right] == nums[right-1]) right--;\n left++; right--;\n }\n }\n }\n return result;\n}", "solution_cpp": "vector> threeSum(vector& nums) {\n sort(nums.begin(), nums.end());\n vector> result;\n for (int i = 0; i < nums.size() - 2; i++) {\n if (i > 0 && nums[i] == nums[i-1]) continue;\n int left = i + 1, right = nums.size() - 1;\n while (left < right) {\n int total = nums[i] + nums[left] + nums[right];\n if (total < 0) left++;\n else if (total > 0) right--;\n else {\n result.push_back({nums[i], nums[left], nums[right]});\n while (left < right && nums[left] == nums[left+1]) left++;\n while (left < right && nums[right] == nums[right-1]) right--;\n left++; right--;\n }\n }\n }\n return result;\n}", "test_cases": ["nums=[-1,0,1,2,-1,-4] -> [[-1,-1,2],[-1,0,1]]"], "key_points": ["排序+双指针", "去重是关键"], "tags": ["two-pointers", "medium", "Google", "Amazon"]} {"problem_id": "algo_00937", "original_id": "container-water", "title": "盛最多水的容器", "category": "two-pointers", "difficulty": "medium", "companies": ["Google", "Uber"], "description": "给定一个长度为 n 的整数数组 height,找出其中的两条线,使得它们与 x 轴共同构成的容器可以容纳最多的水。", "solution_python": "def maxArea(height):\n left, right = 0, len(height) - 1\n max_area = 0\n while left < right:\n h = min(height[left], height[right])\n max_area = max(max_area, h * (right - left))\n if height[left] < height[right]: left += 1\n else: right -= 1\n return max_area", "solution_java": "public int maxArea(int[] height) {\n int left = 0, right = height.length - 1, maxArea = 0;\n while (left < right) {\n int h = Math.min(height[left], height[right]);\n maxArea = Math.max(maxArea, h * (right - left));\n if (height[left] < height[right]) left++;\n else right--;\n }\n return maxArea;\n}", "solution_cpp": "int maxArea(vector& height) {\n int left = 0, right = height.size() - 1, maxArea = 0;\n while (left < right) {\n int h = min(height[left], height[right]);\n maxArea = max(maxArea, h * (right - left));\n if (height[left] < height[right]) left++;\n else right--;\n }\n return maxArea;\n}", "test_cases": ["height=[1,8,6,2,5,4,8,3,7] -> 49"], "key_points": ["移动短边指针", "面积=min(h1,h2)*width"], "tags": ["two-pointers", "medium", "Google", "Uber"]} {"problem_id": "algo_00938", "original_id": "min-stack", "title": "最小栈", "category": "stack", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "设计一个支持 push,pop,top 操作,并能在常数时间内检索到最小元素的栈。", "solution_python": "class MinStack:\n def __init__(self):\n self.stack = []\n self.min_stack = []\n def push(self, val):\n self.stack.append(val)\n self.min_stack.append(min(val, self.min_stack[-1] if self.min_stack else val))\n def pop(self):\n self.stack.pop(); self.min_stack.pop()\n def top(self): return self.stack[-1]\n def getMin(self): return self.min_stack[-1]", "solution_java": "class MinStack {\n Stack stack = new Stack<>();\n Stack minStack = new Stack<>();\n public void push(int val) { stack.push(val); minStack.push(Math.min(val, minStack.isEmpty() ? val : minStack.peek())); }\n public void pop() { stack.pop(); minStack.pop(); }\n public int top() { return stack.peek(); }\n public int getMin() { return minStack.peek(); }\n}", "solution_cpp": "class MinStack {\n stack st, minSt;\npublic:\n void push(int val) { st.push(val); minSt.push(min(val, minSt.empty() ? val : minSt.top())); }\n void pop() { st.pop(); minSt.pop(); }\n int top() { return st.top(); }\n int getMin() { return minSt.top(); }\n};", "test_cases": ["push(-2), push(0), push(-3) -> getMin() returns -3"], "key_points": ["辅助栈记录最小值", "O(1)时间获取最小值"], "tags": ["stack", "medium", "Google", "Microsoft"]} {"problem_id": "algo_00939", "original_id": "lru-cache", "title": "LRU缓存", "category": "design", "difficulty": "hard", "companies": ["Google", "Amazon"], "description": "设计和实现一个 LRU(最近最少使用)缓存机制。", "solution_python": "class LRUCache:\n def __init__(self, capacity):\n self.capacity = capacity\n self.cache = {}\n self.order = []\n def get(self, key):\n if key not in self.cache: return -1\n self.order.remove(key); self.order.append(key)\n return self.cache[key]\n def put(self, key, value):\n if key in self.cache:\n self.order.remove(key)\n elif len(self.cache) >= self.capacity:\n del self.cache[self.order.pop(0)]\n self.cache[key] = value; self.order.append(key)", "solution_java": "class LRUCache {\n int capacity;\n LinkedHashMap cache = new LinkedHashMap<>();\n public LRUCache(int cap) { capacity = cap; }\n public int get(int key) { return cache.containsKey(key) ? cache.remove(key) : -1; }\n public void put(int key, int val) {\n if (cache.containsKey(key)) cache.remove(key);\n else if (cache.size() >= capacity) cache.remove(cache.keySet().iterator().next());\n cache.put(key, val);\n }\n}", "solution_cpp": "class LRUCache {\n int cap;\n list> dll;\n unordered_map>::iterator> cache;\npublic:\n LRUCache(int capacity) : cap(capacity) {}\n int get(int key) {\n auto it = cache.find(key);\n if (it == cache.end()) return -1;\n dll.splice(dll.end(), dll, it->second);\n return it->second->second;\n }\n void put(int key, int value) {\n auto it = cache.find(key);\n if (it != cache.end()) dll.erase(it->second);\n else if (cache.size() >= cap) { cache.erase(dll.front().first); dll.pop_front(); }\n dll.push_back({key, value});\n cache[key] = --dll.end();\n }\n};", "test_cases": ["put(1,1), put(2,2), get(1) -> 1"], "key_points": ["HashMap + 双向链表", "O(1)时间操作"], "tags": ["design", "hard", "Google", "Amazon"]} {"problem_id": "algo_00940", "original_id": "num-islands", "title": "岛屿数量", "category": "graph", "difficulty": "medium", "companies": ["Google", "Facebook"], "description": "给你一个由 '1'(陆地)和 '0'(水)组成的二维网格,请你计算网格中岛屿的数量。岛屿总是被水包围,且只能由水平或垂直方向相邻的陆地连接形成。", "solution_python": "def numIslands(grid):\n if not grid: return 0\n rows, cols = len(grid), len(grid[0])\n count = 0\n def dfs(r, c):\n if r < 0 or r >= rows or c < 0 or c >= cols or grid[r][c] != '1': return\n grid[r][c] = '0'\n dfs(r+1, c); dfs(r-1, c); dfs(r, c+1); dfs(r, c-1)\n for r in range(rows):\n for c in range(cols):\n if grid[r][c] == '1': count += 1; dfs(r, c)\n return count", "solution_java": "public int numIslands(char[][] grid) {\n if (grid.length == 0) return 0;\n int count = 0;\n for (int i = 0; i < grid.length; i++)\n for (int j = 0; j < grid[0].length; j++)\n if (grid[i][j] == '1') { count++; dfs(grid, i, j); }\n return count;\n}\nprivate void dfs(char[][] grid, int r, int c) {\n if (r < 0 || r >= grid.length || c < 0 || c >= grid[0].length || grid[r][c] != '1') return;\n grid[r][c] = '0';\n dfs(grid, r+1, c); dfs(grid, r-1, c); dfs(grid, r, c+1); dfs(grid, r, c-1);\n}", "solution_cpp": "int numIslands(vector>& grid) {\n if (grid.empty()) return 0;\n int count = 0;\n for (int i = 0; i < grid.size(); i++)\n for (int j = 0; j < grid[0].size(); j++)\n if (grid[i][j] == '1') { count++; dfs(grid, i, j); }\n return count;\n}\nvoid dfs(vector>& grid, int r, int c) {\n if (r < 0 || r >= grid.size() || c < 0 || c >= grid[0].size() || grid[r][c] != '1') return;\n grid[r][c] = '0';\n dfs(grid, r+1, c); dfs(grid, r-1, c); dfs(grid, r, c+1); dfs(grid, r, c-1);\n}", "test_cases": ["grid=[[1,1,1,1,0],[1,1,0,1,0],[1,1,0,0,0],[0,0,0,0,0]] -> 1"], "key_points": ["DFS/BFS遍历", "访问后标记为0避免重复"], "tags": ["graph", "medium", "Google", "Facebook"]} {"problem_id": "algo_00941", "original_id": "two-sum", "title": "两数之和", "category": "array", "difficulty": "easy", "companies": ["Amazon", "Google"], "description": "给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那两个整数,并返回他们的数组下标。", "solution_python": "def twoSum(nums, target):\n hashmap = {}\n for i, num in enumerate(nums):\n complement = target - num\n if complement in hashmap:\n return [hashmap[complement], i]\n hashmap[num] = i\n return []", "solution_java": "public int[] twoSum(int[] nums, int target) {\n Map map = new HashMap<>();\n for (int i = 0; i < nums.length; i++) {\n int complement = target - nums[i];\n if (map.containsKey(complement)) return new int[]{map.get(complement), i};\n map.put(nums[i], i);\n }\n return new int[]{};\n}", "solution_cpp": "vector twoSum(vector& nums, int target) {\n unordered_map m;\n for (int i = 0; i < nums.size(); i++) {\n if (m.count(target - nums[i])) return {m[target - nums[i]], i};\n m[nums[i]] = i;\n }\n return {};\n}", "test_cases": ["nums=[2,7,11,15], target=9 -> [0,1]", "nums=[3,2,4], target=6 -> [1,2]"], "key_points": ["哈希表一次遍历", "空间换时间"], "tags": ["array", "easy", "Amazon", "Google"]} {"problem_id": "algo_00942", "original_id": "merge-sorted", "title": "合并两个有序数组", "category": "array", "difficulty": "easy", "companies": ["Microsoft", "Uber"], "description": "给你两个按非递减顺序排列的整数数组 nums1 和 nums2,另有两个整数 m 和 n,分别表示 nums1 和 nums2 中的元素数目。请你合并 nums2 到 nums1 中。", "solution_python": "def merge(nums1, m, nums2, n):\n p1, p2, p = m-1, n-1, m+n-1\n while p1 >= 0 and p2 >= 0:\n if nums1[p1] > nums2[p2]: nums1[p] = nums1[p1]; p1 -= 1\n else: nums1[p] = nums2[p2]; p2 -= 1\n p -= 1\n while p2 >= 0: nums1[p] = nums2[p2]; p2 -= 1; p -= 1", "solution_java": "public void merge(int[] nums1, int m, int[] nums2, int n) {\n int p1 = m-1, p2 = n-1, p = m+n-1;\n while (p1 >= 0 && p2 >= 0) {\n nums1[p--] = nums1[p1] > nums2[p2] ? nums1[p1--] : nums2[p2--];\n }\n while (p2 >= 0) nums1[p--] = nums2[p2--];\n}", "solution_cpp": "void merge(vector& nums1, int m, vector& nums2, int n) {\n int p1 = m-1, p2 = n-1, p = m+n-1;\n while (p1 >= 0 && p2 >= 0) nums1[p--] = nums1[p1] > nums2[p2] ? nums1[p1--] : nums2[p2--];\n while (p2 >= 0) nums1[p--] = nums2[p2--];\n}", "test_cases": ["nums1=[1,2,3], m=3, nums2=[2,5,6], n=3 -> [1,2,2,3,5,6]", "nums1=[], m=0, nums2=[1], n=1 -> [1]"], "key_points": ["从后往前合并", "三指针技巧"], "tags": ["array", "easy", "Microsoft", "Uber"]} {"problem_id": "algo_00943", "original_id": "max-subarray", "title": "最大子数组和", "category": "array", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "给你一个整数数组 nums ,请你找出一个具有最大和的连续子数组,返回其最大和。", "solution_python": "def maxSubArray(nums):\n max_sum = current = nums[0]\n for num in nums[1:]:\n current = max(num, current + num)\n max_sum = max(max_sum, current)\n return max_sum", "solution_java": "public int maxSubArray(int[] nums) {\n int maxSum = nums[0], curr = nums[0];\n for (int i = 1; i < nums.length; i++) {\n curr = Math.max(nums[i], curr + nums[i]);\n maxSum = Math.max(maxSum, curr);\n }\n return maxSum;\n}", "solution_cpp": "int maxSubArray(vector& nums) {\n int maxSum = nums[0], curr = nums[0];\n for (int i = 1; i < nums.size(); i++) {\n curr = max(nums[i], curr + nums[i]);\n maxSum = max(maxSum, curr);\n }\n return maxSum;\n}", "test_cases": ["nums=[-2,1,-3,4,-1,2,1,-5,4] -> 6", "nums=[1] -> 1"], "key_points": ["Kadane算法", "动态规划基础题"], "tags": ["array", "medium", "Google", "Microsoft"]} {"problem_id": "algo_00944", "original_id": "valid-parentheses", "title": "有效的括号", "category": "string", "difficulty": "easy", "companies": ["Google", "Uber"], "description": "给定一个只包括 '(',')','{','}','[',']' 的字符串 s,判断字符串是否有效。", "solution_python": "def isValid(s):\n stack = []\n mapping = {')': '(', ']': '[', '}': '{'}\n for c in s:\n if c in mapping:\n if not stack or stack[-1] != mapping[c]: return False\n stack.pop()\n else: stack.append(c)\n return not stack", "solution_java": "public boolean isValid(String s) {\n Stack stack = new Stack<>();\n Map map = Map.of(')', '(', ']', '[', '}', '{');\n for (char c : s.toCharArray()) {\n if (map.containsValue(c)) stack.push(c);\n else if (!stack.isEmpty() && stack.pop() != map.get(c)) return false;\n }\n return stack.isEmpty();\n}", "solution_cpp": "bool isValid(string s) {\n stack st;\n unordered_map m = {{')','('},{']','['},{'}','{'}};\n for (char c : s) {\n if (m.find(c) == m.end()) st.push(c);\n else if (st.empty() || st.top() != m[c]) return false;\n else st.pop();\n }\n return st.empty();\n}", "test_cases": ["s=\"()\" -> true", "s=\"()[]{}\" -> true", "s=\"(]\" -> false"], "key_points": ["栈匹配法", "注意空栈边界"], "tags": ["string", "easy", "Google", "Uber"]} {"problem_id": "algo_00945", "original_id": "longest-palindrome", "title": "最长回文子串", "category": "string", "difficulty": "medium", "companies": ["Google", "Amazon"], "description": "给你一个字符串 s,找到 s 中最长的回文子串。", "solution_python": "def longestPalindrome(s):\n def expand(l, r):\n while l >= 0 and r < len(s) and s[l] == s[r]: l -= 1; r += 1\n return l + 1, r - 1\n start = end = 0\n for i in range(len(s)):\n l1, r1 = expand(i, i)\n l2, r2 = expand(i, i + 1)\n if r1 - l1 > end - start: start, end = l1, r1\n if r2 - l2 > end - start: start, end = l2, r2\n return s[start:end+1]", "solution_java": "public String longestPalindrome(String s) {\n int start = 0, end = 0;\n for (int i = 0; i < s.length(); i++) {\n int len1 = expand(s, i, i), len2 = expand(s, i, i+1);\n int len = Math.max(len1, len2);\n if (len > end - start) { start = i - (len-1)/2; end = i + len/2; }\n }\n return s.substring(start, end + 1);\n}\nprivate int expand(String s, int l, int r) {\n while (l >= 0 && r < s.length() && s.charAt(l) == s.charAt(r)) { l--; r++; }\n return r - l - 1;\n}", "solution_cpp": "string longestPalindrome(string s) {\n int start = 0, end = 0;\n for (int i = 0; i < s.size(); i++) {\n int len1 = expand(s, i, i), len2 = expand(s, i, i+1);\n if (max(len1, len2) > end - start) { start = i - (max(len1,len2)-1)/2; end = i + max(len1,len2)/2; }\n }\n return s.substr(start, end - start + 1);\n}", "test_cases": ["s=\"babad\" -> bab或aba", "s=\"cbbd\" -> bb"], "key_points": ["中心扩展法", "处理奇偶长度"], "tags": ["string", "medium", "Google", "Amazon"]} {"problem_id": "algo_00946", "original_id": "reverse-list", "title": "反转链表", "category": "linkedlist", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "给你单链表的头节点 head,请你反转链表,并返回反转后的链表。", "solution_python": "def reverseList(head):\n prev = None\n curr = head\n while curr:\n nxt = curr.next\n curr.next = prev\n prev = curr\n curr = nxt\n return prev", "solution_java": "public ListNode reverseList(ListNode head) {\n ListNode prev = null, curr = head;\n while (curr != null) {\n ListNode next = curr.next;\n curr.next = prev;\n prev = curr;\n curr = next;\n }\n return prev;\n}", "solution_cpp": "ListNode* reverseList(ListNode* head) {\n ListNode* prev = nullptr, *curr = head;\n while (curr) {\n ListNode* next = curr->next;\n curr->next = prev;\n prev = curr;\n curr = next;\n }\n return prev;\n}", "test_cases": ["head=[1,2,3,4,5] -> [5,4,3,2,1]", "head=[1,2] -> [2,1]"], "key_points": ["迭代法 O(1)空间", "递归法 O(n)空间"], "tags": ["linkedlist", "medium", "Google", "Microsoft"]} {"problem_id": "algo_00947", "original_id": "middle-node", "title": "链表的中间结点", "category": "linkedlist", "difficulty": "easy", "companies": ["Amazon", "Facebook"], "description": "给你单链表的头节点 head,请你找出并返回链表的中间结点。如果有两个中间结点,则返回第二个中间结点。", "solution_python": "def middleNode(head):\n slow = fast = head\n while fast and fast.next:\n slow = slow.next\n fast = fast.next.next\n return slow", "solution_java": "public ListNode middleNode(ListNode head) {\n ListNode slow = head, fast = head;\n while (fast != null && fast.next != null) {\n slow = slow.next;\n fast = fast.next.next;\n }\n return slow;\n}", "solution_cpp": "ListNode* middleNode(ListNode* head) {\n ListNode* slow = head, *fast = head;\n while (fast && fast->next) { slow = slow->next; fast = fast->next->next; }\n return slow;\n}", "test_cases": ["head=[1,2,3,4,5] -> 3", "head=[1,2,3,4,5,6] -> 4"], "key_points": ["快慢指针", "O(n)时间O(1)空间"], "tags": ["linkedlist", "easy", "Amazon", "Facebook"]} {"problem_id": "algo_00948", "original_id": "max-depth", "title": "二叉树的最大深度", "category": "tree", "difficulty": "easy", "companies": ["Microsoft", "Apple"], "description": "给定一个二叉树 root,返回其最大深度。", "solution_python": "def maxDepth(root):\n if not root: return 0\n return max(maxDepth(root.left), maxDepth(root.right)) + 1", "solution_java": "public int maxDepth(TreeNode root) {\n if (root == null) return 0;\n return Math.max(maxDepth(root.left), maxDepth(root.right)) + 1;\n}", "solution_cpp": "int maxDepth(TreeNode* root) {\n if (!root) return 0;\n return max(maxDepth(root->left), maxDepth(root->right)) + 1;\n}", "test_cases": ["root=[3,9,20,null,null,15,7] -> 3", "root=[1,null,2] -> 2"], "key_points": ["DFS递归", "层序遍历也可"], "tags": ["tree", "easy", "Microsoft", "Apple"]} {"problem_id": "algo_00949", "original_id": "inorder-traversal", "title": "二叉树的中序遍历", "category": "tree", "difficulty": "easy", "companies": ["Google", "Microsoft"], "description": "给定一个二叉树的根节点 root,返回它的中序遍历结果。", "solution_python": "def inorderTraversal(root):\n result = []\n def dfs(node):\n if node:\n dfs(node.left)\n result.append(node.val)\n dfs(node.right)\n dfs(root)\n return result", "solution_java": "public List inorderTraversal(TreeNode root) {\n List res = new ArrayList<>();\n dfs(root, res);\n return res;\n}\nprivate void dfs(TreeNode node, List res) {\n if (node == null) return;\n dfs(node.left, res); res.add(node.val); dfs(node.right, res);\n}", "solution_cpp": "vector inorderTraversal(TreeNode* root) {\n vector res;\n dfs(root, res);\n return res;\n}\nvoid dfs(TreeNode* node, vector& res) {\n if (!node) return;\n dfs(node->left, res); res.push_back(node->val); dfs(node->right, res);\n}", "test_cases": ["root=[1,null,2,3] -> [1,3,2]", "root=[] -> []"], "key_points": ["左-根-右顺序", "递归最简洁"], "tags": ["tree", "easy", "Google", "Microsoft"]} {"problem_id": "algo_00950", "original_id": "binary-search", "title": "二分查找", "category": "binarysearch", "difficulty": "easy", "companies": ["Google", "Amazon"], "description": "给定一个 n 个元素有序的(升序)整型数组 nums 和一个目标值 target,写一个函数搜索 nums 中的 target,如果目标值存在返回下标,否则返回 -1。", "solution_python": "def search(nums, target):\n left, right = 0, len(nums) - 1\n while left <= right:\n mid = (left + right) // 2\n if nums[mid] == target: return mid\n elif nums[mid] < target: left = mid + 1\n else: right = mid - 1\n return -1", "solution_java": "public int search(int[] nums, int target) {\n int left = 0, right = nums.length - 1;\n while (left <= right) {\n int mid = left + (right - left) / 2;\n if (nums[mid] == target) return mid;\n else if (nums[mid] < target) left = mid + 1;\n else right = mid - 1;\n }\n return -1;\n}", "solution_cpp": "int search(vector& nums, int target) {\n int left = 0, right = nums.size() - 1;\n while (left <= right) {\n int mid = left + (right - left) / 2;\n if (nums[mid] == target) return mid;\n else if (nums[mid] < target) left = mid + 1;\n else right = mid - 1;\n }\n return -1;\n}", "test_cases": ["nums=[-1,0,3,5,9,12], target=9 -> 4", "nums=[-1,0,3,5,9,12], target=2 -> -1"], "key_points": ["标准模板", "注意防溢出写法"], "tags": ["binarysearch", "easy", "Google", "Amazon"]} {"problem_id": "algo_00951", "original_id": "climbing-stairs", "title": "爬楼梯", "category": "dp", "difficulty": "easy", "companies": ["Amazon", "Google"], "description": "假设你正在爬楼梯。需要 n 阶你才能到达楼顶。每次你可以爬 1 或 2 个台阶。你有多少种不同的方法可以爬到楼顶?", "solution_python": "def climbStairs(n):\n if n <= 2: return n\n a, b = 1, 2\n for _ in range(3, n+1):\n a, b = b, a + b\n return b", "solution_java": "public int climbStairs(int n) {\n if (n <= 2) return n;\n int a = 1, b = 2;\n for (int i = 3; i <= n; i++) { int temp = a + b; a = b; b = temp; }\n return b;\n}", "solution_cpp": "int climbStairs(int n) {\n if (n <= 2) return n;\n int a = 1, b = 2;\n for (int i = 3; i <= n; i++) { int temp = a + b; a = b; b = temp; }\n return b;\n}", "test_cases": ["n=2 -> 2", "n=3 -> 3", "n=5 -> 8"], "key_points": ["斐波那契数列", "滚动数组优化空间"], "tags": ["dp", "easy", "Amazon", "Google"]} {"problem_id": "algo_00952", "original_id": "coin-change", "title": "零钱兑换", "category": "dp", "difficulty": "medium", "companies": ["Google", "Amazon"], "description": "给你一个整数数组 coins 表示不同面额的硬币,以及一个整数 amount 表示总金额。计算并返回可以凑成总金额所需的最少的硬币个数。如果没有任何一种硬币组合能组成总金额,返回 -1。", "solution_python": "def coinChange(coins, amount):\n dp = [float('inf')] * (amount + 1)\n dp[0] = 0\n for coin in coins:\n for x in range(coin, amount + 1):\n dp[x] = min(dp[x], dp[x - coin] + 1)\n return dp[amount] if dp[amount] != float('inf') else -1", "solution_java": "public int coinChange(int[] coins, int amount) {\n int[] dp = new int[amount + 1];\n Arrays.fill(dp, amount + 1);\n dp[0] = 0;\n for (int coin : coins) {\n for (int x = coin; x <= amount; x++) {\n dp[x] = Math.min(dp[x], dp[x - coin] + 1);\n }\n }\n return dp[amount] > amount ? -1 : dp[amount];\n}", "solution_cpp": "int coinChange(vector& coins, int amount) {\n vector dp(amount + 1, amount + 1);\n dp[0] = 0;\n for (int coin : coins) {\n for (int x = coin; x <= amount; x++) {\n dp[x] = min(dp[x], dp[x - coin] + 1);\n }\n }\n return dp[amount] > amount ? -1 : dp[amount];\n}", "test_cases": ["coins=[1,2,5], amount=11 -> 3", "coins=[2], amount=3 -> -1"], "key_points": ["完全背包问题", "dp[x] = min(dp[x-coin]+1)"], "tags": ["dp", "medium", "Google", "Amazon"]} {"problem_id": "algo_00953", "original_id": "subsets", "title": "子集", "category": "backtracking", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "给你一个整数数组 nums ,数组中的元素 互不相同 。返回该数组所有可能的子集(幂集)。", "solution_python": "def subsets(nums):\n result = []\n def backtrack(start, path):\n result.append(path[:])\n for i in range(start, len(nums)):\n path.append(nums[i])\n backtrack(i + 1, path)\n path.pop()\n backtrack(0, [])\n return result", "solution_java": "public List> subsets(int[] nums) {\n List> result = new ArrayList<>();\n backtrack(nums, 0, new ArrayList<>(), result);\n return result;\n}\nprivate void backtrack(int[] nums, int start, List path, List> result) {\n result.add(new ArrayList<>(path));\n for (int i = start; i < nums.length; i++) {\n path.add(nums[i]);\n backtrack(nums, i + 1, path, result);\n path.remove(path.size() - 1);\n }\n}", "solution_cpp": "vector> subsets(vector& nums) {\n vector> result;\n vector path;\n backtrack(nums, 0, path, result);\n return result;\n}\nvoid backtrack(vector& nums, int start, vector& path, vector>& result) {\n result.push_back(path);\n for (int i = start; i < nums.size(); i++) {\n path.push_back(nums[i]);\n backtrack(nums, i + 1, path, result);\n path.pop_back();\n }\n}", "test_cases": ["nums=[1,2,3] -> [[],[1],[2],[1,2],[3],[1,3],[2,3],[1,2,3]]"], "key_points": ["选或不选", "DFS遍历子集树"], "tags": ["backtracking", "medium", "Google", "Microsoft"]} {"problem_id": "algo_00954", "original_id": "permutations", "title": "全排列", "category": "backtracking", "difficulty": "medium", "companies": ["Google", "Facebook"], "description": "给定一个不含重复数字的数组 nums,返回其所有可能的全排列。", "solution_python": "def permute(nums):\n result = []\n def backtrack(path, used):\n if len(path) == len(nums):\n result.append(path[:])\n return\n for i in range(len(nums)):\n if used[i]: continue\n used[i] = True\n path.append(nums[i])\n backtrack(path, used)\n path.pop()\n used[i] = False\n backtrack([], [False]*len(nums))\n return result", "solution_java": "public List> permute(int[] nums) {\n List> result = new ArrayList<>();\n boolean[] used = new boolean[nums.length];\n backtrack(nums, used, new ArrayList<>(), result);\n return result;\n}\nprivate void backtrack(int[] nums, boolean[] used, List path, List> result) {\n if (path.size() == nums.length) { result.add(new ArrayList<>(path)); return; }\n for (int i = 0; i < nums.length; i++) {\n if (used[i]) continue;\n used[i] = true;\n path.add(nums[i]);\n backtrack(nums, used, path, result);\n path.remove(path.size() - 1);\n used[i] = false;\n }\n}", "solution_cpp": "vector> permute(vector& nums) {\n vector> result;\n vector used(nums.size(), false);\n vector path;\n backtrack(nums, used, path, result);\n return result;\n}\nvoid backtrack(vector& nums, vector& used, vector& path, vector>& result) {\n if (path.size() == nums.size()) { result.push_back(path); return; }\n for (int i = 0; i < nums.size(); i++) {\n if (used[i]) continue;\n used[i] = true;\n path.push_back(nums[i]);\n backtrack(nums, used, path, result);\n path.pop_back();\n used[i] = false;\n }\n}", "test_cases": ["nums=[1,2,3] -> [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]"], "key_points": ["标记已使用元素", "回溯经典模板"], "tags": ["backtracking", "medium", "Google", "Facebook"]} {"problem_id": "algo_00955", "original_id": "top-k-frequent", "title": "前K个高频元素", "category": "heap", "difficulty": "medium", "companies": ["Amazon", "Facebook"], "description": "给你一个整数数组 nums 和一个整数 k,请你返回其中出现频率前 k 高的元素。", "solution_python": "import heapq\nfrom collections import Counter\ndef topKFrequent(nums, k):\n count = Counter(nums)\n heap = []\n for num, freq in count.items():\n heapq.heappush(heap, (freq, num))\n if len(heap) > k: heapq.heappop(heap)\n return [num for freq, num in heap]", "solution_java": "public int[] topKFrequent(int[] nums, int k) {\n Map count = new HashMap<>();\n for (int n : nums) count.put(n, count.getOrDefault(n, 0) + 1);\n PriorityQueue> heap = \n new PriorityQueue<>((a, b) -> a.getValue() - b.getValue());\n for (Map.Entry e : count.entrySet()) {\n heap.offer(e);\n if (heap.size() > k) heap.poll();\n }\n int[] res = new int[k];\n for (int i = k - 1; i >= 0; i--) res[i] = heap.poll().getKey();\n return res;\n}", "solution_cpp": "vector topKFrequent(vector& nums, int k) {\n unordered_map count;\n for (int n : nums) count[n]++;\n priority_queue, vector>, greater>> heap;\n for (auto& [num, freq] : count) {\n heap.push({freq, num});\n if (heap.size() > k) heap.pop();\n }\n vector res;\n while (!heap.empty()) { res.push_back(heap.top().second); heap.pop(); }\n reverse(res.begin(), res.end());\n return res;\n}", "test_cases": ["nums=[1,1,1,2,2,3], k=2 -> [1,2]", "nums=[1], k=1 -> [1]"], "key_points": ["小顶堆保持大小k", "时间复杂度O(nlogk)"], "tags": ["heap", "medium", "Amazon", "Facebook"]} {"problem_id": "algo_00956", "original_id": "3sum", "title": "三数之和", "category": "two-pointers", "difficulty": "medium", "companies": ["Google", "Amazon"], "description": "给你一个整数数组 nums,判断是否存在三元组满足和为0,返回所有不重复的三元组。", "solution_python": "def threeSum(nums):\n nums.sort()\n result = []\n for i in range(len(nums) - 2):\n if i > 0 and nums[i] == nums[i-1]: continue\n left, right = i + 1, len(nums) - 1\n while left < right:\n total = nums[i] + nums[left] + nums[right]\n if total < 0: left += 1\n elif total > 0: right -= 1\n else:\n result.append([nums[i], nums[left], nums[right]])\n while left < right and nums[left] == nums[left+1]: left += 1\n while left < right and nums[right] == nums[right-1]: right -= 1\n left += 1; right -= 1\n return result", "solution_java": "public List> threeSum(int[] nums) {\n Arrays.sort(nums);\n List> result = new ArrayList<>();\n for (int i = 0; i < nums.length - 2; i++) {\n if (i > 0 && nums[i] == nums[i-1]) continue;\n int left = i + 1, right = nums.length - 1;\n while (left < right) {\n int total = nums[i] + nums[left] + nums[right];\n if (total < 0) left++;\n else if (total > 0) right--;\n else {\n result.add(Arrays.asList(nums[i], nums[left], nums[right]));\n while (left < right && nums[left] == nums[left+1]) left++;\n while (left < right && nums[right] == nums[right-1]) right--;\n left++; right--;\n }\n }\n }\n return result;\n}", "solution_cpp": "vector> threeSum(vector& nums) {\n sort(nums.begin(), nums.end());\n vector> result;\n for (int i = 0; i < nums.size() - 2; i++) {\n if (i > 0 && nums[i] == nums[i-1]) continue;\n int left = i + 1, right = nums.size() - 1;\n while (left < right) {\n int total = nums[i] + nums[left] + nums[right];\n if (total < 0) left++;\n else if (total > 0) right--;\n else {\n result.push_back({nums[i], nums[left], nums[right]});\n while (left < right && nums[left] == nums[left+1]) left++;\n while (left < right && nums[right] == nums[right-1]) right--;\n left++; right--;\n }\n }\n }\n return result;\n}", "test_cases": ["nums=[-1,0,1,2,-1,-4] -> [[-1,-1,2],[-1,0,1]]"], "key_points": ["排序+双指针", "去重是关键"], "tags": ["two-pointers", "medium", "Google", "Amazon"]} {"problem_id": "algo_00957", "original_id": "container-water", "title": "盛最多水的容器", "category": "two-pointers", "difficulty": "medium", "companies": ["Google", "Uber"], "description": "给定一个长度为 n 的整数数组 height,找出其中的两条线,使得它们与 x 轴共同构成的容器可以容纳最多的水。", "solution_python": "def maxArea(height):\n left, right = 0, len(height) - 1\n max_area = 0\n while left < right:\n h = min(height[left], height[right])\n max_area = max(max_area, h * (right - left))\n if height[left] < height[right]: left += 1\n else: right -= 1\n return max_area", "solution_java": "public int maxArea(int[] height) {\n int left = 0, right = height.length - 1, maxArea = 0;\n while (left < right) {\n int h = Math.min(height[left], height[right]);\n maxArea = Math.max(maxArea, h * (right - left));\n if (height[left] < height[right]) left++;\n else right--;\n }\n return maxArea;\n}", "solution_cpp": "int maxArea(vector& height) {\n int left = 0, right = height.size() - 1, maxArea = 0;\n while (left < right) {\n int h = min(height[left], height[right]);\n maxArea = max(maxArea, h * (right - left));\n if (height[left] < height[right]) left++;\n else right--;\n }\n return maxArea;\n}", "test_cases": ["height=[1,8,6,2,5,4,8,3,7] -> 49"], "key_points": ["移动短边指针", "面积=min(h1,h2)*width"], "tags": ["two-pointers", "medium", "Google", "Uber"]} {"problem_id": "algo_00958", "original_id": "min-stack", "title": "最小栈", "category": "stack", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "设计一个支持 push,pop,top 操作,并能在常数时间内检索到最小元素的栈。", "solution_python": "class MinStack:\n def __init__(self):\n self.stack = []\n self.min_stack = []\n def push(self, val):\n self.stack.append(val)\n self.min_stack.append(min(val, self.min_stack[-1] if self.min_stack else val))\n def pop(self):\n self.stack.pop(); self.min_stack.pop()\n def top(self): return self.stack[-1]\n def getMin(self): return self.min_stack[-1]", "solution_java": "class MinStack {\n Stack stack = new Stack<>();\n Stack minStack = new Stack<>();\n public void push(int val) { stack.push(val); minStack.push(Math.min(val, minStack.isEmpty() ? val : minStack.peek())); }\n public void pop() { stack.pop(); minStack.pop(); }\n public int top() { return stack.peek(); }\n public int getMin() { return minStack.peek(); }\n}", "solution_cpp": "class MinStack {\n stack st, minSt;\npublic:\n void push(int val) { st.push(val); minSt.push(min(val, minSt.empty() ? val : minSt.top())); }\n void pop() { st.pop(); minSt.pop(); }\n int top() { return st.top(); }\n int getMin() { return minSt.top(); }\n};", "test_cases": ["push(-2), push(0), push(-3) -> getMin() returns -3"], "key_points": ["辅助栈记录最小值", "O(1)时间获取最小值"], "tags": ["stack", "medium", "Google", "Microsoft"]} {"problem_id": "algo_00959", "original_id": "lru-cache", "title": "LRU缓存", "category": "design", "difficulty": "hard", "companies": ["Google", "Amazon"], "description": "设计和实现一个 LRU(最近最少使用)缓存机制。", "solution_python": "class LRUCache:\n def __init__(self, capacity):\n self.capacity = capacity\n self.cache = {}\n self.order = []\n def get(self, key):\n if key not in self.cache: return -1\n self.order.remove(key); self.order.append(key)\n return self.cache[key]\n def put(self, key, value):\n if key in self.cache:\n self.order.remove(key)\n elif len(self.cache) >= self.capacity:\n del self.cache[self.order.pop(0)]\n self.cache[key] = value; self.order.append(key)", "solution_java": "class LRUCache {\n int capacity;\n LinkedHashMap cache = new LinkedHashMap<>();\n public LRUCache(int cap) { capacity = cap; }\n public int get(int key) { return cache.containsKey(key) ? cache.remove(key) : -1; }\n public void put(int key, int val) {\n if (cache.containsKey(key)) cache.remove(key);\n else if (cache.size() >= capacity) cache.remove(cache.keySet().iterator().next());\n cache.put(key, val);\n }\n}", "solution_cpp": "class LRUCache {\n int cap;\n list> dll;\n unordered_map>::iterator> cache;\npublic:\n LRUCache(int capacity) : cap(capacity) {}\n int get(int key) {\n auto it = cache.find(key);\n if (it == cache.end()) return -1;\n dll.splice(dll.end(), dll, it->second);\n return it->second->second;\n }\n void put(int key, int value) {\n auto it = cache.find(key);\n if (it != cache.end()) dll.erase(it->second);\n else if (cache.size() >= cap) { cache.erase(dll.front().first); dll.pop_front(); }\n dll.push_back({key, value});\n cache[key] = --dll.end();\n }\n};", "test_cases": ["put(1,1), put(2,2), get(1) -> 1"], "key_points": ["HashMap + 双向链表", "O(1)时间操作"], "tags": ["design", "hard", "Google", "Amazon"]} {"problem_id": "algo_00960", "original_id": "num-islands", "title": "岛屿数量", "category": "graph", "difficulty": "medium", "companies": ["Google", "Facebook"], "description": "给你一个由 '1'(陆地)和 '0'(水)组成的二维网格,请你计算网格中岛屿的数量。岛屿总是被水包围,且只能由水平或垂直方向相邻的陆地连接形成。", "solution_python": "def numIslands(grid):\n if not grid: return 0\n rows, cols = len(grid), len(grid[0])\n count = 0\n def dfs(r, c):\n if r < 0 or r >= rows or c < 0 or c >= cols or grid[r][c] != '1': return\n grid[r][c] = '0'\n dfs(r+1, c); dfs(r-1, c); dfs(r, c+1); dfs(r, c-1)\n for r in range(rows):\n for c in range(cols):\n if grid[r][c] == '1': count += 1; dfs(r, c)\n return count", "solution_java": "public int numIslands(char[][] grid) {\n if (grid.length == 0) return 0;\n int count = 0;\n for (int i = 0; i < grid.length; i++)\n for (int j = 0; j < grid[0].length; j++)\n if (grid[i][j] == '1') { count++; dfs(grid, i, j); }\n return count;\n}\nprivate void dfs(char[][] grid, int r, int c) {\n if (r < 0 || r >= grid.length || c < 0 || c >= grid[0].length || grid[r][c] != '1') return;\n grid[r][c] = '0';\n dfs(grid, r+1, c); dfs(grid, r-1, c); dfs(grid, r, c+1); dfs(grid, r, c-1);\n}", "solution_cpp": "int numIslands(vector>& grid) {\n if (grid.empty()) return 0;\n int count = 0;\n for (int i = 0; i < grid.size(); i++)\n for (int j = 0; j < grid[0].size(); j++)\n if (grid[i][j] == '1') { count++; dfs(grid, i, j); }\n return count;\n}\nvoid dfs(vector>& grid, int r, int c) {\n if (r < 0 || r >= grid.size() || c < 0 || c >= grid[0].size() || grid[r][c] != '1') return;\n grid[r][c] = '0';\n dfs(grid, r+1, c); dfs(grid, r-1, c); dfs(grid, r, c+1); dfs(grid, r, c-1);\n}", "test_cases": ["grid=[[1,1,1,1,0],[1,1,0,1,0],[1,1,0,0,0],[0,0,0,0,0]] -> 1"], "key_points": ["DFS/BFS遍历", "访问后标记为0避免重复"], "tags": ["graph", "medium", "Google", "Facebook"]} {"problem_id": "algo_00961", "original_id": "two-sum", "title": "两数之和", "category": "array", "difficulty": "easy", "companies": ["Amazon", "Google"], "description": "给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那两个整数,并返回他们的数组下标。", "solution_python": "def twoSum(nums, target):\n hashmap = {}\n for i, num in enumerate(nums):\n complement = target - num\n if complement in hashmap:\n return [hashmap[complement], i]\n hashmap[num] = i\n return []", "solution_java": "public int[] twoSum(int[] nums, int target) {\n Map map = new HashMap<>();\n for (int i = 0; i < nums.length; i++) {\n int complement = target - nums[i];\n if (map.containsKey(complement)) return new int[]{map.get(complement), i};\n map.put(nums[i], i);\n }\n return new int[]{};\n}", "solution_cpp": "vector twoSum(vector& nums, int target) {\n unordered_map m;\n for (int i = 0; i < nums.size(); i++) {\n if (m.count(target - nums[i])) return {m[target - nums[i]], i};\n m[nums[i]] = i;\n }\n return {};\n}", "test_cases": ["nums=[2,7,11,15], target=9 -> [0,1]", "nums=[3,2,4], target=6 -> [1,2]"], "key_points": ["哈希表一次遍历", "空间换时间"], "tags": ["array", "easy", "Amazon", "Google"]} {"problem_id": "algo_00962", "original_id": "merge-sorted", "title": "合并两个有序数组", "category": "array", "difficulty": "easy", "companies": ["Microsoft", "Uber"], "description": "给你两个按非递减顺序排列的整数数组 nums1 和 nums2,另有两个整数 m 和 n,分别表示 nums1 和 nums2 中的元素数目。请你合并 nums2 到 nums1 中。", "solution_python": "def merge(nums1, m, nums2, n):\n p1, p2, p = m-1, n-1, m+n-1\n while p1 >= 0 and p2 >= 0:\n if nums1[p1] > nums2[p2]: nums1[p] = nums1[p1]; p1 -= 1\n else: nums1[p] = nums2[p2]; p2 -= 1\n p -= 1\n while p2 >= 0: nums1[p] = nums2[p2]; p2 -= 1; p -= 1", "solution_java": "public void merge(int[] nums1, int m, int[] nums2, int n) {\n int p1 = m-1, p2 = n-1, p = m+n-1;\n while (p1 >= 0 && p2 >= 0) {\n nums1[p--] = nums1[p1] > nums2[p2] ? nums1[p1--] : nums2[p2--];\n }\n while (p2 >= 0) nums1[p--] = nums2[p2--];\n}", "solution_cpp": "void merge(vector& nums1, int m, vector& nums2, int n) {\n int p1 = m-1, p2 = n-1, p = m+n-1;\n while (p1 >= 0 && p2 >= 0) nums1[p--] = nums1[p1] > nums2[p2] ? nums1[p1--] : nums2[p2--];\n while (p2 >= 0) nums1[p--] = nums2[p2--];\n}", "test_cases": ["nums1=[1,2,3], m=3, nums2=[2,5,6], n=3 -> [1,2,2,3,5,6]", "nums1=[], m=0, nums2=[1], n=1 -> [1]"], "key_points": ["从后往前合并", "三指针技巧"], "tags": ["array", "easy", "Microsoft", "Uber"]} {"problem_id": "algo_00963", "original_id": "max-subarray", "title": "最大子数组和", "category": "array", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "给你一个整数数组 nums ,请你找出一个具有最大和的连续子数组,返回其最大和。", "solution_python": "def maxSubArray(nums):\n max_sum = current = nums[0]\n for num in nums[1:]:\n current = max(num, current + num)\n max_sum = max(max_sum, current)\n return max_sum", "solution_java": "public int maxSubArray(int[] nums) {\n int maxSum = nums[0], curr = nums[0];\n for (int i = 1; i < nums.length; i++) {\n curr = Math.max(nums[i], curr + nums[i]);\n maxSum = Math.max(maxSum, curr);\n }\n return maxSum;\n}", "solution_cpp": "int maxSubArray(vector& nums) {\n int maxSum = nums[0], curr = nums[0];\n for (int i = 1; i < nums.size(); i++) {\n curr = max(nums[i], curr + nums[i]);\n maxSum = max(maxSum, curr);\n }\n return maxSum;\n}", "test_cases": ["nums=[-2,1,-3,4,-1,2,1,-5,4] -> 6", "nums=[1] -> 1"], "key_points": ["Kadane算法", "动态规划基础题"], "tags": ["array", "medium", "Google", "Microsoft"]} {"problem_id": "algo_00964", "original_id": "valid-parentheses", "title": "有效的括号", "category": "string", "difficulty": "easy", "companies": ["Google", "Uber"], "description": "给定一个只包括 '(',')','{','}','[',']' 的字符串 s,判断字符串是否有效。", "solution_python": "def isValid(s):\n stack = []\n mapping = {')': '(', ']': '[', '}': '{'}\n for c in s:\n if c in mapping:\n if not stack or stack[-1] != mapping[c]: return False\n stack.pop()\n else: stack.append(c)\n return not stack", "solution_java": "public boolean isValid(String s) {\n Stack stack = new Stack<>();\n Map map = Map.of(')', '(', ']', '[', '}', '{');\n for (char c : s.toCharArray()) {\n if (map.containsValue(c)) stack.push(c);\n else if (!stack.isEmpty() && stack.pop() != map.get(c)) return false;\n }\n return stack.isEmpty();\n}", "solution_cpp": "bool isValid(string s) {\n stack st;\n unordered_map m = {{')','('},{']','['},{'}','{'}};\n for (char c : s) {\n if (m.find(c) == m.end()) st.push(c);\n else if (st.empty() || st.top() != m[c]) return false;\n else st.pop();\n }\n return st.empty();\n}", "test_cases": ["s=\"()\" -> true", "s=\"()[]{}\" -> true", "s=\"(]\" -> false"], "key_points": ["栈匹配法", "注意空栈边界"], "tags": ["string", "easy", "Google", "Uber"]} {"problem_id": "algo_00965", "original_id": "longest-palindrome", "title": "最长回文子串", "category": "string", "difficulty": "medium", "companies": ["Google", "Amazon"], "description": "给你一个字符串 s,找到 s 中最长的回文子串。", "solution_python": "def longestPalindrome(s):\n def expand(l, r):\n while l >= 0 and r < len(s) and s[l] == s[r]: l -= 1; r += 1\n return l + 1, r - 1\n start = end = 0\n for i in range(len(s)):\n l1, r1 = expand(i, i)\n l2, r2 = expand(i, i + 1)\n if r1 - l1 > end - start: start, end = l1, r1\n if r2 - l2 > end - start: start, end = l2, r2\n return s[start:end+1]", "solution_java": "public String longestPalindrome(String s) {\n int start = 0, end = 0;\n for (int i = 0; i < s.length(); i++) {\n int len1 = expand(s, i, i), len2 = expand(s, i, i+1);\n int len = Math.max(len1, len2);\n if (len > end - start) { start = i - (len-1)/2; end = i + len/2; }\n }\n return s.substring(start, end + 1);\n}\nprivate int expand(String s, int l, int r) {\n while (l >= 0 && r < s.length() && s.charAt(l) == s.charAt(r)) { l--; r++; }\n return r - l - 1;\n}", "solution_cpp": "string longestPalindrome(string s) {\n int start = 0, end = 0;\n for (int i = 0; i < s.size(); i++) {\n int len1 = expand(s, i, i), len2 = expand(s, i, i+1);\n if (max(len1, len2) > end - start) { start = i - (max(len1,len2)-1)/2; end = i + max(len1,len2)/2; }\n }\n return s.substr(start, end - start + 1);\n}", "test_cases": ["s=\"babad\" -> bab或aba", "s=\"cbbd\" -> bb"], "key_points": ["中心扩展法", "处理奇偶长度"], "tags": ["string", "medium", "Google", "Amazon"]} {"problem_id": "algo_00966", "original_id": "reverse-list", "title": "反转链表", "category": "linkedlist", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "给你单链表的头节点 head,请你反转链表,并返回反转后的链表。", "solution_python": "def reverseList(head):\n prev = None\n curr = head\n while curr:\n nxt = curr.next\n curr.next = prev\n prev = curr\n curr = nxt\n return prev", "solution_java": "public ListNode reverseList(ListNode head) {\n ListNode prev = null, curr = head;\n while (curr != null) {\n ListNode next = curr.next;\n curr.next = prev;\n prev = curr;\n curr = next;\n }\n return prev;\n}", "solution_cpp": "ListNode* reverseList(ListNode* head) {\n ListNode* prev = nullptr, *curr = head;\n while (curr) {\n ListNode* next = curr->next;\n curr->next = prev;\n prev = curr;\n curr = next;\n }\n return prev;\n}", "test_cases": ["head=[1,2,3,4,5] -> [5,4,3,2,1]", "head=[1,2] -> [2,1]"], "key_points": ["迭代法 O(1)空间", "递归法 O(n)空间"], "tags": ["linkedlist", "medium", "Google", "Microsoft"]} {"problem_id": "algo_00967", "original_id": "middle-node", "title": "链表的中间结点", "category": "linkedlist", "difficulty": "easy", "companies": ["Amazon", "Facebook"], "description": "给你单链表的头节点 head,请你找出并返回链表的中间结点。如果有两个中间结点,则返回第二个中间结点。", "solution_python": "def middleNode(head):\n slow = fast = head\n while fast and fast.next:\n slow = slow.next\n fast = fast.next.next\n return slow", "solution_java": "public ListNode middleNode(ListNode head) {\n ListNode slow = head, fast = head;\n while (fast != null && fast.next != null) {\n slow = slow.next;\n fast = fast.next.next;\n }\n return slow;\n}", "solution_cpp": "ListNode* middleNode(ListNode* head) {\n ListNode* slow = head, *fast = head;\n while (fast && fast->next) { slow = slow->next; fast = fast->next->next; }\n return slow;\n}", "test_cases": ["head=[1,2,3,4,5] -> 3", "head=[1,2,3,4,5,6] -> 4"], "key_points": ["快慢指针", "O(n)时间O(1)空间"], "tags": ["linkedlist", "easy", "Amazon", "Facebook"]} {"problem_id": "algo_00968", "original_id": "max-depth", "title": "二叉树的最大深度", "category": "tree", "difficulty": "easy", "companies": ["Microsoft", "Apple"], "description": "给定一个二叉树 root,返回其最大深度。", "solution_python": "def maxDepth(root):\n if not root: return 0\n return max(maxDepth(root.left), maxDepth(root.right)) + 1", "solution_java": "public int maxDepth(TreeNode root) {\n if (root == null) return 0;\n return Math.max(maxDepth(root.left), maxDepth(root.right)) + 1;\n}", "solution_cpp": "int maxDepth(TreeNode* root) {\n if (!root) return 0;\n return max(maxDepth(root->left), maxDepth(root->right)) + 1;\n}", "test_cases": ["root=[3,9,20,null,null,15,7] -> 3", "root=[1,null,2] -> 2"], "key_points": ["DFS递归", "层序遍历也可"], "tags": ["tree", "easy", "Microsoft", "Apple"]} {"problem_id": "algo_00969", "original_id": "inorder-traversal", "title": "二叉树的中序遍历", "category": "tree", "difficulty": "easy", "companies": ["Google", "Microsoft"], "description": "给定一个二叉树的根节点 root,返回它的中序遍历结果。", "solution_python": "def inorderTraversal(root):\n result = []\n def dfs(node):\n if node:\n dfs(node.left)\n result.append(node.val)\n dfs(node.right)\n dfs(root)\n return result", "solution_java": "public List inorderTraversal(TreeNode root) {\n List res = new ArrayList<>();\n dfs(root, res);\n return res;\n}\nprivate void dfs(TreeNode node, List res) {\n if (node == null) return;\n dfs(node.left, res); res.add(node.val); dfs(node.right, res);\n}", "solution_cpp": "vector inorderTraversal(TreeNode* root) {\n vector res;\n dfs(root, res);\n return res;\n}\nvoid dfs(TreeNode* node, vector& res) {\n if (!node) return;\n dfs(node->left, res); res.push_back(node->val); dfs(node->right, res);\n}", "test_cases": ["root=[1,null,2,3] -> [1,3,2]", "root=[] -> []"], "key_points": ["左-根-右顺序", "递归最简洁"], "tags": ["tree", "easy", "Google", "Microsoft"]} {"problem_id": "algo_00970", "original_id": "binary-search", "title": "二分查找", "category": "binarysearch", "difficulty": "easy", "companies": ["Google", "Amazon"], "description": "给定一个 n 个元素有序的(升序)整型数组 nums 和一个目标值 target,写一个函数搜索 nums 中的 target,如果目标值存在返回下标,否则返回 -1。", "solution_python": "def search(nums, target):\n left, right = 0, len(nums) - 1\n while left <= right:\n mid = (left + right) // 2\n if nums[mid] == target: return mid\n elif nums[mid] < target: left = mid + 1\n else: right = mid - 1\n return -1", "solution_java": "public int search(int[] nums, int target) {\n int left = 0, right = nums.length - 1;\n while (left <= right) {\n int mid = left + (right - left) / 2;\n if (nums[mid] == target) return mid;\n else if (nums[mid] < target) left = mid + 1;\n else right = mid - 1;\n }\n return -1;\n}", "solution_cpp": "int search(vector& nums, int target) {\n int left = 0, right = nums.size() - 1;\n while (left <= right) {\n int mid = left + (right - left) / 2;\n if (nums[mid] == target) return mid;\n else if (nums[mid] < target) left = mid + 1;\n else right = mid - 1;\n }\n return -1;\n}", "test_cases": ["nums=[-1,0,3,5,9,12], target=9 -> 4", "nums=[-1,0,3,5,9,12], target=2 -> -1"], "key_points": ["标准模板", "注意防溢出写法"], "tags": ["binarysearch", "easy", "Google", "Amazon"]} {"problem_id": "algo_00971", "original_id": "climbing-stairs", "title": "爬楼梯", "category": "dp", "difficulty": "easy", "companies": ["Amazon", "Google"], "description": "假设你正在爬楼梯。需要 n 阶你才能到达楼顶。每次你可以爬 1 或 2 个台阶。你有多少种不同的方法可以爬到楼顶?", "solution_python": "def climbStairs(n):\n if n <= 2: return n\n a, b = 1, 2\n for _ in range(3, n+1):\n a, b = b, a + b\n return b", "solution_java": "public int climbStairs(int n) {\n if (n <= 2) return n;\n int a = 1, b = 2;\n for (int i = 3; i <= n; i++) { int temp = a + b; a = b; b = temp; }\n return b;\n}", "solution_cpp": "int climbStairs(int n) {\n if (n <= 2) return n;\n int a = 1, b = 2;\n for (int i = 3; i <= n; i++) { int temp = a + b; a = b; b = temp; }\n return b;\n}", "test_cases": ["n=2 -> 2", "n=3 -> 3", "n=5 -> 8"], "key_points": ["斐波那契数列", "滚动数组优化空间"], "tags": ["dp", "easy", "Amazon", "Google"]} {"problem_id": "algo_00972", "original_id": "coin-change", "title": "零钱兑换", "category": "dp", "difficulty": "medium", "companies": ["Google", "Amazon"], "description": "给你一个整数数组 coins 表示不同面额的硬币,以及一个整数 amount 表示总金额。计算并返回可以凑成总金额所需的最少的硬币个数。如果没有任何一种硬币组合能组成总金额,返回 -1。", "solution_python": "def coinChange(coins, amount):\n dp = [float('inf')] * (amount + 1)\n dp[0] = 0\n for coin in coins:\n for x in range(coin, amount + 1):\n dp[x] = min(dp[x], dp[x - coin] + 1)\n return dp[amount] if dp[amount] != float('inf') else -1", "solution_java": "public int coinChange(int[] coins, int amount) {\n int[] dp = new int[amount + 1];\n Arrays.fill(dp, amount + 1);\n dp[0] = 0;\n for (int coin : coins) {\n for (int x = coin; x <= amount; x++) {\n dp[x] = Math.min(dp[x], dp[x - coin] + 1);\n }\n }\n return dp[amount] > amount ? -1 : dp[amount];\n}", "solution_cpp": "int coinChange(vector& coins, int amount) {\n vector dp(amount + 1, amount + 1);\n dp[0] = 0;\n for (int coin : coins) {\n for (int x = coin; x <= amount; x++) {\n dp[x] = min(dp[x], dp[x - coin] + 1);\n }\n }\n return dp[amount] > amount ? -1 : dp[amount];\n}", "test_cases": ["coins=[1,2,5], amount=11 -> 3", "coins=[2], amount=3 -> -1"], "key_points": ["完全背包问题", "dp[x] = min(dp[x-coin]+1)"], "tags": ["dp", "medium", "Google", "Amazon"]} {"problem_id": "algo_00973", "original_id": "subsets", "title": "子集", "category": "backtracking", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "给你一个整数数组 nums ,数组中的元素 互不相同 。返回该数组所有可能的子集(幂集)。", "solution_python": "def subsets(nums):\n result = []\n def backtrack(start, path):\n result.append(path[:])\n for i in range(start, len(nums)):\n path.append(nums[i])\n backtrack(i + 1, path)\n path.pop()\n backtrack(0, [])\n return result", "solution_java": "public List> subsets(int[] nums) {\n List> result = new ArrayList<>();\n backtrack(nums, 0, new ArrayList<>(), result);\n return result;\n}\nprivate void backtrack(int[] nums, int start, List path, List> result) {\n result.add(new ArrayList<>(path));\n for (int i = start; i < nums.length; i++) {\n path.add(nums[i]);\n backtrack(nums, i + 1, path, result);\n path.remove(path.size() - 1);\n }\n}", "solution_cpp": "vector> subsets(vector& nums) {\n vector> result;\n vector path;\n backtrack(nums, 0, path, result);\n return result;\n}\nvoid backtrack(vector& nums, int start, vector& path, vector>& result) {\n result.push_back(path);\n for (int i = start; i < nums.size(); i++) {\n path.push_back(nums[i]);\n backtrack(nums, i + 1, path, result);\n path.pop_back();\n }\n}", "test_cases": ["nums=[1,2,3] -> [[],[1],[2],[1,2],[3],[1,3],[2,3],[1,2,3]]"], "key_points": ["选或不选", "DFS遍历子集树"], "tags": ["backtracking", "medium", "Google", "Microsoft"]} {"problem_id": "algo_00974", "original_id": "permutations", "title": "全排列", "category": "backtracking", "difficulty": "medium", "companies": ["Google", "Facebook"], "description": "给定一个不含重复数字的数组 nums,返回其所有可能的全排列。", "solution_python": "def permute(nums):\n result = []\n def backtrack(path, used):\n if len(path) == len(nums):\n result.append(path[:])\n return\n for i in range(len(nums)):\n if used[i]: continue\n used[i] = True\n path.append(nums[i])\n backtrack(path, used)\n path.pop()\n used[i] = False\n backtrack([], [False]*len(nums))\n return result", "solution_java": "public List> permute(int[] nums) {\n List> result = new ArrayList<>();\n boolean[] used = new boolean[nums.length];\n backtrack(nums, used, new ArrayList<>(), result);\n return result;\n}\nprivate void backtrack(int[] nums, boolean[] used, List path, List> result) {\n if (path.size() == nums.length) { result.add(new ArrayList<>(path)); return; }\n for (int i = 0; i < nums.length; i++) {\n if (used[i]) continue;\n used[i] = true;\n path.add(nums[i]);\n backtrack(nums, used, path, result);\n path.remove(path.size() - 1);\n used[i] = false;\n }\n}", "solution_cpp": "vector> permute(vector& nums) {\n vector> result;\n vector used(nums.size(), false);\n vector path;\n backtrack(nums, used, path, result);\n return result;\n}\nvoid backtrack(vector& nums, vector& used, vector& path, vector>& result) {\n if (path.size() == nums.size()) { result.push_back(path); return; }\n for (int i = 0; i < nums.size(); i++) {\n if (used[i]) continue;\n used[i] = true;\n path.push_back(nums[i]);\n backtrack(nums, used, path, result);\n path.pop_back();\n used[i] = false;\n }\n}", "test_cases": ["nums=[1,2,3] -> [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]"], "key_points": ["标记已使用元素", "回溯经典模板"], "tags": ["backtracking", "medium", "Google", "Facebook"]} {"problem_id": "algo_00975", "original_id": "top-k-frequent", "title": "前K个高频元素", "category": "heap", "difficulty": "medium", "companies": ["Amazon", "Facebook"], "description": "给你一个整数数组 nums 和一个整数 k,请你返回其中出现频率前 k 高的元素。", "solution_python": "import heapq\nfrom collections import Counter\ndef topKFrequent(nums, k):\n count = Counter(nums)\n heap = []\n for num, freq in count.items():\n heapq.heappush(heap, (freq, num))\n if len(heap) > k: heapq.heappop(heap)\n return [num for freq, num in heap]", "solution_java": "public int[] topKFrequent(int[] nums, int k) {\n Map count = new HashMap<>();\n for (int n : nums) count.put(n, count.getOrDefault(n, 0) + 1);\n PriorityQueue> heap = \n new PriorityQueue<>((a, b) -> a.getValue() - b.getValue());\n for (Map.Entry e : count.entrySet()) {\n heap.offer(e);\n if (heap.size() > k) heap.poll();\n }\n int[] res = new int[k];\n for (int i = k - 1; i >= 0; i--) res[i] = heap.poll().getKey();\n return res;\n}", "solution_cpp": "vector topKFrequent(vector& nums, int k) {\n unordered_map count;\n for (int n : nums) count[n]++;\n priority_queue, vector>, greater>> heap;\n for (auto& [num, freq] : count) {\n heap.push({freq, num});\n if (heap.size() > k) heap.pop();\n }\n vector res;\n while (!heap.empty()) { res.push_back(heap.top().second); heap.pop(); }\n reverse(res.begin(), res.end());\n return res;\n}", "test_cases": ["nums=[1,1,1,2,2,3], k=2 -> [1,2]", "nums=[1], k=1 -> [1]"], "key_points": ["小顶堆保持大小k", "时间复杂度O(nlogk)"], "tags": ["heap", "medium", "Amazon", "Facebook"]} {"problem_id": "algo_00976", "original_id": "3sum", "title": "三数之和", "category": "two-pointers", "difficulty": "medium", "companies": ["Google", "Amazon"], "description": "给你一个整数数组 nums,判断是否存在三元组满足和为0,返回所有不重复的三元组。", "solution_python": "def threeSum(nums):\n nums.sort()\n result = []\n for i in range(len(nums) - 2):\n if i > 0 and nums[i] == nums[i-1]: continue\n left, right = i + 1, len(nums) - 1\n while left < right:\n total = nums[i] + nums[left] + nums[right]\n if total < 0: left += 1\n elif total > 0: right -= 1\n else:\n result.append([nums[i], nums[left], nums[right]])\n while left < right and nums[left] == nums[left+1]: left += 1\n while left < right and nums[right] == nums[right-1]: right -= 1\n left += 1; right -= 1\n return result", "solution_java": "public List> threeSum(int[] nums) {\n Arrays.sort(nums);\n List> result = new ArrayList<>();\n for (int i = 0; i < nums.length - 2; i++) {\n if (i > 0 && nums[i] == nums[i-1]) continue;\n int left = i + 1, right = nums.length - 1;\n while (left < right) {\n int total = nums[i] + nums[left] + nums[right];\n if (total < 0) left++;\n else if (total > 0) right--;\n else {\n result.add(Arrays.asList(nums[i], nums[left], nums[right]));\n while (left < right && nums[left] == nums[left+1]) left++;\n while (left < right && nums[right] == nums[right-1]) right--;\n left++; right--;\n }\n }\n }\n return result;\n}", "solution_cpp": "vector> threeSum(vector& nums) {\n sort(nums.begin(), nums.end());\n vector> result;\n for (int i = 0; i < nums.size() - 2; i++) {\n if (i > 0 && nums[i] == nums[i-1]) continue;\n int left = i + 1, right = nums.size() - 1;\n while (left < right) {\n int total = nums[i] + nums[left] + nums[right];\n if (total < 0) left++;\n else if (total > 0) right--;\n else {\n result.push_back({nums[i], nums[left], nums[right]});\n while (left < right && nums[left] == nums[left+1]) left++;\n while (left < right && nums[right] == nums[right-1]) right--;\n left++; right--;\n }\n }\n }\n return result;\n}", "test_cases": ["nums=[-1,0,1,2,-1,-4] -> [[-1,-1,2],[-1,0,1]]"], "key_points": ["排序+双指针", "去重是关键"], "tags": ["two-pointers", "medium", "Google", "Amazon"]} {"problem_id": "algo_00977", "original_id": "container-water", "title": "盛最多水的容器", "category": "two-pointers", "difficulty": "medium", "companies": ["Google", "Uber"], "description": "给定一个长度为 n 的整数数组 height,找出其中的两条线,使得它们与 x 轴共同构成的容器可以容纳最多的水。", "solution_python": "def maxArea(height):\n left, right = 0, len(height) - 1\n max_area = 0\n while left < right:\n h = min(height[left], height[right])\n max_area = max(max_area, h * (right - left))\n if height[left] < height[right]: left += 1\n else: right -= 1\n return max_area", "solution_java": "public int maxArea(int[] height) {\n int left = 0, right = height.length - 1, maxArea = 0;\n while (left < right) {\n int h = Math.min(height[left], height[right]);\n maxArea = Math.max(maxArea, h * (right - left));\n if (height[left] < height[right]) left++;\n else right--;\n }\n return maxArea;\n}", "solution_cpp": "int maxArea(vector& height) {\n int left = 0, right = height.size() - 1, maxArea = 0;\n while (left < right) {\n int h = min(height[left], height[right]);\n maxArea = max(maxArea, h * (right - left));\n if (height[left] < height[right]) left++;\n else right--;\n }\n return maxArea;\n}", "test_cases": ["height=[1,8,6,2,5,4,8,3,7] -> 49"], "key_points": ["移动短边指针", "面积=min(h1,h2)*width"], "tags": ["two-pointers", "medium", "Google", "Uber"]} {"problem_id": "algo_00978", "original_id": "min-stack", "title": "最小栈", "category": "stack", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "设计一个支持 push,pop,top 操作,并能在常数时间内检索到最小元素的栈。", "solution_python": "class MinStack:\n def __init__(self):\n self.stack = []\n self.min_stack = []\n def push(self, val):\n self.stack.append(val)\n self.min_stack.append(min(val, self.min_stack[-1] if self.min_stack else val))\n def pop(self):\n self.stack.pop(); self.min_stack.pop()\n def top(self): return self.stack[-1]\n def getMin(self): return self.min_stack[-1]", "solution_java": "class MinStack {\n Stack stack = new Stack<>();\n Stack minStack = new Stack<>();\n public void push(int val) { stack.push(val); minStack.push(Math.min(val, minStack.isEmpty() ? val : minStack.peek())); }\n public void pop() { stack.pop(); minStack.pop(); }\n public int top() { return stack.peek(); }\n public int getMin() { return minStack.peek(); }\n}", "solution_cpp": "class MinStack {\n stack st, minSt;\npublic:\n void push(int val) { st.push(val); minSt.push(min(val, minSt.empty() ? val : minSt.top())); }\n void pop() { st.pop(); minSt.pop(); }\n int top() { return st.top(); }\n int getMin() { return minSt.top(); }\n};", "test_cases": ["push(-2), push(0), push(-3) -> getMin() returns -3"], "key_points": ["辅助栈记录最小值", "O(1)时间获取最小值"], "tags": ["stack", "medium", "Google", "Microsoft"]} {"problem_id": "algo_00979", "original_id": "lru-cache", "title": "LRU缓存", "category": "design", "difficulty": "hard", "companies": ["Google", "Amazon"], "description": "设计和实现一个 LRU(最近最少使用)缓存机制。", "solution_python": "class LRUCache:\n def __init__(self, capacity):\n self.capacity = capacity\n self.cache = {}\n self.order = []\n def get(self, key):\n if key not in self.cache: return -1\n self.order.remove(key); self.order.append(key)\n return self.cache[key]\n def put(self, key, value):\n if key in self.cache:\n self.order.remove(key)\n elif len(self.cache) >= self.capacity:\n del self.cache[self.order.pop(0)]\n self.cache[key] = value; self.order.append(key)", "solution_java": "class LRUCache {\n int capacity;\n LinkedHashMap cache = new LinkedHashMap<>();\n public LRUCache(int cap) { capacity = cap; }\n public int get(int key) { return cache.containsKey(key) ? cache.remove(key) : -1; }\n public void put(int key, int val) {\n if (cache.containsKey(key)) cache.remove(key);\n else if (cache.size() >= capacity) cache.remove(cache.keySet().iterator().next());\n cache.put(key, val);\n }\n}", "solution_cpp": "class LRUCache {\n int cap;\n list> dll;\n unordered_map>::iterator> cache;\npublic:\n LRUCache(int capacity) : cap(capacity) {}\n int get(int key) {\n auto it = cache.find(key);\n if (it == cache.end()) return -1;\n dll.splice(dll.end(), dll, it->second);\n return it->second->second;\n }\n void put(int key, int value) {\n auto it = cache.find(key);\n if (it != cache.end()) dll.erase(it->second);\n else if (cache.size() >= cap) { cache.erase(dll.front().first); dll.pop_front(); }\n dll.push_back({key, value});\n cache[key] = --dll.end();\n }\n};", "test_cases": ["put(1,1), put(2,2), get(1) -> 1"], "key_points": ["HashMap + 双向链表", "O(1)时间操作"], "tags": ["design", "hard", "Google", "Amazon"]} {"problem_id": "algo_00980", "original_id": "num-islands", "title": "岛屿数量", "category": "graph", "difficulty": "medium", "companies": ["Google", "Facebook"], "description": "给你一个由 '1'(陆地)和 '0'(水)组成的二维网格,请你计算网格中岛屿的数量。岛屿总是被水包围,且只能由水平或垂直方向相邻的陆地连接形成。", "solution_python": "def numIslands(grid):\n if not grid: return 0\n rows, cols = len(grid), len(grid[0])\n count = 0\n def dfs(r, c):\n if r < 0 or r >= rows or c < 0 or c >= cols or grid[r][c] != '1': return\n grid[r][c] = '0'\n dfs(r+1, c); dfs(r-1, c); dfs(r, c+1); dfs(r, c-1)\n for r in range(rows):\n for c in range(cols):\n if grid[r][c] == '1': count += 1; dfs(r, c)\n return count", "solution_java": "public int numIslands(char[][] grid) {\n if (grid.length == 0) return 0;\n int count = 0;\n for (int i = 0; i < grid.length; i++)\n for (int j = 0; j < grid[0].length; j++)\n if (grid[i][j] == '1') { count++; dfs(grid, i, j); }\n return count;\n}\nprivate void dfs(char[][] grid, int r, int c) {\n if (r < 0 || r >= grid.length || c < 0 || c >= grid[0].length || grid[r][c] != '1') return;\n grid[r][c] = '0';\n dfs(grid, r+1, c); dfs(grid, r-1, c); dfs(grid, r, c+1); dfs(grid, r, c-1);\n}", "solution_cpp": "int numIslands(vector>& grid) {\n if (grid.empty()) return 0;\n int count = 0;\n for (int i = 0; i < grid.size(); i++)\n for (int j = 0; j < grid[0].size(); j++)\n if (grid[i][j] == '1') { count++; dfs(grid, i, j); }\n return count;\n}\nvoid dfs(vector>& grid, int r, int c) {\n if (r < 0 || r >= grid.size() || c < 0 || c >= grid[0].size() || grid[r][c] != '1') return;\n grid[r][c] = '0';\n dfs(grid, r+1, c); dfs(grid, r-1, c); dfs(grid, r, c+1); dfs(grid, r, c-1);\n}", "test_cases": ["grid=[[1,1,1,1,0],[1,1,0,1,0],[1,1,0,0,0],[0,0,0,0,0]] -> 1"], "key_points": ["DFS/BFS遍历", "访问后标记为0避免重复"], "tags": ["graph", "medium", "Google", "Facebook"]} {"problem_id": "algo_00981", "original_id": "two-sum", "title": "两数之和", "category": "array", "difficulty": "easy", "companies": ["Amazon", "Google"], "description": "给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那两个整数,并返回他们的数组下标。", "solution_python": "def twoSum(nums, target):\n hashmap = {}\n for i, num in enumerate(nums):\n complement = target - num\n if complement in hashmap:\n return [hashmap[complement], i]\n hashmap[num] = i\n return []", "solution_java": "public int[] twoSum(int[] nums, int target) {\n Map map = new HashMap<>();\n for (int i = 0; i < nums.length; i++) {\n int complement = target - nums[i];\n if (map.containsKey(complement)) return new int[]{map.get(complement), i};\n map.put(nums[i], i);\n }\n return new int[]{};\n}", "solution_cpp": "vector twoSum(vector& nums, int target) {\n unordered_map m;\n for (int i = 0; i < nums.size(); i++) {\n if (m.count(target - nums[i])) return {m[target - nums[i]], i};\n m[nums[i]] = i;\n }\n return {};\n}", "test_cases": ["nums=[2,7,11,15], target=9 -> [0,1]", "nums=[3,2,4], target=6 -> [1,2]"], "key_points": ["哈希表一次遍历", "空间换时间"], "tags": ["array", "easy", "Amazon", "Google"]} {"problem_id": "algo_00982", "original_id": "merge-sorted", "title": "合并两个有序数组", "category": "array", "difficulty": "easy", "companies": ["Microsoft", "Uber"], "description": "给你两个按非递减顺序排列的整数数组 nums1 和 nums2,另有两个整数 m 和 n,分别表示 nums1 和 nums2 中的元素数目。请你合并 nums2 到 nums1 中。", "solution_python": "def merge(nums1, m, nums2, n):\n p1, p2, p = m-1, n-1, m+n-1\n while p1 >= 0 and p2 >= 0:\n if nums1[p1] > nums2[p2]: nums1[p] = nums1[p1]; p1 -= 1\n else: nums1[p] = nums2[p2]; p2 -= 1\n p -= 1\n while p2 >= 0: nums1[p] = nums2[p2]; p2 -= 1; p -= 1", "solution_java": "public void merge(int[] nums1, int m, int[] nums2, int n) {\n int p1 = m-1, p2 = n-1, p = m+n-1;\n while (p1 >= 0 && p2 >= 0) {\n nums1[p--] = nums1[p1] > nums2[p2] ? nums1[p1--] : nums2[p2--];\n }\n while (p2 >= 0) nums1[p--] = nums2[p2--];\n}", "solution_cpp": "void merge(vector& nums1, int m, vector& nums2, int n) {\n int p1 = m-1, p2 = n-1, p = m+n-1;\n while (p1 >= 0 && p2 >= 0) nums1[p--] = nums1[p1] > nums2[p2] ? nums1[p1--] : nums2[p2--];\n while (p2 >= 0) nums1[p--] = nums2[p2--];\n}", "test_cases": ["nums1=[1,2,3], m=3, nums2=[2,5,6], n=3 -> [1,2,2,3,5,6]", "nums1=[], m=0, nums2=[1], n=1 -> [1]"], "key_points": ["从后往前合并", "三指针技巧"], "tags": ["array", "easy", "Microsoft", "Uber"]} {"problem_id": "algo_00983", "original_id": "max-subarray", "title": "最大子数组和", "category": "array", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "给你一个整数数组 nums ,请你找出一个具有最大和的连续子数组,返回其最大和。", "solution_python": "def maxSubArray(nums):\n max_sum = current = nums[0]\n for num in nums[1:]:\n current = max(num, current + num)\n max_sum = max(max_sum, current)\n return max_sum", "solution_java": "public int maxSubArray(int[] nums) {\n int maxSum = nums[0], curr = nums[0];\n for (int i = 1; i < nums.length; i++) {\n curr = Math.max(nums[i], curr + nums[i]);\n maxSum = Math.max(maxSum, curr);\n }\n return maxSum;\n}", "solution_cpp": "int maxSubArray(vector& nums) {\n int maxSum = nums[0], curr = nums[0];\n for (int i = 1; i < nums.size(); i++) {\n curr = max(nums[i], curr + nums[i]);\n maxSum = max(maxSum, curr);\n }\n return maxSum;\n}", "test_cases": ["nums=[-2,1,-3,4,-1,2,1,-5,4] -> 6", "nums=[1] -> 1"], "key_points": ["Kadane算法", "动态规划基础题"], "tags": ["array", "medium", "Google", "Microsoft"]} {"problem_id": "algo_00984", "original_id": "valid-parentheses", "title": "有效的括号", "category": "string", "difficulty": "easy", "companies": ["Google", "Uber"], "description": "给定一个只包括 '(',')','{','}','[',']' 的字符串 s,判断字符串是否有效。", "solution_python": "def isValid(s):\n stack = []\n mapping = {')': '(', ']': '[', '}': '{'}\n for c in s:\n if c in mapping:\n if not stack or stack[-1] != mapping[c]: return False\n stack.pop()\n else: stack.append(c)\n return not stack", "solution_java": "public boolean isValid(String s) {\n Stack stack = new Stack<>();\n Map map = Map.of(')', '(', ']', '[', '}', '{');\n for (char c : s.toCharArray()) {\n if (map.containsValue(c)) stack.push(c);\n else if (!stack.isEmpty() && stack.pop() != map.get(c)) return false;\n }\n return stack.isEmpty();\n}", "solution_cpp": "bool isValid(string s) {\n stack st;\n unordered_map m = {{')','('},{']','['},{'}','{'}};\n for (char c : s) {\n if (m.find(c) == m.end()) st.push(c);\n else if (st.empty() || st.top() != m[c]) return false;\n else st.pop();\n }\n return st.empty();\n}", "test_cases": ["s=\"()\" -> true", "s=\"()[]{}\" -> true", "s=\"(]\" -> false"], "key_points": ["栈匹配法", "注意空栈边界"], "tags": ["string", "easy", "Google", "Uber"]} {"problem_id": "algo_00985", "original_id": "longest-palindrome", "title": "最长回文子串", "category": "string", "difficulty": "medium", "companies": ["Google", "Amazon"], "description": "给你一个字符串 s,找到 s 中最长的回文子串。", "solution_python": "def longestPalindrome(s):\n def expand(l, r):\n while l >= 0 and r < len(s) and s[l] == s[r]: l -= 1; r += 1\n return l + 1, r - 1\n start = end = 0\n for i in range(len(s)):\n l1, r1 = expand(i, i)\n l2, r2 = expand(i, i + 1)\n if r1 - l1 > end - start: start, end = l1, r1\n if r2 - l2 > end - start: start, end = l2, r2\n return s[start:end+1]", "solution_java": "public String longestPalindrome(String s) {\n int start = 0, end = 0;\n for (int i = 0; i < s.length(); i++) {\n int len1 = expand(s, i, i), len2 = expand(s, i, i+1);\n int len = Math.max(len1, len2);\n if (len > end - start) { start = i - (len-1)/2; end = i + len/2; }\n }\n return s.substring(start, end + 1);\n}\nprivate int expand(String s, int l, int r) {\n while (l >= 0 && r < s.length() && s.charAt(l) == s.charAt(r)) { l--; r++; }\n return r - l - 1;\n}", "solution_cpp": "string longestPalindrome(string s) {\n int start = 0, end = 0;\n for (int i = 0; i < s.size(); i++) {\n int len1 = expand(s, i, i), len2 = expand(s, i, i+1);\n if (max(len1, len2) > end - start) { start = i - (max(len1,len2)-1)/2; end = i + max(len1,len2)/2; }\n }\n return s.substr(start, end - start + 1);\n}", "test_cases": ["s=\"babad\" -> bab或aba", "s=\"cbbd\" -> bb"], "key_points": ["中心扩展法", "处理奇偶长度"], "tags": ["string", "medium", "Google", "Amazon"]} {"problem_id": "algo_00986", "original_id": "reverse-list", "title": "反转链表", "category": "linkedlist", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "给你单链表的头节点 head,请你反转链表,并返回反转后的链表。", "solution_python": "def reverseList(head):\n prev = None\n curr = head\n while curr:\n nxt = curr.next\n curr.next = prev\n prev = curr\n curr = nxt\n return prev", "solution_java": "public ListNode reverseList(ListNode head) {\n ListNode prev = null, curr = head;\n while (curr != null) {\n ListNode next = curr.next;\n curr.next = prev;\n prev = curr;\n curr = next;\n }\n return prev;\n}", "solution_cpp": "ListNode* reverseList(ListNode* head) {\n ListNode* prev = nullptr, *curr = head;\n while (curr) {\n ListNode* next = curr->next;\n curr->next = prev;\n prev = curr;\n curr = next;\n }\n return prev;\n}", "test_cases": ["head=[1,2,3,4,5] -> [5,4,3,2,1]", "head=[1,2] -> [2,1]"], "key_points": ["迭代法 O(1)空间", "递归法 O(n)空间"], "tags": ["linkedlist", "medium", "Google", "Microsoft"]} {"problem_id": "algo_00987", "original_id": "middle-node", "title": "链表的中间结点", "category": "linkedlist", "difficulty": "easy", "companies": ["Amazon", "Facebook"], "description": "给你单链表的头节点 head,请你找出并返回链表的中间结点。如果有两个中间结点,则返回第二个中间结点。", "solution_python": "def middleNode(head):\n slow = fast = head\n while fast and fast.next:\n slow = slow.next\n fast = fast.next.next\n return slow", "solution_java": "public ListNode middleNode(ListNode head) {\n ListNode slow = head, fast = head;\n while (fast != null && fast.next != null) {\n slow = slow.next;\n fast = fast.next.next;\n }\n return slow;\n}", "solution_cpp": "ListNode* middleNode(ListNode* head) {\n ListNode* slow = head, *fast = head;\n while (fast && fast->next) { slow = slow->next; fast = fast->next->next; }\n return slow;\n}", "test_cases": ["head=[1,2,3,4,5] -> 3", "head=[1,2,3,4,5,6] -> 4"], "key_points": ["快慢指针", "O(n)时间O(1)空间"], "tags": ["linkedlist", "easy", "Amazon", "Facebook"]} {"problem_id": "algo_00988", "original_id": "max-depth", "title": "二叉树的最大深度", "category": "tree", "difficulty": "easy", "companies": ["Microsoft", "Apple"], "description": "给定一个二叉树 root,返回其最大深度。", "solution_python": "def maxDepth(root):\n if not root: return 0\n return max(maxDepth(root.left), maxDepth(root.right)) + 1", "solution_java": "public int maxDepth(TreeNode root) {\n if (root == null) return 0;\n return Math.max(maxDepth(root.left), maxDepth(root.right)) + 1;\n}", "solution_cpp": "int maxDepth(TreeNode* root) {\n if (!root) return 0;\n return max(maxDepth(root->left), maxDepth(root->right)) + 1;\n}", "test_cases": ["root=[3,9,20,null,null,15,7] -> 3", "root=[1,null,2] -> 2"], "key_points": ["DFS递归", "层序遍历也可"], "tags": ["tree", "easy", "Microsoft", "Apple"]} {"problem_id": "algo_00989", "original_id": "inorder-traversal", "title": "二叉树的中序遍历", "category": "tree", "difficulty": "easy", "companies": ["Google", "Microsoft"], "description": "给定一个二叉树的根节点 root,返回它的中序遍历结果。", "solution_python": "def inorderTraversal(root):\n result = []\n def dfs(node):\n if node:\n dfs(node.left)\n result.append(node.val)\n dfs(node.right)\n dfs(root)\n return result", "solution_java": "public List inorderTraversal(TreeNode root) {\n List res = new ArrayList<>();\n dfs(root, res);\n return res;\n}\nprivate void dfs(TreeNode node, List res) {\n if (node == null) return;\n dfs(node.left, res); res.add(node.val); dfs(node.right, res);\n}", "solution_cpp": "vector inorderTraversal(TreeNode* root) {\n vector res;\n dfs(root, res);\n return res;\n}\nvoid dfs(TreeNode* node, vector& res) {\n if (!node) return;\n dfs(node->left, res); res.push_back(node->val); dfs(node->right, res);\n}", "test_cases": ["root=[1,null,2,3] -> [1,3,2]", "root=[] -> []"], "key_points": ["左-根-右顺序", "递归最简洁"], "tags": ["tree", "easy", "Google", "Microsoft"]} {"problem_id": "algo_00990", "original_id": "binary-search", "title": "二分查找", "category": "binarysearch", "difficulty": "easy", "companies": ["Google", "Amazon"], "description": "给定一个 n 个元素有序的(升序)整型数组 nums 和一个目标值 target,写一个函数搜索 nums 中的 target,如果目标值存在返回下标,否则返回 -1。", "solution_python": "def search(nums, target):\n left, right = 0, len(nums) - 1\n while left <= right:\n mid = (left + right) // 2\n if nums[mid] == target: return mid\n elif nums[mid] < target: left = mid + 1\n else: right = mid - 1\n return -1", "solution_java": "public int search(int[] nums, int target) {\n int left = 0, right = nums.length - 1;\n while (left <= right) {\n int mid = left + (right - left) / 2;\n if (nums[mid] == target) return mid;\n else if (nums[mid] < target) left = mid + 1;\n else right = mid - 1;\n }\n return -1;\n}", "solution_cpp": "int search(vector& nums, int target) {\n int left = 0, right = nums.size() - 1;\n while (left <= right) {\n int mid = left + (right - left) / 2;\n if (nums[mid] == target) return mid;\n else if (nums[mid] < target) left = mid + 1;\n else right = mid - 1;\n }\n return -1;\n}", "test_cases": ["nums=[-1,0,3,5,9,12], target=9 -> 4", "nums=[-1,0,3,5,9,12], target=2 -> -1"], "key_points": ["标准模板", "注意防溢出写法"], "tags": ["binarysearch", "easy", "Google", "Amazon"]} {"problem_id": "algo_00991", "original_id": "climbing-stairs", "title": "爬楼梯", "category": "dp", "difficulty": "easy", "companies": ["Amazon", "Google"], "description": "假设你正在爬楼梯。需要 n 阶你才能到达楼顶。每次你可以爬 1 或 2 个台阶。你有多少种不同的方法可以爬到楼顶?", "solution_python": "def climbStairs(n):\n if n <= 2: return n\n a, b = 1, 2\n for _ in range(3, n+1):\n a, b = b, a + b\n return b", "solution_java": "public int climbStairs(int n) {\n if (n <= 2) return n;\n int a = 1, b = 2;\n for (int i = 3; i <= n; i++) { int temp = a + b; a = b; b = temp; }\n return b;\n}", "solution_cpp": "int climbStairs(int n) {\n if (n <= 2) return n;\n int a = 1, b = 2;\n for (int i = 3; i <= n; i++) { int temp = a + b; a = b; b = temp; }\n return b;\n}", "test_cases": ["n=2 -> 2", "n=3 -> 3", "n=5 -> 8"], "key_points": ["斐波那契数列", "滚动数组优化空间"], "tags": ["dp", "easy", "Amazon", "Google"]} {"problem_id": "algo_00992", "original_id": "coin-change", "title": "零钱兑换", "category": "dp", "difficulty": "medium", "companies": ["Google", "Amazon"], "description": "给你一个整数数组 coins 表示不同面额的硬币,以及一个整数 amount 表示总金额。计算并返回可以凑成总金额所需的最少的硬币个数。如果没有任何一种硬币组合能组成总金额,返回 -1。", "solution_python": "def coinChange(coins, amount):\n dp = [float('inf')] * (amount + 1)\n dp[0] = 0\n for coin in coins:\n for x in range(coin, amount + 1):\n dp[x] = min(dp[x], dp[x - coin] + 1)\n return dp[amount] if dp[amount] != float('inf') else -1", "solution_java": "public int coinChange(int[] coins, int amount) {\n int[] dp = new int[amount + 1];\n Arrays.fill(dp, amount + 1);\n dp[0] = 0;\n for (int coin : coins) {\n for (int x = coin; x <= amount; x++) {\n dp[x] = Math.min(dp[x], dp[x - coin] + 1);\n }\n }\n return dp[amount] > amount ? -1 : dp[amount];\n}", "solution_cpp": "int coinChange(vector& coins, int amount) {\n vector dp(amount + 1, amount + 1);\n dp[0] = 0;\n for (int coin : coins) {\n for (int x = coin; x <= amount; x++) {\n dp[x] = min(dp[x], dp[x - coin] + 1);\n }\n }\n return dp[amount] > amount ? -1 : dp[amount];\n}", "test_cases": ["coins=[1,2,5], amount=11 -> 3", "coins=[2], amount=3 -> -1"], "key_points": ["完全背包问题", "dp[x] = min(dp[x-coin]+1)"], "tags": ["dp", "medium", "Google", "Amazon"]} {"problem_id": "algo_00993", "original_id": "subsets", "title": "子集", "category": "backtracking", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "给你一个整数数组 nums ,数组中的元素 互不相同 。返回该数组所有可能的子集(幂集)。", "solution_python": "def subsets(nums):\n result = []\n def backtrack(start, path):\n result.append(path[:])\n for i in range(start, len(nums)):\n path.append(nums[i])\n backtrack(i + 1, path)\n path.pop()\n backtrack(0, [])\n return result", "solution_java": "public List> subsets(int[] nums) {\n List> result = new ArrayList<>();\n backtrack(nums, 0, new ArrayList<>(), result);\n return result;\n}\nprivate void backtrack(int[] nums, int start, List path, List> result) {\n result.add(new ArrayList<>(path));\n for (int i = start; i < nums.length; i++) {\n path.add(nums[i]);\n backtrack(nums, i + 1, path, result);\n path.remove(path.size() - 1);\n }\n}", "solution_cpp": "vector> subsets(vector& nums) {\n vector> result;\n vector path;\n backtrack(nums, 0, path, result);\n return result;\n}\nvoid backtrack(vector& nums, int start, vector& path, vector>& result) {\n result.push_back(path);\n for (int i = start; i < nums.size(); i++) {\n path.push_back(nums[i]);\n backtrack(nums, i + 1, path, result);\n path.pop_back();\n }\n}", "test_cases": ["nums=[1,2,3] -> [[],[1],[2],[1,2],[3],[1,3],[2,3],[1,2,3]]"], "key_points": ["选或不选", "DFS遍历子集树"], "tags": ["backtracking", "medium", "Google", "Microsoft"]} {"problem_id": "algo_00994", "original_id": "permutations", "title": "全排列", "category": "backtracking", "difficulty": "medium", "companies": ["Google", "Facebook"], "description": "给定一个不含重复数字的数组 nums,返回其所有可能的全排列。", "solution_python": "def permute(nums):\n result = []\n def backtrack(path, used):\n if len(path) == len(nums):\n result.append(path[:])\n return\n for i in range(len(nums)):\n if used[i]: continue\n used[i] = True\n path.append(nums[i])\n backtrack(path, used)\n path.pop()\n used[i] = False\n backtrack([], [False]*len(nums))\n return result", "solution_java": "public List> permute(int[] nums) {\n List> result = new ArrayList<>();\n boolean[] used = new boolean[nums.length];\n backtrack(nums, used, new ArrayList<>(), result);\n return result;\n}\nprivate void backtrack(int[] nums, boolean[] used, List path, List> result) {\n if (path.size() == nums.length) { result.add(new ArrayList<>(path)); return; }\n for (int i = 0; i < nums.length; i++) {\n if (used[i]) continue;\n used[i] = true;\n path.add(nums[i]);\n backtrack(nums, used, path, result);\n path.remove(path.size() - 1);\n used[i] = false;\n }\n}", "solution_cpp": "vector> permute(vector& nums) {\n vector> result;\n vector used(nums.size(), false);\n vector path;\n backtrack(nums, used, path, result);\n return result;\n}\nvoid backtrack(vector& nums, vector& used, vector& path, vector>& result) {\n if (path.size() == nums.size()) { result.push_back(path); return; }\n for (int i = 0; i < nums.size(); i++) {\n if (used[i]) continue;\n used[i] = true;\n path.push_back(nums[i]);\n backtrack(nums, used, path, result);\n path.pop_back();\n used[i] = false;\n }\n}", "test_cases": ["nums=[1,2,3] -> [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]"], "key_points": ["标记已使用元素", "回溯经典模板"], "tags": ["backtracking", "medium", "Google", "Facebook"]} {"problem_id": "algo_00995", "original_id": "top-k-frequent", "title": "前K个高频元素", "category": "heap", "difficulty": "medium", "companies": ["Amazon", "Facebook"], "description": "给你一个整数数组 nums 和一个整数 k,请你返回其中出现频率前 k 高的元素。", "solution_python": "import heapq\nfrom collections import Counter\ndef topKFrequent(nums, k):\n count = Counter(nums)\n heap = []\n for num, freq in count.items():\n heapq.heappush(heap, (freq, num))\n if len(heap) > k: heapq.heappop(heap)\n return [num for freq, num in heap]", "solution_java": "public int[] topKFrequent(int[] nums, int k) {\n Map count = new HashMap<>();\n for (int n : nums) count.put(n, count.getOrDefault(n, 0) + 1);\n PriorityQueue> heap = \n new PriorityQueue<>((a, b) -> a.getValue() - b.getValue());\n for (Map.Entry e : count.entrySet()) {\n heap.offer(e);\n if (heap.size() > k) heap.poll();\n }\n int[] res = new int[k];\n for (int i = k - 1; i >= 0; i--) res[i] = heap.poll().getKey();\n return res;\n}", "solution_cpp": "vector topKFrequent(vector& nums, int k) {\n unordered_map count;\n for (int n : nums) count[n]++;\n priority_queue, vector>, greater>> heap;\n for (auto& [num, freq] : count) {\n heap.push({freq, num});\n if (heap.size() > k) heap.pop();\n }\n vector res;\n while (!heap.empty()) { res.push_back(heap.top().second); heap.pop(); }\n reverse(res.begin(), res.end());\n return res;\n}", "test_cases": ["nums=[1,1,1,2,2,3], k=2 -> [1,2]", "nums=[1], k=1 -> [1]"], "key_points": ["小顶堆保持大小k", "时间复杂度O(nlogk)"], "tags": ["heap", "medium", "Amazon", "Facebook"]} {"problem_id": "algo_00996", "original_id": "3sum", "title": "三数之和", "category": "two-pointers", "difficulty": "medium", "companies": ["Google", "Amazon"], "description": "给你一个整数数组 nums,判断是否存在三元组满足和为0,返回所有不重复的三元组。", "solution_python": "def threeSum(nums):\n nums.sort()\n result = []\n for i in range(len(nums) - 2):\n if i > 0 and nums[i] == nums[i-1]: continue\n left, right = i + 1, len(nums) - 1\n while left < right:\n total = nums[i] + nums[left] + nums[right]\n if total < 0: left += 1\n elif total > 0: right -= 1\n else:\n result.append([nums[i], nums[left], nums[right]])\n while left < right and nums[left] == nums[left+1]: left += 1\n while left < right and nums[right] == nums[right-1]: right -= 1\n left += 1; right -= 1\n return result", "solution_java": "public List> threeSum(int[] nums) {\n Arrays.sort(nums);\n List> result = new ArrayList<>();\n for (int i = 0; i < nums.length - 2; i++) {\n if (i > 0 && nums[i] == nums[i-1]) continue;\n int left = i + 1, right = nums.length - 1;\n while (left < right) {\n int total = nums[i] + nums[left] + nums[right];\n if (total < 0) left++;\n else if (total > 0) right--;\n else {\n result.add(Arrays.asList(nums[i], nums[left], nums[right]));\n while (left < right && nums[left] == nums[left+1]) left++;\n while (left < right && nums[right] == nums[right-1]) right--;\n left++; right--;\n }\n }\n }\n return result;\n}", "solution_cpp": "vector> threeSum(vector& nums) {\n sort(nums.begin(), nums.end());\n vector> result;\n for (int i = 0; i < nums.size() - 2; i++) {\n if (i > 0 && nums[i] == nums[i-1]) continue;\n int left = i + 1, right = nums.size() - 1;\n while (left < right) {\n int total = nums[i] + nums[left] + nums[right];\n if (total < 0) left++;\n else if (total > 0) right--;\n else {\n result.push_back({nums[i], nums[left], nums[right]});\n while (left < right && nums[left] == nums[left+1]) left++;\n while (left < right && nums[right] == nums[right-1]) right--;\n left++; right--;\n }\n }\n }\n return result;\n}", "test_cases": ["nums=[-1,0,1,2,-1,-4] -> [[-1,-1,2],[-1,0,1]]"], "key_points": ["排序+双指针", "去重是关键"], "tags": ["two-pointers", "medium", "Google", "Amazon"]} {"problem_id": "algo_00997", "original_id": "container-water", "title": "盛最多水的容器", "category": "two-pointers", "difficulty": "medium", "companies": ["Google", "Uber"], "description": "给定一个长度为 n 的整数数组 height,找出其中的两条线,使得它们与 x 轴共同构成的容器可以容纳最多的水。", "solution_python": "def maxArea(height):\n left, right = 0, len(height) - 1\n max_area = 0\n while left < right:\n h = min(height[left], height[right])\n max_area = max(max_area, h * (right - left))\n if height[left] < height[right]: left += 1\n else: right -= 1\n return max_area", "solution_java": "public int maxArea(int[] height) {\n int left = 0, right = height.length - 1, maxArea = 0;\n while (left < right) {\n int h = Math.min(height[left], height[right]);\n maxArea = Math.max(maxArea, h * (right - left));\n if (height[left] < height[right]) left++;\n else right--;\n }\n return maxArea;\n}", "solution_cpp": "int maxArea(vector& height) {\n int left = 0, right = height.size() - 1, maxArea = 0;\n while (left < right) {\n int h = min(height[left], height[right]);\n maxArea = max(maxArea, h * (right - left));\n if (height[left] < height[right]) left++;\n else right--;\n }\n return maxArea;\n}", "test_cases": ["height=[1,8,6,2,5,4,8,3,7] -> 49"], "key_points": ["移动短边指针", "面积=min(h1,h2)*width"], "tags": ["two-pointers", "medium", "Google", "Uber"]} {"problem_id": "algo_00998", "original_id": "min-stack", "title": "最小栈", "category": "stack", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "设计一个支持 push,pop,top 操作,并能在常数时间内检索到最小元素的栈。", "solution_python": "class MinStack:\n def __init__(self):\n self.stack = []\n self.min_stack = []\n def push(self, val):\n self.stack.append(val)\n self.min_stack.append(min(val, self.min_stack[-1] if self.min_stack else val))\n def pop(self):\n self.stack.pop(); self.min_stack.pop()\n def top(self): return self.stack[-1]\n def getMin(self): return self.min_stack[-1]", "solution_java": "class MinStack {\n Stack stack = new Stack<>();\n Stack minStack = new Stack<>();\n public void push(int val) { stack.push(val); minStack.push(Math.min(val, minStack.isEmpty() ? val : minStack.peek())); }\n public void pop() { stack.pop(); minStack.pop(); }\n public int top() { return stack.peek(); }\n public int getMin() { return minStack.peek(); }\n}", "solution_cpp": "class MinStack {\n stack st, minSt;\npublic:\n void push(int val) { st.push(val); minSt.push(min(val, minSt.empty() ? val : minSt.top())); }\n void pop() { st.pop(); minSt.pop(); }\n int top() { return st.top(); }\n int getMin() { return minSt.top(); }\n};", "test_cases": ["push(-2), push(0), push(-3) -> getMin() returns -3"], "key_points": ["辅助栈记录最小值", "O(1)时间获取最小值"], "tags": ["stack", "medium", "Google", "Microsoft"]} {"problem_id": "algo_00999", "original_id": "lru-cache", "title": "LRU缓存", "category": "design", "difficulty": "hard", "companies": ["Google", "Amazon"], "description": "设计和实现一个 LRU(最近最少使用)缓存机制。", "solution_python": "class LRUCache:\n def __init__(self, capacity):\n self.capacity = capacity\n self.cache = {}\n self.order = []\n def get(self, key):\n if key not in self.cache: return -1\n self.order.remove(key); self.order.append(key)\n return self.cache[key]\n def put(self, key, value):\n if key in self.cache:\n self.order.remove(key)\n elif len(self.cache) >= self.capacity:\n del self.cache[self.order.pop(0)]\n self.cache[key] = value; self.order.append(key)", "solution_java": "class LRUCache {\n int capacity;\n LinkedHashMap cache = new LinkedHashMap<>();\n public LRUCache(int cap) { capacity = cap; }\n public int get(int key) { return cache.containsKey(key) ? cache.remove(key) : -1; }\n public void put(int key, int val) {\n if (cache.containsKey(key)) cache.remove(key);\n else if (cache.size() >= capacity) cache.remove(cache.keySet().iterator().next());\n cache.put(key, val);\n }\n}", "solution_cpp": "class LRUCache {\n int cap;\n list> dll;\n unordered_map>::iterator> cache;\npublic:\n LRUCache(int capacity) : cap(capacity) {}\n int get(int key) {\n auto it = cache.find(key);\n if (it == cache.end()) return -1;\n dll.splice(dll.end(), dll, it->second);\n return it->second->second;\n }\n void put(int key, int value) {\n auto it = cache.find(key);\n if (it != cache.end()) dll.erase(it->second);\n else if (cache.size() >= cap) { cache.erase(dll.front().first); dll.pop_front(); }\n dll.push_back({key, value});\n cache[key] = --dll.end();\n }\n};", "test_cases": ["put(1,1), put(2,2), get(1) -> 1"], "key_points": ["HashMap + 双向链表", "O(1)时间操作"], "tags": ["design", "hard", "Google", "Amazon"]} {"problem_id": "algo_01000", "original_id": "num-islands", "title": "岛屿数量", "category": "graph", "difficulty": "medium", "companies": ["Google", "Facebook"], "description": "给你一个由 '1'(陆地)和 '0'(水)组成的二维网格,请你计算网格中岛屿的数量。岛屿总是被水包围,且只能由水平或垂直方向相邻的陆地连接形成。", "solution_python": "def numIslands(grid):\n if not grid: return 0\n rows, cols = len(grid), len(grid[0])\n count = 0\n def dfs(r, c):\n if r < 0 or r >= rows or c < 0 or c >= cols or grid[r][c] != '1': return\n grid[r][c] = '0'\n dfs(r+1, c); dfs(r-1, c); dfs(r, c+1); dfs(r, c-1)\n for r in range(rows):\n for c in range(cols):\n if grid[r][c] == '1': count += 1; dfs(r, c)\n return count", "solution_java": "public int numIslands(char[][] grid) {\n if (grid.length == 0) return 0;\n int count = 0;\n for (int i = 0; i < grid.length; i++)\n for (int j = 0; j < grid[0].length; j++)\n if (grid[i][j] == '1') { count++; dfs(grid, i, j); }\n return count;\n}\nprivate void dfs(char[][] grid, int r, int c) {\n if (r < 0 || r >= grid.length || c < 0 || c >= grid[0].length || grid[r][c] != '1') return;\n grid[r][c] = '0';\n dfs(grid, r+1, c); dfs(grid, r-1, c); dfs(grid, r, c+1); dfs(grid, r, c-1);\n}", "solution_cpp": "int numIslands(vector>& grid) {\n if (grid.empty()) return 0;\n int count = 0;\n for (int i = 0; i < grid.size(); i++)\n for (int j = 0; j < grid[0].size(); j++)\n if (grid[i][j] == '1') { count++; dfs(grid, i, j); }\n return count;\n}\nvoid dfs(vector>& grid, int r, int c) {\n if (r < 0 || r >= grid.size() || c < 0 || c >= grid[0].size() || grid[r][c] != '1') return;\n grid[r][c] = '0';\n dfs(grid, r+1, c); dfs(grid, r-1, c); dfs(grid, r, c+1); dfs(grid, r, c-1);\n}", "test_cases": ["grid=[[1,1,1,1,0],[1,1,0,1,0],[1,1,0,0,0],[0,0,0,0,0]] -> 1"], "key_points": ["DFS/BFS遍历", "访问后标记为0避免重复"], "tags": ["graph", "medium", "Google", "Facebook"]} {"problem_id": "algo_01001", "original_id": "two-sum", "title": "两数之和", "category": "array", "difficulty": "easy", "companies": ["Amazon", "Google"], "description": "给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那两个整数,并返回他们的数组下标。", "solution_python": "def twoSum(nums, target):\n hashmap = {}\n for i, num in enumerate(nums):\n complement = target - num\n if complement in hashmap:\n return [hashmap[complement], i]\n hashmap[num] = i\n return []", "solution_java": "public int[] twoSum(int[] nums, int target) {\n Map map = new HashMap<>();\n for (int i = 0; i < nums.length; i++) {\n int complement = target - nums[i];\n if (map.containsKey(complement)) return new int[]{map.get(complement), i};\n map.put(nums[i], i);\n }\n return new int[]{};\n}", "solution_cpp": "vector twoSum(vector& nums, int target) {\n unordered_map m;\n for (int i = 0; i < nums.size(); i++) {\n if (m.count(target - nums[i])) return {m[target - nums[i]], i};\n m[nums[i]] = i;\n }\n return {};\n}", "test_cases": ["nums=[2,7,11,15], target=9 -> [0,1]", "nums=[3,2,4], target=6 -> [1,2]"], "key_points": ["哈希表一次遍历", "空间换时间"], "tags": ["array", "easy", "Amazon", "Google"]} {"problem_id": "algo_01002", "original_id": "merge-sorted", "title": "合并两个有序数组", "category": "array", "difficulty": "easy", "companies": ["Microsoft", "Uber"], "description": "给你两个按非递减顺序排列的整数数组 nums1 和 nums2,另有两个整数 m 和 n,分别表示 nums1 和 nums2 中的元素数目。请你合并 nums2 到 nums1 中。", "solution_python": "def merge(nums1, m, nums2, n):\n p1, p2, p = m-1, n-1, m+n-1\n while p1 >= 0 and p2 >= 0:\n if nums1[p1] > nums2[p2]: nums1[p] = nums1[p1]; p1 -= 1\n else: nums1[p] = nums2[p2]; p2 -= 1\n p -= 1\n while p2 >= 0: nums1[p] = nums2[p2]; p2 -= 1; p -= 1", "solution_java": "public void merge(int[] nums1, int m, int[] nums2, int n) {\n int p1 = m-1, p2 = n-1, p = m+n-1;\n while (p1 >= 0 && p2 >= 0) {\n nums1[p--] = nums1[p1] > nums2[p2] ? nums1[p1--] : nums2[p2--];\n }\n while (p2 >= 0) nums1[p--] = nums2[p2--];\n}", "solution_cpp": "void merge(vector& nums1, int m, vector& nums2, int n) {\n int p1 = m-1, p2 = n-1, p = m+n-1;\n while (p1 >= 0 && p2 >= 0) nums1[p--] = nums1[p1] > nums2[p2] ? nums1[p1--] : nums2[p2--];\n while (p2 >= 0) nums1[p--] = nums2[p2--];\n}", "test_cases": ["nums1=[1,2,3], m=3, nums2=[2,5,6], n=3 -> [1,2,2,3,5,6]", "nums1=[], m=0, nums2=[1], n=1 -> [1]"], "key_points": ["从后往前合并", "三指针技巧"], "tags": ["array", "easy", "Microsoft", "Uber"]} {"problem_id": "algo_01003", "original_id": "max-subarray", "title": "最大子数组和", "category": "array", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "给你一个整数数组 nums ,请你找出一个具有最大和的连续子数组,返回其最大和。", "solution_python": "def maxSubArray(nums):\n max_sum = current = nums[0]\n for num in nums[1:]:\n current = max(num, current + num)\n max_sum = max(max_sum, current)\n return max_sum", "solution_java": "public int maxSubArray(int[] nums) {\n int maxSum = nums[0], curr = nums[0];\n for (int i = 1; i < nums.length; i++) {\n curr = Math.max(nums[i], curr + nums[i]);\n maxSum = Math.max(maxSum, curr);\n }\n return maxSum;\n}", "solution_cpp": "int maxSubArray(vector& nums) {\n int maxSum = nums[0], curr = nums[0];\n for (int i = 1; i < nums.size(); i++) {\n curr = max(nums[i], curr + nums[i]);\n maxSum = max(maxSum, curr);\n }\n return maxSum;\n}", "test_cases": ["nums=[-2,1,-3,4,-1,2,1,-5,4] -> 6", "nums=[1] -> 1"], "key_points": ["Kadane算法", "动态规划基础题"], "tags": ["array", "medium", "Google", "Microsoft"]} {"problem_id": "algo_01004", "original_id": "valid-parentheses", "title": "有效的括号", "category": "string", "difficulty": "easy", "companies": ["Google", "Uber"], "description": "给定一个只包括 '(',')','{','}','[',']' 的字符串 s,判断字符串是否有效。", "solution_python": "def isValid(s):\n stack = []\n mapping = {')': '(', ']': '[', '}': '{'}\n for c in s:\n if c in mapping:\n if not stack or stack[-1] != mapping[c]: return False\n stack.pop()\n else: stack.append(c)\n return not stack", "solution_java": "public boolean isValid(String s) {\n Stack stack = new Stack<>();\n Map map = Map.of(')', '(', ']', '[', '}', '{');\n for (char c : s.toCharArray()) {\n if (map.containsValue(c)) stack.push(c);\n else if (!stack.isEmpty() && stack.pop() != map.get(c)) return false;\n }\n return stack.isEmpty();\n}", "solution_cpp": "bool isValid(string s) {\n stack st;\n unordered_map m = {{')','('},{']','['},{'}','{'}};\n for (char c : s) {\n if (m.find(c) == m.end()) st.push(c);\n else if (st.empty() || st.top() != m[c]) return false;\n else st.pop();\n }\n return st.empty();\n}", "test_cases": ["s=\"()\" -> true", "s=\"()[]{}\" -> true", "s=\"(]\" -> false"], "key_points": ["栈匹配法", "注意空栈边界"], "tags": ["string", "easy", "Google", "Uber"]} {"problem_id": "algo_01005", "original_id": "longest-palindrome", "title": "最长回文子串", "category": "string", "difficulty": "medium", "companies": ["Google", "Amazon"], "description": "给你一个字符串 s,找到 s 中最长的回文子串。", "solution_python": "def longestPalindrome(s):\n def expand(l, r):\n while l >= 0 and r < len(s) and s[l] == s[r]: l -= 1; r += 1\n return l + 1, r - 1\n start = end = 0\n for i in range(len(s)):\n l1, r1 = expand(i, i)\n l2, r2 = expand(i, i + 1)\n if r1 - l1 > end - start: start, end = l1, r1\n if r2 - l2 > end - start: start, end = l2, r2\n return s[start:end+1]", "solution_java": "public String longestPalindrome(String s) {\n int start = 0, end = 0;\n for (int i = 0; i < s.length(); i++) {\n int len1 = expand(s, i, i), len2 = expand(s, i, i+1);\n int len = Math.max(len1, len2);\n if (len > end - start) { start = i - (len-1)/2; end = i + len/2; }\n }\n return s.substring(start, end + 1);\n}\nprivate int expand(String s, int l, int r) {\n while (l >= 0 && r < s.length() && s.charAt(l) == s.charAt(r)) { l--; r++; }\n return r - l - 1;\n}", "solution_cpp": "string longestPalindrome(string s) {\n int start = 0, end = 0;\n for (int i = 0; i < s.size(); i++) {\n int len1 = expand(s, i, i), len2 = expand(s, i, i+1);\n if (max(len1, len2) > end - start) { start = i - (max(len1,len2)-1)/2; end = i + max(len1,len2)/2; }\n }\n return s.substr(start, end - start + 1);\n}", "test_cases": ["s=\"babad\" -> bab或aba", "s=\"cbbd\" -> bb"], "key_points": ["中心扩展法", "处理奇偶长度"], "tags": ["string", "medium", "Google", "Amazon"]} {"problem_id": "algo_01006", "original_id": "reverse-list", "title": "反转链表", "category": "linkedlist", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "给你单链表的头节点 head,请你反转链表,并返回反转后的链表。", "solution_python": "def reverseList(head):\n prev = None\n curr = head\n while curr:\n nxt = curr.next\n curr.next = prev\n prev = curr\n curr = nxt\n return prev", "solution_java": "public ListNode reverseList(ListNode head) {\n ListNode prev = null, curr = head;\n while (curr != null) {\n ListNode next = curr.next;\n curr.next = prev;\n prev = curr;\n curr = next;\n }\n return prev;\n}", "solution_cpp": "ListNode* reverseList(ListNode* head) {\n ListNode* prev = nullptr, *curr = head;\n while (curr) {\n ListNode* next = curr->next;\n curr->next = prev;\n prev = curr;\n curr = next;\n }\n return prev;\n}", "test_cases": ["head=[1,2,3,4,5] -> [5,4,3,2,1]", "head=[1,2] -> [2,1]"], "key_points": ["迭代法 O(1)空间", "递归法 O(n)空间"], "tags": ["linkedlist", "medium", "Google", "Microsoft"]} {"problem_id": "algo_01007", "original_id": "middle-node", "title": "链表的中间结点", "category": "linkedlist", "difficulty": "easy", "companies": ["Amazon", "Facebook"], "description": "给你单链表的头节点 head,请你找出并返回链表的中间结点。如果有两个中间结点,则返回第二个中间结点。", "solution_python": "def middleNode(head):\n slow = fast = head\n while fast and fast.next:\n slow = slow.next\n fast = fast.next.next\n return slow", "solution_java": "public ListNode middleNode(ListNode head) {\n ListNode slow = head, fast = head;\n while (fast != null && fast.next != null) {\n slow = slow.next;\n fast = fast.next.next;\n }\n return slow;\n}", "solution_cpp": "ListNode* middleNode(ListNode* head) {\n ListNode* slow = head, *fast = head;\n while (fast && fast->next) { slow = slow->next; fast = fast->next->next; }\n return slow;\n}", "test_cases": ["head=[1,2,3,4,5] -> 3", "head=[1,2,3,4,5,6] -> 4"], "key_points": ["快慢指针", "O(n)时间O(1)空间"], "tags": ["linkedlist", "easy", "Amazon", "Facebook"]} {"problem_id": "algo_01008", "original_id": "max-depth", "title": "二叉树的最大深度", "category": "tree", "difficulty": "easy", "companies": ["Microsoft", "Apple"], "description": "给定一个二叉树 root,返回其最大深度。", "solution_python": "def maxDepth(root):\n if not root: return 0\n return max(maxDepth(root.left), maxDepth(root.right)) + 1", "solution_java": "public int maxDepth(TreeNode root) {\n if (root == null) return 0;\n return Math.max(maxDepth(root.left), maxDepth(root.right)) + 1;\n}", "solution_cpp": "int maxDepth(TreeNode* root) {\n if (!root) return 0;\n return max(maxDepth(root->left), maxDepth(root->right)) + 1;\n}", "test_cases": ["root=[3,9,20,null,null,15,7] -> 3", "root=[1,null,2] -> 2"], "key_points": ["DFS递归", "层序遍历也可"], "tags": ["tree", "easy", "Microsoft", "Apple"]} {"problem_id": "algo_01009", "original_id": "inorder-traversal", "title": "二叉树的中序遍历", "category": "tree", "difficulty": "easy", "companies": ["Google", "Microsoft"], "description": "给定一个二叉树的根节点 root,返回它的中序遍历结果。", "solution_python": "def inorderTraversal(root):\n result = []\n def dfs(node):\n if node:\n dfs(node.left)\n result.append(node.val)\n dfs(node.right)\n dfs(root)\n return result", "solution_java": "public List inorderTraversal(TreeNode root) {\n List res = new ArrayList<>();\n dfs(root, res);\n return res;\n}\nprivate void dfs(TreeNode node, List res) {\n if (node == null) return;\n dfs(node.left, res); res.add(node.val); dfs(node.right, res);\n}", "solution_cpp": "vector inorderTraversal(TreeNode* root) {\n vector res;\n dfs(root, res);\n return res;\n}\nvoid dfs(TreeNode* node, vector& res) {\n if (!node) return;\n dfs(node->left, res); res.push_back(node->val); dfs(node->right, res);\n}", "test_cases": ["root=[1,null,2,3] -> [1,3,2]", "root=[] -> []"], "key_points": ["左-根-右顺序", "递归最简洁"], "tags": ["tree", "easy", "Google", "Microsoft"]} {"problem_id": "algo_01010", "original_id": "binary-search", "title": "二分查找", "category": "binarysearch", "difficulty": "easy", "companies": ["Google", "Amazon"], "description": "给定一个 n 个元素有序的(升序)整型数组 nums 和一个目标值 target,写一个函数搜索 nums 中的 target,如果目标值存在返回下标,否则返回 -1。", "solution_python": "def search(nums, target):\n left, right = 0, len(nums) - 1\n while left <= right:\n mid = (left + right) // 2\n if nums[mid] == target: return mid\n elif nums[mid] < target: left = mid + 1\n else: right = mid - 1\n return -1", "solution_java": "public int search(int[] nums, int target) {\n int left = 0, right = nums.length - 1;\n while (left <= right) {\n int mid = left + (right - left) / 2;\n if (nums[mid] == target) return mid;\n else if (nums[mid] < target) left = mid + 1;\n else right = mid - 1;\n }\n return -1;\n}", "solution_cpp": "int search(vector& nums, int target) {\n int left = 0, right = nums.size() - 1;\n while (left <= right) {\n int mid = left + (right - left) / 2;\n if (nums[mid] == target) return mid;\n else if (nums[mid] < target) left = mid + 1;\n else right = mid - 1;\n }\n return -1;\n}", "test_cases": ["nums=[-1,0,3,5,9,12], target=9 -> 4", "nums=[-1,0,3,5,9,12], target=2 -> -1"], "key_points": ["标准模板", "注意防溢出写法"], "tags": ["binarysearch", "easy", "Google", "Amazon"]} {"problem_id": "algo_01011", "original_id": "climbing-stairs", "title": "爬楼梯", "category": "dp", "difficulty": "easy", "companies": ["Amazon", "Google"], "description": "假设你正在爬楼梯。需要 n 阶你才能到达楼顶。每次你可以爬 1 或 2 个台阶。你有多少种不同的方法可以爬到楼顶?", "solution_python": "def climbStairs(n):\n if n <= 2: return n\n a, b = 1, 2\n for _ in range(3, n+1):\n a, b = b, a + b\n return b", "solution_java": "public int climbStairs(int n) {\n if (n <= 2) return n;\n int a = 1, b = 2;\n for (int i = 3; i <= n; i++) { int temp = a + b; a = b; b = temp; }\n return b;\n}", "solution_cpp": "int climbStairs(int n) {\n if (n <= 2) return n;\n int a = 1, b = 2;\n for (int i = 3; i <= n; i++) { int temp = a + b; a = b; b = temp; }\n return b;\n}", "test_cases": ["n=2 -> 2", "n=3 -> 3", "n=5 -> 8"], "key_points": ["斐波那契数列", "滚动数组优化空间"], "tags": ["dp", "easy", "Amazon", "Google"]} {"problem_id": "algo_01012", "original_id": "coin-change", "title": "零钱兑换", "category": "dp", "difficulty": "medium", "companies": ["Google", "Amazon"], "description": "给你一个整数数组 coins 表示不同面额的硬币,以及一个整数 amount 表示总金额。计算并返回可以凑成总金额所需的最少的硬币个数。如果没有任何一种硬币组合能组成总金额,返回 -1。", "solution_python": "def coinChange(coins, amount):\n dp = [float('inf')] * (amount + 1)\n dp[0] = 0\n for coin in coins:\n for x in range(coin, amount + 1):\n dp[x] = min(dp[x], dp[x - coin] + 1)\n return dp[amount] if dp[amount] != float('inf') else -1", "solution_java": "public int coinChange(int[] coins, int amount) {\n int[] dp = new int[amount + 1];\n Arrays.fill(dp, amount + 1);\n dp[0] = 0;\n for (int coin : coins) {\n for (int x = coin; x <= amount; x++) {\n dp[x] = Math.min(dp[x], dp[x - coin] + 1);\n }\n }\n return dp[amount] > amount ? -1 : dp[amount];\n}", "solution_cpp": "int coinChange(vector& coins, int amount) {\n vector dp(amount + 1, amount + 1);\n dp[0] = 0;\n for (int coin : coins) {\n for (int x = coin; x <= amount; x++) {\n dp[x] = min(dp[x], dp[x - coin] + 1);\n }\n }\n return dp[amount] > amount ? -1 : dp[amount];\n}", "test_cases": ["coins=[1,2,5], amount=11 -> 3", "coins=[2], amount=3 -> -1"], "key_points": ["完全背包问题", "dp[x] = min(dp[x-coin]+1)"], "tags": ["dp", "medium", "Google", "Amazon"]} {"problem_id": "algo_01013", "original_id": "subsets", "title": "子集", "category": "backtracking", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "给你一个整数数组 nums ,数组中的元素 互不相同 。返回该数组所有可能的子集(幂集)。", "solution_python": "def subsets(nums):\n result = []\n def backtrack(start, path):\n result.append(path[:])\n for i in range(start, len(nums)):\n path.append(nums[i])\n backtrack(i + 1, path)\n path.pop()\n backtrack(0, [])\n return result", "solution_java": "public List> subsets(int[] nums) {\n List> result = new ArrayList<>();\n backtrack(nums, 0, new ArrayList<>(), result);\n return result;\n}\nprivate void backtrack(int[] nums, int start, List path, List> result) {\n result.add(new ArrayList<>(path));\n for (int i = start; i < nums.length; i++) {\n path.add(nums[i]);\n backtrack(nums, i + 1, path, result);\n path.remove(path.size() - 1);\n }\n}", "solution_cpp": "vector> subsets(vector& nums) {\n vector> result;\n vector path;\n backtrack(nums, 0, path, result);\n return result;\n}\nvoid backtrack(vector& nums, int start, vector& path, vector>& result) {\n result.push_back(path);\n for (int i = start; i < nums.size(); i++) {\n path.push_back(nums[i]);\n backtrack(nums, i + 1, path, result);\n path.pop_back();\n }\n}", "test_cases": ["nums=[1,2,3] -> [[],[1],[2],[1,2],[3],[1,3],[2,3],[1,2,3]]"], "key_points": ["选或不选", "DFS遍历子集树"], "tags": ["backtracking", "medium", "Google", "Microsoft"]} {"problem_id": "algo_01014", "original_id": "permutations", "title": "全排列", "category": "backtracking", "difficulty": "medium", "companies": ["Google", "Facebook"], "description": "给定一个不含重复数字的数组 nums,返回其所有可能的全排列。", "solution_python": "def permute(nums):\n result = []\n def backtrack(path, used):\n if len(path) == len(nums):\n result.append(path[:])\n return\n for i in range(len(nums)):\n if used[i]: continue\n used[i] = True\n path.append(nums[i])\n backtrack(path, used)\n path.pop()\n used[i] = False\n backtrack([], [False]*len(nums))\n return result", "solution_java": "public List> permute(int[] nums) {\n List> result = new ArrayList<>();\n boolean[] used = new boolean[nums.length];\n backtrack(nums, used, new ArrayList<>(), result);\n return result;\n}\nprivate void backtrack(int[] nums, boolean[] used, List path, List> result) {\n if (path.size() == nums.length) { result.add(new ArrayList<>(path)); return; }\n for (int i = 0; i < nums.length; i++) {\n if (used[i]) continue;\n used[i] = true;\n path.add(nums[i]);\n backtrack(nums, used, path, result);\n path.remove(path.size() - 1);\n used[i] = false;\n }\n}", "solution_cpp": "vector> permute(vector& nums) {\n vector> result;\n vector used(nums.size(), false);\n vector path;\n backtrack(nums, used, path, result);\n return result;\n}\nvoid backtrack(vector& nums, vector& used, vector& path, vector>& result) {\n if (path.size() == nums.size()) { result.push_back(path); return; }\n for (int i = 0; i < nums.size(); i++) {\n if (used[i]) continue;\n used[i] = true;\n path.push_back(nums[i]);\n backtrack(nums, used, path, result);\n path.pop_back();\n used[i] = false;\n }\n}", "test_cases": ["nums=[1,2,3] -> [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]"], "key_points": ["标记已使用元素", "回溯经典模板"], "tags": ["backtracking", "medium", "Google", "Facebook"]} {"problem_id": "algo_01015", "original_id": "top-k-frequent", "title": "前K个高频元素", "category": "heap", "difficulty": "medium", "companies": ["Amazon", "Facebook"], "description": "给你一个整数数组 nums 和一个整数 k,请你返回其中出现频率前 k 高的元素。", "solution_python": "import heapq\nfrom collections import Counter\ndef topKFrequent(nums, k):\n count = Counter(nums)\n heap = []\n for num, freq in count.items():\n heapq.heappush(heap, (freq, num))\n if len(heap) > k: heapq.heappop(heap)\n return [num for freq, num in heap]", "solution_java": "public int[] topKFrequent(int[] nums, int k) {\n Map count = new HashMap<>();\n for (int n : nums) count.put(n, count.getOrDefault(n, 0) + 1);\n PriorityQueue> heap = \n new PriorityQueue<>((a, b) -> a.getValue() - b.getValue());\n for (Map.Entry e : count.entrySet()) {\n heap.offer(e);\n if (heap.size() > k) heap.poll();\n }\n int[] res = new int[k];\n for (int i = k - 1; i >= 0; i--) res[i] = heap.poll().getKey();\n return res;\n}", "solution_cpp": "vector topKFrequent(vector& nums, int k) {\n unordered_map count;\n for (int n : nums) count[n]++;\n priority_queue, vector>, greater>> heap;\n for (auto& [num, freq] : count) {\n heap.push({freq, num});\n if (heap.size() > k) heap.pop();\n }\n vector res;\n while (!heap.empty()) { res.push_back(heap.top().second); heap.pop(); }\n reverse(res.begin(), res.end());\n return res;\n}", "test_cases": ["nums=[1,1,1,2,2,3], k=2 -> [1,2]", "nums=[1], k=1 -> [1]"], "key_points": ["小顶堆保持大小k", "时间复杂度O(nlogk)"], "tags": ["heap", "medium", "Amazon", "Facebook"]} {"problem_id": "algo_01016", "original_id": "3sum", "title": "三数之和", "category": "two-pointers", "difficulty": "medium", "companies": ["Google", "Amazon"], "description": "给你一个整数数组 nums,判断是否存在三元组满足和为0,返回所有不重复的三元组。", "solution_python": "def threeSum(nums):\n nums.sort()\n result = []\n for i in range(len(nums) - 2):\n if i > 0 and nums[i] == nums[i-1]: continue\n left, right = i + 1, len(nums) - 1\n while left < right:\n total = nums[i] + nums[left] + nums[right]\n if total < 0: left += 1\n elif total > 0: right -= 1\n else:\n result.append([nums[i], nums[left], nums[right]])\n while left < right and nums[left] == nums[left+1]: left += 1\n while left < right and nums[right] == nums[right-1]: right -= 1\n left += 1; right -= 1\n return result", "solution_java": "public List> threeSum(int[] nums) {\n Arrays.sort(nums);\n List> result = new ArrayList<>();\n for (int i = 0; i < nums.length - 2; i++) {\n if (i > 0 && nums[i] == nums[i-1]) continue;\n int left = i + 1, right = nums.length - 1;\n while (left < right) {\n int total = nums[i] + nums[left] + nums[right];\n if (total < 0) left++;\n else if (total > 0) right--;\n else {\n result.add(Arrays.asList(nums[i], nums[left], nums[right]));\n while (left < right && nums[left] == nums[left+1]) left++;\n while (left < right && nums[right] == nums[right-1]) right--;\n left++; right--;\n }\n }\n }\n return result;\n}", "solution_cpp": "vector> threeSum(vector& nums) {\n sort(nums.begin(), nums.end());\n vector> result;\n for (int i = 0; i < nums.size() - 2; i++) {\n if (i > 0 && nums[i] == nums[i-1]) continue;\n int left = i + 1, right = nums.size() - 1;\n while (left < right) {\n int total = nums[i] + nums[left] + nums[right];\n if (total < 0) left++;\n else if (total > 0) right--;\n else {\n result.push_back({nums[i], nums[left], nums[right]});\n while (left < right && nums[left] == nums[left+1]) left++;\n while (left < right && nums[right] == nums[right-1]) right--;\n left++; right--;\n }\n }\n }\n return result;\n}", "test_cases": ["nums=[-1,0,1,2,-1,-4] -> [[-1,-1,2],[-1,0,1]]"], "key_points": ["排序+双指针", "去重是关键"], "tags": ["two-pointers", "medium", "Google", "Amazon"]} {"problem_id": "algo_01017", "original_id": "container-water", "title": "盛最多水的容器", "category": "two-pointers", "difficulty": "medium", "companies": ["Google", "Uber"], "description": "给定一个长度为 n 的整数数组 height,找出其中的两条线,使得它们与 x 轴共同构成的容器可以容纳最多的水。", "solution_python": "def maxArea(height):\n left, right = 0, len(height) - 1\n max_area = 0\n while left < right:\n h = min(height[left], height[right])\n max_area = max(max_area, h * (right - left))\n if height[left] < height[right]: left += 1\n else: right -= 1\n return max_area", "solution_java": "public int maxArea(int[] height) {\n int left = 0, right = height.length - 1, maxArea = 0;\n while (left < right) {\n int h = Math.min(height[left], height[right]);\n maxArea = Math.max(maxArea, h * (right - left));\n if (height[left] < height[right]) left++;\n else right--;\n }\n return maxArea;\n}", "solution_cpp": "int maxArea(vector& height) {\n int left = 0, right = height.size() - 1, maxArea = 0;\n while (left < right) {\n int h = min(height[left], height[right]);\n maxArea = max(maxArea, h * (right - left));\n if (height[left] < height[right]) left++;\n else right--;\n }\n return maxArea;\n}", "test_cases": ["height=[1,8,6,2,5,4,8,3,7] -> 49"], "key_points": ["移动短边指针", "面积=min(h1,h2)*width"], "tags": ["two-pointers", "medium", "Google", "Uber"]} {"problem_id": "algo_01018", "original_id": "min-stack", "title": "最小栈", "category": "stack", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "设计一个支持 push,pop,top 操作,并能在常数时间内检索到最小元素的栈。", "solution_python": "class MinStack:\n def __init__(self):\n self.stack = []\n self.min_stack = []\n def push(self, val):\n self.stack.append(val)\n self.min_stack.append(min(val, self.min_stack[-1] if self.min_stack else val))\n def pop(self):\n self.stack.pop(); self.min_stack.pop()\n def top(self): return self.stack[-1]\n def getMin(self): return self.min_stack[-1]", "solution_java": "class MinStack {\n Stack stack = new Stack<>();\n Stack minStack = new Stack<>();\n public void push(int val) { stack.push(val); minStack.push(Math.min(val, minStack.isEmpty() ? val : minStack.peek())); }\n public void pop() { stack.pop(); minStack.pop(); }\n public int top() { return stack.peek(); }\n public int getMin() { return minStack.peek(); }\n}", "solution_cpp": "class MinStack {\n stack st, minSt;\npublic:\n void push(int val) { st.push(val); minSt.push(min(val, minSt.empty() ? val : minSt.top())); }\n void pop() { st.pop(); minSt.pop(); }\n int top() { return st.top(); }\n int getMin() { return minSt.top(); }\n};", "test_cases": ["push(-2), push(0), push(-3) -> getMin() returns -3"], "key_points": ["辅助栈记录最小值", "O(1)时间获取最小值"], "tags": ["stack", "medium", "Google", "Microsoft"]} {"problem_id": "algo_01019", "original_id": "lru-cache", "title": "LRU缓存", "category": "design", "difficulty": "hard", "companies": ["Google", "Amazon"], "description": "设计和实现一个 LRU(最近最少使用)缓存机制。", "solution_python": "class LRUCache:\n def __init__(self, capacity):\n self.capacity = capacity\n self.cache = {}\n self.order = []\n def get(self, key):\n if key not in self.cache: return -1\n self.order.remove(key); self.order.append(key)\n return self.cache[key]\n def put(self, key, value):\n if key in self.cache:\n self.order.remove(key)\n elif len(self.cache) >= self.capacity:\n del self.cache[self.order.pop(0)]\n self.cache[key] = value; self.order.append(key)", "solution_java": "class LRUCache {\n int capacity;\n LinkedHashMap cache = new LinkedHashMap<>();\n public LRUCache(int cap) { capacity = cap; }\n public int get(int key) { return cache.containsKey(key) ? cache.remove(key) : -1; }\n public void put(int key, int val) {\n if (cache.containsKey(key)) cache.remove(key);\n else if (cache.size() >= capacity) cache.remove(cache.keySet().iterator().next());\n cache.put(key, val);\n }\n}", "solution_cpp": "class LRUCache {\n int cap;\n list> dll;\n unordered_map>::iterator> cache;\npublic:\n LRUCache(int capacity) : cap(capacity) {}\n int get(int key) {\n auto it = cache.find(key);\n if (it == cache.end()) return -1;\n dll.splice(dll.end(), dll, it->second);\n return it->second->second;\n }\n void put(int key, int value) {\n auto it = cache.find(key);\n if (it != cache.end()) dll.erase(it->second);\n else if (cache.size() >= cap) { cache.erase(dll.front().first); dll.pop_front(); }\n dll.push_back({key, value});\n cache[key] = --dll.end();\n }\n};", "test_cases": ["put(1,1), put(2,2), get(1) -> 1"], "key_points": ["HashMap + 双向链表", "O(1)时间操作"], "tags": ["design", "hard", "Google", "Amazon"]} {"problem_id": "algo_01020", "original_id": "num-islands", "title": "岛屿数量", "category": "graph", "difficulty": "medium", "companies": ["Google", "Facebook"], "description": "给你一个由 '1'(陆地)和 '0'(水)组成的二维网格,请你计算网格中岛屿的数量。岛屿总是被水包围,且只能由水平或垂直方向相邻的陆地连接形成。", "solution_python": "def numIslands(grid):\n if not grid: return 0\n rows, cols = len(grid), len(grid[0])\n count = 0\n def dfs(r, c):\n if r < 0 or r >= rows or c < 0 or c >= cols or grid[r][c] != '1': return\n grid[r][c] = '0'\n dfs(r+1, c); dfs(r-1, c); dfs(r, c+1); dfs(r, c-1)\n for r in range(rows):\n for c in range(cols):\n if grid[r][c] == '1': count += 1; dfs(r, c)\n return count", "solution_java": "public int numIslands(char[][] grid) {\n if (grid.length == 0) return 0;\n int count = 0;\n for (int i = 0; i < grid.length; i++)\n for (int j = 0; j < grid[0].length; j++)\n if (grid[i][j] == '1') { count++; dfs(grid, i, j); }\n return count;\n}\nprivate void dfs(char[][] grid, int r, int c) {\n if (r < 0 || r >= grid.length || c < 0 || c >= grid[0].length || grid[r][c] != '1') return;\n grid[r][c] = '0';\n dfs(grid, r+1, c); dfs(grid, r-1, c); dfs(grid, r, c+1); dfs(grid, r, c-1);\n}", "solution_cpp": "int numIslands(vector>& grid) {\n if (grid.empty()) return 0;\n int count = 0;\n for (int i = 0; i < grid.size(); i++)\n for (int j = 0; j < grid[0].size(); j++)\n if (grid[i][j] == '1') { count++; dfs(grid, i, j); }\n return count;\n}\nvoid dfs(vector>& grid, int r, int c) {\n if (r < 0 || r >= grid.size() || c < 0 || c >= grid[0].size() || grid[r][c] != '1') return;\n grid[r][c] = '0';\n dfs(grid, r+1, c); dfs(grid, r-1, c); dfs(grid, r, c+1); dfs(grid, r, c-1);\n}", "test_cases": ["grid=[[1,1,1,1,0],[1,1,0,1,0],[1,1,0,0,0],[0,0,0,0,0]] -> 1"], "key_points": ["DFS/BFS遍历", "访问后标记为0避免重复"], "tags": ["graph", "medium", "Google", "Facebook"]} {"problem_id": "algo_01021", "original_id": "two-sum", "title": "两数之和", "category": "array", "difficulty": "easy", "companies": ["Amazon", "Google"], "description": "给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那两个整数,并返回他们的数组下标。", "solution_python": "def twoSum(nums, target):\n hashmap = {}\n for i, num in enumerate(nums):\n complement = target - num\n if complement in hashmap:\n return [hashmap[complement], i]\n hashmap[num] = i\n return []", "solution_java": "public int[] twoSum(int[] nums, int target) {\n Map map = new HashMap<>();\n for (int i = 0; i < nums.length; i++) {\n int complement = target - nums[i];\n if (map.containsKey(complement)) return new int[]{map.get(complement), i};\n map.put(nums[i], i);\n }\n return new int[]{};\n}", "solution_cpp": "vector twoSum(vector& nums, int target) {\n unordered_map m;\n for (int i = 0; i < nums.size(); i++) {\n if (m.count(target - nums[i])) return {m[target - nums[i]], i};\n m[nums[i]] = i;\n }\n return {};\n}", "test_cases": ["nums=[2,7,11,15], target=9 -> [0,1]", "nums=[3,2,4], target=6 -> [1,2]"], "key_points": ["哈希表一次遍历", "空间换时间"], "tags": ["array", "easy", "Amazon", "Google"]} {"problem_id": "algo_01022", "original_id": "merge-sorted", "title": "合并两个有序数组", "category": "array", "difficulty": "easy", "companies": ["Microsoft", "Uber"], "description": "给你两个按非递减顺序排列的整数数组 nums1 和 nums2,另有两个整数 m 和 n,分别表示 nums1 和 nums2 中的元素数目。请你合并 nums2 到 nums1 中。", "solution_python": "def merge(nums1, m, nums2, n):\n p1, p2, p = m-1, n-1, m+n-1\n while p1 >= 0 and p2 >= 0:\n if nums1[p1] > nums2[p2]: nums1[p] = nums1[p1]; p1 -= 1\n else: nums1[p] = nums2[p2]; p2 -= 1\n p -= 1\n while p2 >= 0: nums1[p] = nums2[p2]; p2 -= 1; p -= 1", "solution_java": "public void merge(int[] nums1, int m, int[] nums2, int n) {\n int p1 = m-1, p2 = n-1, p = m+n-1;\n while (p1 >= 0 && p2 >= 0) {\n nums1[p--] = nums1[p1] > nums2[p2] ? nums1[p1--] : nums2[p2--];\n }\n while (p2 >= 0) nums1[p--] = nums2[p2--];\n}", "solution_cpp": "void merge(vector& nums1, int m, vector& nums2, int n) {\n int p1 = m-1, p2 = n-1, p = m+n-1;\n while (p1 >= 0 && p2 >= 0) nums1[p--] = nums1[p1] > nums2[p2] ? nums1[p1--] : nums2[p2--];\n while (p2 >= 0) nums1[p--] = nums2[p2--];\n}", "test_cases": ["nums1=[1,2,3], m=3, nums2=[2,5,6], n=3 -> [1,2,2,3,5,6]", "nums1=[], m=0, nums2=[1], n=1 -> [1]"], "key_points": ["从后往前合并", "三指针技巧"], "tags": ["array", "easy", "Microsoft", "Uber"]} {"problem_id": "algo_01023", "original_id": "max-subarray", "title": "最大子数组和", "category": "array", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "给你一个整数数组 nums ,请你找出一个具有最大和的连续子数组,返回其最大和。", "solution_python": "def maxSubArray(nums):\n max_sum = current = nums[0]\n for num in nums[1:]:\n current = max(num, current + num)\n max_sum = max(max_sum, current)\n return max_sum", "solution_java": "public int maxSubArray(int[] nums) {\n int maxSum = nums[0], curr = nums[0];\n for (int i = 1; i < nums.length; i++) {\n curr = Math.max(nums[i], curr + nums[i]);\n maxSum = Math.max(maxSum, curr);\n }\n return maxSum;\n}", "solution_cpp": "int maxSubArray(vector& nums) {\n int maxSum = nums[0], curr = nums[0];\n for (int i = 1; i < nums.size(); i++) {\n curr = max(nums[i], curr + nums[i]);\n maxSum = max(maxSum, curr);\n }\n return maxSum;\n}", "test_cases": ["nums=[-2,1,-3,4,-1,2,1,-5,4] -> 6", "nums=[1] -> 1"], "key_points": ["Kadane算法", "动态规划基础题"], "tags": ["array", "medium", "Google", "Microsoft"]} {"problem_id": "algo_01024", "original_id": "valid-parentheses", "title": "有效的括号", "category": "string", "difficulty": "easy", "companies": ["Google", "Uber"], "description": "给定一个只包括 '(',')','{','}','[',']' 的字符串 s,判断字符串是否有效。", "solution_python": "def isValid(s):\n stack = []\n mapping = {')': '(', ']': '[', '}': '{'}\n for c in s:\n if c in mapping:\n if not stack or stack[-1] != mapping[c]: return False\n stack.pop()\n else: stack.append(c)\n return not stack", "solution_java": "public boolean isValid(String s) {\n Stack stack = new Stack<>();\n Map map = Map.of(')', '(', ']', '[', '}', '{');\n for (char c : s.toCharArray()) {\n if (map.containsValue(c)) stack.push(c);\n else if (!stack.isEmpty() && stack.pop() != map.get(c)) return false;\n }\n return stack.isEmpty();\n}", "solution_cpp": "bool isValid(string s) {\n stack st;\n unordered_map m = {{')','('},{']','['},{'}','{'}};\n for (char c : s) {\n if (m.find(c) == m.end()) st.push(c);\n else if (st.empty() || st.top() != m[c]) return false;\n else st.pop();\n }\n return st.empty();\n}", "test_cases": ["s=\"()\" -> true", "s=\"()[]{}\" -> true", "s=\"(]\" -> false"], "key_points": ["栈匹配法", "注意空栈边界"], "tags": ["string", "easy", "Google", "Uber"]} {"problem_id": "algo_01025", "original_id": "longest-palindrome", "title": "最长回文子串", "category": "string", "difficulty": "medium", "companies": ["Google", "Amazon"], "description": "给你一个字符串 s,找到 s 中最长的回文子串。", "solution_python": "def longestPalindrome(s):\n def expand(l, r):\n while l >= 0 and r < len(s) and s[l] == s[r]: l -= 1; r += 1\n return l + 1, r - 1\n start = end = 0\n for i in range(len(s)):\n l1, r1 = expand(i, i)\n l2, r2 = expand(i, i + 1)\n if r1 - l1 > end - start: start, end = l1, r1\n if r2 - l2 > end - start: start, end = l2, r2\n return s[start:end+1]", "solution_java": "public String longestPalindrome(String s) {\n int start = 0, end = 0;\n for (int i = 0; i < s.length(); i++) {\n int len1 = expand(s, i, i), len2 = expand(s, i, i+1);\n int len = Math.max(len1, len2);\n if (len > end - start) { start = i - (len-1)/2; end = i + len/2; }\n }\n return s.substring(start, end + 1);\n}\nprivate int expand(String s, int l, int r) {\n while (l >= 0 && r < s.length() && s.charAt(l) == s.charAt(r)) { l--; r++; }\n return r - l - 1;\n}", "solution_cpp": "string longestPalindrome(string s) {\n int start = 0, end = 0;\n for (int i = 0; i < s.size(); i++) {\n int len1 = expand(s, i, i), len2 = expand(s, i, i+1);\n if (max(len1, len2) > end - start) { start = i - (max(len1,len2)-1)/2; end = i + max(len1,len2)/2; }\n }\n return s.substr(start, end - start + 1);\n}", "test_cases": ["s=\"babad\" -> bab或aba", "s=\"cbbd\" -> bb"], "key_points": ["中心扩展法", "处理奇偶长度"], "tags": ["string", "medium", "Google", "Amazon"]} {"problem_id": "algo_01026", "original_id": "reverse-list", "title": "反转链表", "category": "linkedlist", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "给你单链表的头节点 head,请你反转链表,并返回反转后的链表。", "solution_python": "def reverseList(head):\n prev = None\n curr = head\n while curr:\n nxt = curr.next\n curr.next = prev\n prev = curr\n curr = nxt\n return prev", "solution_java": "public ListNode reverseList(ListNode head) {\n ListNode prev = null, curr = head;\n while (curr != null) {\n ListNode next = curr.next;\n curr.next = prev;\n prev = curr;\n curr = next;\n }\n return prev;\n}", "solution_cpp": "ListNode* reverseList(ListNode* head) {\n ListNode* prev = nullptr, *curr = head;\n while (curr) {\n ListNode* next = curr->next;\n curr->next = prev;\n prev = curr;\n curr = next;\n }\n return prev;\n}", "test_cases": ["head=[1,2,3,4,5] -> [5,4,3,2,1]", "head=[1,2] -> [2,1]"], "key_points": ["迭代法 O(1)空间", "递归法 O(n)空间"], "tags": ["linkedlist", "medium", "Google", "Microsoft"]} {"problem_id": "algo_01027", "original_id": "middle-node", "title": "链表的中间结点", "category": "linkedlist", "difficulty": "easy", "companies": ["Amazon", "Facebook"], "description": "给你单链表的头节点 head,请你找出并返回链表的中间结点。如果有两个中间结点,则返回第二个中间结点。", "solution_python": "def middleNode(head):\n slow = fast = head\n while fast and fast.next:\n slow = slow.next\n fast = fast.next.next\n return slow", "solution_java": "public ListNode middleNode(ListNode head) {\n ListNode slow = head, fast = head;\n while (fast != null && fast.next != null) {\n slow = slow.next;\n fast = fast.next.next;\n }\n return slow;\n}", "solution_cpp": "ListNode* middleNode(ListNode* head) {\n ListNode* slow = head, *fast = head;\n while (fast && fast->next) { slow = slow->next; fast = fast->next->next; }\n return slow;\n}", "test_cases": ["head=[1,2,3,4,5] -> 3", "head=[1,2,3,4,5,6] -> 4"], "key_points": ["快慢指针", "O(n)时间O(1)空间"], "tags": ["linkedlist", "easy", "Amazon", "Facebook"]} {"problem_id": "algo_01028", "original_id": "max-depth", "title": "二叉树的最大深度", "category": "tree", "difficulty": "easy", "companies": ["Microsoft", "Apple"], "description": "给定一个二叉树 root,返回其最大深度。", "solution_python": "def maxDepth(root):\n if not root: return 0\n return max(maxDepth(root.left), maxDepth(root.right)) + 1", "solution_java": "public int maxDepth(TreeNode root) {\n if (root == null) return 0;\n return Math.max(maxDepth(root.left), maxDepth(root.right)) + 1;\n}", "solution_cpp": "int maxDepth(TreeNode* root) {\n if (!root) return 0;\n return max(maxDepth(root->left), maxDepth(root->right)) + 1;\n}", "test_cases": ["root=[3,9,20,null,null,15,7] -> 3", "root=[1,null,2] -> 2"], "key_points": ["DFS递归", "层序遍历也可"], "tags": ["tree", "easy", "Microsoft", "Apple"]} {"problem_id": "algo_01029", "original_id": "inorder-traversal", "title": "二叉树的中序遍历", "category": "tree", "difficulty": "easy", "companies": ["Google", "Microsoft"], "description": "给定一个二叉树的根节点 root,返回它的中序遍历结果。", "solution_python": "def inorderTraversal(root):\n result = []\n def dfs(node):\n if node:\n dfs(node.left)\n result.append(node.val)\n dfs(node.right)\n dfs(root)\n return result", "solution_java": "public List inorderTraversal(TreeNode root) {\n List res = new ArrayList<>();\n dfs(root, res);\n return res;\n}\nprivate void dfs(TreeNode node, List res) {\n if (node == null) return;\n dfs(node.left, res); res.add(node.val); dfs(node.right, res);\n}", "solution_cpp": "vector inorderTraversal(TreeNode* root) {\n vector res;\n dfs(root, res);\n return res;\n}\nvoid dfs(TreeNode* node, vector& res) {\n if (!node) return;\n dfs(node->left, res); res.push_back(node->val); dfs(node->right, res);\n}", "test_cases": ["root=[1,null,2,3] -> [1,3,2]", "root=[] -> []"], "key_points": ["左-根-右顺序", "递归最简洁"], "tags": ["tree", "easy", "Google", "Microsoft"]} {"problem_id": "algo_01030", "original_id": "binary-search", "title": "二分查找", "category": "binarysearch", "difficulty": "easy", "companies": ["Google", "Amazon"], "description": "给定一个 n 个元素有序的(升序)整型数组 nums 和一个目标值 target,写一个函数搜索 nums 中的 target,如果目标值存在返回下标,否则返回 -1。", "solution_python": "def search(nums, target):\n left, right = 0, len(nums) - 1\n while left <= right:\n mid = (left + right) // 2\n if nums[mid] == target: return mid\n elif nums[mid] < target: left = mid + 1\n else: right = mid - 1\n return -1", "solution_java": "public int search(int[] nums, int target) {\n int left = 0, right = nums.length - 1;\n while (left <= right) {\n int mid = left + (right - left) / 2;\n if (nums[mid] == target) return mid;\n else if (nums[mid] < target) left = mid + 1;\n else right = mid - 1;\n }\n return -1;\n}", "solution_cpp": "int search(vector& nums, int target) {\n int left = 0, right = nums.size() - 1;\n while (left <= right) {\n int mid = left + (right - left) / 2;\n if (nums[mid] == target) return mid;\n else if (nums[mid] < target) left = mid + 1;\n else right = mid - 1;\n }\n return -1;\n}", "test_cases": ["nums=[-1,0,3,5,9,12], target=9 -> 4", "nums=[-1,0,3,5,9,12], target=2 -> -1"], "key_points": ["标准模板", "注意防溢出写法"], "tags": ["binarysearch", "easy", "Google", "Amazon"]} {"problem_id": "algo_01031", "original_id": "climbing-stairs", "title": "爬楼梯", "category": "dp", "difficulty": "easy", "companies": ["Amazon", "Google"], "description": "假设你正在爬楼梯。需要 n 阶你才能到达楼顶。每次你可以爬 1 或 2 个台阶。你有多少种不同的方法可以爬到楼顶?", "solution_python": "def climbStairs(n):\n if n <= 2: return n\n a, b = 1, 2\n for _ in range(3, n+1):\n a, b = b, a + b\n return b", "solution_java": "public int climbStairs(int n) {\n if (n <= 2) return n;\n int a = 1, b = 2;\n for (int i = 3; i <= n; i++) { int temp = a + b; a = b; b = temp; }\n return b;\n}", "solution_cpp": "int climbStairs(int n) {\n if (n <= 2) return n;\n int a = 1, b = 2;\n for (int i = 3; i <= n; i++) { int temp = a + b; a = b; b = temp; }\n return b;\n}", "test_cases": ["n=2 -> 2", "n=3 -> 3", "n=5 -> 8"], "key_points": ["斐波那契数列", "滚动数组优化空间"], "tags": ["dp", "easy", "Amazon", "Google"]} {"problem_id": "algo_01032", "original_id": "coin-change", "title": "零钱兑换", "category": "dp", "difficulty": "medium", "companies": ["Google", "Amazon"], "description": "给你一个整数数组 coins 表示不同面额的硬币,以及一个整数 amount 表示总金额。计算并返回可以凑成总金额所需的最少的硬币个数。如果没有任何一种硬币组合能组成总金额,返回 -1。", "solution_python": "def coinChange(coins, amount):\n dp = [float('inf')] * (amount + 1)\n dp[0] = 0\n for coin in coins:\n for x in range(coin, amount + 1):\n dp[x] = min(dp[x], dp[x - coin] + 1)\n return dp[amount] if dp[amount] != float('inf') else -1", "solution_java": "public int coinChange(int[] coins, int amount) {\n int[] dp = new int[amount + 1];\n Arrays.fill(dp, amount + 1);\n dp[0] = 0;\n for (int coin : coins) {\n for (int x = coin; x <= amount; x++) {\n dp[x] = Math.min(dp[x], dp[x - coin] + 1);\n }\n }\n return dp[amount] > amount ? -1 : dp[amount];\n}", "solution_cpp": "int coinChange(vector& coins, int amount) {\n vector dp(amount + 1, amount + 1);\n dp[0] = 0;\n for (int coin : coins) {\n for (int x = coin; x <= amount; x++) {\n dp[x] = min(dp[x], dp[x - coin] + 1);\n }\n }\n return dp[amount] > amount ? -1 : dp[amount];\n}", "test_cases": ["coins=[1,2,5], amount=11 -> 3", "coins=[2], amount=3 -> -1"], "key_points": ["完全背包问题", "dp[x] = min(dp[x-coin]+1)"], "tags": ["dp", "medium", "Google", "Amazon"]} {"problem_id": "algo_01033", "original_id": "subsets", "title": "子集", "category": "backtracking", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "给你一个整数数组 nums ,数组中的元素 互不相同 。返回该数组所有可能的子集(幂集)。", "solution_python": "def subsets(nums):\n result = []\n def backtrack(start, path):\n result.append(path[:])\n for i in range(start, len(nums)):\n path.append(nums[i])\n backtrack(i + 1, path)\n path.pop()\n backtrack(0, [])\n return result", "solution_java": "public List> subsets(int[] nums) {\n List> result = new ArrayList<>();\n backtrack(nums, 0, new ArrayList<>(), result);\n return result;\n}\nprivate void backtrack(int[] nums, int start, List path, List> result) {\n result.add(new ArrayList<>(path));\n for (int i = start; i < nums.length; i++) {\n path.add(nums[i]);\n backtrack(nums, i + 1, path, result);\n path.remove(path.size() - 1);\n }\n}", "solution_cpp": "vector> subsets(vector& nums) {\n vector> result;\n vector path;\n backtrack(nums, 0, path, result);\n return result;\n}\nvoid backtrack(vector& nums, int start, vector& path, vector>& result) {\n result.push_back(path);\n for (int i = start; i < nums.size(); i++) {\n path.push_back(nums[i]);\n backtrack(nums, i + 1, path, result);\n path.pop_back();\n }\n}", "test_cases": ["nums=[1,2,3] -> [[],[1],[2],[1,2],[3],[1,3],[2,3],[1,2,3]]"], "key_points": ["选或不选", "DFS遍历子集树"], "tags": ["backtracking", "medium", "Google", "Microsoft"]} {"problem_id": "algo_01034", "original_id": "permutations", "title": "全排列", "category": "backtracking", "difficulty": "medium", "companies": ["Google", "Facebook"], "description": "给定一个不含重复数字的数组 nums,返回其所有可能的全排列。", "solution_python": "def permute(nums):\n result = []\n def backtrack(path, used):\n if len(path) == len(nums):\n result.append(path[:])\n return\n for i in range(len(nums)):\n if used[i]: continue\n used[i] = True\n path.append(nums[i])\n backtrack(path, used)\n path.pop()\n used[i] = False\n backtrack([], [False]*len(nums))\n return result", "solution_java": "public List> permute(int[] nums) {\n List> result = new ArrayList<>();\n boolean[] used = new boolean[nums.length];\n backtrack(nums, used, new ArrayList<>(), result);\n return result;\n}\nprivate void backtrack(int[] nums, boolean[] used, List path, List> result) {\n if (path.size() == nums.length) { result.add(new ArrayList<>(path)); return; }\n for (int i = 0; i < nums.length; i++) {\n if (used[i]) continue;\n used[i] = true;\n path.add(nums[i]);\n backtrack(nums, used, path, result);\n path.remove(path.size() - 1);\n used[i] = false;\n }\n}", "solution_cpp": "vector> permute(vector& nums) {\n vector> result;\n vector used(nums.size(), false);\n vector path;\n backtrack(nums, used, path, result);\n return result;\n}\nvoid backtrack(vector& nums, vector& used, vector& path, vector>& result) {\n if (path.size() == nums.size()) { result.push_back(path); return; }\n for (int i = 0; i < nums.size(); i++) {\n if (used[i]) continue;\n used[i] = true;\n path.push_back(nums[i]);\n backtrack(nums, used, path, result);\n path.pop_back();\n used[i] = false;\n }\n}", "test_cases": ["nums=[1,2,3] -> [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]"], "key_points": ["标记已使用元素", "回溯经典模板"], "tags": ["backtracking", "medium", "Google", "Facebook"]} {"problem_id": "algo_01035", "original_id": "top-k-frequent", "title": "前K个高频元素", "category": "heap", "difficulty": "medium", "companies": ["Amazon", "Facebook"], "description": "给你一个整数数组 nums 和一个整数 k,请你返回其中出现频率前 k 高的元素。", "solution_python": "import heapq\nfrom collections import Counter\ndef topKFrequent(nums, k):\n count = Counter(nums)\n heap = []\n for num, freq in count.items():\n heapq.heappush(heap, (freq, num))\n if len(heap) > k: heapq.heappop(heap)\n return [num for freq, num in heap]", "solution_java": "public int[] topKFrequent(int[] nums, int k) {\n Map count = new HashMap<>();\n for (int n : nums) count.put(n, count.getOrDefault(n, 0) + 1);\n PriorityQueue> heap = \n new PriorityQueue<>((a, b) -> a.getValue() - b.getValue());\n for (Map.Entry e : count.entrySet()) {\n heap.offer(e);\n if (heap.size() > k) heap.poll();\n }\n int[] res = new int[k];\n for (int i = k - 1; i >= 0; i--) res[i] = heap.poll().getKey();\n return res;\n}", "solution_cpp": "vector topKFrequent(vector& nums, int k) {\n unordered_map count;\n for (int n : nums) count[n]++;\n priority_queue, vector>, greater>> heap;\n for (auto& [num, freq] : count) {\n heap.push({freq, num});\n if (heap.size() > k) heap.pop();\n }\n vector res;\n while (!heap.empty()) { res.push_back(heap.top().second); heap.pop(); }\n reverse(res.begin(), res.end());\n return res;\n}", "test_cases": ["nums=[1,1,1,2,2,3], k=2 -> [1,2]", "nums=[1], k=1 -> [1]"], "key_points": ["小顶堆保持大小k", "时间复杂度O(nlogk)"], "tags": ["heap", "medium", "Amazon", "Facebook"]} {"problem_id": "algo_01036", "original_id": "3sum", "title": "三数之和", "category": "two-pointers", "difficulty": "medium", "companies": ["Google", "Amazon"], "description": "给你一个整数数组 nums,判断是否存在三元组满足和为0,返回所有不重复的三元组。", "solution_python": "def threeSum(nums):\n nums.sort()\n result = []\n for i in range(len(nums) - 2):\n if i > 0 and nums[i] == nums[i-1]: continue\n left, right = i + 1, len(nums) - 1\n while left < right:\n total = nums[i] + nums[left] + nums[right]\n if total < 0: left += 1\n elif total > 0: right -= 1\n else:\n result.append([nums[i], nums[left], nums[right]])\n while left < right and nums[left] == nums[left+1]: left += 1\n while left < right and nums[right] == nums[right-1]: right -= 1\n left += 1; right -= 1\n return result", "solution_java": "public List> threeSum(int[] nums) {\n Arrays.sort(nums);\n List> result = new ArrayList<>();\n for (int i = 0; i < nums.length - 2; i++) {\n if (i > 0 && nums[i] == nums[i-1]) continue;\n int left = i + 1, right = nums.length - 1;\n while (left < right) {\n int total = nums[i] + nums[left] + nums[right];\n if (total < 0) left++;\n else if (total > 0) right--;\n else {\n result.add(Arrays.asList(nums[i], nums[left], nums[right]));\n while (left < right && nums[left] == nums[left+1]) left++;\n while (left < right && nums[right] == nums[right-1]) right--;\n left++; right--;\n }\n }\n }\n return result;\n}", "solution_cpp": "vector> threeSum(vector& nums) {\n sort(nums.begin(), nums.end());\n vector> result;\n for (int i = 0; i < nums.size() - 2; i++) {\n if (i > 0 && nums[i] == nums[i-1]) continue;\n int left = i + 1, right = nums.size() - 1;\n while (left < right) {\n int total = nums[i] + nums[left] + nums[right];\n if (total < 0) left++;\n else if (total > 0) right--;\n else {\n result.push_back({nums[i], nums[left], nums[right]});\n while (left < right && nums[left] == nums[left+1]) left++;\n while (left < right && nums[right] == nums[right-1]) right--;\n left++; right--;\n }\n }\n }\n return result;\n}", "test_cases": ["nums=[-1,0,1,2,-1,-4] -> [[-1,-1,2],[-1,0,1]]"], "key_points": ["排序+双指针", "去重是关键"], "tags": ["two-pointers", "medium", "Google", "Amazon"]} {"problem_id": "algo_01037", "original_id": "container-water", "title": "盛最多水的容器", "category": "two-pointers", "difficulty": "medium", "companies": ["Google", "Uber"], "description": "给定一个长度为 n 的整数数组 height,找出其中的两条线,使得它们与 x 轴共同构成的容器可以容纳最多的水。", "solution_python": "def maxArea(height):\n left, right = 0, len(height) - 1\n max_area = 0\n while left < right:\n h = min(height[left], height[right])\n max_area = max(max_area, h * (right - left))\n if height[left] < height[right]: left += 1\n else: right -= 1\n return max_area", "solution_java": "public int maxArea(int[] height) {\n int left = 0, right = height.length - 1, maxArea = 0;\n while (left < right) {\n int h = Math.min(height[left], height[right]);\n maxArea = Math.max(maxArea, h * (right - left));\n if (height[left] < height[right]) left++;\n else right--;\n }\n return maxArea;\n}", "solution_cpp": "int maxArea(vector& height) {\n int left = 0, right = height.size() - 1, maxArea = 0;\n while (left < right) {\n int h = min(height[left], height[right]);\n maxArea = max(maxArea, h * (right - left));\n if (height[left] < height[right]) left++;\n else right--;\n }\n return maxArea;\n}", "test_cases": ["height=[1,8,6,2,5,4,8,3,7] -> 49"], "key_points": ["移动短边指针", "面积=min(h1,h2)*width"], "tags": ["two-pointers", "medium", "Google", "Uber"]} {"problem_id": "algo_01038", "original_id": "min-stack", "title": "最小栈", "category": "stack", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "设计一个支持 push,pop,top 操作,并能在常数时间内检索到最小元素的栈。", "solution_python": "class MinStack:\n def __init__(self):\n self.stack = []\n self.min_stack = []\n def push(self, val):\n self.stack.append(val)\n self.min_stack.append(min(val, self.min_stack[-1] if self.min_stack else val))\n def pop(self):\n self.stack.pop(); self.min_stack.pop()\n def top(self): return self.stack[-1]\n def getMin(self): return self.min_stack[-1]", "solution_java": "class MinStack {\n Stack stack = new Stack<>();\n Stack minStack = new Stack<>();\n public void push(int val) { stack.push(val); minStack.push(Math.min(val, minStack.isEmpty() ? val : minStack.peek())); }\n public void pop() { stack.pop(); minStack.pop(); }\n public int top() { return stack.peek(); }\n public int getMin() { return minStack.peek(); }\n}", "solution_cpp": "class MinStack {\n stack st, minSt;\npublic:\n void push(int val) { st.push(val); minSt.push(min(val, minSt.empty() ? val : minSt.top())); }\n void pop() { st.pop(); minSt.pop(); }\n int top() { return st.top(); }\n int getMin() { return minSt.top(); }\n};", "test_cases": ["push(-2), push(0), push(-3) -> getMin() returns -3"], "key_points": ["辅助栈记录最小值", "O(1)时间获取最小值"], "tags": ["stack", "medium", "Google", "Microsoft"]} {"problem_id": "algo_01039", "original_id": "lru-cache", "title": "LRU缓存", "category": "design", "difficulty": "hard", "companies": ["Google", "Amazon"], "description": "设计和实现一个 LRU(最近最少使用)缓存机制。", "solution_python": "class LRUCache:\n def __init__(self, capacity):\n self.capacity = capacity\n self.cache = {}\n self.order = []\n def get(self, key):\n if key not in self.cache: return -1\n self.order.remove(key); self.order.append(key)\n return self.cache[key]\n def put(self, key, value):\n if key in self.cache:\n self.order.remove(key)\n elif len(self.cache) >= self.capacity:\n del self.cache[self.order.pop(0)]\n self.cache[key] = value; self.order.append(key)", "solution_java": "class LRUCache {\n int capacity;\n LinkedHashMap cache = new LinkedHashMap<>();\n public LRUCache(int cap) { capacity = cap; }\n public int get(int key) { return cache.containsKey(key) ? cache.remove(key) : -1; }\n public void put(int key, int val) {\n if (cache.containsKey(key)) cache.remove(key);\n else if (cache.size() >= capacity) cache.remove(cache.keySet().iterator().next());\n cache.put(key, val);\n }\n}", "solution_cpp": "class LRUCache {\n int cap;\n list> dll;\n unordered_map>::iterator> cache;\npublic:\n LRUCache(int capacity) : cap(capacity) {}\n int get(int key) {\n auto it = cache.find(key);\n if (it == cache.end()) return -1;\n dll.splice(dll.end(), dll, it->second);\n return it->second->second;\n }\n void put(int key, int value) {\n auto it = cache.find(key);\n if (it != cache.end()) dll.erase(it->second);\n else if (cache.size() >= cap) { cache.erase(dll.front().first); dll.pop_front(); }\n dll.push_back({key, value});\n cache[key] = --dll.end();\n }\n};", "test_cases": ["put(1,1), put(2,2), get(1) -> 1"], "key_points": ["HashMap + 双向链表", "O(1)时间操作"], "tags": ["design", "hard", "Google", "Amazon"]} {"problem_id": "algo_01040", "original_id": "num-islands", "title": "岛屿数量", "category": "graph", "difficulty": "medium", "companies": ["Google", "Facebook"], "description": "给你一个由 '1'(陆地)和 '0'(水)组成的二维网格,请你计算网格中岛屿的数量。岛屿总是被水包围,且只能由水平或垂直方向相邻的陆地连接形成。", "solution_python": "def numIslands(grid):\n if not grid: return 0\n rows, cols = len(grid), len(grid[0])\n count = 0\n def dfs(r, c):\n if r < 0 or r >= rows or c < 0 or c >= cols or grid[r][c] != '1': return\n grid[r][c] = '0'\n dfs(r+1, c); dfs(r-1, c); dfs(r, c+1); dfs(r, c-1)\n for r in range(rows):\n for c in range(cols):\n if grid[r][c] == '1': count += 1; dfs(r, c)\n return count", "solution_java": "public int numIslands(char[][] grid) {\n if (grid.length == 0) return 0;\n int count = 0;\n for (int i = 0; i < grid.length; i++)\n for (int j = 0; j < grid[0].length; j++)\n if (grid[i][j] == '1') { count++; dfs(grid, i, j); }\n return count;\n}\nprivate void dfs(char[][] grid, int r, int c) {\n if (r < 0 || r >= grid.length || c < 0 || c >= grid[0].length || grid[r][c] != '1') return;\n grid[r][c] = '0';\n dfs(grid, r+1, c); dfs(grid, r-1, c); dfs(grid, r, c+1); dfs(grid, r, c-1);\n}", "solution_cpp": "int numIslands(vector>& grid) {\n if (grid.empty()) return 0;\n int count = 0;\n for (int i = 0; i < grid.size(); i++)\n for (int j = 0; j < grid[0].size(); j++)\n if (grid[i][j] == '1') { count++; dfs(grid, i, j); }\n return count;\n}\nvoid dfs(vector>& grid, int r, int c) {\n if (r < 0 || r >= grid.size() || c < 0 || c >= grid[0].size() || grid[r][c] != '1') return;\n grid[r][c] = '0';\n dfs(grid, r+1, c); dfs(grid, r-1, c); dfs(grid, r, c+1); dfs(grid, r, c-1);\n}", "test_cases": ["grid=[[1,1,1,1,0],[1,1,0,1,0],[1,1,0,0,0],[0,0,0,0,0]] -> 1"], "key_points": ["DFS/BFS遍历", "访问后标记为0避免重复"], "tags": ["graph", "medium", "Google", "Facebook"]} {"problem_id": "algo_01041", "original_id": "two-sum", "title": "两数之和", "category": "array", "difficulty": "easy", "companies": ["Amazon", "Google"], "description": "给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那两个整数,并返回他们的数组下标。", "solution_python": "def twoSum(nums, target):\n hashmap = {}\n for i, num in enumerate(nums):\n complement = target - num\n if complement in hashmap:\n return [hashmap[complement], i]\n hashmap[num] = i\n return []", "solution_java": "public int[] twoSum(int[] nums, int target) {\n Map map = new HashMap<>();\n for (int i = 0; i < nums.length; i++) {\n int complement = target - nums[i];\n if (map.containsKey(complement)) return new int[]{map.get(complement), i};\n map.put(nums[i], i);\n }\n return new int[]{};\n}", "solution_cpp": "vector twoSum(vector& nums, int target) {\n unordered_map m;\n for (int i = 0; i < nums.size(); i++) {\n if (m.count(target - nums[i])) return {m[target - nums[i]], i};\n m[nums[i]] = i;\n }\n return {};\n}", "test_cases": ["nums=[2,7,11,15], target=9 -> [0,1]", "nums=[3,2,4], target=6 -> [1,2]"], "key_points": ["哈希表一次遍历", "空间换时间"], "tags": ["array", "easy", "Amazon", "Google"]} {"problem_id": "algo_01042", "original_id": "merge-sorted", "title": "合并两个有序数组", "category": "array", "difficulty": "easy", "companies": ["Microsoft", "Uber"], "description": "给你两个按非递减顺序排列的整数数组 nums1 和 nums2,另有两个整数 m 和 n,分别表示 nums1 和 nums2 中的元素数目。请你合并 nums2 到 nums1 中。", "solution_python": "def merge(nums1, m, nums2, n):\n p1, p2, p = m-1, n-1, m+n-1\n while p1 >= 0 and p2 >= 0:\n if nums1[p1] > nums2[p2]: nums1[p] = nums1[p1]; p1 -= 1\n else: nums1[p] = nums2[p2]; p2 -= 1\n p -= 1\n while p2 >= 0: nums1[p] = nums2[p2]; p2 -= 1; p -= 1", "solution_java": "public void merge(int[] nums1, int m, int[] nums2, int n) {\n int p1 = m-1, p2 = n-1, p = m+n-1;\n while (p1 >= 0 && p2 >= 0) {\n nums1[p--] = nums1[p1] > nums2[p2] ? nums1[p1--] : nums2[p2--];\n }\n while (p2 >= 0) nums1[p--] = nums2[p2--];\n}", "solution_cpp": "void merge(vector& nums1, int m, vector& nums2, int n) {\n int p1 = m-1, p2 = n-1, p = m+n-1;\n while (p1 >= 0 && p2 >= 0) nums1[p--] = nums1[p1] > nums2[p2] ? nums1[p1--] : nums2[p2--];\n while (p2 >= 0) nums1[p--] = nums2[p2--];\n}", "test_cases": ["nums1=[1,2,3], m=3, nums2=[2,5,6], n=3 -> [1,2,2,3,5,6]", "nums1=[], m=0, nums2=[1], n=1 -> [1]"], "key_points": ["从后往前合并", "三指针技巧"], "tags": ["array", "easy", "Microsoft", "Uber"]} {"problem_id": "algo_01043", "original_id": "max-subarray", "title": "最大子数组和", "category": "array", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "给你一个整数数组 nums ,请你找出一个具有最大和的连续子数组,返回其最大和。", "solution_python": "def maxSubArray(nums):\n max_sum = current = nums[0]\n for num in nums[1:]:\n current = max(num, current + num)\n max_sum = max(max_sum, current)\n return max_sum", "solution_java": "public int maxSubArray(int[] nums) {\n int maxSum = nums[0], curr = nums[0];\n for (int i = 1; i < nums.length; i++) {\n curr = Math.max(nums[i], curr + nums[i]);\n maxSum = Math.max(maxSum, curr);\n }\n return maxSum;\n}", "solution_cpp": "int maxSubArray(vector& nums) {\n int maxSum = nums[0], curr = nums[0];\n for (int i = 1; i < nums.size(); i++) {\n curr = max(nums[i], curr + nums[i]);\n maxSum = max(maxSum, curr);\n }\n return maxSum;\n}", "test_cases": ["nums=[-2,1,-3,4,-1,2,1,-5,4] -> 6", "nums=[1] -> 1"], "key_points": ["Kadane算法", "动态规划基础题"], "tags": ["array", "medium", "Google", "Microsoft"]} {"problem_id": "algo_01044", "original_id": "valid-parentheses", "title": "有效的括号", "category": "string", "difficulty": "easy", "companies": ["Google", "Uber"], "description": "给定一个只包括 '(',')','{','}','[',']' 的字符串 s,判断字符串是否有效。", "solution_python": "def isValid(s):\n stack = []\n mapping = {')': '(', ']': '[', '}': '{'}\n for c in s:\n if c in mapping:\n if not stack or stack[-1] != mapping[c]: return False\n stack.pop()\n else: stack.append(c)\n return not stack", "solution_java": "public boolean isValid(String s) {\n Stack stack = new Stack<>();\n Map map = Map.of(')', '(', ']', '[', '}', '{');\n for (char c : s.toCharArray()) {\n if (map.containsValue(c)) stack.push(c);\n else if (!stack.isEmpty() && stack.pop() != map.get(c)) return false;\n }\n return stack.isEmpty();\n}", "solution_cpp": "bool isValid(string s) {\n stack st;\n unordered_map m = {{')','('},{']','['},{'}','{'}};\n for (char c : s) {\n if (m.find(c) == m.end()) st.push(c);\n else if (st.empty() || st.top() != m[c]) return false;\n else st.pop();\n }\n return st.empty();\n}", "test_cases": ["s=\"()\" -> true", "s=\"()[]{}\" -> true", "s=\"(]\" -> false"], "key_points": ["栈匹配法", "注意空栈边界"], "tags": ["string", "easy", "Google", "Uber"]} {"problem_id": "algo_01045", "original_id": "longest-palindrome", "title": "最长回文子串", "category": "string", "difficulty": "medium", "companies": ["Google", "Amazon"], "description": "给你一个字符串 s,找到 s 中最长的回文子串。", "solution_python": "def longestPalindrome(s):\n def expand(l, r):\n while l >= 0 and r < len(s) and s[l] == s[r]: l -= 1; r += 1\n return l + 1, r - 1\n start = end = 0\n for i in range(len(s)):\n l1, r1 = expand(i, i)\n l2, r2 = expand(i, i + 1)\n if r1 - l1 > end - start: start, end = l1, r1\n if r2 - l2 > end - start: start, end = l2, r2\n return s[start:end+1]", "solution_java": "public String longestPalindrome(String s) {\n int start = 0, end = 0;\n for (int i = 0; i < s.length(); i++) {\n int len1 = expand(s, i, i), len2 = expand(s, i, i+1);\n int len = Math.max(len1, len2);\n if (len > end - start) { start = i - (len-1)/2; end = i + len/2; }\n }\n return s.substring(start, end + 1);\n}\nprivate int expand(String s, int l, int r) {\n while (l >= 0 && r < s.length() && s.charAt(l) == s.charAt(r)) { l--; r++; }\n return r - l - 1;\n}", "solution_cpp": "string longestPalindrome(string s) {\n int start = 0, end = 0;\n for (int i = 0; i < s.size(); i++) {\n int len1 = expand(s, i, i), len2 = expand(s, i, i+1);\n if (max(len1, len2) > end - start) { start = i - (max(len1,len2)-1)/2; end = i + max(len1,len2)/2; }\n }\n return s.substr(start, end - start + 1);\n}", "test_cases": ["s=\"babad\" -> bab或aba", "s=\"cbbd\" -> bb"], "key_points": ["中心扩展法", "处理奇偶长度"], "tags": ["string", "medium", "Google", "Amazon"]} {"problem_id": "algo_01046", "original_id": "reverse-list", "title": "反转链表", "category": "linkedlist", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "给你单链表的头节点 head,请你反转链表,并返回反转后的链表。", "solution_python": "def reverseList(head):\n prev = None\n curr = head\n while curr:\n nxt = curr.next\n curr.next = prev\n prev = curr\n curr = nxt\n return prev", "solution_java": "public ListNode reverseList(ListNode head) {\n ListNode prev = null, curr = head;\n while (curr != null) {\n ListNode next = curr.next;\n curr.next = prev;\n prev = curr;\n curr = next;\n }\n return prev;\n}", "solution_cpp": "ListNode* reverseList(ListNode* head) {\n ListNode* prev = nullptr, *curr = head;\n while (curr) {\n ListNode* next = curr->next;\n curr->next = prev;\n prev = curr;\n curr = next;\n }\n return prev;\n}", "test_cases": ["head=[1,2,3,4,5] -> [5,4,3,2,1]", "head=[1,2] -> [2,1]"], "key_points": ["迭代法 O(1)空间", "递归法 O(n)空间"], "tags": ["linkedlist", "medium", "Google", "Microsoft"]} {"problem_id": "algo_01047", "original_id": "middle-node", "title": "链表的中间结点", "category": "linkedlist", "difficulty": "easy", "companies": ["Amazon", "Facebook"], "description": "给你单链表的头节点 head,请你找出并返回链表的中间结点。如果有两个中间结点,则返回第二个中间结点。", "solution_python": "def middleNode(head):\n slow = fast = head\n while fast and fast.next:\n slow = slow.next\n fast = fast.next.next\n return slow", "solution_java": "public ListNode middleNode(ListNode head) {\n ListNode slow = head, fast = head;\n while (fast != null && fast.next != null) {\n slow = slow.next;\n fast = fast.next.next;\n }\n return slow;\n}", "solution_cpp": "ListNode* middleNode(ListNode* head) {\n ListNode* slow = head, *fast = head;\n while (fast && fast->next) { slow = slow->next; fast = fast->next->next; }\n return slow;\n}", "test_cases": ["head=[1,2,3,4,5] -> 3", "head=[1,2,3,4,5,6] -> 4"], "key_points": ["快慢指针", "O(n)时间O(1)空间"], "tags": ["linkedlist", "easy", "Amazon", "Facebook"]} {"problem_id": "algo_01048", "original_id": "max-depth", "title": "二叉树的最大深度", "category": "tree", "difficulty": "easy", "companies": ["Microsoft", "Apple"], "description": "给定一个二叉树 root,返回其最大深度。", "solution_python": "def maxDepth(root):\n if not root: return 0\n return max(maxDepth(root.left), maxDepth(root.right)) + 1", "solution_java": "public int maxDepth(TreeNode root) {\n if (root == null) return 0;\n return Math.max(maxDepth(root.left), maxDepth(root.right)) + 1;\n}", "solution_cpp": "int maxDepth(TreeNode* root) {\n if (!root) return 0;\n return max(maxDepth(root->left), maxDepth(root->right)) + 1;\n}", "test_cases": ["root=[3,9,20,null,null,15,7] -> 3", "root=[1,null,2] -> 2"], "key_points": ["DFS递归", "层序遍历也可"], "tags": ["tree", "easy", "Microsoft", "Apple"]} {"problem_id": "algo_01049", "original_id": "inorder-traversal", "title": "二叉树的中序遍历", "category": "tree", "difficulty": "easy", "companies": ["Google", "Microsoft"], "description": "给定一个二叉树的根节点 root,返回它的中序遍历结果。", "solution_python": "def inorderTraversal(root):\n result = []\n def dfs(node):\n if node:\n dfs(node.left)\n result.append(node.val)\n dfs(node.right)\n dfs(root)\n return result", "solution_java": "public List inorderTraversal(TreeNode root) {\n List res = new ArrayList<>();\n dfs(root, res);\n return res;\n}\nprivate void dfs(TreeNode node, List res) {\n if (node == null) return;\n dfs(node.left, res); res.add(node.val); dfs(node.right, res);\n}", "solution_cpp": "vector inorderTraversal(TreeNode* root) {\n vector res;\n dfs(root, res);\n return res;\n}\nvoid dfs(TreeNode* node, vector& res) {\n if (!node) return;\n dfs(node->left, res); res.push_back(node->val); dfs(node->right, res);\n}", "test_cases": ["root=[1,null,2,3] -> [1,3,2]", "root=[] -> []"], "key_points": ["左-根-右顺序", "递归最简洁"], "tags": ["tree", "easy", "Google", "Microsoft"]} {"problem_id": "algo_01050", "original_id": "binary-search", "title": "二分查找", "category": "binarysearch", "difficulty": "easy", "companies": ["Google", "Amazon"], "description": "给定一个 n 个元素有序的(升序)整型数组 nums 和一个目标值 target,写一个函数搜索 nums 中的 target,如果目标值存在返回下标,否则返回 -1。", "solution_python": "def search(nums, target):\n left, right = 0, len(nums) - 1\n while left <= right:\n mid = (left + right) // 2\n if nums[mid] == target: return mid\n elif nums[mid] < target: left = mid + 1\n else: right = mid - 1\n return -1", "solution_java": "public int search(int[] nums, int target) {\n int left = 0, right = nums.length - 1;\n while (left <= right) {\n int mid = left + (right - left) / 2;\n if (nums[mid] == target) return mid;\n else if (nums[mid] < target) left = mid + 1;\n else right = mid - 1;\n }\n return -1;\n}", "solution_cpp": "int search(vector& nums, int target) {\n int left = 0, right = nums.size() - 1;\n while (left <= right) {\n int mid = left + (right - left) / 2;\n if (nums[mid] == target) return mid;\n else if (nums[mid] < target) left = mid + 1;\n else right = mid - 1;\n }\n return -1;\n}", "test_cases": ["nums=[-1,0,3,5,9,12], target=9 -> 4", "nums=[-1,0,3,5,9,12], target=2 -> -1"], "key_points": ["标准模板", "注意防溢出写法"], "tags": ["binarysearch", "easy", "Google", "Amazon"]} {"problem_id": "algo_01051", "original_id": "climbing-stairs", "title": "爬楼梯", "category": "dp", "difficulty": "easy", "companies": ["Amazon", "Google"], "description": "假设你正在爬楼梯。需要 n 阶你才能到达楼顶。每次你可以爬 1 或 2 个台阶。你有多少种不同的方法可以爬到楼顶?", "solution_python": "def climbStairs(n):\n if n <= 2: return n\n a, b = 1, 2\n for _ in range(3, n+1):\n a, b = b, a + b\n return b", "solution_java": "public int climbStairs(int n) {\n if (n <= 2) return n;\n int a = 1, b = 2;\n for (int i = 3; i <= n; i++) { int temp = a + b; a = b; b = temp; }\n return b;\n}", "solution_cpp": "int climbStairs(int n) {\n if (n <= 2) return n;\n int a = 1, b = 2;\n for (int i = 3; i <= n; i++) { int temp = a + b; a = b; b = temp; }\n return b;\n}", "test_cases": ["n=2 -> 2", "n=3 -> 3", "n=5 -> 8"], "key_points": ["斐波那契数列", "滚动数组优化空间"], "tags": ["dp", "easy", "Amazon", "Google"]} {"problem_id": "algo_01052", "original_id": "coin-change", "title": "零钱兑换", "category": "dp", "difficulty": "medium", "companies": ["Google", "Amazon"], "description": "给你一个整数数组 coins 表示不同面额的硬币,以及一个整数 amount 表示总金额。计算并返回可以凑成总金额所需的最少的硬币个数。如果没有任何一种硬币组合能组成总金额,返回 -1。", "solution_python": "def coinChange(coins, amount):\n dp = [float('inf')] * (amount + 1)\n dp[0] = 0\n for coin in coins:\n for x in range(coin, amount + 1):\n dp[x] = min(dp[x], dp[x - coin] + 1)\n return dp[amount] if dp[amount] != float('inf') else -1", "solution_java": "public int coinChange(int[] coins, int amount) {\n int[] dp = new int[amount + 1];\n Arrays.fill(dp, amount + 1);\n dp[0] = 0;\n for (int coin : coins) {\n for (int x = coin; x <= amount; x++) {\n dp[x] = Math.min(dp[x], dp[x - coin] + 1);\n }\n }\n return dp[amount] > amount ? -1 : dp[amount];\n}", "solution_cpp": "int coinChange(vector& coins, int amount) {\n vector dp(amount + 1, amount + 1);\n dp[0] = 0;\n for (int coin : coins) {\n for (int x = coin; x <= amount; x++) {\n dp[x] = min(dp[x], dp[x - coin] + 1);\n }\n }\n return dp[amount] > amount ? -1 : dp[amount];\n}", "test_cases": ["coins=[1,2,5], amount=11 -> 3", "coins=[2], amount=3 -> -1"], "key_points": ["完全背包问题", "dp[x] = min(dp[x-coin]+1)"], "tags": ["dp", "medium", "Google", "Amazon"]} {"problem_id": "algo_01053", "original_id": "subsets", "title": "子集", "category": "backtracking", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "给你一个整数数组 nums ,数组中的元素 互不相同 。返回该数组所有可能的子集(幂集)。", "solution_python": "def subsets(nums):\n result = []\n def backtrack(start, path):\n result.append(path[:])\n for i in range(start, len(nums)):\n path.append(nums[i])\n backtrack(i + 1, path)\n path.pop()\n backtrack(0, [])\n return result", "solution_java": "public List> subsets(int[] nums) {\n List> result = new ArrayList<>();\n backtrack(nums, 0, new ArrayList<>(), result);\n return result;\n}\nprivate void backtrack(int[] nums, int start, List path, List> result) {\n result.add(new ArrayList<>(path));\n for (int i = start; i < nums.length; i++) {\n path.add(nums[i]);\n backtrack(nums, i + 1, path, result);\n path.remove(path.size() - 1);\n }\n}", "solution_cpp": "vector> subsets(vector& nums) {\n vector> result;\n vector path;\n backtrack(nums, 0, path, result);\n return result;\n}\nvoid backtrack(vector& nums, int start, vector& path, vector>& result) {\n result.push_back(path);\n for (int i = start; i < nums.size(); i++) {\n path.push_back(nums[i]);\n backtrack(nums, i + 1, path, result);\n path.pop_back();\n }\n}", "test_cases": ["nums=[1,2,3] -> [[],[1],[2],[1,2],[3],[1,3],[2,3],[1,2,3]]"], "key_points": ["选或不选", "DFS遍历子集树"], "tags": ["backtracking", "medium", "Google", "Microsoft"]} {"problem_id": "algo_01054", "original_id": "permutations", "title": "全排列", "category": "backtracking", "difficulty": "medium", "companies": ["Google", "Facebook"], "description": "给定一个不含重复数字的数组 nums,返回其所有可能的全排列。", "solution_python": "def permute(nums):\n result = []\n def backtrack(path, used):\n if len(path) == len(nums):\n result.append(path[:])\n return\n for i in range(len(nums)):\n if used[i]: continue\n used[i] = True\n path.append(nums[i])\n backtrack(path, used)\n path.pop()\n used[i] = False\n backtrack([], [False]*len(nums))\n return result", "solution_java": "public List> permute(int[] nums) {\n List> result = new ArrayList<>();\n boolean[] used = new boolean[nums.length];\n backtrack(nums, used, new ArrayList<>(), result);\n return result;\n}\nprivate void backtrack(int[] nums, boolean[] used, List path, List> result) {\n if (path.size() == nums.length) { result.add(new ArrayList<>(path)); return; }\n for (int i = 0; i < nums.length; i++) {\n if (used[i]) continue;\n used[i] = true;\n path.add(nums[i]);\n backtrack(nums, used, path, result);\n path.remove(path.size() - 1);\n used[i] = false;\n }\n}", "solution_cpp": "vector> permute(vector& nums) {\n vector> result;\n vector used(nums.size(), false);\n vector path;\n backtrack(nums, used, path, result);\n return result;\n}\nvoid backtrack(vector& nums, vector& used, vector& path, vector>& result) {\n if (path.size() == nums.size()) { result.push_back(path); return; }\n for (int i = 0; i < nums.size(); i++) {\n if (used[i]) continue;\n used[i] = true;\n path.push_back(nums[i]);\n backtrack(nums, used, path, result);\n path.pop_back();\n used[i] = false;\n }\n}", "test_cases": ["nums=[1,2,3] -> [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]"], "key_points": ["标记已使用元素", "回溯经典模板"], "tags": ["backtracking", "medium", "Google", "Facebook"]} {"problem_id": "algo_01055", "original_id": "top-k-frequent", "title": "前K个高频元素", "category": "heap", "difficulty": "medium", "companies": ["Amazon", "Facebook"], "description": "给你一个整数数组 nums 和一个整数 k,请你返回其中出现频率前 k 高的元素。", "solution_python": "import heapq\nfrom collections import Counter\ndef topKFrequent(nums, k):\n count = Counter(nums)\n heap = []\n for num, freq in count.items():\n heapq.heappush(heap, (freq, num))\n if len(heap) > k: heapq.heappop(heap)\n return [num for freq, num in heap]", "solution_java": "public int[] topKFrequent(int[] nums, int k) {\n Map count = new HashMap<>();\n for (int n : nums) count.put(n, count.getOrDefault(n, 0) + 1);\n PriorityQueue> heap = \n new PriorityQueue<>((a, b) -> a.getValue() - b.getValue());\n for (Map.Entry e : count.entrySet()) {\n heap.offer(e);\n if (heap.size() > k) heap.poll();\n }\n int[] res = new int[k];\n for (int i = k - 1; i >= 0; i--) res[i] = heap.poll().getKey();\n return res;\n}", "solution_cpp": "vector topKFrequent(vector& nums, int k) {\n unordered_map count;\n for (int n : nums) count[n]++;\n priority_queue, vector>, greater>> heap;\n for (auto& [num, freq] : count) {\n heap.push({freq, num});\n if (heap.size() > k) heap.pop();\n }\n vector res;\n while (!heap.empty()) { res.push_back(heap.top().second); heap.pop(); }\n reverse(res.begin(), res.end());\n return res;\n}", "test_cases": ["nums=[1,1,1,2,2,3], k=2 -> [1,2]", "nums=[1], k=1 -> [1]"], "key_points": ["小顶堆保持大小k", "时间复杂度O(nlogk)"], "tags": ["heap", "medium", "Amazon", "Facebook"]} {"problem_id": "algo_01056", "original_id": "3sum", "title": "三数之和", "category": "two-pointers", "difficulty": "medium", "companies": ["Google", "Amazon"], "description": "给你一个整数数组 nums,判断是否存在三元组满足和为0,返回所有不重复的三元组。", "solution_python": "def threeSum(nums):\n nums.sort()\n result = []\n for i in range(len(nums) - 2):\n if i > 0 and nums[i] == nums[i-1]: continue\n left, right = i + 1, len(nums) - 1\n while left < right:\n total = nums[i] + nums[left] + nums[right]\n if total < 0: left += 1\n elif total > 0: right -= 1\n else:\n result.append([nums[i], nums[left], nums[right]])\n while left < right and nums[left] == nums[left+1]: left += 1\n while left < right and nums[right] == nums[right-1]: right -= 1\n left += 1; right -= 1\n return result", "solution_java": "public List> threeSum(int[] nums) {\n Arrays.sort(nums);\n List> result = new ArrayList<>();\n for (int i = 0; i < nums.length - 2; i++) {\n if (i > 0 && nums[i] == nums[i-1]) continue;\n int left = i + 1, right = nums.length - 1;\n while (left < right) {\n int total = nums[i] + nums[left] + nums[right];\n if (total < 0) left++;\n else if (total > 0) right--;\n else {\n result.add(Arrays.asList(nums[i], nums[left], nums[right]));\n while (left < right && nums[left] == nums[left+1]) left++;\n while (left < right && nums[right] == nums[right-1]) right--;\n left++; right--;\n }\n }\n }\n return result;\n}", "solution_cpp": "vector> threeSum(vector& nums) {\n sort(nums.begin(), nums.end());\n vector> result;\n for (int i = 0; i < nums.size() - 2; i++) {\n if (i > 0 && nums[i] == nums[i-1]) continue;\n int left = i + 1, right = nums.size() - 1;\n while (left < right) {\n int total = nums[i] + nums[left] + nums[right];\n if (total < 0) left++;\n else if (total > 0) right--;\n else {\n result.push_back({nums[i], nums[left], nums[right]});\n while (left < right && nums[left] == nums[left+1]) left++;\n while (left < right && nums[right] == nums[right-1]) right--;\n left++; right--;\n }\n }\n }\n return result;\n}", "test_cases": ["nums=[-1,0,1,2,-1,-4] -> [[-1,-1,2],[-1,0,1]]"], "key_points": ["排序+双指针", "去重是关键"], "tags": ["two-pointers", "medium", "Google", "Amazon"]} {"problem_id": "algo_01057", "original_id": "container-water", "title": "盛最多水的容器", "category": "two-pointers", "difficulty": "medium", "companies": ["Google", "Uber"], "description": "给定一个长度为 n 的整数数组 height,找出其中的两条线,使得它们与 x 轴共同构成的容器可以容纳最多的水。", "solution_python": "def maxArea(height):\n left, right = 0, len(height) - 1\n max_area = 0\n while left < right:\n h = min(height[left], height[right])\n max_area = max(max_area, h * (right - left))\n if height[left] < height[right]: left += 1\n else: right -= 1\n return max_area", "solution_java": "public int maxArea(int[] height) {\n int left = 0, right = height.length - 1, maxArea = 0;\n while (left < right) {\n int h = Math.min(height[left], height[right]);\n maxArea = Math.max(maxArea, h * (right - left));\n if (height[left] < height[right]) left++;\n else right--;\n }\n return maxArea;\n}", "solution_cpp": "int maxArea(vector& height) {\n int left = 0, right = height.size() - 1, maxArea = 0;\n while (left < right) {\n int h = min(height[left], height[right]);\n maxArea = max(maxArea, h * (right - left));\n if (height[left] < height[right]) left++;\n else right--;\n }\n return maxArea;\n}", "test_cases": ["height=[1,8,6,2,5,4,8,3,7] -> 49"], "key_points": ["移动短边指针", "面积=min(h1,h2)*width"], "tags": ["two-pointers", "medium", "Google", "Uber"]} {"problem_id": "algo_01058", "original_id": "min-stack", "title": "最小栈", "category": "stack", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "设计一个支持 push,pop,top 操作,并能在常数时间内检索到最小元素的栈。", "solution_python": "class MinStack:\n def __init__(self):\n self.stack = []\n self.min_stack = []\n def push(self, val):\n self.stack.append(val)\n self.min_stack.append(min(val, self.min_stack[-1] if self.min_stack else val))\n def pop(self):\n self.stack.pop(); self.min_stack.pop()\n def top(self): return self.stack[-1]\n def getMin(self): return self.min_stack[-1]", "solution_java": "class MinStack {\n Stack stack = new Stack<>();\n Stack minStack = new Stack<>();\n public void push(int val) { stack.push(val); minStack.push(Math.min(val, minStack.isEmpty() ? val : minStack.peek())); }\n public void pop() { stack.pop(); minStack.pop(); }\n public int top() { return stack.peek(); }\n public int getMin() { return minStack.peek(); }\n}", "solution_cpp": "class MinStack {\n stack st, minSt;\npublic:\n void push(int val) { st.push(val); minSt.push(min(val, minSt.empty() ? val : minSt.top())); }\n void pop() { st.pop(); minSt.pop(); }\n int top() { return st.top(); }\n int getMin() { return minSt.top(); }\n};", "test_cases": ["push(-2), push(0), push(-3) -> getMin() returns -3"], "key_points": ["辅助栈记录最小值", "O(1)时间获取最小值"], "tags": ["stack", "medium", "Google", "Microsoft"]} {"problem_id": "algo_01059", "original_id": "lru-cache", "title": "LRU缓存", "category": "design", "difficulty": "hard", "companies": ["Google", "Amazon"], "description": "设计和实现一个 LRU(最近最少使用)缓存机制。", "solution_python": "class LRUCache:\n def __init__(self, capacity):\n self.capacity = capacity\n self.cache = {}\n self.order = []\n def get(self, key):\n if key not in self.cache: return -1\n self.order.remove(key); self.order.append(key)\n return self.cache[key]\n def put(self, key, value):\n if key in self.cache:\n self.order.remove(key)\n elif len(self.cache) >= self.capacity:\n del self.cache[self.order.pop(0)]\n self.cache[key] = value; self.order.append(key)", "solution_java": "class LRUCache {\n int capacity;\n LinkedHashMap cache = new LinkedHashMap<>();\n public LRUCache(int cap) { capacity = cap; }\n public int get(int key) { return cache.containsKey(key) ? cache.remove(key) : -1; }\n public void put(int key, int val) {\n if (cache.containsKey(key)) cache.remove(key);\n else if (cache.size() >= capacity) cache.remove(cache.keySet().iterator().next());\n cache.put(key, val);\n }\n}", "solution_cpp": "class LRUCache {\n int cap;\n list> dll;\n unordered_map>::iterator> cache;\npublic:\n LRUCache(int capacity) : cap(capacity) {}\n int get(int key) {\n auto it = cache.find(key);\n if (it == cache.end()) return -1;\n dll.splice(dll.end(), dll, it->second);\n return it->second->second;\n }\n void put(int key, int value) {\n auto it = cache.find(key);\n if (it != cache.end()) dll.erase(it->second);\n else if (cache.size() >= cap) { cache.erase(dll.front().first); dll.pop_front(); }\n dll.push_back({key, value});\n cache[key] = --dll.end();\n }\n};", "test_cases": ["put(1,1), put(2,2), get(1) -> 1"], "key_points": ["HashMap + 双向链表", "O(1)时间操作"], "tags": ["design", "hard", "Google", "Amazon"]} {"problem_id": "algo_01060", "original_id": "num-islands", "title": "岛屿数量", "category": "graph", "difficulty": "medium", "companies": ["Google", "Facebook"], "description": "给你一个由 '1'(陆地)和 '0'(水)组成的二维网格,请你计算网格中岛屿的数量。岛屿总是被水包围,且只能由水平或垂直方向相邻的陆地连接形成。", "solution_python": "def numIslands(grid):\n if not grid: return 0\n rows, cols = len(grid), len(grid[0])\n count = 0\n def dfs(r, c):\n if r < 0 or r >= rows or c < 0 or c >= cols or grid[r][c] != '1': return\n grid[r][c] = '0'\n dfs(r+1, c); dfs(r-1, c); dfs(r, c+1); dfs(r, c-1)\n for r in range(rows):\n for c in range(cols):\n if grid[r][c] == '1': count += 1; dfs(r, c)\n return count", "solution_java": "public int numIslands(char[][] grid) {\n if (grid.length == 0) return 0;\n int count = 0;\n for (int i = 0; i < grid.length; i++)\n for (int j = 0; j < grid[0].length; j++)\n if (grid[i][j] == '1') { count++; dfs(grid, i, j); }\n return count;\n}\nprivate void dfs(char[][] grid, int r, int c) {\n if (r < 0 || r >= grid.length || c < 0 || c >= grid[0].length || grid[r][c] != '1') return;\n grid[r][c] = '0';\n dfs(grid, r+1, c); dfs(grid, r-1, c); dfs(grid, r, c+1); dfs(grid, r, c-1);\n}", "solution_cpp": "int numIslands(vector>& grid) {\n if (grid.empty()) return 0;\n int count = 0;\n for (int i = 0; i < grid.size(); i++)\n for (int j = 0; j < grid[0].size(); j++)\n if (grid[i][j] == '1') { count++; dfs(grid, i, j); }\n return count;\n}\nvoid dfs(vector>& grid, int r, int c) {\n if (r < 0 || r >= grid.size() || c < 0 || c >= grid[0].size() || grid[r][c] != '1') return;\n grid[r][c] = '0';\n dfs(grid, r+1, c); dfs(grid, r-1, c); dfs(grid, r, c+1); dfs(grid, r, c-1);\n}", "test_cases": ["grid=[[1,1,1,1,0],[1,1,0,1,0],[1,1,0,0,0],[0,0,0,0,0]] -> 1"], "key_points": ["DFS/BFS遍历", "访问后标记为0避免重复"], "tags": ["graph", "medium", "Google", "Facebook"]} {"problem_id": "algo_01061", "original_id": "two-sum", "title": "两数之和", "category": "array", "difficulty": "easy", "companies": ["Amazon", "Google"], "description": "给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那两个整数,并返回他们的数组下标。", "solution_python": "def twoSum(nums, target):\n hashmap = {}\n for i, num in enumerate(nums):\n complement = target - num\n if complement in hashmap:\n return [hashmap[complement], i]\n hashmap[num] = i\n return []", "solution_java": "public int[] twoSum(int[] nums, int target) {\n Map map = new HashMap<>();\n for (int i = 0; i < nums.length; i++) {\n int complement = target - nums[i];\n if (map.containsKey(complement)) return new int[]{map.get(complement), i};\n map.put(nums[i], i);\n }\n return new int[]{};\n}", "solution_cpp": "vector twoSum(vector& nums, int target) {\n unordered_map m;\n for (int i = 0; i < nums.size(); i++) {\n if (m.count(target - nums[i])) return {m[target - nums[i]], i};\n m[nums[i]] = i;\n }\n return {};\n}", "test_cases": ["nums=[2,7,11,15], target=9 -> [0,1]", "nums=[3,2,4], target=6 -> [1,2]"], "key_points": ["哈希表一次遍历", "空间换时间"], "tags": ["array", "easy", "Amazon", "Google"]} {"problem_id": "algo_01062", "original_id": "merge-sorted", "title": "合并两个有序数组", "category": "array", "difficulty": "easy", "companies": ["Microsoft", "Uber"], "description": "给你两个按非递减顺序排列的整数数组 nums1 和 nums2,另有两个整数 m 和 n,分别表示 nums1 和 nums2 中的元素数目。请你合并 nums2 到 nums1 中。", "solution_python": "def merge(nums1, m, nums2, n):\n p1, p2, p = m-1, n-1, m+n-1\n while p1 >= 0 and p2 >= 0:\n if nums1[p1] > nums2[p2]: nums1[p] = nums1[p1]; p1 -= 1\n else: nums1[p] = nums2[p2]; p2 -= 1\n p -= 1\n while p2 >= 0: nums1[p] = nums2[p2]; p2 -= 1; p -= 1", "solution_java": "public void merge(int[] nums1, int m, int[] nums2, int n) {\n int p1 = m-1, p2 = n-1, p = m+n-1;\n while (p1 >= 0 && p2 >= 0) {\n nums1[p--] = nums1[p1] > nums2[p2] ? nums1[p1--] : nums2[p2--];\n }\n while (p2 >= 0) nums1[p--] = nums2[p2--];\n}", "solution_cpp": "void merge(vector& nums1, int m, vector& nums2, int n) {\n int p1 = m-1, p2 = n-1, p = m+n-1;\n while (p1 >= 0 && p2 >= 0) nums1[p--] = nums1[p1] > nums2[p2] ? nums1[p1--] : nums2[p2--];\n while (p2 >= 0) nums1[p--] = nums2[p2--];\n}", "test_cases": ["nums1=[1,2,3], m=3, nums2=[2,5,6], n=3 -> [1,2,2,3,5,6]", "nums1=[], m=0, nums2=[1], n=1 -> [1]"], "key_points": ["从后往前合并", "三指针技巧"], "tags": ["array", "easy", "Microsoft", "Uber"]} {"problem_id": "algo_01063", "original_id": "max-subarray", "title": "最大子数组和", "category": "array", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "给你一个整数数组 nums ,请你找出一个具有最大和的连续子数组,返回其最大和。", "solution_python": "def maxSubArray(nums):\n max_sum = current = nums[0]\n for num in nums[1:]:\n current = max(num, current + num)\n max_sum = max(max_sum, current)\n return max_sum", "solution_java": "public int maxSubArray(int[] nums) {\n int maxSum = nums[0], curr = nums[0];\n for (int i = 1; i < nums.length; i++) {\n curr = Math.max(nums[i], curr + nums[i]);\n maxSum = Math.max(maxSum, curr);\n }\n return maxSum;\n}", "solution_cpp": "int maxSubArray(vector& nums) {\n int maxSum = nums[0], curr = nums[0];\n for (int i = 1; i < nums.size(); i++) {\n curr = max(nums[i], curr + nums[i]);\n maxSum = max(maxSum, curr);\n }\n return maxSum;\n}", "test_cases": ["nums=[-2,1,-3,4,-1,2,1,-5,4] -> 6", "nums=[1] -> 1"], "key_points": ["Kadane算法", "动态规划基础题"], "tags": ["array", "medium", "Google", "Microsoft"]} {"problem_id": "algo_01064", "original_id": "valid-parentheses", "title": "有效的括号", "category": "string", "difficulty": "easy", "companies": ["Google", "Uber"], "description": "给定一个只包括 '(',')','{','}','[',']' 的字符串 s,判断字符串是否有效。", "solution_python": "def isValid(s):\n stack = []\n mapping = {')': '(', ']': '[', '}': '{'}\n for c in s:\n if c in mapping:\n if not stack or stack[-1] != mapping[c]: return False\n stack.pop()\n else: stack.append(c)\n return not stack", "solution_java": "public boolean isValid(String s) {\n Stack stack = new Stack<>();\n Map map = Map.of(')', '(', ']', '[', '}', '{');\n for (char c : s.toCharArray()) {\n if (map.containsValue(c)) stack.push(c);\n else if (!stack.isEmpty() && stack.pop() != map.get(c)) return false;\n }\n return stack.isEmpty();\n}", "solution_cpp": "bool isValid(string s) {\n stack st;\n unordered_map m = {{')','('},{']','['},{'}','{'}};\n for (char c : s) {\n if (m.find(c) == m.end()) st.push(c);\n else if (st.empty() || st.top() != m[c]) return false;\n else st.pop();\n }\n return st.empty();\n}", "test_cases": ["s=\"()\" -> true", "s=\"()[]{}\" -> true", "s=\"(]\" -> false"], "key_points": ["栈匹配法", "注意空栈边界"], "tags": ["string", "easy", "Google", "Uber"]} {"problem_id": "algo_01065", "original_id": "longest-palindrome", "title": "最长回文子串", "category": "string", "difficulty": "medium", "companies": ["Google", "Amazon"], "description": "给你一个字符串 s,找到 s 中最长的回文子串。", "solution_python": "def longestPalindrome(s):\n def expand(l, r):\n while l >= 0 and r < len(s) and s[l] == s[r]: l -= 1; r += 1\n return l + 1, r - 1\n start = end = 0\n for i in range(len(s)):\n l1, r1 = expand(i, i)\n l2, r2 = expand(i, i + 1)\n if r1 - l1 > end - start: start, end = l1, r1\n if r2 - l2 > end - start: start, end = l2, r2\n return s[start:end+1]", "solution_java": "public String longestPalindrome(String s) {\n int start = 0, end = 0;\n for (int i = 0; i < s.length(); i++) {\n int len1 = expand(s, i, i), len2 = expand(s, i, i+1);\n int len = Math.max(len1, len2);\n if (len > end - start) { start = i - (len-1)/2; end = i + len/2; }\n }\n return s.substring(start, end + 1);\n}\nprivate int expand(String s, int l, int r) {\n while (l >= 0 && r < s.length() && s.charAt(l) == s.charAt(r)) { l--; r++; }\n return r - l - 1;\n}", "solution_cpp": "string longestPalindrome(string s) {\n int start = 0, end = 0;\n for (int i = 0; i < s.size(); i++) {\n int len1 = expand(s, i, i), len2 = expand(s, i, i+1);\n if (max(len1, len2) > end - start) { start = i - (max(len1,len2)-1)/2; end = i + max(len1,len2)/2; }\n }\n return s.substr(start, end - start + 1);\n}", "test_cases": ["s=\"babad\" -> bab或aba", "s=\"cbbd\" -> bb"], "key_points": ["中心扩展法", "处理奇偶长度"], "tags": ["string", "medium", "Google", "Amazon"]} {"problem_id": "algo_01066", "original_id": "reverse-list", "title": "反转链表", "category": "linkedlist", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "给你单链表的头节点 head,请你反转链表,并返回反转后的链表。", "solution_python": "def reverseList(head):\n prev = None\n curr = head\n while curr:\n nxt = curr.next\n curr.next = prev\n prev = curr\n curr = nxt\n return prev", "solution_java": "public ListNode reverseList(ListNode head) {\n ListNode prev = null, curr = head;\n while (curr != null) {\n ListNode next = curr.next;\n curr.next = prev;\n prev = curr;\n curr = next;\n }\n return prev;\n}", "solution_cpp": "ListNode* reverseList(ListNode* head) {\n ListNode* prev = nullptr, *curr = head;\n while (curr) {\n ListNode* next = curr->next;\n curr->next = prev;\n prev = curr;\n curr = next;\n }\n return prev;\n}", "test_cases": ["head=[1,2,3,4,5] -> [5,4,3,2,1]", "head=[1,2] -> [2,1]"], "key_points": ["迭代法 O(1)空间", "递归法 O(n)空间"], "tags": ["linkedlist", "medium", "Google", "Microsoft"]} {"problem_id": "algo_01067", "original_id": "middle-node", "title": "链表的中间结点", "category": "linkedlist", "difficulty": "easy", "companies": ["Amazon", "Facebook"], "description": "给你单链表的头节点 head,请你找出并返回链表的中间结点。如果有两个中间结点,则返回第二个中间结点。", "solution_python": "def middleNode(head):\n slow = fast = head\n while fast and fast.next:\n slow = slow.next\n fast = fast.next.next\n return slow", "solution_java": "public ListNode middleNode(ListNode head) {\n ListNode slow = head, fast = head;\n while (fast != null && fast.next != null) {\n slow = slow.next;\n fast = fast.next.next;\n }\n return slow;\n}", "solution_cpp": "ListNode* middleNode(ListNode* head) {\n ListNode* slow = head, *fast = head;\n while (fast && fast->next) { slow = slow->next; fast = fast->next->next; }\n return slow;\n}", "test_cases": ["head=[1,2,3,4,5] -> 3", "head=[1,2,3,4,5,6] -> 4"], "key_points": ["快慢指针", "O(n)时间O(1)空间"], "tags": ["linkedlist", "easy", "Amazon", "Facebook"]} {"problem_id": "algo_01068", "original_id": "max-depth", "title": "二叉树的最大深度", "category": "tree", "difficulty": "easy", "companies": ["Microsoft", "Apple"], "description": "给定一个二叉树 root,返回其最大深度。", "solution_python": "def maxDepth(root):\n if not root: return 0\n return max(maxDepth(root.left), maxDepth(root.right)) + 1", "solution_java": "public int maxDepth(TreeNode root) {\n if (root == null) return 0;\n return Math.max(maxDepth(root.left), maxDepth(root.right)) + 1;\n}", "solution_cpp": "int maxDepth(TreeNode* root) {\n if (!root) return 0;\n return max(maxDepth(root->left), maxDepth(root->right)) + 1;\n}", "test_cases": ["root=[3,9,20,null,null,15,7] -> 3", "root=[1,null,2] -> 2"], "key_points": ["DFS递归", "层序遍历也可"], "tags": ["tree", "easy", "Microsoft", "Apple"]} {"problem_id": "algo_01069", "original_id": "inorder-traversal", "title": "二叉树的中序遍历", "category": "tree", "difficulty": "easy", "companies": ["Google", "Microsoft"], "description": "给定一个二叉树的根节点 root,返回它的中序遍历结果。", "solution_python": "def inorderTraversal(root):\n result = []\n def dfs(node):\n if node:\n dfs(node.left)\n result.append(node.val)\n dfs(node.right)\n dfs(root)\n return result", "solution_java": "public List inorderTraversal(TreeNode root) {\n List res = new ArrayList<>();\n dfs(root, res);\n return res;\n}\nprivate void dfs(TreeNode node, List res) {\n if (node == null) return;\n dfs(node.left, res); res.add(node.val); dfs(node.right, res);\n}", "solution_cpp": "vector inorderTraversal(TreeNode* root) {\n vector res;\n dfs(root, res);\n return res;\n}\nvoid dfs(TreeNode* node, vector& res) {\n if (!node) return;\n dfs(node->left, res); res.push_back(node->val); dfs(node->right, res);\n}", "test_cases": ["root=[1,null,2,3] -> [1,3,2]", "root=[] -> []"], "key_points": ["左-根-右顺序", "递归最简洁"], "tags": ["tree", "easy", "Google", "Microsoft"]} {"problem_id": "algo_01070", "original_id": "binary-search", "title": "二分查找", "category": "binarysearch", "difficulty": "easy", "companies": ["Google", "Amazon"], "description": "给定一个 n 个元素有序的(升序)整型数组 nums 和一个目标值 target,写一个函数搜索 nums 中的 target,如果目标值存在返回下标,否则返回 -1。", "solution_python": "def search(nums, target):\n left, right = 0, len(nums) - 1\n while left <= right:\n mid = (left + right) // 2\n if nums[mid] == target: return mid\n elif nums[mid] < target: left = mid + 1\n else: right = mid - 1\n return -1", "solution_java": "public int search(int[] nums, int target) {\n int left = 0, right = nums.length - 1;\n while (left <= right) {\n int mid = left + (right - left) / 2;\n if (nums[mid] == target) return mid;\n else if (nums[mid] < target) left = mid + 1;\n else right = mid - 1;\n }\n return -1;\n}", "solution_cpp": "int search(vector& nums, int target) {\n int left = 0, right = nums.size() - 1;\n while (left <= right) {\n int mid = left + (right - left) / 2;\n if (nums[mid] == target) return mid;\n else if (nums[mid] < target) left = mid + 1;\n else right = mid - 1;\n }\n return -1;\n}", "test_cases": ["nums=[-1,0,3,5,9,12], target=9 -> 4", "nums=[-1,0,3,5,9,12], target=2 -> -1"], "key_points": ["标准模板", "注意防溢出写法"], "tags": ["binarysearch", "easy", "Google", "Amazon"]} {"problem_id": "algo_01071", "original_id": "climbing-stairs", "title": "爬楼梯", "category": "dp", "difficulty": "easy", "companies": ["Amazon", "Google"], "description": "假设你正在爬楼梯。需要 n 阶你才能到达楼顶。每次你可以爬 1 或 2 个台阶。你有多少种不同的方法可以爬到楼顶?", "solution_python": "def climbStairs(n):\n if n <= 2: return n\n a, b = 1, 2\n for _ in range(3, n+1):\n a, b = b, a + b\n return b", "solution_java": "public int climbStairs(int n) {\n if (n <= 2) return n;\n int a = 1, b = 2;\n for (int i = 3; i <= n; i++) { int temp = a + b; a = b; b = temp; }\n return b;\n}", "solution_cpp": "int climbStairs(int n) {\n if (n <= 2) return n;\n int a = 1, b = 2;\n for (int i = 3; i <= n; i++) { int temp = a + b; a = b; b = temp; }\n return b;\n}", "test_cases": ["n=2 -> 2", "n=3 -> 3", "n=5 -> 8"], "key_points": ["斐波那契数列", "滚动数组优化空间"], "tags": ["dp", "easy", "Amazon", "Google"]} {"problem_id": "algo_01072", "original_id": "coin-change", "title": "零钱兑换", "category": "dp", "difficulty": "medium", "companies": ["Google", "Amazon"], "description": "给你一个整数数组 coins 表示不同面额的硬币,以及一个整数 amount 表示总金额。计算并返回可以凑成总金额所需的最少的硬币个数。如果没有任何一种硬币组合能组成总金额,返回 -1。", "solution_python": "def coinChange(coins, amount):\n dp = [float('inf')] * (amount + 1)\n dp[0] = 0\n for coin in coins:\n for x in range(coin, amount + 1):\n dp[x] = min(dp[x], dp[x - coin] + 1)\n return dp[amount] if dp[amount] != float('inf') else -1", "solution_java": "public int coinChange(int[] coins, int amount) {\n int[] dp = new int[amount + 1];\n Arrays.fill(dp, amount + 1);\n dp[0] = 0;\n for (int coin : coins) {\n for (int x = coin; x <= amount; x++) {\n dp[x] = Math.min(dp[x], dp[x - coin] + 1);\n }\n }\n return dp[amount] > amount ? -1 : dp[amount];\n}", "solution_cpp": "int coinChange(vector& coins, int amount) {\n vector dp(amount + 1, amount + 1);\n dp[0] = 0;\n for (int coin : coins) {\n for (int x = coin; x <= amount; x++) {\n dp[x] = min(dp[x], dp[x - coin] + 1);\n }\n }\n return dp[amount] > amount ? -1 : dp[amount];\n}", "test_cases": ["coins=[1,2,5], amount=11 -> 3", "coins=[2], amount=3 -> -1"], "key_points": ["完全背包问题", "dp[x] = min(dp[x-coin]+1)"], "tags": ["dp", "medium", "Google", "Amazon"]} {"problem_id": "algo_01073", "original_id": "subsets", "title": "子集", "category": "backtracking", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "给你一个整数数组 nums ,数组中的元素 互不相同 。返回该数组所有可能的子集(幂集)。", "solution_python": "def subsets(nums):\n result = []\n def backtrack(start, path):\n result.append(path[:])\n for i in range(start, len(nums)):\n path.append(nums[i])\n backtrack(i + 1, path)\n path.pop()\n backtrack(0, [])\n return result", "solution_java": "public List> subsets(int[] nums) {\n List> result = new ArrayList<>();\n backtrack(nums, 0, new ArrayList<>(), result);\n return result;\n}\nprivate void backtrack(int[] nums, int start, List path, List> result) {\n result.add(new ArrayList<>(path));\n for (int i = start; i < nums.length; i++) {\n path.add(nums[i]);\n backtrack(nums, i + 1, path, result);\n path.remove(path.size() - 1);\n }\n}", "solution_cpp": "vector> subsets(vector& nums) {\n vector> result;\n vector path;\n backtrack(nums, 0, path, result);\n return result;\n}\nvoid backtrack(vector& nums, int start, vector& path, vector>& result) {\n result.push_back(path);\n for (int i = start; i < nums.size(); i++) {\n path.push_back(nums[i]);\n backtrack(nums, i + 1, path, result);\n path.pop_back();\n }\n}", "test_cases": ["nums=[1,2,3] -> [[],[1],[2],[1,2],[3],[1,3],[2,3],[1,2,3]]"], "key_points": ["选或不选", "DFS遍历子集树"], "tags": ["backtracking", "medium", "Google", "Microsoft"]} {"problem_id": "algo_01074", "original_id": "permutations", "title": "全排列", "category": "backtracking", "difficulty": "medium", "companies": ["Google", "Facebook"], "description": "给定一个不含重复数字的数组 nums,返回其所有可能的全排列。", "solution_python": "def permute(nums):\n result = []\n def backtrack(path, used):\n if len(path) == len(nums):\n result.append(path[:])\n return\n for i in range(len(nums)):\n if used[i]: continue\n used[i] = True\n path.append(nums[i])\n backtrack(path, used)\n path.pop()\n used[i] = False\n backtrack([], [False]*len(nums))\n return result", "solution_java": "public List> permute(int[] nums) {\n List> result = new ArrayList<>();\n boolean[] used = new boolean[nums.length];\n backtrack(nums, used, new ArrayList<>(), result);\n return result;\n}\nprivate void backtrack(int[] nums, boolean[] used, List path, List> result) {\n if (path.size() == nums.length) { result.add(new ArrayList<>(path)); return; }\n for (int i = 0; i < nums.length; i++) {\n if (used[i]) continue;\n used[i] = true;\n path.add(nums[i]);\n backtrack(nums, used, path, result);\n path.remove(path.size() - 1);\n used[i] = false;\n }\n}", "solution_cpp": "vector> permute(vector& nums) {\n vector> result;\n vector used(nums.size(), false);\n vector path;\n backtrack(nums, used, path, result);\n return result;\n}\nvoid backtrack(vector& nums, vector& used, vector& path, vector>& result) {\n if (path.size() == nums.size()) { result.push_back(path); return; }\n for (int i = 0; i < nums.size(); i++) {\n if (used[i]) continue;\n used[i] = true;\n path.push_back(nums[i]);\n backtrack(nums, used, path, result);\n path.pop_back();\n used[i] = false;\n }\n}", "test_cases": ["nums=[1,2,3] -> [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]"], "key_points": ["标记已使用元素", "回溯经典模板"], "tags": ["backtracking", "medium", "Google", "Facebook"]} {"problem_id": "algo_01075", "original_id": "top-k-frequent", "title": "前K个高频元素", "category": "heap", "difficulty": "medium", "companies": ["Amazon", "Facebook"], "description": "给你一个整数数组 nums 和一个整数 k,请你返回其中出现频率前 k 高的元素。", "solution_python": "import heapq\nfrom collections import Counter\ndef topKFrequent(nums, k):\n count = Counter(nums)\n heap = []\n for num, freq in count.items():\n heapq.heappush(heap, (freq, num))\n if len(heap) > k: heapq.heappop(heap)\n return [num for freq, num in heap]", "solution_java": "public int[] topKFrequent(int[] nums, int k) {\n Map count = new HashMap<>();\n for (int n : nums) count.put(n, count.getOrDefault(n, 0) + 1);\n PriorityQueue> heap = \n new PriorityQueue<>((a, b) -> a.getValue() - b.getValue());\n for (Map.Entry e : count.entrySet()) {\n heap.offer(e);\n if (heap.size() > k) heap.poll();\n }\n int[] res = new int[k];\n for (int i = k - 1; i >= 0; i--) res[i] = heap.poll().getKey();\n return res;\n}", "solution_cpp": "vector topKFrequent(vector& nums, int k) {\n unordered_map count;\n for (int n : nums) count[n]++;\n priority_queue, vector>, greater>> heap;\n for (auto& [num, freq] : count) {\n heap.push({freq, num});\n if (heap.size() > k) heap.pop();\n }\n vector res;\n while (!heap.empty()) { res.push_back(heap.top().second); heap.pop(); }\n reverse(res.begin(), res.end());\n return res;\n}", "test_cases": ["nums=[1,1,1,2,2,3], k=2 -> [1,2]", "nums=[1], k=1 -> [1]"], "key_points": ["小顶堆保持大小k", "时间复杂度O(nlogk)"], "tags": ["heap", "medium", "Amazon", "Facebook"]} {"problem_id": "algo_01076", "original_id": "3sum", "title": "三数之和", "category": "two-pointers", "difficulty": "medium", "companies": ["Google", "Amazon"], "description": "给你一个整数数组 nums,判断是否存在三元组满足和为0,返回所有不重复的三元组。", "solution_python": "def threeSum(nums):\n nums.sort()\n result = []\n for i in range(len(nums) - 2):\n if i > 0 and nums[i] == nums[i-1]: continue\n left, right = i + 1, len(nums) - 1\n while left < right:\n total = nums[i] + nums[left] + nums[right]\n if total < 0: left += 1\n elif total > 0: right -= 1\n else:\n result.append([nums[i], nums[left], nums[right]])\n while left < right and nums[left] == nums[left+1]: left += 1\n while left < right and nums[right] == nums[right-1]: right -= 1\n left += 1; right -= 1\n return result", "solution_java": "public List> threeSum(int[] nums) {\n Arrays.sort(nums);\n List> result = new ArrayList<>();\n for (int i = 0; i < nums.length - 2; i++) {\n if (i > 0 && nums[i] == nums[i-1]) continue;\n int left = i + 1, right = nums.length - 1;\n while (left < right) {\n int total = nums[i] + nums[left] + nums[right];\n if (total < 0) left++;\n else if (total > 0) right--;\n else {\n result.add(Arrays.asList(nums[i], nums[left], nums[right]));\n while (left < right && nums[left] == nums[left+1]) left++;\n while (left < right && nums[right] == nums[right-1]) right--;\n left++; right--;\n }\n }\n }\n return result;\n}", "solution_cpp": "vector> threeSum(vector& nums) {\n sort(nums.begin(), nums.end());\n vector> result;\n for (int i = 0; i < nums.size() - 2; i++) {\n if (i > 0 && nums[i] == nums[i-1]) continue;\n int left = i + 1, right = nums.size() - 1;\n while (left < right) {\n int total = nums[i] + nums[left] + nums[right];\n if (total < 0) left++;\n else if (total > 0) right--;\n else {\n result.push_back({nums[i], nums[left], nums[right]});\n while (left < right && nums[left] == nums[left+1]) left++;\n while (left < right && nums[right] == nums[right-1]) right--;\n left++; right--;\n }\n }\n }\n return result;\n}", "test_cases": ["nums=[-1,0,1,2,-1,-4] -> [[-1,-1,2],[-1,0,1]]"], "key_points": ["排序+双指针", "去重是关键"], "tags": ["two-pointers", "medium", "Google", "Amazon"]} {"problem_id": "algo_01077", "original_id": "container-water", "title": "盛最多水的容器", "category": "two-pointers", "difficulty": "medium", "companies": ["Google", "Uber"], "description": "给定一个长度为 n 的整数数组 height,找出其中的两条线,使得它们与 x 轴共同构成的容器可以容纳最多的水。", "solution_python": "def maxArea(height):\n left, right = 0, len(height) - 1\n max_area = 0\n while left < right:\n h = min(height[left], height[right])\n max_area = max(max_area, h * (right - left))\n if height[left] < height[right]: left += 1\n else: right -= 1\n return max_area", "solution_java": "public int maxArea(int[] height) {\n int left = 0, right = height.length - 1, maxArea = 0;\n while (left < right) {\n int h = Math.min(height[left], height[right]);\n maxArea = Math.max(maxArea, h * (right - left));\n if (height[left] < height[right]) left++;\n else right--;\n }\n return maxArea;\n}", "solution_cpp": "int maxArea(vector& height) {\n int left = 0, right = height.size() - 1, maxArea = 0;\n while (left < right) {\n int h = min(height[left], height[right]);\n maxArea = max(maxArea, h * (right - left));\n if (height[left] < height[right]) left++;\n else right--;\n }\n return maxArea;\n}", "test_cases": ["height=[1,8,6,2,5,4,8,3,7] -> 49"], "key_points": ["移动短边指针", "面积=min(h1,h2)*width"], "tags": ["two-pointers", "medium", "Google", "Uber"]} {"problem_id": "algo_01078", "original_id": "min-stack", "title": "最小栈", "category": "stack", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "设计一个支持 push,pop,top 操作,并能在常数时间内检索到最小元素的栈。", "solution_python": "class MinStack:\n def __init__(self):\n self.stack = []\n self.min_stack = []\n def push(self, val):\n self.stack.append(val)\n self.min_stack.append(min(val, self.min_stack[-1] if self.min_stack else val))\n def pop(self):\n self.stack.pop(); self.min_stack.pop()\n def top(self): return self.stack[-1]\n def getMin(self): return self.min_stack[-1]", "solution_java": "class MinStack {\n Stack stack = new Stack<>();\n Stack minStack = new Stack<>();\n public void push(int val) { stack.push(val); minStack.push(Math.min(val, minStack.isEmpty() ? val : minStack.peek())); }\n public void pop() { stack.pop(); minStack.pop(); }\n public int top() { return stack.peek(); }\n public int getMin() { return minStack.peek(); }\n}", "solution_cpp": "class MinStack {\n stack st, minSt;\npublic:\n void push(int val) { st.push(val); minSt.push(min(val, minSt.empty() ? val : minSt.top())); }\n void pop() { st.pop(); minSt.pop(); }\n int top() { return st.top(); }\n int getMin() { return minSt.top(); }\n};", "test_cases": ["push(-2), push(0), push(-3) -> getMin() returns -3"], "key_points": ["辅助栈记录最小值", "O(1)时间获取最小值"], "tags": ["stack", "medium", "Google", "Microsoft"]} {"problem_id": "algo_01079", "original_id": "lru-cache", "title": "LRU缓存", "category": "design", "difficulty": "hard", "companies": ["Google", "Amazon"], "description": "设计和实现一个 LRU(最近最少使用)缓存机制。", "solution_python": "class LRUCache:\n def __init__(self, capacity):\n self.capacity = capacity\n self.cache = {}\n self.order = []\n def get(self, key):\n if key not in self.cache: return -1\n self.order.remove(key); self.order.append(key)\n return self.cache[key]\n def put(self, key, value):\n if key in self.cache:\n self.order.remove(key)\n elif len(self.cache) >= self.capacity:\n del self.cache[self.order.pop(0)]\n self.cache[key] = value; self.order.append(key)", "solution_java": "class LRUCache {\n int capacity;\n LinkedHashMap cache = new LinkedHashMap<>();\n public LRUCache(int cap) { capacity = cap; }\n public int get(int key) { return cache.containsKey(key) ? cache.remove(key) : -1; }\n public void put(int key, int val) {\n if (cache.containsKey(key)) cache.remove(key);\n else if (cache.size() >= capacity) cache.remove(cache.keySet().iterator().next());\n cache.put(key, val);\n }\n}", "solution_cpp": "class LRUCache {\n int cap;\n list> dll;\n unordered_map>::iterator> cache;\npublic:\n LRUCache(int capacity) : cap(capacity) {}\n int get(int key) {\n auto it = cache.find(key);\n if (it == cache.end()) return -1;\n dll.splice(dll.end(), dll, it->second);\n return it->second->second;\n }\n void put(int key, int value) {\n auto it = cache.find(key);\n if (it != cache.end()) dll.erase(it->second);\n else if (cache.size() >= cap) { cache.erase(dll.front().first); dll.pop_front(); }\n dll.push_back({key, value});\n cache[key] = --dll.end();\n }\n};", "test_cases": ["put(1,1), put(2,2), get(1) -> 1"], "key_points": ["HashMap + 双向链表", "O(1)时间操作"], "tags": ["design", "hard", "Google", "Amazon"]} {"problem_id": "algo_01080", "original_id": "num-islands", "title": "岛屿数量", "category": "graph", "difficulty": "medium", "companies": ["Google", "Facebook"], "description": "给你一个由 '1'(陆地)和 '0'(水)组成的二维网格,请你计算网格中岛屿的数量。岛屿总是被水包围,且只能由水平或垂直方向相邻的陆地连接形成。", "solution_python": "def numIslands(grid):\n if not grid: return 0\n rows, cols = len(grid), len(grid[0])\n count = 0\n def dfs(r, c):\n if r < 0 or r >= rows or c < 0 or c >= cols or grid[r][c] != '1': return\n grid[r][c] = '0'\n dfs(r+1, c); dfs(r-1, c); dfs(r, c+1); dfs(r, c-1)\n for r in range(rows):\n for c in range(cols):\n if grid[r][c] == '1': count += 1; dfs(r, c)\n return count", "solution_java": "public int numIslands(char[][] grid) {\n if (grid.length == 0) return 0;\n int count = 0;\n for (int i = 0; i < grid.length; i++)\n for (int j = 0; j < grid[0].length; j++)\n if (grid[i][j] == '1') { count++; dfs(grid, i, j); }\n return count;\n}\nprivate void dfs(char[][] grid, int r, int c) {\n if (r < 0 || r >= grid.length || c < 0 || c >= grid[0].length || grid[r][c] != '1') return;\n grid[r][c] = '0';\n dfs(grid, r+1, c); dfs(grid, r-1, c); dfs(grid, r, c+1); dfs(grid, r, c-1);\n}", "solution_cpp": "int numIslands(vector>& grid) {\n if (grid.empty()) return 0;\n int count = 0;\n for (int i = 0; i < grid.size(); i++)\n for (int j = 0; j < grid[0].size(); j++)\n if (grid[i][j] == '1') { count++; dfs(grid, i, j); }\n return count;\n}\nvoid dfs(vector>& grid, int r, int c) {\n if (r < 0 || r >= grid.size() || c < 0 || c >= grid[0].size() || grid[r][c] != '1') return;\n grid[r][c] = '0';\n dfs(grid, r+1, c); dfs(grid, r-1, c); dfs(grid, r, c+1); dfs(grid, r, c-1);\n}", "test_cases": ["grid=[[1,1,1,1,0],[1,1,0,1,0],[1,1,0,0,0],[0,0,0,0,0]] -> 1"], "key_points": ["DFS/BFS遍历", "访问后标记为0避免重复"], "tags": ["graph", "medium", "Google", "Facebook"]} {"problem_id": "algo_01081", "original_id": "two-sum", "title": "两数之和", "category": "array", "difficulty": "easy", "companies": ["Amazon", "Google"], "description": "给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那两个整数,并返回他们的数组下标。", "solution_python": "def twoSum(nums, target):\n hashmap = {}\n for i, num in enumerate(nums):\n complement = target - num\n if complement in hashmap:\n return [hashmap[complement], i]\n hashmap[num] = i\n return []", "solution_java": "public int[] twoSum(int[] nums, int target) {\n Map map = new HashMap<>();\n for (int i = 0; i < nums.length; i++) {\n int complement = target - nums[i];\n if (map.containsKey(complement)) return new int[]{map.get(complement), i};\n map.put(nums[i], i);\n }\n return new int[]{};\n}", "solution_cpp": "vector twoSum(vector& nums, int target) {\n unordered_map m;\n for (int i = 0; i < nums.size(); i++) {\n if (m.count(target - nums[i])) return {m[target - nums[i]], i};\n m[nums[i]] = i;\n }\n return {};\n}", "test_cases": ["nums=[2,7,11,15], target=9 -> [0,1]", "nums=[3,2,4], target=6 -> [1,2]"], "key_points": ["哈希表一次遍历", "空间换时间"], "tags": ["array", "easy", "Amazon", "Google"]} {"problem_id": "algo_01082", "original_id": "merge-sorted", "title": "合并两个有序数组", "category": "array", "difficulty": "easy", "companies": ["Microsoft", "Uber"], "description": "给你两个按非递减顺序排列的整数数组 nums1 和 nums2,另有两个整数 m 和 n,分别表示 nums1 和 nums2 中的元素数目。请你合并 nums2 到 nums1 中。", "solution_python": "def merge(nums1, m, nums2, n):\n p1, p2, p = m-1, n-1, m+n-1\n while p1 >= 0 and p2 >= 0:\n if nums1[p1] > nums2[p2]: nums1[p] = nums1[p1]; p1 -= 1\n else: nums1[p] = nums2[p2]; p2 -= 1\n p -= 1\n while p2 >= 0: nums1[p] = nums2[p2]; p2 -= 1; p -= 1", "solution_java": "public void merge(int[] nums1, int m, int[] nums2, int n) {\n int p1 = m-1, p2 = n-1, p = m+n-1;\n while (p1 >= 0 && p2 >= 0) {\n nums1[p--] = nums1[p1] > nums2[p2] ? nums1[p1--] : nums2[p2--];\n }\n while (p2 >= 0) nums1[p--] = nums2[p2--];\n}", "solution_cpp": "void merge(vector& nums1, int m, vector& nums2, int n) {\n int p1 = m-1, p2 = n-1, p = m+n-1;\n while (p1 >= 0 && p2 >= 0) nums1[p--] = nums1[p1] > nums2[p2] ? nums1[p1--] : nums2[p2--];\n while (p2 >= 0) nums1[p--] = nums2[p2--];\n}", "test_cases": ["nums1=[1,2,3], m=3, nums2=[2,5,6], n=3 -> [1,2,2,3,5,6]", "nums1=[], m=0, nums2=[1], n=1 -> [1]"], "key_points": ["从后往前合并", "三指针技巧"], "tags": ["array", "easy", "Microsoft", "Uber"]} {"problem_id": "algo_01083", "original_id": "max-subarray", "title": "最大子数组和", "category": "array", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "给你一个整数数组 nums ,请你找出一个具有最大和的连续子数组,返回其最大和。", "solution_python": "def maxSubArray(nums):\n max_sum = current = nums[0]\n for num in nums[1:]:\n current = max(num, current + num)\n max_sum = max(max_sum, current)\n return max_sum", "solution_java": "public int maxSubArray(int[] nums) {\n int maxSum = nums[0], curr = nums[0];\n for (int i = 1; i < nums.length; i++) {\n curr = Math.max(nums[i], curr + nums[i]);\n maxSum = Math.max(maxSum, curr);\n }\n return maxSum;\n}", "solution_cpp": "int maxSubArray(vector& nums) {\n int maxSum = nums[0], curr = nums[0];\n for (int i = 1; i < nums.size(); i++) {\n curr = max(nums[i], curr + nums[i]);\n maxSum = max(maxSum, curr);\n }\n return maxSum;\n}", "test_cases": ["nums=[-2,1,-3,4,-1,2,1,-5,4] -> 6", "nums=[1] -> 1"], "key_points": ["Kadane算法", "动态规划基础题"], "tags": ["array", "medium", "Google", "Microsoft"]} {"problem_id": "algo_01084", "original_id": "valid-parentheses", "title": "有效的括号", "category": "string", "difficulty": "easy", "companies": ["Google", "Uber"], "description": "给定一个只包括 '(',')','{','}','[',']' 的字符串 s,判断字符串是否有效。", "solution_python": "def isValid(s):\n stack = []\n mapping = {')': '(', ']': '[', '}': '{'}\n for c in s:\n if c in mapping:\n if not stack or stack[-1] != mapping[c]: return False\n stack.pop()\n else: stack.append(c)\n return not stack", "solution_java": "public boolean isValid(String s) {\n Stack stack = new Stack<>();\n Map map = Map.of(')', '(', ']', '[', '}', '{');\n for (char c : s.toCharArray()) {\n if (map.containsValue(c)) stack.push(c);\n else if (!stack.isEmpty() && stack.pop() != map.get(c)) return false;\n }\n return stack.isEmpty();\n}", "solution_cpp": "bool isValid(string s) {\n stack st;\n unordered_map m = {{')','('},{']','['},{'}','{'}};\n for (char c : s) {\n if (m.find(c) == m.end()) st.push(c);\n else if (st.empty() || st.top() != m[c]) return false;\n else st.pop();\n }\n return st.empty();\n}", "test_cases": ["s=\"()\" -> true", "s=\"()[]{}\" -> true", "s=\"(]\" -> false"], "key_points": ["栈匹配法", "注意空栈边界"], "tags": ["string", "easy", "Google", "Uber"]} {"problem_id": "algo_01085", "original_id": "longest-palindrome", "title": "最长回文子串", "category": "string", "difficulty": "medium", "companies": ["Google", "Amazon"], "description": "给你一个字符串 s,找到 s 中最长的回文子串。", "solution_python": "def longestPalindrome(s):\n def expand(l, r):\n while l >= 0 and r < len(s) and s[l] == s[r]: l -= 1; r += 1\n return l + 1, r - 1\n start = end = 0\n for i in range(len(s)):\n l1, r1 = expand(i, i)\n l2, r2 = expand(i, i + 1)\n if r1 - l1 > end - start: start, end = l1, r1\n if r2 - l2 > end - start: start, end = l2, r2\n return s[start:end+1]", "solution_java": "public String longestPalindrome(String s) {\n int start = 0, end = 0;\n for (int i = 0; i < s.length(); i++) {\n int len1 = expand(s, i, i), len2 = expand(s, i, i+1);\n int len = Math.max(len1, len2);\n if (len > end - start) { start = i - (len-1)/2; end = i + len/2; }\n }\n return s.substring(start, end + 1);\n}\nprivate int expand(String s, int l, int r) {\n while (l >= 0 && r < s.length() && s.charAt(l) == s.charAt(r)) { l--; r++; }\n return r - l - 1;\n}", "solution_cpp": "string longestPalindrome(string s) {\n int start = 0, end = 0;\n for (int i = 0; i < s.size(); i++) {\n int len1 = expand(s, i, i), len2 = expand(s, i, i+1);\n if (max(len1, len2) > end - start) { start = i - (max(len1,len2)-1)/2; end = i + max(len1,len2)/2; }\n }\n return s.substr(start, end - start + 1);\n}", "test_cases": ["s=\"babad\" -> bab或aba", "s=\"cbbd\" -> bb"], "key_points": ["中心扩展法", "处理奇偶长度"], "tags": ["string", "medium", "Google", "Amazon"]} {"problem_id": "algo_01086", "original_id": "reverse-list", "title": "反转链表", "category": "linkedlist", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "给你单链表的头节点 head,请你反转链表,并返回反转后的链表。", "solution_python": "def reverseList(head):\n prev = None\n curr = head\n while curr:\n nxt = curr.next\n curr.next = prev\n prev = curr\n curr = nxt\n return prev", "solution_java": "public ListNode reverseList(ListNode head) {\n ListNode prev = null, curr = head;\n while (curr != null) {\n ListNode next = curr.next;\n curr.next = prev;\n prev = curr;\n curr = next;\n }\n return prev;\n}", "solution_cpp": "ListNode* reverseList(ListNode* head) {\n ListNode* prev = nullptr, *curr = head;\n while (curr) {\n ListNode* next = curr->next;\n curr->next = prev;\n prev = curr;\n curr = next;\n }\n return prev;\n}", "test_cases": ["head=[1,2,3,4,5] -> [5,4,3,2,1]", "head=[1,2] -> [2,1]"], "key_points": ["迭代法 O(1)空间", "递归法 O(n)空间"], "tags": ["linkedlist", "medium", "Google", "Microsoft"]} {"problem_id": "algo_01087", "original_id": "middle-node", "title": "链表的中间结点", "category": "linkedlist", "difficulty": "easy", "companies": ["Amazon", "Facebook"], "description": "给你单链表的头节点 head,请你找出并返回链表的中间结点。如果有两个中间结点,则返回第二个中间结点。", "solution_python": "def middleNode(head):\n slow = fast = head\n while fast and fast.next:\n slow = slow.next\n fast = fast.next.next\n return slow", "solution_java": "public ListNode middleNode(ListNode head) {\n ListNode slow = head, fast = head;\n while (fast != null && fast.next != null) {\n slow = slow.next;\n fast = fast.next.next;\n }\n return slow;\n}", "solution_cpp": "ListNode* middleNode(ListNode* head) {\n ListNode* slow = head, *fast = head;\n while (fast && fast->next) { slow = slow->next; fast = fast->next->next; }\n return slow;\n}", "test_cases": ["head=[1,2,3,4,5] -> 3", "head=[1,2,3,4,5,6] -> 4"], "key_points": ["快慢指针", "O(n)时间O(1)空间"], "tags": ["linkedlist", "easy", "Amazon", "Facebook"]} {"problem_id": "algo_01088", "original_id": "max-depth", "title": "二叉树的最大深度", "category": "tree", "difficulty": "easy", "companies": ["Microsoft", "Apple"], "description": "给定一个二叉树 root,返回其最大深度。", "solution_python": "def maxDepth(root):\n if not root: return 0\n return max(maxDepth(root.left), maxDepth(root.right)) + 1", "solution_java": "public int maxDepth(TreeNode root) {\n if (root == null) return 0;\n return Math.max(maxDepth(root.left), maxDepth(root.right)) + 1;\n}", "solution_cpp": "int maxDepth(TreeNode* root) {\n if (!root) return 0;\n return max(maxDepth(root->left), maxDepth(root->right)) + 1;\n}", "test_cases": ["root=[3,9,20,null,null,15,7] -> 3", "root=[1,null,2] -> 2"], "key_points": ["DFS递归", "层序遍历也可"], "tags": ["tree", "easy", "Microsoft", "Apple"]} {"problem_id": "algo_01089", "original_id": "inorder-traversal", "title": "二叉树的中序遍历", "category": "tree", "difficulty": "easy", "companies": ["Google", "Microsoft"], "description": "给定一个二叉树的根节点 root,返回它的中序遍历结果。", "solution_python": "def inorderTraversal(root):\n result = []\n def dfs(node):\n if node:\n dfs(node.left)\n result.append(node.val)\n dfs(node.right)\n dfs(root)\n return result", "solution_java": "public List inorderTraversal(TreeNode root) {\n List res = new ArrayList<>();\n dfs(root, res);\n return res;\n}\nprivate void dfs(TreeNode node, List res) {\n if (node == null) return;\n dfs(node.left, res); res.add(node.val); dfs(node.right, res);\n}", "solution_cpp": "vector inorderTraversal(TreeNode* root) {\n vector res;\n dfs(root, res);\n return res;\n}\nvoid dfs(TreeNode* node, vector& res) {\n if (!node) return;\n dfs(node->left, res); res.push_back(node->val); dfs(node->right, res);\n}", "test_cases": ["root=[1,null,2,3] -> [1,3,2]", "root=[] -> []"], "key_points": ["左-根-右顺序", "递归最简洁"], "tags": ["tree", "easy", "Google", "Microsoft"]} {"problem_id": "algo_01090", "original_id": "binary-search", "title": "二分查找", "category": "binarysearch", "difficulty": "easy", "companies": ["Google", "Amazon"], "description": "给定一个 n 个元素有序的(升序)整型数组 nums 和一个目标值 target,写一个函数搜索 nums 中的 target,如果目标值存在返回下标,否则返回 -1。", "solution_python": "def search(nums, target):\n left, right = 0, len(nums) - 1\n while left <= right:\n mid = (left + right) // 2\n if nums[mid] == target: return mid\n elif nums[mid] < target: left = mid + 1\n else: right = mid - 1\n return -1", "solution_java": "public int search(int[] nums, int target) {\n int left = 0, right = nums.length - 1;\n while (left <= right) {\n int mid = left + (right - left) / 2;\n if (nums[mid] == target) return mid;\n else if (nums[mid] < target) left = mid + 1;\n else right = mid - 1;\n }\n return -1;\n}", "solution_cpp": "int search(vector& nums, int target) {\n int left = 0, right = nums.size() - 1;\n while (left <= right) {\n int mid = left + (right - left) / 2;\n if (nums[mid] == target) return mid;\n else if (nums[mid] < target) left = mid + 1;\n else right = mid - 1;\n }\n return -1;\n}", "test_cases": ["nums=[-1,0,3,5,9,12], target=9 -> 4", "nums=[-1,0,3,5,9,12], target=2 -> -1"], "key_points": ["标准模板", "注意防溢出写法"], "tags": ["binarysearch", "easy", "Google", "Amazon"]} {"problem_id": "algo_01091", "original_id": "climbing-stairs", "title": "爬楼梯", "category": "dp", "difficulty": "easy", "companies": ["Amazon", "Google"], "description": "假设你正在爬楼梯。需要 n 阶你才能到达楼顶。每次你可以爬 1 或 2 个台阶。你有多少种不同的方法可以爬到楼顶?", "solution_python": "def climbStairs(n):\n if n <= 2: return n\n a, b = 1, 2\n for _ in range(3, n+1):\n a, b = b, a + b\n return b", "solution_java": "public int climbStairs(int n) {\n if (n <= 2) return n;\n int a = 1, b = 2;\n for (int i = 3; i <= n; i++) { int temp = a + b; a = b; b = temp; }\n return b;\n}", "solution_cpp": "int climbStairs(int n) {\n if (n <= 2) return n;\n int a = 1, b = 2;\n for (int i = 3; i <= n; i++) { int temp = a + b; a = b; b = temp; }\n return b;\n}", "test_cases": ["n=2 -> 2", "n=3 -> 3", "n=5 -> 8"], "key_points": ["斐波那契数列", "滚动数组优化空间"], "tags": ["dp", "easy", "Amazon", "Google"]} {"problem_id": "algo_01092", "original_id": "coin-change", "title": "零钱兑换", "category": "dp", "difficulty": "medium", "companies": ["Google", "Amazon"], "description": "给你一个整数数组 coins 表示不同面额的硬币,以及一个整数 amount 表示总金额。计算并返回可以凑成总金额所需的最少的硬币个数。如果没有任何一种硬币组合能组成总金额,返回 -1。", "solution_python": "def coinChange(coins, amount):\n dp = [float('inf')] * (amount + 1)\n dp[0] = 0\n for coin in coins:\n for x in range(coin, amount + 1):\n dp[x] = min(dp[x], dp[x - coin] + 1)\n return dp[amount] if dp[amount] != float('inf') else -1", "solution_java": "public int coinChange(int[] coins, int amount) {\n int[] dp = new int[amount + 1];\n Arrays.fill(dp, amount + 1);\n dp[0] = 0;\n for (int coin : coins) {\n for (int x = coin; x <= amount; x++) {\n dp[x] = Math.min(dp[x], dp[x - coin] + 1);\n }\n }\n return dp[amount] > amount ? -1 : dp[amount];\n}", "solution_cpp": "int coinChange(vector& coins, int amount) {\n vector dp(amount + 1, amount + 1);\n dp[0] = 0;\n for (int coin : coins) {\n for (int x = coin; x <= amount; x++) {\n dp[x] = min(dp[x], dp[x - coin] + 1);\n }\n }\n return dp[amount] > amount ? -1 : dp[amount];\n}", "test_cases": ["coins=[1,2,5], amount=11 -> 3", "coins=[2], amount=3 -> -1"], "key_points": ["完全背包问题", "dp[x] = min(dp[x-coin]+1)"], "tags": ["dp", "medium", "Google", "Amazon"]} {"problem_id": "algo_01093", "original_id": "subsets", "title": "子集", "category": "backtracking", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "给你一个整数数组 nums ,数组中的元素 互不相同 。返回该数组所有可能的子集(幂集)。", "solution_python": "def subsets(nums):\n result = []\n def backtrack(start, path):\n result.append(path[:])\n for i in range(start, len(nums)):\n path.append(nums[i])\n backtrack(i + 1, path)\n path.pop()\n backtrack(0, [])\n return result", "solution_java": "public List> subsets(int[] nums) {\n List> result = new ArrayList<>();\n backtrack(nums, 0, new ArrayList<>(), result);\n return result;\n}\nprivate void backtrack(int[] nums, int start, List path, List> result) {\n result.add(new ArrayList<>(path));\n for (int i = start; i < nums.length; i++) {\n path.add(nums[i]);\n backtrack(nums, i + 1, path, result);\n path.remove(path.size() - 1);\n }\n}", "solution_cpp": "vector> subsets(vector& nums) {\n vector> result;\n vector path;\n backtrack(nums, 0, path, result);\n return result;\n}\nvoid backtrack(vector& nums, int start, vector& path, vector>& result) {\n result.push_back(path);\n for (int i = start; i < nums.size(); i++) {\n path.push_back(nums[i]);\n backtrack(nums, i + 1, path, result);\n path.pop_back();\n }\n}", "test_cases": ["nums=[1,2,3] -> [[],[1],[2],[1,2],[3],[1,3],[2,3],[1,2,3]]"], "key_points": ["选或不选", "DFS遍历子集树"], "tags": ["backtracking", "medium", "Google", "Microsoft"]} {"problem_id": "algo_01094", "original_id": "permutations", "title": "全排列", "category": "backtracking", "difficulty": "medium", "companies": ["Google", "Facebook"], "description": "给定一个不含重复数字的数组 nums,返回其所有可能的全排列。", "solution_python": "def permute(nums):\n result = []\n def backtrack(path, used):\n if len(path) == len(nums):\n result.append(path[:])\n return\n for i in range(len(nums)):\n if used[i]: continue\n used[i] = True\n path.append(nums[i])\n backtrack(path, used)\n path.pop()\n used[i] = False\n backtrack([], [False]*len(nums))\n return result", "solution_java": "public List> permute(int[] nums) {\n List> result = new ArrayList<>();\n boolean[] used = new boolean[nums.length];\n backtrack(nums, used, new ArrayList<>(), result);\n return result;\n}\nprivate void backtrack(int[] nums, boolean[] used, List path, List> result) {\n if (path.size() == nums.length) { result.add(new ArrayList<>(path)); return; }\n for (int i = 0; i < nums.length; i++) {\n if (used[i]) continue;\n used[i] = true;\n path.add(nums[i]);\n backtrack(nums, used, path, result);\n path.remove(path.size() - 1);\n used[i] = false;\n }\n}", "solution_cpp": "vector> permute(vector& nums) {\n vector> result;\n vector used(nums.size(), false);\n vector path;\n backtrack(nums, used, path, result);\n return result;\n}\nvoid backtrack(vector& nums, vector& used, vector& path, vector>& result) {\n if (path.size() == nums.size()) { result.push_back(path); return; }\n for (int i = 0; i < nums.size(); i++) {\n if (used[i]) continue;\n used[i] = true;\n path.push_back(nums[i]);\n backtrack(nums, used, path, result);\n path.pop_back();\n used[i] = false;\n }\n}", "test_cases": ["nums=[1,2,3] -> [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]"], "key_points": ["标记已使用元素", "回溯经典模板"], "tags": ["backtracking", "medium", "Google", "Facebook"]} {"problem_id": "algo_01095", "original_id": "top-k-frequent", "title": "前K个高频元素", "category": "heap", "difficulty": "medium", "companies": ["Amazon", "Facebook"], "description": "给你一个整数数组 nums 和一个整数 k,请你返回其中出现频率前 k 高的元素。", "solution_python": "import heapq\nfrom collections import Counter\ndef topKFrequent(nums, k):\n count = Counter(nums)\n heap = []\n for num, freq in count.items():\n heapq.heappush(heap, (freq, num))\n if len(heap) > k: heapq.heappop(heap)\n return [num for freq, num in heap]", "solution_java": "public int[] topKFrequent(int[] nums, int k) {\n Map count = new HashMap<>();\n for (int n : nums) count.put(n, count.getOrDefault(n, 0) + 1);\n PriorityQueue> heap = \n new PriorityQueue<>((a, b) -> a.getValue() - b.getValue());\n for (Map.Entry e : count.entrySet()) {\n heap.offer(e);\n if (heap.size() > k) heap.poll();\n }\n int[] res = new int[k];\n for (int i = k - 1; i >= 0; i--) res[i] = heap.poll().getKey();\n return res;\n}", "solution_cpp": "vector topKFrequent(vector& nums, int k) {\n unordered_map count;\n for (int n : nums) count[n]++;\n priority_queue, vector>, greater>> heap;\n for (auto& [num, freq] : count) {\n heap.push({freq, num});\n if (heap.size() > k) heap.pop();\n }\n vector res;\n while (!heap.empty()) { res.push_back(heap.top().second); heap.pop(); }\n reverse(res.begin(), res.end());\n return res;\n}", "test_cases": ["nums=[1,1,1,2,2,3], k=2 -> [1,2]", "nums=[1], k=1 -> [1]"], "key_points": ["小顶堆保持大小k", "时间复杂度O(nlogk)"], "tags": ["heap", "medium", "Amazon", "Facebook"]} {"problem_id": "algo_01096", "original_id": "3sum", "title": "三数之和", "category": "two-pointers", "difficulty": "medium", "companies": ["Google", "Amazon"], "description": "给你一个整数数组 nums,判断是否存在三元组满足和为0,返回所有不重复的三元组。", "solution_python": "def threeSum(nums):\n nums.sort()\n result = []\n for i in range(len(nums) - 2):\n if i > 0 and nums[i] == nums[i-1]: continue\n left, right = i + 1, len(nums) - 1\n while left < right:\n total = nums[i] + nums[left] + nums[right]\n if total < 0: left += 1\n elif total > 0: right -= 1\n else:\n result.append([nums[i], nums[left], nums[right]])\n while left < right and nums[left] == nums[left+1]: left += 1\n while left < right and nums[right] == nums[right-1]: right -= 1\n left += 1; right -= 1\n return result", "solution_java": "public List> threeSum(int[] nums) {\n Arrays.sort(nums);\n List> result = new ArrayList<>();\n for (int i = 0; i < nums.length - 2; i++) {\n if (i > 0 && nums[i] == nums[i-1]) continue;\n int left = i + 1, right = nums.length - 1;\n while (left < right) {\n int total = nums[i] + nums[left] + nums[right];\n if (total < 0) left++;\n else if (total > 0) right--;\n else {\n result.add(Arrays.asList(nums[i], nums[left], nums[right]));\n while (left < right && nums[left] == nums[left+1]) left++;\n while (left < right && nums[right] == nums[right-1]) right--;\n left++; right--;\n }\n }\n }\n return result;\n}", "solution_cpp": "vector> threeSum(vector& nums) {\n sort(nums.begin(), nums.end());\n vector> result;\n for (int i = 0; i < nums.size() - 2; i++) {\n if (i > 0 && nums[i] == nums[i-1]) continue;\n int left = i + 1, right = nums.size() - 1;\n while (left < right) {\n int total = nums[i] + nums[left] + nums[right];\n if (total < 0) left++;\n else if (total > 0) right--;\n else {\n result.push_back({nums[i], nums[left], nums[right]});\n while (left < right && nums[left] == nums[left+1]) left++;\n while (left < right && nums[right] == nums[right-1]) right--;\n left++; right--;\n }\n }\n }\n return result;\n}", "test_cases": ["nums=[-1,0,1,2,-1,-4] -> [[-1,-1,2],[-1,0,1]]"], "key_points": ["排序+双指针", "去重是关键"], "tags": ["two-pointers", "medium", "Google", "Amazon"]} {"problem_id": "algo_01097", "original_id": "container-water", "title": "盛最多水的容器", "category": "two-pointers", "difficulty": "medium", "companies": ["Google", "Uber"], "description": "给定一个长度为 n 的整数数组 height,找出其中的两条线,使得它们与 x 轴共同构成的容器可以容纳最多的水。", "solution_python": "def maxArea(height):\n left, right = 0, len(height) - 1\n max_area = 0\n while left < right:\n h = min(height[left], height[right])\n max_area = max(max_area, h * (right - left))\n if height[left] < height[right]: left += 1\n else: right -= 1\n return max_area", "solution_java": "public int maxArea(int[] height) {\n int left = 0, right = height.length - 1, maxArea = 0;\n while (left < right) {\n int h = Math.min(height[left], height[right]);\n maxArea = Math.max(maxArea, h * (right - left));\n if (height[left] < height[right]) left++;\n else right--;\n }\n return maxArea;\n}", "solution_cpp": "int maxArea(vector& height) {\n int left = 0, right = height.size() - 1, maxArea = 0;\n while (left < right) {\n int h = min(height[left], height[right]);\n maxArea = max(maxArea, h * (right - left));\n if (height[left] < height[right]) left++;\n else right--;\n }\n return maxArea;\n}", "test_cases": ["height=[1,8,6,2,5,4,8,3,7] -> 49"], "key_points": ["移动短边指针", "面积=min(h1,h2)*width"], "tags": ["two-pointers", "medium", "Google", "Uber"]} {"problem_id": "algo_01098", "original_id": "min-stack", "title": "最小栈", "category": "stack", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "设计一个支持 push,pop,top 操作,并能在常数时间内检索到最小元素的栈。", "solution_python": "class MinStack:\n def __init__(self):\n self.stack = []\n self.min_stack = []\n def push(self, val):\n self.stack.append(val)\n self.min_stack.append(min(val, self.min_stack[-1] if self.min_stack else val))\n def pop(self):\n self.stack.pop(); self.min_stack.pop()\n def top(self): return self.stack[-1]\n def getMin(self): return self.min_stack[-1]", "solution_java": "class MinStack {\n Stack stack = new Stack<>();\n Stack minStack = new Stack<>();\n public void push(int val) { stack.push(val); minStack.push(Math.min(val, minStack.isEmpty() ? val : minStack.peek())); }\n public void pop() { stack.pop(); minStack.pop(); }\n public int top() { return stack.peek(); }\n public int getMin() { return minStack.peek(); }\n}", "solution_cpp": "class MinStack {\n stack st, minSt;\npublic:\n void push(int val) { st.push(val); minSt.push(min(val, minSt.empty() ? val : minSt.top())); }\n void pop() { st.pop(); minSt.pop(); }\n int top() { return st.top(); }\n int getMin() { return minSt.top(); }\n};", "test_cases": ["push(-2), push(0), push(-3) -> getMin() returns -3"], "key_points": ["辅助栈记录最小值", "O(1)时间获取最小值"], "tags": ["stack", "medium", "Google", "Microsoft"]} {"problem_id": "algo_01099", "original_id": "lru-cache", "title": "LRU缓存", "category": "design", "difficulty": "hard", "companies": ["Google", "Amazon"], "description": "设计和实现一个 LRU(最近最少使用)缓存机制。", "solution_python": "class LRUCache:\n def __init__(self, capacity):\n self.capacity = capacity\n self.cache = {}\n self.order = []\n def get(self, key):\n if key not in self.cache: return -1\n self.order.remove(key); self.order.append(key)\n return self.cache[key]\n def put(self, key, value):\n if key in self.cache:\n self.order.remove(key)\n elif len(self.cache) >= self.capacity:\n del self.cache[self.order.pop(0)]\n self.cache[key] = value; self.order.append(key)", "solution_java": "class LRUCache {\n int capacity;\n LinkedHashMap cache = new LinkedHashMap<>();\n public LRUCache(int cap) { capacity = cap; }\n public int get(int key) { return cache.containsKey(key) ? cache.remove(key) : -1; }\n public void put(int key, int val) {\n if (cache.containsKey(key)) cache.remove(key);\n else if (cache.size() >= capacity) cache.remove(cache.keySet().iterator().next());\n cache.put(key, val);\n }\n}", "solution_cpp": "class LRUCache {\n int cap;\n list> dll;\n unordered_map>::iterator> cache;\npublic:\n LRUCache(int capacity) : cap(capacity) {}\n int get(int key) {\n auto it = cache.find(key);\n if (it == cache.end()) return -1;\n dll.splice(dll.end(), dll, it->second);\n return it->second->second;\n }\n void put(int key, int value) {\n auto it = cache.find(key);\n if (it != cache.end()) dll.erase(it->second);\n else if (cache.size() >= cap) { cache.erase(dll.front().first); dll.pop_front(); }\n dll.push_back({key, value});\n cache[key] = --dll.end();\n }\n};", "test_cases": ["put(1,1), put(2,2), get(1) -> 1"], "key_points": ["HashMap + 双向链表", "O(1)时间操作"], "tags": ["design", "hard", "Google", "Amazon"]} {"problem_id": "algo_01100", "original_id": "num-islands", "title": "岛屿数量", "category": "graph", "difficulty": "medium", "companies": ["Google", "Facebook"], "description": "给你一个由 '1'(陆地)和 '0'(水)组成的二维网格,请你计算网格中岛屿的数量。岛屿总是被水包围,且只能由水平或垂直方向相邻的陆地连接形成。", "solution_python": "def numIslands(grid):\n if not grid: return 0\n rows, cols = len(grid), len(grid[0])\n count = 0\n def dfs(r, c):\n if r < 0 or r >= rows or c < 0 or c >= cols or grid[r][c] != '1': return\n grid[r][c] = '0'\n dfs(r+1, c); dfs(r-1, c); dfs(r, c+1); dfs(r, c-1)\n for r in range(rows):\n for c in range(cols):\n if grid[r][c] == '1': count += 1; dfs(r, c)\n return count", "solution_java": "public int numIslands(char[][] grid) {\n if (grid.length == 0) return 0;\n int count = 0;\n for (int i = 0; i < grid.length; i++)\n for (int j = 0; j < grid[0].length; j++)\n if (grid[i][j] == '1') { count++; dfs(grid, i, j); }\n return count;\n}\nprivate void dfs(char[][] grid, int r, int c) {\n if (r < 0 || r >= grid.length || c < 0 || c >= grid[0].length || grid[r][c] != '1') return;\n grid[r][c] = '0';\n dfs(grid, r+1, c); dfs(grid, r-1, c); dfs(grid, r, c+1); dfs(grid, r, c-1);\n}", "solution_cpp": "int numIslands(vector>& grid) {\n if (grid.empty()) return 0;\n int count = 0;\n for (int i = 0; i < grid.size(); i++)\n for (int j = 0; j < grid[0].size(); j++)\n if (grid[i][j] == '1') { count++; dfs(grid, i, j); }\n return count;\n}\nvoid dfs(vector>& grid, int r, int c) {\n if (r < 0 || r >= grid.size() || c < 0 || c >= grid[0].size() || grid[r][c] != '1') return;\n grid[r][c] = '0';\n dfs(grid, r+1, c); dfs(grid, r-1, c); dfs(grid, r, c+1); dfs(grid, r, c-1);\n}", "test_cases": ["grid=[[1,1,1,1,0],[1,1,0,1,0],[1,1,0,0,0],[0,0,0,0,0]] -> 1"], "key_points": ["DFS/BFS遍历", "访问后标记为0避免重复"], "tags": ["graph", "medium", "Google", "Facebook"]} {"problem_id": "algo_01101", "original_id": "two-sum", "title": "两数之和", "category": "array", "difficulty": "easy", "companies": ["Amazon", "Google"], "description": "给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那两个整数,并返回他们的数组下标。", "solution_python": "def twoSum(nums, target):\n hashmap = {}\n for i, num in enumerate(nums):\n complement = target - num\n if complement in hashmap:\n return [hashmap[complement], i]\n hashmap[num] = i\n return []", "solution_java": "public int[] twoSum(int[] nums, int target) {\n Map map = new HashMap<>();\n for (int i = 0; i < nums.length; i++) {\n int complement = target - nums[i];\n if (map.containsKey(complement)) return new int[]{map.get(complement), i};\n map.put(nums[i], i);\n }\n return new int[]{};\n}", "solution_cpp": "vector twoSum(vector& nums, int target) {\n unordered_map m;\n for (int i = 0; i < nums.size(); i++) {\n if (m.count(target - nums[i])) return {m[target - nums[i]], i};\n m[nums[i]] = i;\n }\n return {};\n}", "test_cases": ["nums=[2,7,11,15], target=9 -> [0,1]", "nums=[3,2,4], target=6 -> [1,2]"], "key_points": ["哈希表一次遍历", "空间换时间"], "tags": ["array", "easy", "Amazon", "Google"]} {"problem_id": "algo_01102", "original_id": "merge-sorted", "title": "合并两个有序数组", "category": "array", "difficulty": "easy", "companies": ["Microsoft", "Uber"], "description": "给你两个按非递减顺序排列的整数数组 nums1 和 nums2,另有两个整数 m 和 n,分别表示 nums1 和 nums2 中的元素数目。请你合并 nums2 到 nums1 中。", "solution_python": "def merge(nums1, m, nums2, n):\n p1, p2, p = m-1, n-1, m+n-1\n while p1 >= 0 and p2 >= 0:\n if nums1[p1] > nums2[p2]: nums1[p] = nums1[p1]; p1 -= 1\n else: nums1[p] = nums2[p2]; p2 -= 1\n p -= 1\n while p2 >= 0: nums1[p] = nums2[p2]; p2 -= 1; p -= 1", "solution_java": "public void merge(int[] nums1, int m, int[] nums2, int n) {\n int p1 = m-1, p2 = n-1, p = m+n-1;\n while (p1 >= 0 && p2 >= 0) {\n nums1[p--] = nums1[p1] > nums2[p2] ? nums1[p1--] : nums2[p2--];\n }\n while (p2 >= 0) nums1[p--] = nums2[p2--];\n}", "solution_cpp": "void merge(vector& nums1, int m, vector& nums2, int n) {\n int p1 = m-1, p2 = n-1, p = m+n-1;\n while (p1 >= 0 && p2 >= 0) nums1[p--] = nums1[p1] > nums2[p2] ? nums1[p1--] : nums2[p2--];\n while (p2 >= 0) nums1[p--] = nums2[p2--];\n}", "test_cases": ["nums1=[1,2,3], m=3, nums2=[2,5,6], n=3 -> [1,2,2,3,5,6]", "nums1=[], m=0, nums2=[1], n=1 -> [1]"], "key_points": ["从后往前合并", "三指针技巧"], "tags": ["array", "easy", "Microsoft", "Uber"]} {"problem_id": "algo_01103", "original_id": "max-subarray", "title": "最大子数组和", "category": "array", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "给你一个整数数组 nums ,请你找出一个具有最大和的连续子数组,返回其最大和。", "solution_python": "def maxSubArray(nums):\n max_sum = current = nums[0]\n for num in nums[1:]:\n current = max(num, current + num)\n max_sum = max(max_sum, current)\n return max_sum", "solution_java": "public int maxSubArray(int[] nums) {\n int maxSum = nums[0], curr = nums[0];\n for (int i = 1; i < nums.length; i++) {\n curr = Math.max(nums[i], curr + nums[i]);\n maxSum = Math.max(maxSum, curr);\n }\n return maxSum;\n}", "solution_cpp": "int maxSubArray(vector& nums) {\n int maxSum = nums[0], curr = nums[0];\n for (int i = 1; i < nums.size(); i++) {\n curr = max(nums[i], curr + nums[i]);\n maxSum = max(maxSum, curr);\n }\n return maxSum;\n}", "test_cases": ["nums=[-2,1,-3,4,-1,2,1,-5,4] -> 6", "nums=[1] -> 1"], "key_points": ["Kadane算法", "动态规划基础题"], "tags": ["array", "medium", "Google", "Microsoft"]} {"problem_id": "algo_01104", "original_id": "valid-parentheses", "title": "有效的括号", "category": "string", "difficulty": "easy", "companies": ["Google", "Uber"], "description": "给定一个只包括 '(',')','{','}','[',']' 的字符串 s,判断字符串是否有效。", "solution_python": "def isValid(s):\n stack = []\n mapping = {')': '(', ']': '[', '}': '{'}\n for c in s:\n if c in mapping:\n if not stack or stack[-1] != mapping[c]: return False\n stack.pop()\n else: stack.append(c)\n return not stack", "solution_java": "public boolean isValid(String s) {\n Stack stack = new Stack<>();\n Map map = Map.of(')', '(', ']', '[', '}', '{');\n for (char c : s.toCharArray()) {\n if (map.containsValue(c)) stack.push(c);\n else if (!stack.isEmpty() && stack.pop() != map.get(c)) return false;\n }\n return stack.isEmpty();\n}", "solution_cpp": "bool isValid(string s) {\n stack st;\n unordered_map m = {{')','('},{']','['},{'}','{'}};\n for (char c : s) {\n if (m.find(c) == m.end()) st.push(c);\n else if (st.empty() || st.top() != m[c]) return false;\n else st.pop();\n }\n return st.empty();\n}", "test_cases": ["s=\"()\" -> true", "s=\"()[]{}\" -> true", "s=\"(]\" -> false"], "key_points": ["栈匹配法", "注意空栈边界"], "tags": ["string", "easy", "Google", "Uber"]} {"problem_id": "algo_01105", "original_id": "longest-palindrome", "title": "最长回文子串", "category": "string", "difficulty": "medium", "companies": ["Google", "Amazon"], "description": "给你一个字符串 s,找到 s 中最长的回文子串。", "solution_python": "def longestPalindrome(s):\n def expand(l, r):\n while l >= 0 and r < len(s) and s[l] == s[r]: l -= 1; r += 1\n return l + 1, r - 1\n start = end = 0\n for i in range(len(s)):\n l1, r1 = expand(i, i)\n l2, r2 = expand(i, i + 1)\n if r1 - l1 > end - start: start, end = l1, r1\n if r2 - l2 > end - start: start, end = l2, r2\n return s[start:end+1]", "solution_java": "public String longestPalindrome(String s) {\n int start = 0, end = 0;\n for (int i = 0; i < s.length(); i++) {\n int len1 = expand(s, i, i), len2 = expand(s, i, i+1);\n int len = Math.max(len1, len2);\n if (len > end - start) { start = i - (len-1)/2; end = i + len/2; }\n }\n return s.substring(start, end + 1);\n}\nprivate int expand(String s, int l, int r) {\n while (l >= 0 && r < s.length() && s.charAt(l) == s.charAt(r)) { l--; r++; }\n return r - l - 1;\n}", "solution_cpp": "string longestPalindrome(string s) {\n int start = 0, end = 0;\n for (int i = 0; i < s.size(); i++) {\n int len1 = expand(s, i, i), len2 = expand(s, i, i+1);\n if (max(len1, len2) > end - start) { start = i - (max(len1,len2)-1)/2; end = i + max(len1,len2)/2; }\n }\n return s.substr(start, end - start + 1);\n}", "test_cases": ["s=\"babad\" -> bab或aba", "s=\"cbbd\" -> bb"], "key_points": ["中心扩展法", "处理奇偶长度"], "tags": ["string", "medium", "Google", "Amazon"]} {"problem_id": "algo_01106", "original_id": "reverse-list", "title": "反转链表", "category": "linkedlist", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "给你单链表的头节点 head,请你反转链表,并返回反转后的链表。", "solution_python": "def reverseList(head):\n prev = None\n curr = head\n while curr:\n nxt = curr.next\n curr.next = prev\n prev = curr\n curr = nxt\n return prev", "solution_java": "public ListNode reverseList(ListNode head) {\n ListNode prev = null, curr = head;\n while (curr != null) {\n ListNode next = curr.next;\n curr.next = prev;\n prev = curr;\n curr = next;\n }\n return prev;\n}", "solution_cpp": "ListNode* reverseList(ListNode* head) {\n ListNode* prev = nullptr, *curr = head;\n while (curr) {\n ListNode* next = curr->next;\n curr->next = prev;\n prev = curr;\n curr = next;\n }\n return prev;\n}", "test_cases": ["head=[1,2,3,4,5] -> [5,4,3,2,1]", "head=[1,2] -> [2,1]"], "key_points": ["迭代法 O(1)空间", "递归法 O(n)空间"], "tags": ["linkedlist", "medium", "Google", "Microsoft"]} {"problem_id": "algo_01107", "original_id": "middle-node", "title": "链表的中间结点", "category": "linkedlist", "difficulty": "easy", "companies": ["Amazon", "Facebook"], "description": "给你单链表的头节点 head,请你找出并返回链表的中间结点。如果有两个中间结点,则返回第二个中间结点。", "solution_python": "def middleNode(head):\n slow = fast = head\n while fast and fast.next:\n slow = slow.next\n fast = fast.next.next\n return slow", "solution_java": "public ListNode middleNode(ListNode head) {\n ListNode slow = head, fast = head;\n while (fast != null && fast.next != null) {\n slow = slow.next;\n fast = fast.next.next;\n }\n return slow;\n}", "solution_cpp": "ListNode* middleNode(ListNode* head) {\n ListNode* slow = head, *fast = head;\n while (fast && fast->next) { slow = slow->next; fast = fast->next->next; }\n return slow;\n}", "test_cases": ["head=[1,2,3,4,5] -> 3", "head=[1,2,3,4,5,6] -> 4"], "key_points": ["快慢指针", "O(n)时间O(1)空间"], "tags": ["linkedlist", "easy", "Amazon", "Facebook"]} {"problem_id": "algo_01108", "original_id": "max-depth", "title": "二叉树的最大深度", "category": "tree", "difficulty": "easy", "companies": ["Microsoft", "Apple"], "description": "给定一个二叉树 root,返回其最大深度。", "solution_python": "def maxDepth(root):\n if not root: return 0\n return max(maxDepth(root.left), maxDepth(root.right)) + 1", "solution_java": "public int maxDepth(TreeNode root) {\n if (root == null) return 0;\n return Math.max(maxDepth(root.left), maxDepth(root.right)) + 1;\n}", "solution_cpp": "int maxDepth(TreeNode* root) {\n if (!root) return 0;\n return max(maxDepth(root->left), maxDepth(root->right)) + 1;\n}", "test_cases": ["root=[3,9,20,null,null,15,7] -> 3", "root=[1,null,2] -> 2"], "key_points": ["DFS递归", "层序遍历也可"], "tags": ["tree", "easy", "Microsoft", "Apple"]} {"problem_id": "algo_01109", "original_id": "inorder-traversal", "title": "二叉树的中序遍历", "category": "tree", "difficulty": "easy", "companies": ["Google", "Microsoft"], "description": "给定一个二叉树的根节点 root,返回它的中序遍历结果。", "solution_python": "def inorderTraversal(root):\n result = []\n def dfs(node):\n if node:\n dfs(node.left)\n result.append(node.val)\n dfs(node.right)\n dfs(root)\n return result", "solution_java": "public List inorderTraversal(TreeNode root) {\n List res = new ArrayList<>();\n dfs(root, res);\n return res;\n}\nprivate void dfs(TreeNode node, List res) {\n if (node == null) return;\n dfs(node.left, res); res.add(node.val); dfs(node.right, res);\n}", "solution_cpp": "vector inorderTraversal(TreeNode* root) {\n vector res;\n dfs(root, res);\n return res;\n}\nvoid dfs(TreeNode* node, vector& res) {\n if (!node) return;\n dfs(node->left, res); res.push_back(node->val); dfs(node->right, res);\n}", "test_cases": ["root=[1,null,2,3] -> [1,3,2]", "root=[] -> []"], "key_points": ["左-根-右顺序", "递归最简洁"], "tags": ["tree", "easy", "Google", "Microsoft"]} {"problem_id": "algo_01110", "original_id": "binary-search", "title": "二分查找", "category": "binarysearch", "difficulty": "easy", "companies": ["Google", "Amazon"], "description": "给定一个 n 个元素有序的(升序)整型数组 nums 和一个目标值 target,写一个函数搜索 nums 中的 target,如果目标值存在返回下标,否则返回 -1。", "solution_python": "def search(nums, target):\n left, right = 0, len(nums) - 1\n while left <= right:\n mid = (left + right) // 2\n if nums[mid] == target: return mid\n elif nums[mid] < target: left = mid + 1\n else: right = mid - 1\n return -1", "solution_java": "public int search(int[] nums, int target) {\n int left = 0, right = nums.length - 1;\n while (left <= right) {\n int mid = left + (right - left) / 2;\n if (nums[mid] == target) return mid;\n else if (nums[mid] < target) left = mid + 1;\n else right = mid - 1;\n }\n return -1;\n}", "solution_cpp": "int search(vector& nums, int target) {\n int left = 0, right = nums.size() - 1;\n while (left <= right) {\n int mid = left + (right - left) / 2;\n if (nums[mid] == target) return mid;\n else if (nums[mid] < target) left = mid + 1;\n else right = mid - 1;\n }\n return -1;\n}", "test_cases": ["nums=[-1,0,3,5,9,12], target=9 -> 4", "nums=[-1,0,3,5,9,12], target=2 -> -1"], "key_points": ["标准模板", "注意防溢出写法"], "tags": ["binarysearch", "easy", "Google", "Amazon"]} {"problem_id": "algo_01111", "original_id": "climbing-stairs", "title": "爬楼梯", "category": "dp", "difficulty": "easy", "companies": ["Amazon", "Google"], "description": "假设你正在爬楼梯。需要 n 阶你才能到达楼顶。每次你可以爬 1 或 2 个台阶。你有多少种不同的方法可以爬到楼顶?", "solution_python": "def climbStairs(n):\n if n <= 2: return n\n a, b = 1, 2\n for _ in range(3, n+1):\n a, b = b, a + b\n return b", "solution_java": "public int climbStairs(int n) {\n if (n <= 2) return n;\n int a = 1, b = 2;\n for (int i = 3; i <= n; i++) { int temp = a + b; a = b; b = temp; }\n return b;\n}", "solution_cpp": "int climbStairs(int n) {\n if (n <= 2) return n;\n int a = 1, b = 2;\n for (int i = 3; i <= n; i++) { int temp = a + b; a = b; b = temp; }\n return b;\n}", "test_cases": ["n=2 -> 2", "n=3 -> 3", "n=5 -> 8"], "key_points": ["斐波那契数列", "滚动数组优化空间"], "tags": ["dp", "easy", "Amazon", "Google"]} {"problem_id": "algo_01112", "original_id": "coin-change", "title": "零钱兑换", "category": "dp", "difficulty": "medium", "companies": ["Google", "Amazon"], "description": "给你一个整数数组 coins 表示不同面额的硬币,以及一个整数 amount 表示总金额。计算并返回可以凑成总金额所需的最少的硬币个数。如果没有任何一种硬币组合能组成总金额,返回 -1。", "solution_python": "def coinChange(coins, amount):\n dp = [float('inf')] * (amount + 1)\n dp[0] = 0\n for coin in coins:\n for x in range(coin, amount + 1):\n dp[x] = min(dp[x], dp[x - coin] + 1)\n return dp[amount] if dp[amount] != float('inf') else -1", "solution_java": "public int coinChange(int[] coins, int amount) {\n int[] dp = new int[amount + 1];\n Arrays.fill(dp, amount + 1);\n dp[0] = 0;\n for (int coin : coins) {\n for (int x = coin; x <= amount; x++) {\n dp[x] = Math.min(dp[x], dp[x - coin] + 1);\n }\n }\n return dp[amount] > amount ? -1 : dp[amount];\n}", "solution_cpp": "int coinChange(vector& coins, int amount) {\n vector dp(amount + 1, amount + 1);\n dp[0] = 0;\n for (int coin : coins) {\n for (int x = coin; x <= amount; x++) {\n dp[x] = min(dp[x], dp[x - coin] + 1);\n }\n }\n return dp[amount] > amount ? -1 : dp[amount];\n}", "test_cases": ["coins=[1,2,5], amount=11 -> 3", "coins=[2], amount=3 -> -1"], "key_points": ["完全背包问题", "dp[x] = min(dp[x-coin]+1)"], "tags": ["dp", "medium", "Google", "Amazon"]} {"problem_id": "algo_01113", "original_id": "subsets", "title": "子集", "category": "backtracking", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "给你一个整数数组 nums ,数组中的元素 互不相同 。返回该数组所有可能的子集(幂集)。", "solution_python": "def subsets(nums):\n result = []\n def backtrack(start, path):\n result.append(path[:])\n for i in range(start, len(nums)):\n path.append(nums[i])\n backtrack(i + 1, path)\n path.pop()\n backtrack(0, [])\n return result", "solution_java": "public List> subsets(int[] nums) {\n List> result = new ArrayList<>();\n backtrack(nums, 0, new ArrayList<>(), result);\n return result;\n}\nprivate void backtrack(int[] nums, int start, List path, List> result) {\n result.add(new ArrayList<>(path));\n for (int i = start; i < nums.length; i++) {\n path.add(nums[i]);\n backtrack(nums, i + 1, path, result);\n path.remove(path.size() - 1);\n }\n}", "solution_cpp": "vector> subsets(vector& nums) {\n vector> result;\n vector path;\n backtrack(nums, 0, path, result);\n return result;\n}\nvoid backtrack(vector& nums, int start, vector& path, vector>& result) {\n result.push_back(path);\n for (int i = start; i < nums.size(); i++) {\n path.push_back(nums[i]);\n backtrack(nums, i + 1, path, result);\n path.pop_back();\n }\n}", "test_cases": ["nums=[1,2,3] -> [[],[1],[2],[1,2],[3],[1,3],[2,3],[1,2,3]]"], "key_points": ["选或不选", "DFS遍历子集树"], "tags": ["backtracking", "medium", "Google", "Microsoft"]} {"problem_id": "algo_01114", "original_id": "permutations", "title": "全排列", "category": "backtracking", "difficulty": "medium", "companies": ["Google", "Facebook"], "description": "给定一个不含重复数字的数组 nums,返回其所有可能的全排列。", "solution_python": "def permute(nums):\n result = []\n def backtrack(path, used):\n if len(path) == len(nums):\n result.append(path[:])\n return\n for i in range(len(nums)):\n if used[i]: continue\n used[i] = True\n path.append(nums[i])\n backtrack(path, used)\n path.pop()\n used[i] = False\n backtrack([], [False]*len(nums))\n return result", "solution_java": "public List> permute(int[] nums) {\n List> result = new ArrayList<>();\n boolean[] used = new boolean[nums.length];\n backtrack(nums, used, new ArrayList<>(), result);\n return result;\n}\nprivate void backtrack(int[] nums, boolean[] used, List path, List> result) {\n if (path.size() == nums.length) { result.add(new ArrayList<>(path)); return; }\n for (int i = 0; i < nums.length; i++) {\n if (used[i]) continue;\n used[i] = true;\n path.add(nums[i]);\n backtrack(nums, used, path, result);\n path.remove(path.size() - 1);\n used[i] = false;\n }\n}", "solution_cpp": "vector> permute(vector& nums) {\n vector> result;\n vector used(nums.size(), false);\n vector path;\n backtrack(nums, used, path, result);\n return result;\n}\nvoid backtrack(vector& nums, vector& used, vector& path, vector>& result) {\n if (path.size() == nums.size()) { result.push_back(path); return; }\n for (int i = 0; i < nums.size(); i++) {\n if (used[i]) continue;\n used[i] = true;\n path.push_back(nums[i]);\n backtrack(nums, used, path, result);\n path.pop_back();\n used[i] = false;\n }\n}", "test_cases": ["nums=[1,2,3] -> [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]"], "key_points": ["标记已使用元素", "回溯经典模板"], "tags": ["backtracking", "medium", "Google", "Facebook"]} {"problem_id": "algo_01115", "original_id": "top-k-frequent", "title": "前K个高频元素", "category": "heap", "difficulty": "medium", "companies": ["Amazon", "Facebook"], "description": "给你一个整数数组 nums 和一个整数 k,请你返回其中出现频率前 k 高的元素。", "solution_python": "import heapq\nfrom collections import Counter\ndef topKFrequent(nums, k):\n count = Counter(nums)\n heap = []\n for num, freq in count.items():\n heapq.heappush(heap, (freq, num))\n if len(heap) > k: heapq.heappop(heap)\n return [num for freq, num in heap]", "solution_java": "public int[] topKFrequent(int[] nums, int k) {\n Map count = new HashMap<>();\n for (int n : nums) count.put(n, count.getOrDefault(n, 0) + 1);\n PriorityQueue> heap = \n new PriorityQueue<>((a, b) -> a.getValue() - b.getValue());\n for (Map.Entry e : count.entrySet()) {\n heap.offer(e);\n if (heap.size() > k) heap.poll();\n }\n int[] res = new int[k];\n for (int i = k - 1; i >= 0; i--) res[i] = heap.poll().getKey();\n return res;\n}", "solution_cpp": "vector topKFrequent(vector& nums, int k) {\n unordered_map count;\n for (int n : nums) count[n]++;\n priority_queue, vector>, greater>> heap;\n for (auto& [num, freq] : count) {\n heap.push({freq, num});\n if (heap.size() > k) heap.pop();\n }\n vector res;\n while (!heap.empty()) { res.push_back(heap.top().second); heap.pop(); }\n reverse(res.begin(), res.end());\n return res;\n}", "test_cases": ["nums=[1,1,1,2,2,3], k=2 -> [1,2]", "nums=[1], k=1 -> [1]"], "key_points": ["小顶堆保持大小k", "时间复杂度O(nlogk)"], "tags": ["heap", "medium", "Amazon", "Facebook"]} {"problem_id": "algo_01116", "original_id": "3sum", "title": "三数之和", "category": "two-pointers", "difficulty": "medium", "companies": ["Google", "Amazon"], "description": "给你一个整数数组 nums,判断是否存在三元组满足和为0,返回所有不重复的三元组。", "solution_python": "def threeSum(nums):\n nums.sort()\n result = []\n for i in range(len(nums) - 2):\n if i > 0 and nums[i] == nums[i-1]: continue\n left, right = i + 1, len(nums) - 1\n while left < right:\n total = nums[i] + nums[left] + nums[right]\n if total < 0: left += 1\n elif total > 0: right -= 1\n else:\n result.append([nums[i], nums[left], nums[right]])\n while left < right and nums[left] == nums[left+1]: left += 1\n while left < right and nums[right] == nums[right-1]: right -= 1\n left += 1; right -= 1\n return result", "solution_java": "public List> threeSum(int[] nums) {\n Arrays.sort(nums);\n List> result = new ArrayList<>();\n for (int i = 0; i < nums.length - 2; i++) {\n if (i > 0 && nums[i] == nums[i-1]) continue;\n int left = i + 1, right = nums.length - 1;\n while (left < right) {\n int total = nums[i] + nums[left] + nums[right];\n if (total < 0) left++;\n else if (total > 0) right--;\n else {\n result.add(Arrays.asList(nums[i], nums[left], nums[right]));\n while (left < right && nums[left] == nums[left+1]) left++;\n while (left < right && nums[right] == nums[right-1]) right--;\n left++; right--;\n }\n }\n }\n return result;\n}", "solution_cpp": "vector> threeSum(vector& nums) {\n sort(nums.begin(), nums.end());\n vector> result;\n for (int i = 0; i < nums.size() - 2; i++) {\n if (i > 0 && nums[i] == nums[i-1]) continue;\n int left = i + 1, right = nums.size() - 1;\n while (left < right) {\n int total = nums[i] + nums[left] + nums[right];\n if (total < 0) left++;\n else if (total > 0) right--;\n else {\n result.push_back({nums[i], nums[left], nums[right]});\n while (left < right && nums[left] == nums[left+1]) left++;\n while (left < right && nums[right] == nums[right-1]) right--;\n left++; right--;\n }\n }\n }\n return result;\n}", "test_cases": ["nums=[-1,0,1,2,-1,-4] -> [[-1,-1,2],[-1,0,1]]"], "key_points": ["排序+双指针", "去重是关键"], "tags": ["two-pointers", "medium", "Google", "Amazon"]} {"problem_id": "algo_01117", "original_id": "container-water", "title": "盛最多水的容器", "category": "two-pointers", "difficulty": "medium", "companies": ["Google", "Uber"], "description": "给定一个长度为 n 的整数数组 height,找出其中的两条线,使得它们与 x 轴共同构成的容器可以容纳最多的水。", "solution_python": "def maxArea(height):\n left, right = 0, len(height) - 1\n max_area = 0\n while left < right:\n h = min(height[left], height[right])\n max_area = max(max_area, h * (right - left))\n if height[left] < height[right]: left += 1\n else: right -= 1\n return max_area", "solution_java": "public int maxArea(int[] height) {\n int left = 0, right = height.length - 1, maxArea = 0;\n while (left < right) {\n int h = Math.min(height[left], height[right]);\n maxArea = Math.max(maxArea, h * (right - left));\n if (height[left] < height[right]) left++;\n else right--;\n }\n return maxArea;\n}", "solution_cpp": "int maxArea(vector& height) {\n int left = 0, right = height.size() - 1, maxArea = 0;\n while (left < right) {\n int h = min(height[left], height[right]);\n maxArea = max(maxArea, h * (right - left));\n if (height[left] < height[right]) left++;\n else right--;\n }\n return maxArea;\n}", "test_cases": ["height=[1,8,6,2,5,4,8,3,7] -> 49"], "key_points": ["移动短边指针", "面积=min(h1,h2)*width"], "tags": ["two-pointers", "medium", "Google", "Uber"]} {"problem_id": "algo_01118", "original_id": "min-stack", "title": "最小栈", "category": "stack", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "设计一个支持 push,pop,top 操作,并能在常数时间内检索到最小元素的栈。", "solution_python": "class MinStack:\n def __init__(self):\n self.stack = []\n self.min_stack = []\n def push(self, val):\n self.stack.append(val)\n self.min_stack.append(min(val, self.min_stack[-1] if self.min_stack else val))\n def pop(self):\n self.stack.pop(); self.min_stack.pop()\n def top(self): return self.stack[-1]\n def getMin(self): return self.min_stack[-1]", "solution_java": "class MinStack {\n Stack stack = new Stack<>();\n Stack minStack = new Stack<>();\n public void push(int val) { stack.push(val); minStack.push(Math.min(val, minStack.isEmpty() ? val : minStack.peek())); }\n public void pop() { stack.pop(); minStack.pop(); }\n public int top() { return stack.peek(); }\n public int getMin() { return minStack.peek(); }\n}", "solution_cpp": "class MinStack {\n stack st, minSt;\npublic:\n void push(int val) { st.push(val); minSt.push(min(val, minSt.empty() ? val : minSt.top())); }\n void pop() { st.pop(); minSt.pop(); }\n int top() { return st.top(); }\n int getMin() { return minSt.top(); }\n};", "test_cases": ["push(-2), push(0), push(-3) -> getMin() returns -3"], "key_points": ["辅助栈记录最小值", "O(1)时间获取最小值"], "tags": ["stack", "medium", "Google", "Microsoft"]} {"problem_id": "algo_01119", "original_id": "lru-cache", "title": "LRU缓存", "category": "design", "difficulty": "hard", "companies": ["Google", "Amazon"], "description": "设计和实现一个 LRU(最近最少使用)缓存机制。", "solution_python": "class LRUCache:\n def __init__(self, capacity):\n self.capacity = capacity\n self.cache = {}\n self.order = []\n def get(self, key):\n if key not in self.cache: return -1\n self.order.remove(key); self.order.append(key)\n return self.cache[key]\n def put(self, key, value):\n if key in self.cache:\n self.order.remove(key)\n elif len(self.cache) >= self.capacity:\n del self.cache[self.order.pop(0)]\n self.cache[key] = value; self.order.append(key)", "solution_java": "class LRUCache {\n int capacity;\n LinkedHashMap cache = new LinkedHashMap<>();\n public LRUCache(int cap) { capacity = cap; }\n public int get(int key) { return cache.containsKey(key) ? cache.remove(key) : -1; }\n public void put(int key, int val) {\n if (cache.containsKey(key)) cache.remove(key);\n else if (cache.size() >= capacity) cache.remove(cache.keySet().iterator().next());\n cache.put(key, val);\n }\n}", "solution_cpp": "class LRUCache {\n int cap;\n list> dll;\n unordered_map>::iterator> cache;\npublic:\n LRUCache(int capacity) : cap(capacity) {}\n int get(int key) {\n auto it = cache.find(key);\n if (it == cache.end()) return -1;\n dll.splice(dll.end(), dll, it->second);\n return it->second->second;\n }\n void put(int key, int value) {\n auto it = cache.find(key);\n if (it != cache.end()) dll.erase(it->second);\n else if (cache.size() >= cap) { cache.erase(dll.front().first); dll.pop_front(); }\n dll.push_back({key, value});\n cache[key] = --dll.end();\n }\n};", "test_cases": ["put(1,1), put(2,2), get(1) -> 1"], "key_points": ["HashMap + 双向链表", "O(1)时间操作"], "tags": ["design", "hard", "Google", "Amazon"]} {"problem_id": "algo_01120", "original_id": "num-islands", "title": "岛屿数量", "category": "graph", "difficulty": "medium", "companies": ["Google", "Facebook"], "description": "给你一个由 '1'(陆地)和 '0'(水)组成的二维网格,请你计算网格中岛屿的数量。岛屿总是被水包围,且只能由水平或垂直方向相邻的陆地连接形成。", "solution_python": "def numIslands(grid):\n if not grid: return 0\n rows, cols = len(grid), len(grid[0])\n count = 0\n def dfs(r, c):\n if r < 0 or r >= rows or c < 0 or c >= cols or grid[r][c] != '1': return\n grid[r][c] = '0'\n dfs(r+1, c); dfs(r-1, c); dfs(r, c+1); dfs(r, c-1)\n for r in range(rows):\n for c in range(cols):\n if grid[r][c] == '1': count += 1; dfs(r, c)\n return count", "solution_java": "public int numIslands(char[][] grid) {\n if (grid.length == 0) return 0;\n int count = 0;\n for (int i = 0; i < grid.length; i++)\n for (int j = 0; j < grid[0].length; j++)\n if (grid[i][j] == '1') { count++; dfs(grid, i, j); }\n return count;\n}\nprivate void dfs(char[][] grid, int r, int c) {\n if (r < 0 || r >= grid.length || c < 0 || c >= grid[0].length || grid[r][c] != '1') return;\n grid[r][c] = '0';\n dfs(grid, r+1, c); dfs(grid, r-1, c); dfs(grid, r, c+1); dfs(grid, r, c-1);\n}", "solution_cpp": "int numIslands(vector>& grid) {\n if (grid.empty()) return 0;\n int count = 0;\n for (int i = 0; i < grid.size(); i++)\n for (int j = 0; j < grid[0].size(); j++)\n if (grid[i][j] == '1') { count++; dfs(grid, i, j); }\n return count;\n}\nvoid dfs(vector>& grid, int r, int c) {\n if (r < 0 || r >= grid.size() || c < 0 || c >= grid[0].size() || grid[r][c] != '1') return;\n grid[r][c] = '0';\n dfs(grid, r+1, c); dfs(grid, r-1, c); dfs(grid, r, c+1); dfs(grid, r, c-1);\n}", "test_cases": ["grid=[[1,1,1,1,0],[1,1,0,1,0],[1,1,0,0,0],[0,0,0,0,0]] -> 1"], "key_points": ["DFS/BFS遍历", "访问后标记为0避免重复"], "tags": ["graph", "medium", "Google", "Facebook"]} {"problem_id": "algo_01121", "original_id": "two-sum", "title": "两数之和", "category": "array", "difficulty": "easy", "companies": ["Amazon", "Google"], "description": "给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那两个整数,并返回他们的数组下标。", "solution_python": "def twoSum(nums, target):\n hashmap = {}\n for i, num in enumerate(nums):\n complement = target - num\n if complement in hashmap:\n return [hashmap[complement], i]\n hashmap[num] = i\n return []", "solution_java": "public int[] twoSum(int[] nums, int target) {\n Map map = new HashMap<>();\n for (int i = 0; i < nums.length; i++) {\n int complement = target - nums[i];\n if (map.containsKey(complement)) return new int[]{map.get(complement), i};\n map.put(nums[i], i);\n }\n return new int[]{};\n}", "solution_cpp": "vector twoSum(vector& nums, int target) {\n unordered_map m;\n for (int i = 0; i < nums.size(); i++) {\n if (m.count(target - nums[i])) return {m[target - nums[i]], i};\n m[nums[i]] = i;\n }\n return {};\n}", "test_cases": ["nums=[2,7,11,15], target=9 -> [0,1]", "nums=[3,2,4], target=6 -> [1,2]"], "key_points": ["哈希表一次遍历", "空间换时间"], "tags": ["array", "easy", "Amazon", "Google"]} {"problem_id": "algo_01122", "original_id": "merge-sorted", "title": "合并两个有序数组", "category": "array", "difficulty": "easy", "companies": ["Microsoft", "Uber"], "description": "给你两个按非递减顺序排列的整数数组 nums1 和 nums2,另有两个整数 m 和 n,分别表示 nums1 和 nums2 中的元素数目。请你合并 nums2 到 nums1 中。", "solution_python": "def merge(nums1, m, nums2, n):\n p1, p2, p = m-1, n-1, m+n-1\n while p1 >= 0 and p2 >= 0:\n if nums1[p1] > nums2[p2]: nums1[p] = nums1[p1]; p1 -= 1\n else: nums1[p] = nums2[p2]; p2 -= 1\n p -= 1\n while p2 >= 0: nums1[p] = nums2[p2]; p2 -= 1; p -= 1", "solution_java": "public void merge(int[] nums1, int m, int[] nums2, int n) {\n int p1 = m-1, p2 = n-1, p = m+n-1;\n while (p1 >= 0 && p2 >= 0) {\n nums1[p--] = nums1[p1] > nums2[p2] ? nums1[p1--] : nums2[p2--];\n }\n while (p2 >= 0) nums1[p--] = nums2[p2--];\n}", "solution_cpp": "void merge(vector& nums1, int m, vector& nums2, int n) {\n int p1 = m-1, p2 = n-1, p = m+n-1;\n while (p1 >= 0 && p2 >= 0) nums1[p--] = nums1[p1] > nums2[p2] ? nums1[p1--] : nums2[p2--];\n while (p2 >= 0) nums1[p--] = nums2[p2--];\n}", "test_cases": ["nums1=[1,2,3], m=3, nums2=[2,5,6], n=3 -> [1,2,2,3,5,6]", "nums1=[], m=0, nums2=[1], n=1 -> [1]"], "key_points": ["从后往前合并", "三指针技巧"], "tags": ["array", "easy", "Microsoft", "Uber"]} {"problem_id": "algo_01123", "original_id": "max-subarray", "title": "最大子数组和", "category": "array", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "给你一个整数数组 nums ,请你找出一个具有最大和的连续子数组,返回其最大和。", "solution_python": "def maxSubArray(nums):\n max_sum = current = nums[0]\n for num in nums[1:]:\n current = max(num, current + num)\n max_sum = max(max_sum, current)\n return max_sum", "solution_java": "public int maxSubArray(int[] nums) {\n int maxSum = nums[0], curr = nums[0];\n for (int i = 1; i < nums.length; i++) {\n curr = Math.max(nums[i], curr + nums[i]);\n maxSum = Math.max(maxSum, curr);\n }\n return maxSum;\n}", "solution_cpp": "int maxSubArray(vector& nums) {\n int maxSum = nums[0], curr = nums[0];\n for (int i = 1; i < nums.size(); i++) {\n curr = max(nums[i], curr + nums[i]);\n maxSum = max(maxSum, curr);\n }\n return maxSum;\n}", "test_cases": ["nums=[-2,1,-3,4,-1,2,1,-5,4] -> 6", "nums=[1] -> 1"], "key_points": ["Kadane算法", "动态规划基础题"], "tags": ["array", "medium", "Google", "Microsoft"]} {"problem_id": "algo_01124", "original_id": "valid-parentheses", "title": "有效的括号", "category": "string", "difficulty": "easy", "companies": ["Google", "Uber"], "description": "给定一个只包括 '(',')','{','}','[',']' 的字符串 s,判断字符串是否有效。", "solution_python": "def isValid(s):\n stack = []\n mapping = {')': '(', ']': '[', '}': '{'}\n for c in s:\n if c in mapping:\n if not stack or stack[-1] != mapping[c]: return False\n stack.pop()\n else: stack.append(c)\n return not stack", "solution_java": "public boolean isValid(String s) {\n Stack stack = new Stack<>();\n Map map = Map.of(')', '(', ']', '[', '}', '{');\n for (char c : s.toCharArray()) {\n if (map.containsValue(c)) stack.push(c);\n else if (!stack.isEmpty() && stack.pop() != map.get(c)) return false;\n }\n return stack.isEmpty();\n}", "solution_cpp": "bool isValid(string s) {\n stack st;\n unordered_map m = {{')','('},{']','['},{'}','{'}};\n for (char c : s) {\n if (m.find(c) == m.end()) st.push(c);\n else if (st.empty() || st.top() != m[c]) return false;\n else st.pop();\n }\n return st.empty();\n}", "test_cases": ["s=\"()\" -> true", "s=\"()[]{}\" -> true", "s=\"(]\" -> false"], "key_points": ["栈匹配法", "注意空栈边界"], "tags": ["string", "easy", "Google", "Uber"]} {"problem_id": "algo_01125", "original_id": "longest-palindrome", "title": "最长回文子串", "category": "string", "difficulty": "medium", "companies": ["Google", "Amazon"], "description": "给你一个字符串 s,找到 s 中最长的回文子串。", "solution_python": "def longestPalindrome(s):\n def expand(l, r):\n while l >= 0 and r < len(s) and s[l] == s[r]: l -= 1; r += 1\n return l + 1, r - 1\n start = end = 0\n for i in range(len(s)):\n l1, r1 = expand(i, i)\n l2, r2 = expand(i, i + 1)\n if r1 - l1 > end - start: start, end = l1, r1\n if r2 - l2 > end - start: start, end = l2, r2\n return s[start:end+1]", "solution_java": "public String longestPalindrome(String s) {\n int start = 0, end = 0;\n for (int i = 0; i < s.length(); i++) {\n int len1 = expand(s, i, i), len2 = expand(s, i, i+1);\n int len = Math.max(len1, len2);\n if (len > end - start) { start = i - (len-1)/2; end = i + len/2; }\n }\n return s.substring(start, end + 1);\n}\nprivate int expand(String s, int l, int r) {\n while (l >= 0 && r < s.length() && s.charAt(l) == s.charAt(r)) { l--; r++; }\n return r - l - 1;\n}", "solution_cpp": "string longestPalindrome(string s) {\n int start = 0, end = 0;\n for (int i = 0; i < s.size(); i++) {\n int len1 = expand(s, i, i), len2 = expand(s, i, i+1);\n if (max(len1, len2) > end - start) { start = i - (max(len1,len2)-1)/2; end = i + max(len1,len2)/2; }\n }\n return s.substr(start, end - start + 1);\n}", "test_cases": ["s=\"babad\" -> bab或aba", "s=\"cbbd\" -> bb"], "key_points": ["中心扩展法", "处理奇偶长度"], "tags": ["string", "medium", "Google", "Amazon"]} {"problem_id": "algo_01126", "original_id": "reverse-list", "title": "反转链表", "category": "linkedlist", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "给你单链表的头节点 head,请你反转链表,并返回反转后的链表。", "solution_python": "def reverseList(head):\n prev = None\n curr = head\n while curr:\n nxt = curr.next\n curr.next = prev\n prev = curr\n curr = nxt\n return prev", "solution_java": "public ListNode reverseList(ListNode head) {\n ListNode prev = null, curr = head;\n while (curr != null) {\n ListNode next = curr.next;\n curr.next = prev;\n prev = curr;\n curr = next;\n }\n return prev;\n}", "solution_cpp": "ListNode* reverseList(ListNode* head) {\n ListNode* prev = nullptr, *curr = head;\n while (curr) {\n ListNode* next = curr->next;\n curr->next = prev;\n prev = curr;\n curr = next;\n }\n return prev;\n}", "test_cases": ["head=[1,2,3,4,5] -> [5,4,3,2,1]", "head=[1,2] -> [2,1]"], "key_points": ["迭代法 O(1)空间", "递归法 O(n)空间"], "tags": ["linkedlist", "medium", "Google", "Microsoft"]} {"problem_id": "algo_01127", "original_id": "middle-node", "title": "链表的中间结点", "category": "linkedlist", "difficulty": "easy", "companies": ["Amazon", "Facebook"], "description": "给你单链表的头节点 head,请你找出并返回链表的中间结点。如果有两个中间结点,则返回第二个中间结点。", "solution_python": "def middleNode(head):\n slow = fast = head\n while fast and fast.next:\n slow = slow.next\n fast = fast.next.next\n return slow", "solution_java": "public ListNode middleNode(ListNode head) {\n ListNode slow = head, fast = head;\n while (fast != null && fast.next != null) {\n slow = slow.next;\n fast = fast.next.next;\n }\n return slow;\n}", "solution_cpp": "ListNode* middleNode(ListNode* head) {\n ListNode* slow = head, *fast = head;\n while (fast && fast->next) { slow = slow->next; fast = fast->next->next; }\n return slow;\n}", "test_cases": ["head=[1,2,3,4,5] -> 3", "head=[1,2,3,4,5,6] -> 4"], "key_points": ["快慢指针", "O(n)时间O(1)空间"], "tags": ["linkedlist", "easy", "Amazon", "Facebook"]} {"problem_id": "algo_01128", "original_id": "max-depth", "title": "二叉树的最大深度", "category": "tree", "difficulty": "easy", "companies": ["Microsoft", "Apple"], "description": "给定一个二叉树 root,返回其最大深度。", "solution_python": "def maxDepth(root):\n if not root: return 0\n return max(maxDepth(root.left), maxDepth(root.right)) + 1", "solution_java": "public int maxDepth(TreeNode root) {\n if (root == null) return 0;\n return Math.max(maxDepth(root.left), maxDepth(root.right)) + 1;\n}", "solution_cpp": "int maxDepth(TreeNode* root) {\n if (!root) return 0;\n return max(maxDepth(root->left), maxDepth(root->right)) + 1;\n}", "test_cases": ["root=[3,9,20,null,null,15,7] -> 3", "root=[1,null,2] -> 2"], "key_points": ["DFS递归", "层序遍历也可"], "tags": ["tree", "easy", "Microsoft", "Apple"]} {"problem_id": "algo_01129", "original_id": "inorder-traversal", "title": "二叉树的中序遍历", "category": "tree", "difficulty": "easy", "companies": ["Google", "Microsoft"], "description": "给定一个二叉树的根节点 root,返回它的中序遍历结果。", "solution_python": "def inorderTraversal(root):\n result = []\n def dfs(node):\n if node:\n dfs(node.left)\n result.append(node.val)\n dfs(node.right)\n dfs(root)\n return result", "solution_java": "public List inorderTraversal(TreeNode root) {\n List res = new ArrayList<>();\n dfs(root, res);\n return res;\n}\nprivate void dfs(TreeNode node, List res) {\n if (node == null) return;\n dfs(node.left, res); res.add(node.val); dfs(node.right, res);\n}", "solution_cpp": "vector inorderTraversal(TreeNode* root) {\n vector res;\n dfs(root, res);\n return res;\n}\nvoid dfs(TreeNode* node, vector& res) {\n if (!node) return;\n dfs(node->left, res); res.push_back(node->val); dfs(node->right, res);\n}", "test_cases": ["root=[1,null,2,3] -> [1,3,2]", "root=[] -> []"], "key_points": ["左-根-右顺序", "递归最简洁"], "tags": ["tree", "easy", "Google", "Microsoft"]} {"problem_id": "algo_01130", "original_id": "binary-search", "title": "二分查找", "category": "binarysearch", "difficulty": "easy", "companies": ["Google", "Amazon"], "description": "给定一个 n 个元素有序的(升序)整型数组 nums 和一个目标值 target,写一个函数搜索 nums 中的 target,如果目标值存在返回下标,否则返回 -1。", "solution_python": "def search(nums, target):\n left, right = 0, len(nums) - 1\n while left <= right:\n mid = (left + right) // 2\n if nums[mid] == target: return mid\n elif nums[mid] < target: left = mid + 1\n else: right = mid - 1\n return -1", "solution_java": "public int search(int[] nums, int target) {\n int left = 0, right = nums.length - 1;\n while (left <= right) {\n int mid = left + (right - left) / 2;\n if (nums[mid] == target) return mid;\n else if (nums[mid] < target) left = mid + 1;\n else right = mid - 1;\n }\n return -1;\n}", "solution_cpp": "int search(vector& nums, int target) {\n int left = 0, right = nums.size() - 1;\n while (left <= right) {\n int mid = left + (right - left) / 2;\n if (nums[mid] == target) return mid;\n else if (nums[mid] < target) left = mid + 1;\n else right = mid - 1;\n }\n return -1;\n}", "test_cases": ["nums=[-1,0,3,5,9,12], target=9 -> 4", "nums=[-1,0,3,5,9,12], target=2 -> -1"], "key_points": ["标准模板", "注意防溢出写法"], "tags": ["binarysearch", "easy", "Google", "Amazon"]} {"problem_id": "algo_01131", "original_id": "climbing-stairs", "title": "爬楼梯", "category": "dp", "difficulty": "easy", "companies": ["Amazon", "Google"], "description": "假设你正在爬楼梯。需要 n 阶你才能到达楼顶。每次你可以爬 1 或 2 个台阶。你有多少种不同的方法可以爬到楼顶?", "solution_python": "def climbStairs(n):\n if n <= 2: return n\n a, b = 1, 2\n for _ in range(3, n+1):\n a, b = b, a + b\n return b", "solution_java": "public int climbStairs(int n) {\n if (n <= 2) return n;\n int a = 1, b = 2;\n for (int i = 3; i <= n; i++) { int temp = a + b; a = b; b = temp; }\n return b;\n}", "solution_cpp": "int climbStairs(int n) {\n if (n <= 2) return n;\n int a = 1, b = 2;\n for (int i = 3; i <= n; i++) { int temp = a + b; a = b; b = temp; }\n return b;\n}", "test_cases": ["n=2 -> 2", "n=3 -> 3", "n=5 -> 8"], "key_points": ["斐波那契数列", "滚动数组优化空间"], "tags": ["dp", "easy", "Amazon", "Google"]} {"problem_id": "algo_01132", "original_id": "coin-change", "title": "零钱兑换", "category": "dp", "difficulty": "medium", "companies": ["Google", "Amazon"], "description": "给你一个整数数组 coins 表示不同面额的硬币,以及一个整数 amount 表示总金额。计算并返回可以凑成总金额所需的最少的硬币个数。如果没有任何一种硬币组合能组成总金额,返回 -1。", "solution_python": "def coinChange(coins, amount):\n dp = [float('inf')] * (amount + 1)\n dp[0] = 0\n for coin in coins:\n for x in range(coin, amount + 1):\n dp[x] = min(dp[x], dp[x - coin] + 1)\n return dp[amount] if dp[amount] != float('inf') else -1", "solution_java": "public int coinChange(int[] coins, int amount) {\n int[] dp = new int[amount + 1];\n Arrays.fill(dp, amount + 1);\n dp[0] = 0;\n for (int coin : coins) {\n for (int x = coin; x <= amount; x++) {\n dp[x] = Math.min(dp[x], dp[x - coin] + 1);\n }\n }\n return dp[amount] > amount ? -1 : dp[amount];\n}", "solution_cpp": "int coinChange(vector& coins, int amount) {\n vector dp(amount + 1, amount + 1);\n dp[0] = 0;\n for (int coin : coins) {\n for (int x = coin; x <= amount; x++) {\n dp[x] = min(dp[x], dp[x - coin] + 1);\n }\n }\n return dp[amount] > amount ? -1 : dp[amount];\n}", "test_cases": ["coins=[1,2,5], amount=11 -> 3", "coins=[2], amount=3 -> -1"], "key_points": ["完全背包问题", "dp[x] = min(dp[x-coin]+1)"], "tags": ["dp", "medium", "Google", "Amazon"]} {"problem_id": "algo_01133", "original_id": "subsets", "title": "子集", "category": "backtracking", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "给你一个整数数组 nums ,数组中的元素 互不相同 。返回该数组所有可能的子集(幂集)。", "solution_python": "def subsets(nums):\n result = []\n def backtrack(start, path):\n result.append(path[:])\n for i in range(start, len(nums)):\n path.append(nums[i])\n backtrack(i + 1, path)\n path.pop()\n backtrack(0, [])\n return result", "solution_java": "public List> subsets(int[] nums) {\n List> result = new ArrayList<>();\n backtrack(nums, 0, new ArrayList<>(), result);\n return result;\n}\nprivate void backtrack(int[] nums, int start, List path, List> result) {\n result.add(new ArrayList<>(path));\n for (int i = start; i < nums.length; i++) {\n path.add(nums[i]);\n backtrack(nums, i + 1, path, result);\n path.remove(path.size() - 1);\n }\n}", "solution_cpp": "vector> subsets(vector& nums) {\n vector> result;\n vector path;\n backtrack(nums, 0, path, result);\n return result;\n}\nvoid backtrack(vector& nums, int start, vector& path, vector>& result) {\n result.push_back(path);\n for (int i = start; i < nums.size(); i++) {\n path.push_back(nums[i]);\n backtrack(nums, i + 1, path, result);\n path.pop_back();\n }\n}", "test_cases": ["nums=[1,2,3] -> [[],[1],[2],[1,2],[3],[1,3],[2,3],[1,2,3]]"], "key_points": ["选或不选", "DFS遍历子集树"], "tags": ["backtracking", "medium", "Google", "Microsoft"]} {"problem_id": "algo_01134", "original_id": "permutations", "title": "全排列", "category": "backtracking", "difficulty": "medium", "companies": ["Google", "Facebook"], "description": "给定一个不含重复数字的数组 nums,返回其所有可能的全排列。", "solution_python": "def permute(nums):\n result = []\n def backtrack(path, used):\n if len(path) == len(nums):\n result.append(path[:])\n return\n for i in range(len(nums)):\n if used[i]: continue\n used[i] = True\n path.append(nums[i])\n backtrack(path, used)\n path.pop()\n used[i] = False\n backtrack([], [False]*len(nums))\n return result", "solution_java": "public List> permute(int[] nums) {\n List> result = new ArrayList<>();\n boolean[] used = new boolean[nums.length];\n backtrack(nums, used, new ArrayList<>(), result);\n return result;\n}\nprivate void backtrack(int[] nums, boolean[] used, List path, List> result) {\n if (path.size() == nums.length) { result.add(new ArrayList<>(path)); return; }\n for (int i = 0; i < nums.length; i++) {\n if (used[i]) continue;\n used[i] = true;\n path.add(nums[i]);\n backtrack(nums, used, path, result);\n path.remove(path.size() - 1);\n used[i] = false;\n }\n}", "solution_cpp": "vector> permute(vector& nums) {\n vector> result;\n vector used(nums.size(), false);\n vector path;\n backtrack(nums, used, path, result);\n return result;\n}\nvoid backtrack(vector& nums, vector& used, vector& path, vector>& result) {\n if (path.size() == nums.size()) { result.push_back(path); return; }\n for (int i = 0; i < nums.size(); i++) {\n if (used[i]) continue;\n used[i] = true;\n path.push_back(nums[i]);\n backtrack(nums, used, path, result);\n path.pop_back();\n used[i] = false;\n }\n}", "test_cases": ["nums=[1,2,3] -> [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]"], "key_points": ["标记已使用元素", "回溯经典模板"], "tags": ["backtracking", "medium", "Google", "Facebook"]} {"problem_id": "algo_01135", "original_id": "top-k-frequent", "title": "前K个高频元素", "category": "heap", "difficulty": "medium", "companies": ["Amazon", "Facebook"], "description": "给你一个整数数组 nums 和一个整数 k,请你返回其中出现频率前 k 高的元素。", "solution_python": "import heapq\nfrom collections import Counter\ndef topKFrequent(nums, k):\n count = Counter(nums)\n heap = []\n for num, freq in count.items():\n heapq.heappush(heap, (freq, num))\n if len(heap) > k: heapq.heappop(heap)\n return [num for freq, num in heap]", "solution_java": "public int[] topKFrequent(int[] nums, int k) {\n Map count = new HashMap<>();\n for (int n : nums) count.put(n, count.getOrDefault(n, 0) + 1);\n PriorityQueue> heap = \n new PriorityQueue<>((a, b) -> a.getValue() - b.getValue());\n for (Map.Entry e : count.entrySet()) {\n heap.offer(e);\n if (heap.size() > k) heap.poll();\n }\n int[] res = new int[k];\n for (int i = k - 1; i >= 0; i--) res[i] = heap.poll().getKey();\n return res;\n}", "solution_cpp": "vector topKFrequent(vector& nums, int k) {\n unordered_map count;\n for (int n : nums) count[n]++;\n priority_queue, vector>, greater>> heap;\n for (auto& [num, freq] : count) {\n heap.push({freq, num});\n if (heap.size() > k) heap.pop();\n }\n vector res;\n while (!heap.empty()) { res.push_back(heap.top().second); heap.pop(); }\n reverse(res.begin(), res.end());\n return res;\n}", "test_cases": ["nums=[1,1,1,2,2,3], k=2 -> [1,2]", "nums=[1], k=1 -> [1]"], "key_points": ["小顶堆保持大小k", "时间复杂度O(nlogk)"], "tags": ["heap", "medium", "Amazon", "Facebook"]} {"problem_id": "algo_01136", "original_id": "3sum", "title": "三数之和", "category": "two-pointers", "difficulty": "medium", "companies": ["Google", "Amazon"], "description": "给你一个整数数组 nums,判断是否存在三元组满足和为0,返回所有不重复的三元组。", "solution_python": "def threeSum(nums):\n nums.sort()\n result = []\n for i in range(len(nums) - 2):\n if i > 0 and nums[i] == nums[i-1]: continue\n left, right = i + 1, len(nums) - 1\n while left < right:\n total = nums[i] + nums[left] + nums[right]\n if total < 0: left += 1\n elif total > 0: right -= 1\n else:\n result.append([nums[i], nums[left], nums[right]])\n while left < right and nums[left] == nums[left+1]: left += 1\n while left < right and nums[right] == nums[right-1]: right -= 1\n left += 1; right -= 1\n return result", "solution_java": "public List> threeSum(int[] nums) {\n Arrays.sort(nums);\n List> result = new ArrayList<>();\n for (int i = 0; i < nums.length - 2; i++) {\n if (i > 0 && nums[i] == nums[i-1]) continue;\n int left = i + 1, right = nums.length - 1;\n while (left < right) {\n int total = nums[i] + nums[left] + nums[right];\n if (total < 0) left++;\n else if (total > 0) right--;\n else {\n result.add(Arrays.asList(nums[i], nums[left], nums[right]));\n while (left < right && nums[left] == nums[left+1]) left++;\n while (left < right && nums[right] == nums[right-1]) right--;\n left++; right--;\n }\n }\n }\n return result;\n}", "solution_cpp": "vector> threeSum(vector& nums) {\n sort(nums.begin(), nums.end());\n vector> result;\n for (int i = 0; i < nums.size() - 2; i++) {\n if (i > 0 && nums[i] == nums[i-1]) continue;\n int left = i + 1, right = nums.size() - 1;\n while (left < right) {\n int total = nums[i] + nums[left] + nums[right];\n if (total < 0) left++;\n else if (total > 0) right--;\n else {\n result.push_back({nums[i], nums[left], nums[right]});\n while (left < right && nums[left] == nums[left+1]) left++;\n while (left < right && nums[right] == nums[right-1]) right--;\n left++; right--;\n }\n }\n }\n return result;\n}", "test_cases": ["nums=[-1,0,1,2,-1,-4] -> [[-1,-1,2],[-1,0,1]]"], "key_points": ["排序+双指针", "去重是关键"], "tags": ["two-pointers", "medium", "Google", "Amazon"]} {"problem_id": "algo_01137", "original_id": "container-water", "title": "盛最多水的容器", "category": "two-pointers", "difficulty": "medium", "companies": ["Google", "Uber"], "description": "给定一个长度为 n 的整数数组 height,找出其中的两条线,使得它们与 x 轴共同构成的容器可以容纳最多的水。", "solution_python": "def maxArea(height):\n left, right = 0, len(height) - 1\n max_area = 0\n while left < right:\n h = min(height[left], height[right])\n max_area = max(max_area, h * (right - left))\n if height[left] < height[right]: left += 1\n else: right -= 1\n return max_area", "solution_java": "public int maxArea(int[] height) {\n int left = 0, right = height.length - 1, maxArea = 0;\n while (left < right) {\n int h = Math.min(height[left], height[right]);\n maxArea = Math.max(maxArea, h * (right - left));\n if (height[left] < height[right]) left++;\n else right--;\n }\n return maxArea;\n}", "solution_cpp": "int maxArea(vector& height) {\n int left = 0, right = height.size() - 1, maxArea = 0;\n while (left < right) {\n int h = min(height[left], height[right]);\n maxArea = max(maxArea, h * (right - left));\n if (height[left] < height[right]) left++;\n else right--;\n }\n return maxArea;\n}", "test_cases": ["height=[1,8,6,2,5,4,8,3,7] -> 49"], "key_points": ["移动短边指针", "面积=min(h1,h2)*width"], "tags": ["two-pointers", "medium", "Google", "Uber"]} {"problem_id": "algo_01138", "original_id": "min-stack", "title": "最小栈", "category": "stack", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "设计一个支持 push,pop,top 操作,并能在常数时间内检索到最小元素的栈。", "solution_python": "class MinStack:\n def __init__(self):\n self.stack = []\n self.min_stack = []\n def push(self, val):\n self.stack.append(val)\n self.min_stack.append(min(val, self.min_stack[-1] if self.min_stack else val))\n def pop(self):\n self.stack.pop(); self.min_stack.pop()\n def top(self): return self.stack[-1]\n def getMin(self): return self.min_stack[-1]", "solution_java": "class MinStack {\n Stack stack = new Stack<>();\n Stack minStack = new Stack<>();\n public void push(int val) { stack.push(val); minStack.push(Math.min(val, minStack.isEmpty() ? val : minStack.peek())); }\n public void pop() { stack.pop(); minStack.pop(); }\n public int top() { return stack.peek(); }\n public int getMin() { return minStack.peek(); }\n}", "solution_cpp": "class MinStack {\n stack st, minSt;\npublic:\n void push(int val) { st.push(val); minSt.push(min(val, minSt.empty() ? val : minSt.top())); }\n void pop() { st.pop(); minSt.pop(); }\n int top() { return st.top(); }\n int getMin() { return minSt.top(); }\n};", "test_cases": ["push(-2), push(0), push(-3) -> getMin() returns -3"], "key_points": ["辅助栈记录最小值", "O(1)时间获取最小值"], "tags": ["stack", "medium", "Google", "Microsoft"]} {"problem_id": "algo_01139", "original_id": "lru-cache", "title": "LRU缓存", "category": "design", "difficulty": "hard", "companies": ["Google", "Amazon"], "description": "设计和实现一个 LRU(最近最少使用)缓存机制。", "solution_python": "class LRUCache:\n def __init__(self, capacity):\n self.capacity = capacity\n self.cache = {}\n self.order = []\n def get(self, key):\n if key not in self.cache: return -1\n self.order.remove(key); self.order.append(key)\n return self.cache[key]\n def put(self, key, value):\n if key in self.cache:\n self.order.remove(key)\n elif len(self.cache) >= self.capacity:\n del self.cache[self.order.pop(0)]\n self.cache[key] = value; self.order.append(key)", "solution_java": "class LRUCache {\n int capacity;\n LinkedHashMap cache = new LinkedHashMap<>();\n public LRUCache(int cap) { capacity = cap; }\n public int get(int key) { return cache.containsKey(key) ? cache.remove(key) : -1; }\n public void put(int key, int val) {\n if (cache.containsKey(key)) cache.remove(key);\n else if (cache.size() >= capacity) cache.remove(cache.keySet().iterator().next());\n cache.put(key, val);\n }\n}", "solution_cpp": "class LRUCache {\n int cap;\n list> dll;\n unordered_map>::iterator> cache;\npublic:\n LRUCache(int capacity) : cap(capacity) {}\n int get(int key) {\n auto it = cache.find(key);\n if (it == cache.end()) return -1;\n dll.splice(dll.end(), dll, it->second);\n return it->second->second;\n }\n void put(int key, int value) {\n auto it = cache.find(key);\n if (it != cache.end()) dll.erase(it->second);\n else if (cache.size() >= cap) { cache.erase(dll.front().first); dll.pop_front(); }\n dll.push_back({key, value});\n cache[key] = --dll.end();\n }\n};", "test_cases": ["put(1,1), put(2,2), get(1) -> 1"], "key_points": ["HashMap + 双向链表", "O(1)时间操作"], "tags": ["design", "hard", "Google", "Amazon"]} {"problem_id": "algo_01140", "original_id": "num-islands", "title": "岛屿数量", "category": "graph", "difficulty": "medium", "companies": ["Google", "Facebook"], "description": "给你一个由 '1'(陆地)和 '0'(水)组成的二维网格,请你计算网格中岛屿的数量。岛屿总是被水包围,且只能由水平或垂直方向相邻的陆地连接形成。", "solution_python": "def numIslands(grid):\n if not grid: return 0\n rows, cols = len(grid), len(grid[0])\n count = 0\n def dfs(r, c):\n if r < 0 or r >= rows or c < 0 or c >= cols or grid[r][c] != '1': return\n grid[r][c] = '0'\n dfs(r+1, c); dfs(r-1, c); dfs(r, c+1); dfs(r, c-1)\n for r in range(rows):\n for c in range(cols):\n if grid[r][c] == '1': count += 1; dfs(r, c)\n return count", "solution_java": "public int numIslands(char[][] grid) {\n if (grid.length == 0) return 0;\n int count = 0;\n for (int i = 0; i < grid.length; i++)\n for (int j = 0; j < grid[0].length; j++)\n if (grid[i][j] == '1') { count++; dfs(grid, i, j); }\n return count;\n}\nprivate void dfs(char[][] grid, int r, int c) {\n if (r < 0 || r >= grid.length || c < 0 || c >= grid[0].length || grid[r][c] != '1') return;\n grid[r][c] = '0';\n dfs(grid, r+1, c); dfs(grid, r-1, c); dfs(grid, r, c+1); dfs(grid, r, c-1);\n}", "solution_cpp": "int numIslands(vector>& grid) {\n if (grid.empty()) return 0;\n int count = 0;\n for (int i = 0; i < grid.size(); i++)\n for (int j = 0; j < grid[0].size(); j++)\n if (grid[i][j] == '1') { count++; dfs(grid, i, j); }\n return count;\n}\nvoid dfs(vector>& grid, int r, int c) {\n if (r < 0 || r >= grid.size() || c < 0 || c >= grid[0].size() || grid[r][c] != '1') return;\n grid[r][c] = '0';\n dfs(grid, r+1, c); dfs(grid, r-1, c); dfs(grid, r, c+1); dfs(grid, r, c-1);\n}", "test_cases": ["grid=[[1,1,1,1,0],[1,1,0,1,0],[1,1,0,0,0],[0,0,0,0,0]] -> 1"], "key_points": ["DFS/BFS遍历", "访问后标记为0避免重复"], "tags": ["graph", "medium", "Google", "Facebook"]} {"problem_id": "algo_01141", "original_id": "two-sum", "title": "两数之和", "category": "array", "difficulty": "easy", "companies": ["Amazon", "Google"], "description": "给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那两个整数,并返回他们的数组下标。", "solution_python": "def twoSum(nums, target):\n hashmap = {}\n for i, num in enumerate(nums):\n complement = target - num\n if complement in hashmap:\n return [hashmap[complement], i]\n hashmap[num] = i\n return []", "solution_java": "public int[] twoSum(int[] nums, int target) {\n Map map = new HashMap<>();\n for (int i = 0; i < nums.length; i++) {\n int complement = target - nums[i];\n if (map.containsKey(complement)) return new int[]{map.get(complement), i};\n map.put(nums[i], i);\n }\n return new int[]{};\n}", "solution_cpp": "vector twoSum(vector& nums, int target) {\n unordered_map m;\n for (int i = 0; i < nums.size(); i++) {\n if (m.count(target - nums[i])) return {m[target - nums[i]], i};\n m[nums[i]] = i;\n }\n return {};\n}", "test_cases": ["nums=[2,7,11,15], target=9 -> [0,1]", "nums=[3,2,4], target=6 -> [1,2]"], "key_points": ["哈希表一次遍历", "空间换时间"], "tags": ["array", "easy", "Amazon", "Google"]} {"problem_id": "algo_01142", "original_id": "merge-sorted", "title": "合并两个有序数组", "category": "array", "difficulty": "easy", "companies": ["Microsoft", "Uber"], "description": "给你两个按非递减顺序排列的整数数组 nums1 和 nums2,另有两个整数 m 和 n,分别表示 nums1 和 nums2 中的元素数目。请你合并 nums2 到 nums1 中。", "solution_python": "def merge(nums1, m, nums2, n):\n p1, p2, p = m-1, n-1, m+n-1\n while p1 >= 0 and p2 >= 0:\n if nums1[p1] > nums2[p2]: nums1[p] = nums1[p1]; p1 -= 1\n else: nums1[p] = nums2[p2]; p2 -= 1\n p -= 1\n while p2 >= 0: nums1[p] = nums2[p2]; p2 -= 1; p -= 1", "solution_java": "public void merge(int[] nums1, int m, int[] nums2, int n) {\n int p1 = m-1, p2 = n-1, p = m+n-1;\n while (p1 >= 0 && p2 >= 0) {\n nums1[p--] = nums1[p1] > nums2[p2] ? nums1[p1--] : nums2[p2--];\n }\n while (p2 >= 0) nums1[p--] = nums2[p2--];\n}", "solution_cpp": "void merge(vector& nums1, int m, vector& nums2, int n) {\n int p1 = m-1, p2 = n-1, p = m+n-1;\n while (p1 >= 0 && p2 >= 0) nums1[p--] = nums1[p1] > nums2[p2] ? nums1[p1--] : nums2[p2--];\n while (p2 >= 0) nums1[p--] = nums2[p2--];\n}", "test_cases": ["nums1=[1,2,3], m=3, nums2=[2,5,6], n=3 -> [1,2,2,3,5,6]", "nums1=[], m=0, nums2=[1], n=1 -> [1]"], "key_points": ["从后往前合并", "三指针技巧"], "tags": ["array", "easy", "Microsoft", "Uber"]} {"problem_id": "algo_01143", "original_id": "max-subarray", "title": "最大子数组和", "category": "array", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "给你一个整数数组 nums ,请你找出一个具有最大和的连续子数组,返回其最大和。", "solution_python": "def maxSubArray(nums):\n max_sum = current = nums[0]\n for num in nums[1:]:\n current = max(num, current + num)\n max_sum = max(max_sum, current)\n return max_sum", "solution_java": "public int maxSubArray(int[] nums) {\n int maxSum = nums[0], curr = nums[0];\n for (int i = 1; i < nums.length; i++) {\n curr = Math.max(nums[i], curr + nums[i]);\n maxSum = Math.max(maxSum, curr);\n }\n return maxSum;\n}", "solution_cpp": "int maxSubArray(vector& nums) {\n int maxSum = nums[0], curr = nums[0];\n for (int i = 1; i < nums.size(); i++) {\n curr = max(nums[i], curr + nums[i]);\n maxSum = max(maxSum, curr);\n }\n return maxSum;\n}", "test_cases": ["nums=[-2,1,-3,4,-1,2,1,-5,4] -> 6", "nums=[1] -> 1"], "key_points": ["Kadane算法", "动态规划基础题"], "tags": ["array", "medium", "Google", "Microsoft"]} {"problem_id": "algo_01144", "original_id": "valid-parentheses", "title": "有效的括号", "category": "string", "difficulty": "easy", "companies": ["Google", "Uber"], "description": "给定一个只包括 '(',')','{','}','[',']' 的字符串 s,判断字符串是否有效。", "solution_python": "def isValid(s):\n stack = []\n mapping = {')': '(', ']': '[', '}': '{'}\n for c in s:\n if c in mapping:\n if not stack or stack[-1] != mapping[c]: return False\n stack.pop()\n else: stack.append(c)\n return not stack", "solution_java": "public boolean isValid(String s) {\n Stack stack = new Stack<>();\n Map map = Map.of(')', '(', ']', '[', '}', '{');\n for (char c : s.toCharArray()) {\n if (map.containsValue(c)) stack.push(c);\n else if (!stack.isEmpty() && stack.pop() != map.get(c)) return false;\n }\n return stack.isEmpty();\n}", "solution_cpp": "bool isValid(string s) {\n stack st;\n unordered_map m = {{')','('},{']','['},{'}','{'}};\n for (char c : s) {\n if (m.find(c) == m.end()) st.push(c);\n else if (st.empty() || st.top() != m[c]) return false;\n else st.pop();\n }\n return st.empty();\n}", "test_cases": ["s=\"()\" -> true", "s=\"()[]{}\" -> true", "s=\"(]\" -> false"], "key_points": ["栈匹配法", "注意空栈边界"], "tags": ["string", "easy", "Google", "Uber"]} {"problem_id": "algo_01145", "original_id": "longest-palindrome", "title": "最长回文子串", "category": "string", "difficulty": "medium", "companies": ["Google", "Amazon"], "description": "给你一个字符串 s,找到 s 中最长的回文子串。", "solution_python": "def longestPalindrome(s):\n def expand(l, r):\n while l >= 0 and r < len(s) and s[l] == s[r]: l -= 1; r += 1\n return l + 1, r - 1\n start = end = 0\n for i in range(len(s)):\n l1, r1 = expand(i, i)\n l2, r2 = expand(i, i + 1)\n if r1 - l1 > end - start: start, end = l1, r1\n if r2 - l2 > end - start: start, end = l2, r2\n return s[start:end+1]", "solution_java": "public String longestPalindrome(String s) {\n int start = 0, end = 0;\n for (int i = 0; i < s.length(); i++) {\n int len1 = expand(s, i, i), len2 = expand(s, i, i+1);\n int len = Math.max(len1, len2);\n if (len > end - start) { start = i - (len-1)/2; end = i + len/2; }\n }\n return s.substring(start, end + 1);\n}\nprivate int expand(String s, int l, int r) {\n while (l >= 0 && r < s.length() && s.charAt(l) == s.charAt(r)) { l--; r++; }\n return r - l - 1;\n}", "solution_cpp": "string longestPalindrome(string s) {\n int start = 0, end = 0;\n for (int i = 0; i < s.size(); i++) {\n int len1 = expand(s, i, i), len2 = expand(s, i, i+1);\n if (max(len1, len2) > end - start) { start = i - (max(len1,len2)-1)/2; end = i + max(len1,len2)/2; }\n }\n return s.substr(start, end - start + 1);\n}", "test_cases": ["s=\"babad\" -> bab或aba", "s=\"cbbd\" -> bb"], "key_points": ["中心扩展法", "处理奇偶长度"], "tags": ["string", "medium", "Google", "Amazon"]} {"problem_id": "algo_01146", "original_id": "reverse-list", "title": "反转链表", "category": "linkedlist", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "给你单链表的头节点 head,请你反转链表,并返回反转后的链表。", "solution_python": "def reverseList(head):\n prev = None\n curr = head\n while curr:\n nxt = curr.next\n curr.next = prev\n prev = curr\n curr = nxt\n return prev", "solution_java": "public ListNode reverseList(ListNode head) {\n ListNode prev = null, curr = head;\n while (curr != null) {\n ListNode next = curr.next;\n curr.next = prev;\n prev = curr;\n curr = next;\n }\n return prev;\n}", "solution_cpp": "ListNode* reverseList(ListNode* head) {\n ListNode* prev = nullptr, *curr = head;\n while (curr) {\n ListNode* next = curr->next;\n curr->next = prev;\n prev = curr;\n curr = next;\n }\n return prev;\n}", "test_cases": ["head=[1,2,3,4,5] -> [5,4,3,2,1]", "head=[1,2] -> [2,1]"], "key_points": ["迭代法 O(1)空间", "递归法 O(n)空间"], "tags": ["linkedlist", "medium", "Google", "Microsoft"]} {"problem_id": "algo_01147", "original_id": "middle-node", "title": "链表的中间结点", "category": "linkedlist", "difficulty": "easy", "companies": ["Amazon", "Facebook"], "description": "给你单链表的头节点 head,请你找出并返回链表的中间结点。如果有两个中间结点,则返回第二个中间结点。", "solution_python": "def middleNode(head):\n slow = fast = head\n while fast and fast.next:\n slow = slow.next\n fast = fast.next.next\n return slow", "solution_java": "public ListNode middleNode(ListNode head) {\n ListNode slow = head, fast = head;\n while (fast != null && fast.next != null) {\n slow = slow.next;\n fast = fast.next.next;\n }\n return slow;\n}", "solution_cpp": "ListNode* middleNode(ListNode* head) {\n ListNode* slow = head, *fast = head;\n while (fast && fast->next) { slow = slow->next; fast = fast->next->next; }\n return slow;\n}", "test_cases": ["head=[1,2,3,4,5] -> 3", "head=[1,2,3,4,5,6] -> 4"], "key_points": ["快慢指针", "O(n)时间O(1)空间"], "tags": ["linkedlist", "easy", "Amazon", "Facebook"]} {"problem_id": "algo_01148", "original_id": "max-depth", "title": "二叉树的最大深度", "category": "tree", "difficulty": "easy", "companies": ["Microsoft", "Apple"], "description": "给定一个二叉树 root,返回其最大深度。", "solution_python": "def maxDepth(root):\n if not root: return 0\n return max(maxDepth(root.left), maxDepth(root.right)) + 1", "solution_java": "public int maxDepth(TreeNode root) {\n if (root == null) return 0;\n return Math.max(maxDepth(root.left), maxDepth(root.right)) + 1;\n}", "solution_cpp": "int maxDepth(TreeNode* root) {\n if (!root) return 0;\n return max(maxDepth(root->left), maxDepth(root->right)) + 1;\n}", "test_cases": ["root=[3,9,20,null,null,15,7] -> 3", "root=[1,null,2] -> 2"], "key_points": ["DFS递归", "层序遍历也可"], "tags": ["tree", "easy", "Microsoft", "Apple"]} {"problem_id": "algo_01149", "original_id": "inorder-traversal", "title": "二叉树的中序遍历", "category": "tree", "difficulty": "easy", "companies": ["Google", "Microsoft"], "description": "给定一个二叉树的根节点 root,返回它的中序遍历结果。", "solution_python": "def inorderTraversal(root):\n result = []\n def dfs(node):\n if node:\n dfs(node.left)\n result.append(node.val)\n dfs(node.right)\n dfs(root)\n return result", "solution_java": "public List inorderTraversal(TreeNode root) {\n List res = new ArrayList<>();\n dfs(root, res);\n return res;\n}\nprivate void dfs(TreeNode node, List res) {\n if (node == null) return;\n dfs(node.left, res); res.add(node.val); dfs(node.right, res);\n}", "solution_cpp": "vector inorderTraversal(TreeNode* root) {\n vector res;\n dfs(root, res);\n return res;\n}\nvoid dfs(TreeNode* node, vector& res) {\n if (!node) return;\n dfs(node->left, res); res.push_back(node->val); dfs(node->right, res);\n}", "test_cases": ["root=[1,null,2,3] -> [1,3,2]", "root=[] -> []"], "key_points": ["左-根-右顺序", "递归最简洁"], "tags": ["tree", "easy", "Google", "Microsoft"]} {"problem_id": "algo_01150", "original_id": "binary-search", "title": "二分查找", "category": "binarysearch", "difficulty": "easy", "companies": ["Google", "Amazon"], "description": "给定一个 n 个元素有序的(升序)整型数组 nums 和一个目标值 target,写一个函数搜索 nums 中的 target,如果目标值存在返回下标,否则返回 -1。", "solution_python": "def search(nums, target):\n left, right = 0, len(nums) - 1\n while left <= right:\n mid = (left + right) // 2\n if nums[mid] == target: return mid\n elif nums[mid] < target: left = mid + 1\n else: right = mid - 1\n return -1", "solution_java": "public int search(int[] nums, int target) {\n int left = 0, right = nums.length - 1;\n while (left <= right) {\n int mid = left + (right - left) / 2;\n if (nums[mid] == target) return mid;\n else if (nums[mid] < target) left = mid + 1;\n else right = mid - 1;\n }\n return -1;\n}", "solution_cpp": "int search(vector& nums, int target) {\n int left = 0, right = nums.size() - 1;\n while (left <= right) {\n int mid = left + (right - left) / 2;\n if (nums[mid] == target) return mid;\n else if (nums[mid] < target) left = mid + 1;\n else right = mid - 1;\n }\n return -1;\n}", "test_cases": ["nums=[-1,0,3,5,9,12], target=9 -> 4", "nums=[-1,0,3,5,9,12], target=2 -> -1"], "key_points": ["标准模板", "注意防溢出写法"], "tags": ["binarysearch", "easy", "Google", "Amazon"]} {"problem_id": "algo_01151", "original_id": "climbing-stairs", "title": "爬楼梯", "category": "dp", "difficulty": "easy", "companies": ["Amazon", "Google"], "description": "假设你正在爬楼梯。需要 n 阶你才能到达楼顶。每次你可以爬 1 或 2 个台阶。你有多少种不同的方法可以爬到楼顶?", "solution_python": "def climbStairs(n):\n if n <= 2: return n\n a, b = 1, 2\n for _ in range(3, n+1):\n a, b = b, a + b\n return b", "solution_java": "public int climbStairs(int n) {\n if (n <= 2) return n;\n int a = 1, b = 2;\n for (int i = 3; i <= n; i++) { int temp = a + b; a = b; b = temp; }\n return b;\n}", "solution_cpp": "int climbStairs(int n) {\n if (n <= 2) return n;\n int a = 1, b = 2;\n for (int i = 3; i <= n; i++) { int temp = a + b; a = b; b = temp; }\n return b;\n}", "test_cases": ["n=2 -> 2", "n=3 -> 3", "n=5 -> 8"], "key_points": ["斐波那契数列", "滚动数组优化空间"], "tags": ["dp", "easy", "Amazon", "Google"]} {"problem_id": "algo_01152", "original_id": "coin-change", "title": "零钱兑换", "category": "dp", "difficulty": "medium", "companies": ["Google", "Amazon"], "description": "给你一个整数数组 coins 表示不同面额的硬币,以及一个整数 amount 表示总金额。计算并返回可以凑成总金额所需的最少的硬币个数。如果没有任何一种硬币组合能组成总金额,返回 -1。", "solution_python": "def coinChange(coins, amount):\n dp = [float('inf')] * (amount + 1)\n dp[0] = 0\n for coin in coins:\n for x in range(coin, amount + 1):\n dp[x] = min(dp[x], dp[x - coin] + 1)\n return dp[amount] if dp[amount] != float('inf') else -1", "solution_java": "public int coinChange(int[] coins, int amount) {\n int[] dp = new int[amount + 1];\n Arrays.fill(dp, amount + 1);\n dp[0] = 0;\n for (int coin : coins) {\n for (int x = coin; x <= amount; x++) {\n dp[x] = Math.min(dp[x], dp[x - coin] + 1);\n }\n }\n return dp[amount] > amount ? -1 : dp[amount];\n}", "solution_cpp": "int coinChange(vector& coins, int amount) {\n vector dp(amount + 1, amount + 1);\n dp[0] = 0;\n for (int coin : coins) {\n for (int x = coin; x <= amount; x++) {\n dp[x] = min(dp[x], dp[x - coin] + 1);\n }\n }\n return dp[amount] > amount ? -1 : dp[amount];\n}", "test_cases": ["coins=[1,2,5], amount=11 -> 3", "coins=[2], amount=3 -> -1"], "key_points": ["完全背包问题", "dp[x] = min(dp[x-coin]+1)"], "tags": ["dp", "medium", "Google", "Amazon"]} {"problem_id": "algo_01153", "original_id": "subsets", "title": "子集", "category": "backtracking", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "给你一个整数数组 nums ,数组中的元素 互不相同 。返回该数组所有可能的子集(幂集)。", "solution_python": "def subsets(nums):\n result = []\n def backtrack(start, path):\n result.append(path[:])\n for i in range(start, len(nums)):\n path.append(nums[i])\n backtrack(i + 1, path)\n path.pop()\n backtrack(0, [])\n return result", "solution_java": "public List> subsets(int[] nums) {\n List> result = new ArrayList<>();\n backtrack(nums, 0, new ArrayList<>(), result);\n return result;\n}\nprivate void backtrack(int[] nums, int start, List path, List> result) {\n result.add(new ArrayList<>(path));\n for (int i = start; i < nums.length; i++) {\n path.add(nums[i]);\n backtrack(nums, i + 1, path, result);\n path.remove(path.size() - 1);\n }\n}", "solution_cpp": "vector> subsets(vector& nums) {\n vector> result;\n vector path;\n backtrack(nums, 0, path, result);\n return result;\n}\nvoid backtrack(vector& nums, int start, vector& path, vector>& result) {\n result.push_back(path);\n for (int i = start; i < nums.size(); i++) {\n path.push_back(nums[i]);\n backtrack(nums, i + 1, path, result);\n path.pop_back();\n }\n}", "test_cases": ["nums=[1,2,3] -> [[],[1],[2],[1,2],[3],[1,3],[2,3],[1,2,3]]"], "key_points": ["选或不选", "DFS遍历子集树"], "tags": ["backtracking", "medium", "Google", "Microsoft"]} {"problem_id": "algo_01154", "original_id": "permutations", "title": "全排列", "category": "backtracking", "difficulty": "medium", "companies": ["Google", "Facebook"], "description": "给定一个不含重复数字的数组 nums,返回其所有可能的全排列。", "solution_python": "def permute(nums):\n result = []\n def backtrack(path, used):\n if len(path) == len(nums):\n result.append(path[:])\n return\n for i in range(len(nums)):\n if used[i]: continue\n used[i] = True\n path.append(nums[i])\n backtrack(path, used)\n path.pop()\n used[i] = False\n backtrack([], [False]*len(nums))\n return result", "solution_java": "public List> permute(int[] nums) {\n List> result = new ArrayList<>();\n boolean[] used = new boolean[nums.length];\n backtrack(nums, used, new ArrayList<>(), result);\n return result;\n}\nprivate void backtrack(int[] nums, boolean[] used, List path, List> result) {\n if (path.size() == nums.length) { result.add(new ArrayList<>(path)); return; }\n for (int i = 0; i < nums.length; i++) {\n if (used[i]) continue;\n used[i] = true;\n path.add(nums[i]);\n backtrack(nums, used, path, result);\n path.remove(path.size() - 1);\n used[i] = false;\n }\n}", "solution_cpp": "vector> permute(vector& nums) {\n vector> result;\n vector used(nums.size(), false);\n vector path;\n backtrack(nums, used, path, result);\n return result;\n}\nvoid backtrack(vector& nums, vector& used, vector& path, vector>& result) {\n if (path.size() == nums.size()) { result.push_back(path); return; }\n for (int i = 0; i < nums.size(); i++) {\n if (used[i]) continue;\n used[i] = true;\n path.push_back(nums[i]);\n backtrack(nums, used, path, result);\n path.pop_back();\n used[i] = false;\n }\n}", "test_cases": ["nums=[1,2,3] -> [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]"], "key_points": ["标记已使用元素", "回溯经典模板"], "tags": ["backtracking", "medium", "Google", "Facebook"]} {"problem_id": "algo_01155", "original_id": "top-k-frequent", "title": "前K个高频元素", "category": "heap", "difficulty": "medium", "companies": ["Amazon", "Facebook"], "description": "给你一个整数数组 nums 和一个整数 k,请你返回其中出现频率前 k 高的元素。", "solution_python": "import heapq\nfrom collections import Counter\ndef topKFrequent(nums, k):\n count = Counter(nums)\n heap = []\n for num, freq in count.items():\n heapq.heappush(heap, (freq, num))\n if len(heap) > k: heapq.heappop(heap)\n return [num for freq, num in heap]", "solution_java": "public int[] topKFrequent(int[] nums, int k) {\n Map count = new HashMap<>();\n for (int n : nums) count.put(n, count.getOrDefault(n, 0) + 1);\n PriorityQueue> heap = \n new PriorityQueue<>((a, b) -> a.getValue() - b.getValue());\n for (Map.Entry e : count.entrySet()) {\n heap.offer(e);\n if (heap.size() > k) heap.poll();\n }\n int[] res = new int[k];\n for (int i = k - 1; i >= 0; i--) res[i] = heap.poll().getKey();\n return res;\n}", "solution_cpp": "vector topKFrequent(vector& nums, int k) {\n unordered_map count;\n for (int n : nums) count[n]++;\n priority_queue, vector>, greater>> heap;\n for (auto& [num, freq] : count) {\n heap.push({freq, num});\n if (heap.size() > k) heap.pop();\n }\n vector res;\n while (!heap.empty()) { res.push_back(heap.top().second); heap.pop(); }\n reverse(res.begin(), res.end());\n return res;\n}", "test_cases": ["nums=[1,1,1,2,2,3], k=2 -> [1,2]", "nums=[1], k=1 -> [1]"], "key_points": ["小顶堆保持大小k", "时间复杂度O(nlogk)"], "tags": ["heap", "medium", "Amazon", "Facebook"]} {"problem_id": "algo_01156", "original_id": "3sum", "title": "三数之和", "category": "two-pointers", "difficulty": "medium", "companies": ["Google", "Amazon"], "description": "给你一个整数数组 nums,判断是否存在三元组满足和为0,返回所有不重复的三元组。", "solution_python": "def threeSum(nums):\n nums.sort()\n result = []\n for i in range(len(nums) - 2):\n if i > 0 and nums[i] == nums[i-1]: continue\n left, right = i + 1, len(nums) - 1\n while left < right:\n total = nums[i] + nums[left] + nums[right]\n if total < 0: left += 1\n elif total > 0: right -= 1\n else:\n result.append([nums[i], nums[left], nums[right]])\n while left < right and nums[left] == nums[left+1]: left += 1\n while left < right and nums[right] == nums[right-1]: right -= 1\n left += 1; right -= 1\n return result", "solution_java": "public List> threeSum(int[] nums) {\n Arrays.sort(nums);\n List> result = new ArrayList<>();\n for (int i = 0; i < nums.length - 2; i++) {\n if (i > 0 && nums[i] == nums[i-1]) continue;\n int left = i + 1, right = nums.length - 1;\n while (left < right) {\n int total = nums[i] + nums[left] + nums[right];\n if (total < 0) left++;\n else if (total > 0) right--;\n else {\n result.add(Arrays.asList(nums[i], nums[left], nums[right]));\n while (left < right && nums[left] == nums[left+1]) left++;\n while (left < right && nums[right] == nums[right-1]) right--;\n left++; right--;\n }\n }\n }\n return result;\n}", "solution_cpp": "vector> threeSum(vector& nums) {\n sort(nums.begin(), nums.end());\n vector> result;\n for (int i = 0; i < nums.size() - 2; i++) {\n if (i > 0 && nums[i] == nums[i-1]) continue;\n int left = i + 1, right = nums.size() - 1;\n while (left < right) {\n int total = nums[i] + nums[left] + nums[right];\n if (total < 0) left++;\n else if (total > 0) right--;\n else {\n result.push_back({nums[i], nums[left], nums[right]});\n while (left < right && nums[left] == nums[left+1]) left++;\n while (left < right && nums[right] == nums[right-1]) right--;\n left++; right--;\n }\n }\n }\n return result;\n}", "test_cases": ["nums=[-1,0,1,2,-1,-4] -> [[-1,-1,2],[-1,0,1]]"], "key_points": ["排序+双指针", "去重是关键"], "tags": ["two-pointers", "medium", "Google", "Amazon"]} {"problem_id": "algo_01157", "original_id": "container-water", "title": "盛最多水的容器", "category": "two-pointers", "difficulty": "medium", "companies": ["Google", "Uber"], "description": "给定一个长度为 n 的整数数组 height,找出其中的两条线,使得它们与 x 轴共同构成的容器可以容纳最多的水。", "solution_python": "def maxArea(height):\n left, right = 0, len(height) - 1\n max_area = 0\n while left < right:\n h = min(height[left], height[right])\n max_area = max(max_area, h * (right - left))\n if height[left] < height[right]: left += 1\n else: right -= 1\n return max_area", "solution_java": "public int maxArea(int[] height) {\n int left = 0, right = height.length - 1, maxArea = 0;\n while (left < right) {\n int h = Math.min(height[left], height[right]);\n maxArea = Math.max(maxArea, h * (right - left));\n if (height[left] < height[right]) left++;\n else right--;\n }\n return maxArea;\n}", "solution_cpp": "int maxArea(vector& height) {\n int left = 0, right = height.size() - 1, maxArea = 0;\n while (left < right) {\n int h = min(height[left], height[right]);\n maxArea = max(maxArea, h * (right - left));\n if (height[left] < height[right]) left++;\n else right--;\n }\n return maxArea;\n}", "test_cases": ["height=[1,8,6,2,5,4,8,3,7] -> 49"], "key_points": ["移动短边指针", "面积=min(h1,h2)*width"], "tags": ["two-pointers", "medium", "Google", "Uber"]} {"problem_id": "algo_01158", "original_id": "min-stack", "title": "最小栈", "category": "stack", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "设计一个支持 push,pop,top 操作,并能在常数时间内检索到最小元素的栈。", "solution_python": "class MinStack:\n def __init__(self):\n self.stack = []\n self.min_stack = []\n def push(self, val):\n self.stack.append(val)\n self.min_stack.append(min(val, self.min_stack[-1] if self.min_stack else val))\n def pop(self):\n self.stack.pop(); self.min_stack.pop()\n def top(self): return self.stack[-1]\n def getMin(self): return self.min_stack[-1]", "solution_java": "class MinStack {\n Stack stack = new Stack<>();\n Stack minStack = new Stack<>();\n public void push(int val) { stack.push(val); minStack.push(Math.min(val, minStack.isEmpty() ? val : minStack.peek())); }\n public void pop() { stack.pop(); minStack.pop(); }\n public int top() { return stack.peek(); }\n public int getMin() { return minStack.peek(); }\n}", "solution_cpp": "class MinStack {\n stack st, minSt;\npublic:\n void push(int val) { st.push(val); minSt.push(min(val, minSt.empty() ? val : minSt.top())); }\n void pop() { st.pop(); minSt.pop(); }\n int top() { return st.top(); }\n int getMin() { return minSt.top(); }\n};", "test_cases": ["push(-2), push(0), push(-3) -> getMin() returns -3"], "key_points": ["辅助栈记录最小值", "O(1)时间获取最小值"], "tags": ["stack", "medium", "Google", "Microsoft"]} {"problem_id": "algo_01159", "original_id": "lru-cache", "title": "LRU缓存", "category": "design", "difficulty": "hard", "companies": ["Google", "Amazon"], "description": "设计和实现一个 LRU(最近最少使用)缓存机制。", "solution_python": "class LRUCache:\n def __init__(self, capacity):\n self.capacity = capacity\n self.cache = {}\n self.order = []\n def get(self, key):\n if key not in self.cache: return -1\n self.order.remove(key); self.order.append(key)\n return self.cache[key]\n def put(self, key, value):\n if key in self.cache:\n self.order.remove(key)\n elif len(self.cache) >= self.capacity:\n del self.cache[self.order.pop(0)]\n self.cache[key] = value; self.order.append(key)", "solution_java": "class LRUCache {\n int capacity;\n LinkedHashMap cache = new LinkedHashMap<>();\n public LRUCache(int cap) { capacity = cap; }\n public int get(int key) { return cache.containsKey(key) ? cache.remove(key) : -1; }\n public void put(int key, int val) {\n if (cache.containsKey(key)) cache.remove(key);\n else if (cache.size() >= capacity) cache.remove(cache.keySet().iterator().next());\n cache.put(key, val);\n }\n}", "solution_cpp": "class LRUCache {\n int cap;\n list> dll;\n unordered_map>::iterator> cache;\npublic:\n LRUCache(int capacity) : cap(capacity) {}\n int get(int key) {\n auto it = cache.find(key);\n if (it == cache.end()) return -1;\n dll.splice(dll.end(), dll, it->second);\n return it->second->second;\n }\n void put(int key, int value) {\n auto it = cache.find(key);\n if (it != cache.end()) dll.erase(it->second);\n else if (cache.size() >= cap) { cache.erase(dll.front().first); dll.pop_front(); }\n dll.push_back({key, value});\n cache[key] = --dll.end();\n }\n};", "test_cases": ["put(1,1), put(2,2), get(1) -> 1"], "key_points": ["HashMap + 双向链表", "O(1)时间操作"], "tags": ["design", "hard", "Google", "Amazon"]} {"problem_id": "algo_01160", "original_id": "num-islands", "title": "岛屿数量", "category": "graph", "difficulty": "medium", "companies": ["Google", "Facebook"], "description": "给你一个由 '1'(陆地)和 '0'(水)组成的二维网格,请你计算网格中岛屿的数量。岛屿总是被水包围,且只能由水平或垂直方向相邻的陆地连接形成。", "solution_python": "def numIslands(grid):\n if not grid: return 0\n rows, cols = len(grid), len(grid[0])\n count = 0\n def dfs(r, c):\n if r < 0 or r >= rows or c < 0 or c >= cols or grid[r][c] != '1': return\n grid[r][c] = '0'\n dfs(r+1, c); dfs(r-1, c); dfs(r, c+1); dfs(r, c-1)\n for r in range(rows):\n for c in range(cols):\n if grid[r][c] == '1': count += 1; dfs(r, c)\n return count", "solution_java": "public int numIslands(char[][] grid) {\n if (grid.length == 0) return 0;\n int count = 0;\n for (int i = 0; i < grid.length; i++)\n for (int j = 0; j < grid[0].length; j++)\n if (grid[i][j] == '1') { count++; dfs(grid, i, j); }\n return count;\n}\nprivate void dfs(char[][] grid, int r, int c) {\n if (r < 0 || r >= grid.length || c < 0 || c >= grid[0].length || grid[r][c] != '1') return;\n grid[r][c] = '0';\n dfs(grid, r+1, c); dfs(grid, r-1, c); dfs(grid, r, c+1); dfs(grid, r, c-1);\n}", "solution_cpp": "int numIslands(vector>& grid) {\n if (grid.empty()) return 0;\n int count = 0;\n for (int i = 0; i < grid.size(); i++)\n for (int j = 0; j < grid[0].size(); j++)\n if (grid[i][j] == '1') { count++; dfs(grid, i, j); }\n return count;\n}\nvoid dfs(vector>& grid, int r, int c) {\n if (r < 0 || r >= grid.size() || c < 0 || c >= grid[0].size() || grid[r][c] != '1') return;\n grid[r][c] = '0';\n dfs(grid, r+1, c); dfs(grid, r-1, c); dfs(grid, r, c+1); dfs(grid, r, c-1);\n}", "test_cases": ["grid=[[1,1,1,1,0],[1,1,0,1,0],[1,1,0,0,0],[0,0,0,0,0]] -> 1"], "key_points": ["DFS/BFS遍历", "访问后标记为0避免重复"], "tags": ["graph", "medium", "Google", "Facebook"]} {"problem_id": "algo_01161", "original_id": "two-sum", "title": "两数之和", "category": "array", "difficulty": "easy", "companies": ["Amazon", "Google"], "description": "给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那两个整数,并返回他们的数组下标。", "solution_python": "def twoSum(nums, target):\n hashmap = {}\n for i, num in enumerate(nums):\n complement = target - num\n if complement in hashmap:\n return [hashmap[complement], i]\n hashmap[num] = i\n return []", "solution_java": "public int[] twoSum(int[] nums, int target) {\n Map map = new HashMap<>();\n for (int i = 0; i < nums.length; i++) {\n int complement = target - nums[i];\n if (map.containsKey(complement)) return new int[]{map.get(complement), i};\n map.put(nums[i], i);\n }\n return new int[]{};\n}", "solution_cpp": "vector twoSum(vector& nums, int target) {\n unordered_map m;\n for (int i = 0; i < nums.size(); i++) {\n if (m.count(target - nums[i])) return {m[target - nums[i]], i};\n m[nums[i]] = i;\n }\n return {};\n}", "test_cases": ["nums=[2,7,11,15], target=9 -> [0,1]", "nums=[3,2,4], target=6 -> [1,2]"], "key_points": ["哈希表一次遍历", "空间换时间"], "tags": ["array", "easy", "Amazon", "Google"]} {"problem_id": "algo_01162", "original_id": "merge-sorted", "title": "合并两个有序数组", "category": "array", "difficulty": "easy", "companies": ["Microsoft", "Uber"], "description": "给你两个按非递减顺序排列的整数数组 nums1 和 nums2,另有两个整数 m 和 n,分别表示 nums1 和 nums2 中的元素数目。请你合并 nums2 到 nums1 中。", "solution_python": "def merge(nums1, m, nums2, n):\n p1, p2, p = m-1, n-1, m+n-1\n while p1 >= 0 and p2 >= 0:\n if nums1[p1] > nums2[p2]: nums1[p] = nums1[p1]; p1 -= 1\n else: nums1[p] = nums2[p2]; p2 -= 1\n p -= 1\n while p2 >= 0: nums1[p] = nums2[p2]; p2 -= 1; p -= 1", "solution_java": "public void merge(int[] nums1, int m, int[] nums2, int n) {\n int p1 = m-1, p2 = n-1, p = m+n-1;\n while (p1 >= 0 && p2 >= 0) {\n nums1[p--] = nums1[p1] > nums2[p2] ? nums1[p1--] : nums2[p2--];\n }\n while (p2 >= 0) nums1[p--] = nums2[p2--];\n}", "solution_cpp": "void merge(vector& nums1, int m, vector& nums2, int n) {\n int p1 = m-1, p2 = n-1, p = m+n-1;\n while (p1 >= 0 && p2 >= 0) nums1[p--] = nums1[p1] > nums2[p2] ? nums1[p1--] : nums2[p2--];\n while (p2 >= 0) nums1[p--] = nums2[p2--];\n}", "test_cases": ["nums1=[1,2,3], m=3, nums2=[2,5,6], n=3 -> [1,2,2,3,5,6]", "nums1=[], m=0, nums2=[1], n=1 -> [1]"], "key_points": ["从后往前合并", "三指针技巧"], "tags": ["array", "easy", "Microsoft", "Uber"]} {"problem_id": "algo_01163", "original_id": "max-subarray", "title": "最大子数组和", "category": "array", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "给你一个整数数组 nums ,请你找出一个具有最大和的连续子数组,返回其最大和。", "solution_python": "def maxSubArray(nums):\n max_sum = current = nums[0]\n for num in nums[1:]:\n current = max(num, current + num)\n max_sum = max(max_sum, current)\n return max_sum", "solution_java": "public int maxSubArray(int[] nums) {\n int maxSum = nums[0], curr = nums[0];\n for (int i = 1; i < nums.length; i++) {\n curr = Math.max(nums[i], curr + nums[i]);\n maxSum = Math.max(maxSum, curr);\n }\n return maxSum;\n}", "solution_cpp": "int maxSubArray(vector& nums) {\n int maxSum = nums[0], curr = nums[0];\n for (int i = 1; i < nums.size(); i++) {\n curr = max(nums[i], curr + nums[i]);\n maxSum = max(maxSum, curr);\n }\n return maxSum;\n}", "test_cases": ["nums=[-2,1,-3,4,-1,2,1,-5,4] -> 6", "nums=[1] -> 1"], "key_points": ["Kadane算法", "动态规划基础题"], "tags": ["array", "medium", "Google", "Microsoft"]} {"problem_id": "algo_01164", "original_id": "valid-parentheses", "title": "有效的括号", "category": "string", "difficulty": "easy", "companies": ["Google", "Uber"], "description": "给定一个只包括 '(',')','{','}','[',']' 的字符串 s,判断字符串是否有效。", "solution_python": "def isValid(s):\n stack = []\n mapping = {')': '(', ']': '[', '}': '{'}\n for c in s:\n if c in mapping:\n if not stack or stack[-1] != mapping[c]: return False\n stack.pop()\n else: stack.append(c)\n return not stack", "solution_java": "public boolean isValid(String s) {\n Stack stack = new Stack<>();\n Map map = Map.of(')', '(', ']', '[', '}', '{');\n for (char c : s.toCharArray()) {\n if (map.containsValue(c)) stack.push(c);\n else if (!stack.isEmpty() && stack.pop() != map.get(c)) return false;\n }\n return stack.isEmpty();\n}", "solution_cpp": "bool isValid(string s) {\n stack st;\n unordered_map m = {{')','('},{']','['},{'}','{'}};\n for (char c : s) {\n if (m.find(c) == m.end()) st.push(c);\n else if (st.empty() || st.top() != m[c]) return false;\n else st.pop();\n }\n return st.empty();\n}", "test_cases": ["s=\"()\" -> true", "s=\"()[]{}\" -> true", "s=\"(]\" -> false"], "key_points": ["栈匹配法", "注意空栈边界"], "tags": ["string", "easy", "Google", "Uber"]} {"problem_id": "algo_01165", "original_id": "longest-palindrome", "title": "最长回文子串", "category": "string", "difficulty": "medium", "companies": ["Google", "Amazon"], "description": "给你一个字符串 s,找到 s 中最长的回文子串。", "solution_python": "def longestPalindrome(s):\n def expand(l, r):\n while l >= 0 and r < len(s) and s[l] == s[r]: l -= 1; r += 1\n return l + 1, r - 1\n start = end = 0\n for i in range(len(s)):\n l1, r1 = expand(i, i)\n l2, r2 = expand(i, i + 1)\n if r1 - l1 > end - start: start, end = l1, r1\n if r2 - l2 > end - start: start, end = l2, r2\n return s[start:end+1]", "solution_java": "public String longestPalindrome(String s) {\n int start = 0, end = 0;\n for (int i = 0; i < s.length(); i++) {\n int len1 = expand(s, i, i), len2 = expand(s, i, i+1);\n int len = Math.max(len1, len2);\n if (len > end - start) { start = i - (len-1)/2; end = i + len/2; }\n }\n return s.substring(start, end + 1);\n}\nprivate int expand(String s, int l, int r) {\n while (l >= 0 && r < s.length() && s.charAt(l) == s.charAt(r)) { l--; r++; }\n return r - l - 1;\n}", "solution_cpp": "string longestPalindrome(string s) {\n int start = 0, end = 0;\n for (int i = 0; i < s.size(); i++) {\n int len1 = expand(s, i, i), len2 = expand(s, i, i+1);\n if (max(len1, len2) > end - start) { start = i - (max(len1,len2)-1)/2; end = i + max(len1,len2)/2; }\n }\n return s.substr(start, end - start + 1);\n}", "test_cases": ["s=\"babad\" -> bab或aba", "s=\"cbbd\" -> bb"], "key_points": ["中心扩展法", "处理奇偶长度"], "tags": ["string", "medium", "Google", "Amazon"]} {"problem_id": "algo_01166", "original_id": "reverse-list", "title": "反转链表", "category": "linkedlist", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "给你单链表的头节点 head,请你反转链表,并返回反转后的链表。", "solution_python": "def reverseList(head):\n prev = None\n curr = head\n while curr:\n nxt = curr.next\n curr.next = prev\n prev = curr\n curr = nxt\n return prev", "solution_java": "public ListNode reverseList(ListNode head) {\n ListNode prev = null, curr = head;\n while (curr != null) {\n ListNode next = curr.next;\n curr.next = prev;\n prev = curr;\n curr = next;\n }\n return prev;\n}", "solution_cpp": "ListNode* reverseList(ListNode* head) {\n ListNode* prev = nullptr, *curr = head;\n while (curr) {\n ListNode* next = curr->next;\n curr->next = prev;\n prev = curr;\n curr = next;\n }\n return prev;\n}", "test_cases": ["head=[1,2,3,4,5] -> [5,4,3,2,1]", "head=[1,2] -> [2,1]"], "key_points": ["迭代法 O(1)空间", "递归法 O(n)空间"], "tags": ["linkedlist", "medium", "Google", "Microsoft"]} {"problem_id": "algo_01167", "original_id": "middle-node", "title": "链表的中间结点", "category": "linkedlist", "difficulty": "easy", "companies": ["Amazon", "Facebook"], "description": "给你单链表的头节点 head,请你找出并返回链表的中间结点。如果有两个中间结点,则返回第二个中间结点。", "solution_python": "def middleNode(head):\n slow = fast = head\n while fast and fast.next:\n slow = slow.next\n fast = fast.next.next\n return slow", "solution_java": "public ListNode middleNode(ListNode head) {\n ListNode slow = head, fast = head;\n while (fast != null && fast.next != null) {\n slow = slow.next;\n fast = fast.next.next;\n }\n return slow;\n}", "solution_cpp": "ListNode* middleNode(ListNode* head) {\n ListNode* slow = head, *fast = head;\n while (fast && fast->next) { slow = slow->next; fast = fast->next->next; }\n return slow;\n}", "test_cases": ["head=[1,2,3,4,5] -> 3", "head=[1,2,3,4,5,6] -> 4"], "key_points": ["快慢指针", "O(n)时间O(1)空间"], "tags": ["linkedlist", "easy", "Amazon", "Facebook"]} {"problem_id": "algo_01168", "original_id": "max-depth", "title": "二叉树的最大深度", "category": "tree", "difficulty": "easy", "companies": ["Microsoft", "Apple"], "description": "给定一个二叉树 root,返回其最大深度。", "solution_python": "def maxDepth(root):\n if not root: return 0\n return max(maxDepth(root.left), maxDepth(root.right)) + 1", "solution_java": "public int maxDepth(TreeNode root) {\n if (root == null) return 0;\n return Math.max(maxDepth(root.left), maxDepth(root.right)) + 1;\n}", "solution_cpp": "int maxDepth(TreeNode* root) {\n if (!root) return 0;\n return max(maxDepth(root->left), maxDepth(root->right)) + 1;\n}", "test_cases": ["root=[3,9,20,null,null,15,7] -> 3", "root=[1,null,2] -> 2"], "key_points": ["DFS递归", "层序遍历也可"], "tags": ["tree", "easy", "Microsoft", "Apple"]} {"problem_id": "algo_01169", "original_id": "inorder-traversal", "title": "二叉树的中序遍历", "category": "tree", "difficulty": "easy", "companies": ["Google", "Microsoft"], "description": "给定一个二叉树的根节点 root,返回它的中序遍历结果。", "solution_python": "def inorderTraversal(root):\n result = []\n def dfs(node):\n if node:\n dfs(node.left)\n result.append(node.val)\n dfs(node.right)\n dfs(root)\n return result", "solution_java": "public List inorderTraversal(TreeNode root) {\n List res = new ArrayList<>();\n dfs(root, res);\n return res;\n}\nprivate void dfs(TreeNode node, List res) {\n if (node == null) return;\n dfs(node.left, res); res.add(node.val); dfs(node.right, res);\n}", "solution_cpp": "vector inorderTraversal(TreeNode* root) {\n vector res;\n dfs(root, res);\n return res;\n}\nvoid dfs(TreeNode* node, vector& res) {\n if (!node) return;\n dfs(node->left, res); res.push_back(node->val); dfs(node->right, res);\n}", "test_cases": ["root=[1,null,2,3] -> [1,3,2]", "root=[] -> []"], "key_points": ["左-根-右顺序", "递归最简洁"], "tags": ["tree", "easy", "Google", "Microsoft"]} {"problem_id": "algo_01170", "original_id": "binary-search", "title": "二分查找", "category": "binarysearch", "difficulty": "easy", "companies": ["Google", "Amazon"], "description": "给定一个 n 个元素有序的(升序)整型数组 nums 和一个目标值 target,写一个函数搜索 nums 中的 target,如果目标值存在返回下标,否则返回 -1。", "solution_python": "def search(nums, target):\n left, right = 0, len(nums) - 1\n while left <= right:\n mid = (left + right) // 2\n if nums[mid] == target: return mid\n elif nums[mid] < target: left = mid + 1\n else: right = mid - 1\n return -1", "solution_java": "public int search(int[] nums, int target) {\n int left = 0, right = nums.length - 1;\n while (left <= right) {\n int mid = left + (right - left) / 2;\n if (nums[mid] == target) return mid;\n else if (nums[mid] < target) left = mid + 1;\n else right = mid - 1;\n }\n return -1;\n}", "solution_cpp": "int search(vector& nums, int target) {\n int left = 0, right = nums.size() - 1;\n while (left <= right) {\n int mid = left + (right - left) / 2;\n if (nums[mid] == target) return mid;\n else if (nums[mid] < target) left = mid + 1;\n else right = mid - 1;\n }\n return -1;\n}", "test_cases": ["nums=[-1,0,3,5,9,12], target=9 -> 4", "nums=[-1,0,3,5,9,12], target=2 -> -1"], "key_points": ["标准模板", "注意防溢出写法"], "tags": ["binarysearch", "easy", "Google", "Amazon"]} {"problem_id": "algo_01171", "original_id": "climbing-stairs", "title": "爬楼梯", "category": "dp", "difficulty": "easy", "companies": ["Amazon", "Google"], "description": "假设你正在爬楼梯。需要 n 阶你才能到达楼顶。每次你可以爬 1 或 2 个台阶。你有多少种不同的方法可以爬到楼顶?", "solution_python": "def climbStairs(n):\n if n <= 2: return n\n a, b = 1, 2\n for _ in range(3, n+1):\n a, b = b, a + b\n return b", "solution_java": "public int climbStairs(int n) {\n if (n <= 2) return n;\n int a = 1, b = 2;\n for (int i = 3; i <= n; i++) { int temp = a + b; a = b; b = temp; }\n return b;\n}", "solution_cpp": "int climbStairs(int n) {\n if (n <= 2) return n;\n int a = 1, b = 2;\n for (int i = 3; i <= n; i++) { int temp = a + b; a = b; b = temp; }\n return b;\n}", "test_cases": ["n=2 -> 2", "n=3 -> 3", "n=5 -> 8"], "key_points": ["斐波那契数列", "滚动数组优化空间"], "tags": ["dp", "easy", "Amazon", "Google"]} {"problem_id": "algo_01172", "original_id": "coin-change", "title": "零钱兑换", "category": "dp", "difficulty": "medium", "companies": ["Google", "Amazon"], "description": "给你一个整数数组 coins 表示不同面额的硬币,以及一个整数 amount 表示总金额。计算并返回可以凑成总金额所需的最少的硬币个数。如果没有任何一种硬币组合能组成总金额,返回 -1。", "solution_python": "def coinChange(coins, amount):\n dp = [float('inf')] * (amount + 1)\n dp[0] = 0\n for coin in coins:\n for x in range(coin, amount + 1):\n dp[x] = min(dp[x], dp[x - coin] + 1)\n return dp[amount] if dp[amount] != float('inf') else -1", "solution_java": "public int coinChange(int[] coins, int amount) {\n int[] dp = new int[amount + 1];\n Arrays.fill(dp, amount + 1);\n dp[0] = 0;\n for (int coin : coins) {\n for (int x = coin; x <= amount; x++) {\n dp[x] = Math.min(dp[x], dp[x - coin] + 1);\n }\n }\n return dp[amount] > amount ? -1 : dp[amount];\n}", "solution_cpp": "int coinChange(vector& coins, int amount) {\n vector dp(amount + 1, amount + 1);\n dp[0] = 0;\n for (int coin : coins) {\n for (int x = coin; x <= amount; x++) {\n dp[x] = min(dp[x], dp[x - coin] + 1);\n }\n }\n return dp[amount] > amount ? -1 : dp[amount];\n}", "test_cases": ["coins=[1,2,5], amount=11 -> 3", "coins=[2], amount=3 -> -1"], "key_points": ["完全背包问题", "dp[x] = min(dp[x-coin]+1)"], "tags": ["dp", "medium", "Google", "Amazon"]} {"problem_id": "algo_01173", "original_id": "subsets", "title": "子集", "category": "backtracking", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "给你一个整数数组 nums ,数组中的元素 互不相同 。返回该数组所有可能的子集(幂集)。", "solution_python": "def subsets(nums):\n result = []\n def backtrack(start, path):\n result.append(path[:])\n for i in range(start, len(nums)):\n path.append(nums[i])\n backtrack(i + 1, path)\n path.pop()\n backtrack(0, [])\n return result", "solution_java": "public List> subsets(int[] nums) {\n List> result = new ArrayList<>();\n backtrack(nums, 0, new ArrayList<>(), result);\n return result;\n}\nprivate void backtrack(int[] nums, int start, List path, List> result) {\n result.add(new ArrayList<>(path));\n for (int i = start; i < nums.length; i++) {\n path.add(nums[i]);\n backtrack(nums, i + 1, path, result);\n path.remove(path.size() - 1);\n }\n}", "solution_cpp": "vector> subsets(vector& nums) {\n vector> result;\n vector path;\n backtrack(nums, 0, path, result);\n return result;\n}\nvoid backtrack(vector& nums, int start, vector& path, vector>& result) {\n result.push_back(path);\n for (int i = start; i < nums.size(); i++) {\n path.push_back(nums[i]);\n backtrack(nums, i + 1, path, result);\n path.pop_back();\n }\n}", "test_cases": ["nums=[1,2,3] -> [[],[1],[2],[1,2],[3],[1,3],[2,3],[1,2,3]]"], "key_points": ["选或不选", "DFS遍历子集树"], "tags": ["backtracking", "medium", "Google", "Microsoft"]} {"problem_id": "algo_01174", "original_id": "permutations", "title": "全排列", "category": "backtracking", "difficulty": "medium", "companies": ["Google", "Facebook"], "description": "给定一个不含重复数字的数组 nums,返回其所有可能的全排列。", "solution_python": "def permute(nums):\n result = []\n def backtrack(path, used):\n if len(path) == len(nums):\n result.append(path[:])\n return\n for i in range(len(nums)):\n if used[i]: continue\n used[i] = True\n path.append(nums[i])\n backtrack(path, used)\n path.pop()\n used[i] = False\n backtrack([], [False]*len(nums))\n return result", "solution_java": "public List> permute(int[] nums) {\n List> result = new ArrayList<>();\n boolean[] used = new boolean[nums.length];\n backtrack(nums, used, new ArrayList<>(), result);\n return result;\n}\nprivate void backtrack(int[] nums, boolean[] used, List path, List> result) {\n if (path.size() == nums.length) { result.add(new ArrayList<>(path)); return; }\n for (int i = 0; i < nums.length; i++) {\n if (used[i]) continue;\n used[i] = true;\n path.add(nums[i]);\n backtrack(nums, used, path, result);\n path.remove(path.size() - 1);\n used[i] = false;\n }\n}", "solution_cpp": "vector> permute(vector& nums) {\n vector> result;\n vector used(nums.size(), false);\n vector path;\n backtrack(nums, used, path, result);\n return result;\n}\nvoid backtrack(vector& nums, vector& used, vector& path, vector>& result) {\n if (path.size() == nums.size()) { result.push_back(path); return; }\n for (int i = 0; i < nums.size(); i++) {\n if (used[i]) continue;\n used[i] = true;\n path.push_back(nums[i]);\n backtrack(nums, used, path, result);\n path.pop_back();\n used[i] = false;\n }\n}", "test_cases": ["nums=[1,2,3] -> [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]"], "key_points": ["标记已使用元素", "回溯经典模板"], "tags": ["backtracking", "medium", "Google", "Facebook"]} {"problem_id": "algo_01175", "original_id": "top-k-frequent", "title": "前K个高频元素", "category": "heap", "difficulty": "medium", "companies": ["Amazon", "Facebook"], "description": "给你一个整数数组 nums 和一个整数 k,请你返回其中出现频率前 k 高的元素。", "solution_python": "import heapq\nfrom collections import Counter\ndef topKFrequent(nums, k):\n count = Counter(nums)\n heap = []\n for num, freq in count.items():\n heapq.heappush(heap, (freq, num))\n if len(heap) > k: heapq.heappop(heap)\n return [num for freq, num in heap]", "solution_java": "public int[] topKFrequent(int[] nums, int k) {\n Map count = new HashMap<>();\n for (int n : nums) count.put(n, count.getOrDefault(n, 0) + 1);\n PriorityQueue> heap = \n new PriorityQueue<>((a, b) -> a.getValue() - b.getValue());\n for (Map.Entry e : count.entrySet()) {\n heap.offer(e);\n if (heap.size() > k) heap.poll();\n }\n int[] res = new int[k];\n for (int i = k - 1; i >= 0; i--) res[i] = heap.poll().getKey();\n return res;\n}", "solution_cpp": "vector topKFrequent(vector& nums, int k) {\n unordered_map count;\n for (int n : nums) count[n]++;\n priority_queue, vector>, greater>> heap;\n for (auto& [num, freq] : count) {\n heap.push({freq, num});\n if (heap.size() > k) heap.pop();\n }\n vector res;\n while (!heap.empty()) { res.push_back(heap.top().second); heap.pop(); }\n reverse(res.begin(), res.end());\n return res;\n}", "test_cases": ["nums=[1,1,1,2,2,3], k=2 -> [1,2]", "nums=[1], k=1 -> [1]"], "key_points": ["小顶堆保持大小k", "时间复杂度O(nlogk)"], "tags": ["heap", "medium", "Amazon", "Facebook"]} {"problem_id": "algo_01176", "original_id": "3sum", "title": "三数之和", "category": "two-pointers", "difficulty": "medium", "companies": ["Google", "Amazon"], "description": "给你一个整数数组 nums,判断是否存在三元组满足和为0,返回所有不重复的三元组。", "solution_python": "def threeSum(nums):\n nums.sort()\n result = []\n for i in range(len(nums) - 2):\n if i > 0 and nums[i] == nums[i-1]: continue\n left, right = i + 1, len(nums) - 1\n while left < right:\n total = nums[i] + nums[left] + nums[right]\n if total < 0: left += 1\n elif total > 0: right -= 1\n else:\n result.append([nums[i], nums[left], nums[right]])\n while left < right and nums[left] == nums[left+1]: left += 1\n while left < right and nums[right] == nums[right-1]: right -= 1\n left += 1; right -= 1\n return result", "solution_java": "public List> threeSum(int[] nums) {\n Arrays.sort(nums);\n List> result = new ArrayList<>();\n for (int i = 0; i < nums.length - 2; i++) {\n if (i > 0 && nums[i] == nums[i-1]) continue;\n int left = i + 1, right = nums.length - 1;\n while (left < right) {\n int total = nums[i] + nums[left] + nums[right];\n if (total < 0) left++;\n else if (total > 0) right--;\n else {\n result.add(Arrays.asList(nums[i], nums[left], nums[right]));\n while (left < right && nums[left] == nums[left+1]) left++;\n while (left < right && nums[right] == nums[right-1]) right--;\n left++; right--;\n }\n }\n }\n return result;\n}", "solution_cpp": "vector> threeSum(vector& nums) {\n sort(nums.begin(), nums.end());\n vector> result;\n for (int i = 0; i < nums.size() - 2; i++) {\n if (i > 0 && nums[i] == nums[i-1]) continue;\n int left = i + 1, right = nums.size() - 1;\n while (left < right) {\n int total = nums[i] + nums[left] + nums[right];\n if (total < 0) left++;\n else if (total > 0) right--;\n else {\n result.push_back({nums[i], nums[left], nums[right]});\n while (left < right && nums[left] == nums[left+1]) left++;\n while (left < right && nums[right] == nums[right-1]) right--;\n left++; right--;\n }\n }\n }\n return result;\n}", "test_cases": ["nums=[-1,0,1,2,-1,-4] -> [[-1,-1,2],[-1,0,1]]"], "key_points": ["排序+双指针", "去重是关键"], "tags": ["two-pointers", "medium", "Google", "Amazon"]} {"problem_id": "algo_01177", "original_id": "container-water", "title": "盛最多水的容器", "category": "two-pointers", "difficulty": "medium", "companies": ["Google", "Uber"], "description": "给定一个长度为 n 的整数数组 height,找出其中的两条线,使得它们与 x 轴共同构成的容器可以容纳最多的水。", "solution_python": "def maxArea(height):\n left, right = 0, len(height) - 1\n max_area = 0\n while left < right:\n h = min(height[left], height[right])\n max_area = max(max_area, h * (right - left))\n if height[left] < height[right]: left += 1\n else: right -= 1\n return max_area", "solution_java": "public int maxArea(int[] height) {\n int left = 0, right = height.length - 1, maxArea = 0;\n while (left < right) {\n int h = Math.min(height[left], height[right]);\n maxArea = Math.max(maxArea, h * (right - left));\n if (height[left] < height[right]) left++;\n else right--;\n }\n return maxArea;\n}", "solution_cpp": "int maxArea(vector& height) {\n int left = 0, right = height.size() - 1, maxArea = 0;\n while (left < right) {\n int h = min(height[left], height[right]);\n maxArea = max(maxArea, h * (right - left));\n if (height[left] < height[right]) left++;\n else right--;\n }\n return maxArea;\n}", "test_cases": ["height=[1,8,6,2,5,4,8,3,7] -> 49"], "key_points": ["移动短边指针", "面积=min(h1,h2)*width"], "tags": ["two-pointers", "medium", "Google", "Uber"]} {"problem_id": "algo_01178", "original_id": "min-stack", "title": "最小栈", "category": "stack", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "设计一个支持 push,pop,top 操作,并能在常数时间内检索到最小元素的栈。", "solution_python": "class MinStack:\n def __init__(self):\n self.stack = []\n self.min_stack = []\n def push(self, val):\n self.stack.append(val)\n self.min_stack.append(min(val, self.min_stack[-1] if self.min_stack else val))\n def pop(self):\n self.stack.pop(); self.min_stack.pop()\n def top(self): return self.stack[-1]\n def getMin(self): return self.min_stack[-1]", "solution_java": "class MinStack {\n Stack stack = new Stack<>();\n Stack minStack = new Stack<>();\n public void push(int val) { stack.push(val); minStack.push(Math.min(val, minStack.isEmpty() ? val : minStack.peek())); }\n public void pop() { stack.pop(); minStack.pop(); }\n public int top() { return stack.peek(); }\n public int getMin() { return minStack.peek(); }\n}", "solution_cpp": "class MinStack {\n stack st, minSt;\npublic:\n void push(int val) { st.push(val); minSt.push(min(val, minSt.empty() ? val : minSt.top())); }\n void pop() { st.pop(); minSt.pop(); }\n int top() { return st.top(); }\n int getMin() { return minSt.top(); }\n};", "test_cases": ["push(-2), push(0), push(-3) -> getMin() returns -3"], "key_points": ["辅助栈记录最小值", "O(1)时间获取最小值"], "tags": ["stack", "medium", "Google", "Microsoft"]} {"problem_id": "algo_01179", "original_id": "lru-cache", "title": "LRU缓存", "category": "design", "difficulty": "hard", "companies": ["Google", "Amazon"], "description": "设计和实现一个 LRU(最近最少使用)缓存机制。", "solution_python": "class LRUCache:\n def __init__(self, capacity):\n self.capacity = capacity\n self.cache = {}\n self.order = []\n def get(self, key):\n if key not in self.cache: return -1\n self.order.remove(key); self.order.append(key)\n return self.cache[key]\n def put(self, key, value):\n if key in self.cache:\n self.order.remove(key)\n elif len(self.cache) >= self.capacity:\n del self.cache[self.order.pop(0)]\n self.cache[key] = value; self.order.append(key)", "solution_java": "class LRUCache {\n int capacity;\n LinkedHashMap cache = new LinkedHashMap<>();\n public LRUCache(int cap) { capacity = cap; }\n public int get(int key) { return cache.containsKey(key) ? cache.remove(key) : -1; }\n public void put(int key, int val) {\n if (cache.containsKey(key)) cache.remove(key);\n else if (cache.size() >= capacity) cache.remove(cache.keySet().iterator().next());\n cache.put(key, val);\n }\n}", "solution_cpp": "class LRUCache {\n int cap;\n list> dll;\n unordered_map>::iterator> cache;\npublic:\n LRUCache(int capacity) : cap(capacity) {}\n int get(int key) {\n auto it = cache.find(key);\n if (it == cache.end()) return -1;\n dll.splice(dll.end(), dll, it->second);\n return it->second->second;\n }\n void put(int key, int value) {\n auto it = cache.find(key);\n if (it != cache.end()) dll.erase(it->second);\n else if (cache.size() >= cap) { cache.erase(dll.front().first); dll.pop_front(); }\n dll.push_back({key, value});\n cache[key] = --dll.end();\n }\n};", "test_cases": ["put(1,1), put(2,2), get(1) -> 1"], "key_points": ["HashMap + 双向链表", "O(1)时间操作"], "tags": ["design", "hard", "Google", "Amazon"]} {"problem_id": "algo_01180", "original_id": "num-islands", "title": "岛屿数量", "category": "graph", "difficulty": "medium", "companies": ["Google", "Facebook"], "description": "给你一个由 '1'(陆地)和 '0'(水)组成的二维网格,请你计算网格中岛屿的数量。岛屿总是被水包围,且只能由水平或垂直方向相邻的陆地连接形成。", "solution_python": "def numIslands(grid):\n if not grid: return 0\n rows, cols = len(grid), len(grid[0])\n count = 0\n def dfs(r, c):\n if r < 0 or r >= rows or c < 0 or c >= cols or grid[r][c] != '1': return\n grid[r][c] = '0'\n dfs(r+1, c); dfs(r-1, c); dfs(r, c+1); dfs(r, c-1)\n for r in range(rows):\n for c in range(cols):\n if grid[r][c] == '1': count += 1; dfs(r, c)\n return count", "solution_java": "public int numIslands(char[][] grid) {\n if (grid.length == 0) return 0;\n int count = 0;\n for (int i = 0; i < grid.length; i++)\n for (int j = 0; j < grid[0].length; j++)\n if (grid[i][j] == '1') { count++; dfs(grid, i, j); }\n return count;\n}\nprivate void dfs(char[][] grid, int r, int c) {\n if (r < 0 || r >= grid.length || c < 0 || c >= grid[0].length || grid[r][c] != '1') return;\n grid[r][c] = '0';\n dfs(grid, r+1, c); dfs(grid, r-1, c); dfs(grid, r, c+1); dfs(grid, r, c-1);\n}", "solution_cpp": "int numIslands(vector>& grid) {\n if (grid.empty()) return 0;\n int count = 0;\n for (int i = 0; i < grid.size(); i++)\n for (int j = 0; j < grid[0].size(); j++)\n if (grid[i][j] == '1') { count++; dfs(grid, i, j); }\n return count;\n}\nvoid dfs(vector>& grid, int r, int c) {\n if (r < 0 || r >= grid.size() || c < 0 || c >= grid[0].size() || grid[r][c] != '1') return;\n grid[r][c] = '0';\n dfs(grid, r+1, c); dfs(grid, r-1, c); dfs(grid, r, c+1); dfs(grid, r, c-1);\n}", "test_cases": ["grid=[[1,1,1,1,0],[1,1,0,1,0],[1,1,0,0,0],[0,0,0,0,0]] -> 1"], "key_points": ["DFS/BFS遍历", "访问后标记为0避免重复"], "tags": ["graph", "medium", "Google", "Facebook"]} {"problem_id": "algo_01181", "original_id": "two-sum", "title": "两数之和", "category": "array", "difficulty": "easy", "companies": ["Amazon", "Google"], "description": "给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那两个整数,并返回他们的数组下标。", "solution_python": "def twoSum(nums, target):\n hashmap = {}\n for i, num in enumerate(nums):\n complement = target - num\n if complement in hashmap:\n return [hashmap[complement], i]\n hashmap[num] = i\n return []", "solution_java": "public int[] twoSum(int[] nums, int target) {\n Map map = new HashMap<>();\n for (int i = 0; i < nums.length; i++) {\n int complement = target - nums[i];\n if (map.containsKey(complement)) return new int[]{map.get(complement), i};\n map.put(nums[i], i);\n }\n return new int[]{};\n}", "solution_cpp": "vector twoSum(vector& nums, int target) {\n unordered_map m;\n for (int i = 0; i < nums.size(); i++) {\n if (m.count(target - nums[i])) return {m[target - nums[i]], i};\n m[nums[i]] = i;\n }\n return {};\n}", "test_cases": ["nums=[2,7,11,15], target=9 -> [0,1]", "nums=[3,2,4], target=6 -> [1,2]"], "key_points": ["哈希表一次遍历", "空间换时间"], "tags": ["array", "easy", "Amazon", "Google"]} {"problem_id": "algo_01182", "original_id": "merge-sorted", "title": "合并两个有序数组", "category": "array", "difficulty": "easy", "companies": ["Microsoft", "Uber"], "description": "给你两个按非递减顺序排列的整数数组 nums1 和 nums2,另有两个整数 m 和 n,分别表示 nums1 和 nums2 中的元素数目。请你合并 nums2 到 nums1 中。", "solution_python": "def merge(nums1, m, nums2, n):\n p1, p2, p = m-1, n-1, m+n-1\n while p1 >= 0 and p2 >= 0:\n if nums1[p1] > nums2[p2]: nums1[p] = nums1[p1]; p1 -= 1\n else: nums1[p] = nums2[p2]; p2 -= 1\n p -= 1\n while p2 >= 0: nums1[p] = nums2[p2]; p2 -= 1; p -= 1", "solution_java": "public void merge(int[] nums1, int m, int[] nums2, int n) {\n int p1 = m-1, p2 = n-1, p = m+n-1;\n while (p1 >= 0 && p2 >= 0) {\n nums1[p--] = nums1[p1] > nums2[p2] ? nums1[p1--] : nums2[p2--];\n }\n while (p2 >= 0) nums1[p--] = nums2[p2--];\n}", "solution_cpp": "void merge(vector& nums1, int m, vector& nums2, int n) {\n int p1 = m-1, p2 = n-1, p = m+n-1;\n while (p1 >= 0 && p2 >= 0) nums1[p--] = nums1[p1] > nums2[p2] ? nums1[p1--] : nums2[p2--];\n while (p2 >= 0) nums1[p--] = nums2[p2--];\n}", "test_cases": ["nums1=[1,2,3], m=3, nums2=[2,5,6], n=3 -> [1,2,2,3,5,6]", "nums1=[], m=0, nums2=[1], n=1 -> [1]"], "key_points": ["从后往前合并", "三指针技巧"], "tags": ["array", "easy", "Microsoft", "Uber"]} {"problem_id": "algo_01183", "original_id": "max-subarray", "title": "最大子数组和", "category": "array", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "给你一个整数数组 nums ,请你找出一个具有最大和的连续子数组,返回其最大和。", "solution_python": "def maxSubArray(nums):\n max_sum = current = nums[0]\n for num in nums[1:]:\n current = max(num, current + num)\n max_sum = max(max_sum, current)\n return max_sum", "solution_java": "public int maxSubArray(int[] nums) {\n int maxSum = nums[0], curr = nums[0];\n for (int i = 1; i < nums.length; i++) {\n curr = Math.max(nums[i], curr + nums[i]);\n maxSum = Math.max(maxSum, curr);\n }\n return maxSum;\n}", "solution_cpp": "int maxSubArray(vector& nums) {\n int maxSum = nums[0], curr = nums[0];\n for (int i = 1; i < nums.size(); i++) {\n curr = max(nums[i], curr + nums[i]);\n maxSum = max(maxSum, curr);\n }\n return maxSum;\n}", "test_cases": ["nums=[-2,1,-3,4,-1,2,1,-5,4] -> 6", "nums=[1] -> 1"], "key_points": ["Kadane算法", "动态规划基础题"], "tags": ["array", "medium", "Google", "Microsoft"]} {"problem_id": "algo_01184", "original_id": "valid-parentheses", "title": "有效的括号", "category": "string", "difficulty": "easy", "companies": ["Google", "Uber"], "description": "给定一个只包括 '(',')','{','}','[',']' 的字符串 s,判断字符串是否有效。", "solution_python": "def isValid(s):\n stack = []\n mapping = {')': '(', ']': '[', '}': '{'}\n for c in s:\n if c in mapping:\n if not stack or stack[-1] != mapping[c]: return False\n stack.pop()\n else: stack.append(c)\n return not stack", "solution_java": "public boolean isValid(String s) {\n Stack stack = new Stack<>();\n Map map = Map.of(')', '(', ']', '[', '}', '{');\n for (char c : s.toCharArray()) {\n if (map.containsValue(c)) stack.push(c);\n else if (!stack.isEmpty() && stack.pop() != map.get(c)) return false;\n }\n return stack.isEmpty();\n}", "solution_cpp": "bool isValid(string s) {\n stack st;\n unordered_map m = {{')','('},{']','['},{'}','{'}};\n for (char c : s) {\n if (m.find(c) == m.end()) st.push(c);\n else if (st.empty() || st.top() != m[c]) return false;\n else st.pop();\n }\n return st.empty();\n}", "test_cases": ["s=\"()\" -> true", "s=\"()[]{}\" -> true", "s=\"(]\" -> false"], "key_points": ["栈匹配法", "注意空栈边界"], "tags": ["string", "easy", "Google", "Uber"]} {"problem_id": "algo_01185", "original_id": "longest-palindrome", "title": "最长回文子串", "category": "string", "difficulty": "medium", "companies": ["Google", "Amazon"], "description": "给你一个字符串 s,找到 s 中最长的回文子串。", "solution_python": "def longestPalindrome(s):\n def expand(l, r):\n while l >= 0 and r < len(s) and s[l] == s[r]: l -= 1; r += 1\n return l + 1, r - 1\n start = end = 0\n for i in range(len(s)):\n l1, r1 = expand(i, i)\n l2, r2 = expand(i, i + 1)\n if r1 - l1 > end - start: start, end = l1, r1\n if r2 - l2 > end - start: start, end = l2, r2\n return s[start:end+1]", "solution_java": "public String longestPalindrome(String s) {\n int start = 0, end = 0;\n for (int i = 0; i < s.length(); i++) {\n int len1 = expand(s, i, i), len2 = expand(s, i, i+1);\n int len = Math.max(len1, len2);\n if (len > end - start) { start = i - (len-1)/2; end = i + len/2; }\n }\n return s.substring(start, end + 1);\n}\nprivate int expand(String s, int l, int r) {\n while (l >= 0 && r < s.length() && s.charAt(l) == s.charAt(r)) { l--; r++; }\n return r - l - 1;\n}", "solution_cpp": "string longestPalindrome(string s) {\n int start = 0, end = 0;\n for (int i = 0; i < s.size(); i++) {\n int len1 = expand(s, i, i), len2 = expand(s, i, i+1);\n if (max(len1, len2) > end - start) { start = i - (max(len1,len2)-1)/2; end = i + max(len1,len2)/2; }\n }\n return s.substr(start, end - start + 1);\n}", "test_cases": ["s=\"babad\" -> bab或aba", "s=\"cbbd\" -> bb"], "key_points": ["中心扩展法", "处理奇偶长度"], "tags": ["string", "medium", "Google", "Amazon"]} {"problem_id": "algo_01186", "original_id": "reverse-list", "title": "反转链表", "category": "linkedlist", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "给你单链表的头节点 head,请你反转链表,并返回反转后的链表。", "solution_python": "def reverseList(head):\n prev = None\n curr = head\n while curr:\n nxt = curr.next\n curr.next = prev\n prev = curr\n curr = nxt\n return prev", "solution_java": "public ListNode reverseList(ListNode head) {\n ListNode prev = null, curr = head;\n while (curr != null) {\n ListNode next = curr.next;\n curr.next = prev;\n prev = curr;\n curr = next;\n }\n return prev;\n}", "solution_cpp": "ListNode* reverseList(ListNode* head) {\n ListNode* prev = nullptr, *curr = head;\n while (curr) {\n ListNode* next = curr->next;\n curr->next = prev;\n prev = curr;\n curr = next;\n }\n return prev;\n}", "test_cases": ["head=[1,2,3,4,5] -> [5,4,3,2,1]", "head=[1,2] -> [2,1]"], "key_points": ["迭代法 O(1)空间", "递归法 O(n)空间"], "tags": ["linkedlist", "medium", "Google", "Microsoft"]} {"problem_id": "algo_01187", "original_id": "middle-node", "title": "链表的中间结点", "category": "linkedlist", "difficulty": "easy", "companies": ["Amazon", "Facebook"], "description": "给你单链表的头节点 head,请你找出并返回链表的中间结点。如果有两个中间结点,则返回第二个中间结点。", "solution_python": "def middleNode(head):\n slow = fast = head\n while fast and fast.next:\n slow = slow.next\n fast = fast.next.next\n return slow", "solution_java": "public ListNode middleNode(ListNode head) {\n ListNode slow = head, fast = head;\n while (fast != null && fast.next != null) {\n slow = slow.next;\n fast = fast.next.next;\n }\n return slow;\n}", "solution_cpp": "ListNode* middleNode(ListNode* head) {\n ListNode* slow = head, *fast = head;\n while (fast && fast->next) { slow = slow->next; fast = fast->next->next; }\n return slow;\n}", "test_cases": ["head=[1,2,3,4,5] -> 3", "head=[1,2,3,4,5,6] -> 4"], "key_points": ["快慢指针", "O(n)时间O(1)空间"], "tags": ["linkedlist", "easy", "Amazon", "Facebook"]} {"problem_id": "algo_01188", "original_id": "max-depth", "title": "二叉树的最大深度", "category": "tree", "difficulty": "easy", "companies": ["Microsoft", "Apple"], "description": "给定一个二叉树 root,返回其最大深度。", "solution_python": "def maxDepth(root):\n if not root: return 0\n return max(maxDepth(root.left), maxDepth(root.right)) + 1", "solution_java": "public int maxDepth(TreeNode root) {\n if (root == null) return 0;\n return Math.max(maxDepth(root.left), maxDepth(root.right)) + 1;\n}", "solution_cpp": "int maxDepth(TreeNode* root) {\n if (!root) return 0;\n return max(maxDepth(root->left), maxDepth(root->right)) + 1;\n}", "test_cases": ["root=[3,9,20,null,null,15,7] -> 3", "root=[1,null,2] -> 2"], "key_points": ["DFS递归", "层序遍历也可"], "tags": ["tree", "easy", "Microsoft", "Apple"]} {"problem_id": "algo_01189", "original_id": "inorder-traversal", "title": "二叉树的中序遍历", "category": "tree", "difficulty": "easy", "companies": ["Google", "Microsoft"], "description": "给定一个二叉树的根节点 root,返回它的中序遍历结果。", "solution_python": "def inorderTraversal(root):\n result = []\n def dfs(node):\n if node:\n dfs(node.left)\n result.append(node.val)\n dfs(node.right)\n dfs(root)\n return result", "solution_java": "public List inorderTraversal(TreeNode root) {\n List res = new ArrayList<>();\n dfs(root, res);\n return res;\n}\nprivate void dfs(TreeNode node, List res) {\n if (node == null) return;\n dfs(node.left, res); res.add(node.val); dfs(node.right, res);\n}", "solution_cpp": "vector inorderTraversal(TreeNode* root) {\n vector res;\n dfs(root, res);\n return res;\n}\nvoid dfs(TreeNode* node, vector& res) {\n if (!node) return;\n dfs(node->left, res); res.push_back(node->val); dfs(node->right, res);\n}", "test_cases": ["root=[1,null,2,3] -> [1,3,2]", "root=[] -> []"], "key_points": ["左-根-右顺序", "递归最简洁"], "tags": ["tree", "easy", "Google", "Microsoft"]} {"problem_id": "algo_01190", "original_id": "binary-search", "title": "二分查找", "category": "binarysearch", "difficulty": "easy", "companies": ["Google", "Amazon"], "description": "给定一个 n 个元素有序的(升序)整型数组 nums 和一个目标值 target,写一个函数搜索 nums 中的 target,如果目标值存在返回下标,否则返回 -1。", "solution_python": "def search(nums, target):\n left, right = 0, len(nums) - 1\n while left <= right:\n mid = (left + right) // 2\n if nums[mid] == target: return mid\n elif nums[mid] < target: left = mid + 1\n else: right = mid - 1\n return -1", "solution_java": "public int search(int[] nums, int target) {\n int left = 0, right = nums.length - 1;\n while (left <= right) {\n int mid = left + (right - left) / 2;\n if (nums[mid] == target) return mid;\n else if (nums[mid] < target) left = mid + 1;\n else right = mid - 1;\n }\n return -1;\n}", "solution_cpp": "int search(vector& nums, int target) {\n int left = 0, right = nums.size() - 1;\n while (left <= right) {\n int mid = left + (right - left) / 2;\n if (nums[mid] == target) return mid;\n else if (nums[mid] < target) left = mid + 1;\n else right = mid - 1;\n }\n return -1;\n}", "test_cases": ["nums=[-1,0,3,5,9,12], target=9 -> 4", "nums=[-1,0,3,5,9,12], target=2 -> -1"], "key_points": ["标准模板", "注意防溢出写法"], "tags": ["binarysearch", "easy", "Google", "Amazon"]} {"problem_id": "algo_01191", "original_id": "climbing-stairs", "title": "爬楼梯", "category": "dp", "difficulty": "easy", "companies": ["Amazon", "Google"], "description": "假设你正在爬楼梯。需要 n 阶你才能到达楼顶。每次你可以爬 1 或 2 个台阶。你有多少种不同的方法可以爬到楼顶?", "solution_python": "def climbStairs(n):\n if n <= 2: return n\n a, b = 1, 2\n for _ in range(3, n+1):\n a, b = b, a + b\n return b", "solution_java": "public int climbStairs(int n) {\n if (n <= 2) return n;\n int a = 1, b = 2;\n for (int i = 3; i <= n; i++) { int temp = a + b; a = b; b = temp; }\n return b;\n}", "solution_cpp": "int climbStairs(int n) {\n if (n <= 2) return n;\n int a = 1, b = 2;\n for (int i = 3; i <= n; i++) { int temp = a + b; a = b; b = temp; }\n return b;\n}", "test_cases": ["n=2 -> 2", "n=3 -> 3", "n=5 -> 8"], "key_points": ["斐波那契数列", "滚动数组优化空间"], "tags": ["dp", "easy", "Amazon", "Google"]} {"problem_id": "algo_01192", "original_id": "coin-change", "title": "零钱兑换", "category": "dp", "difficulty": "medium", "companies": ["Google", "Amazon"], "description": "给你一个整数数组 coins 表示不同面额的硬币,以及一个整数 amount 表示总金额。计算并返回可以凑成总金额所需的最少的硬币个数。如果没有任何一种硬币组合能组成总金额,返回 -1。", "solution_python": "def coinChange(coins, amount):\n dp = [float('inf')] * (amount + 1)\n dp[0] = 0\n for coin in coins:\n for x in range(coin, amount + 1):\n dp[x] = min(dp[x], dp[x - coin] + 1)\n return dp[amount] if dp[amount] != float('inf') else -1", "solution_java": "public int coinChange(int[] coins, int amount) {\n int[] dp = new int[amount + 1];\n Arrays.fill(dp, amount + 1);\n dp[0] = 0;\n for (int coin : coins) {\n for (int x = coin; x <= amount; x++) {\n dp[x] = Math.min(dp[x], dp[x - coin] + 1);\n }\n }\n return dp[amount] > amount ? -1 : dp[amount];\n}", "solution_cpp": "int coinChange(vector& coins, int amount) {\n vector dp(amount + 1, amount + 1);\n dp[0] = 0;\n for (int coin : coins) {\n for (int x = coin; x <= amount; x++) {\n dp[x] = min(dp[x], dp[x - coin] + 1);\n }\n }\n return dp[amount] > amount ? -1 : dp[amount];\n}", "test_cases": ["coins=[1,2,5], amount=11 -> 3", "coins=[2], amount=3 -> -1"], "key_points": ["完全背包问题", "dp[x] = min(dp[x-coin]+1)"], "tags": ["dp", "medium", "Google", "Amazon"]} {"problem_id": "algo_01193", "original_id": "subsets", "title": "子集", "category": "backtracking", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "给你一个整数数组 nums ,数组中的元素 互不相同 。返回该数组所有可能的子集(幂集)。", "solution_python": "def subsets(nums):\n result = []\n def backtrack(start, path):\n result.append(path[:])\n for i in range(start, len(nums)):\n path.append(nums[i])\n backtrack(i + 1, path)\n path.pop()\n backtrack(0, [])\n return result", "solution_java": "public List> subsets(int[] nums) {\n List> result = new ArrayList<>();\n backtrack(nums, 0, new ArrayList<>(), result);\n return result;\n}\nprivate void backtrack(int[] nums, int start, List path, List> result) {\n result.add(new ArrayList<>(path));\n for (int i = start; i < nums.length; i++) {\n path.add(nums[i]);\n backtrack(nums, i + 1, path, result);\n path.remove(path.size() - 1);\n }\n}", "solution_cpp": "vector> subsets(vector& nums) {\n vector> result;\n vector path;\n backtrack(nums, 0, path, result);\n return result;\n}\nvoid backtrack(vector& nums, int start, vector& path, vector>& result) {\n result.push_back(path);\n for (int i = start; i < nums.size(); i++) {\n path.push_back(nums[i]);\n backtrack(nums, i + 1, path, result);\n path.pop_back();\n }\n}", "test_cases": ["nums=[1,2,3] -> [[],[1],[2],[1,2],[3],[1,3],[2,3],[1,2,3]]"], "key_points": ["选或不选", "DFS遍历子集树"], "tags": ["backtracking", "medium", "Google", "Microsoft"]} {"problem_id": "algo_01194", "original_id": "permutations", "title": "全排列", "category": "backtracking", "difficulty": "medium", "companies": ["Google", "Facebook"], "description": "给定一个不含重复数字的数组 nums,返回其所有可能的全排列。", "solution_python": "def permute(nums):\n result = []\n def backtrack(path, used):\n if len(path) == len(nums):\n result.append(path[:])\n return\n for i in range(len(nums)):\n if used[i]: continue\n used[i] = True\n path.append(nums[i])\n backtrack(path, used)\n path.pop()\n used[i] = False\n backtrack([], [False]*len(nums))\n return result", "solution_java": "public List> permute(int[] nums) {\n List> result = new ArrayList<>();\n boolean[] used = new boolean[nums.length];\n backtrack(nums, used, new ArrayList<>(), result);\n return result;\n}\nprivate void backtrack(int[] nums, boolean[] used, List path, List> result) {\n if (path.size() == nums.length) { result.add(new ArrayList<>(path)); return; }\n for (int i = 0; i < nums.length; i++) {\n if (used[i]) continue;\n used[i] = true;\n path.add(nums[i]);\n backtrack(nums, used, path, result);\n path.remove(path.size() - 1);\n used[i] = false;\n }\n}", "solution_cpp": "vector> permute(vector& nums) {\n vector> result;\n vector used(nums.size(), false);\n vector path;\n backtrack(nums, used, path, result);\n return result;\n}\nvoid backtrack(vector& nums, vector& used, vector& path, vector>& result) {\n if (path.size() == nums.size()) { result.push_back(path); return; }\n for (int i = 0; i < nums.size(); i++) {\n if (used[i]) continue;\n used[i] = true;\n path.push_back(nums[i]);\n backtrack(nums, used, path, result);\n path.pop_back();\n used[i] = false;\n }\n}", "test_cases": ["nums=[1,2,3] -> [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]"], "key_points": ["标记已使用元素", "回溯经典模板"], "tags": ["backtracking", "medium", "Google", "Facebook"]} {"problem_id": "algo_01195", "original_id": "top-k-frequent", "title": "前K个高频元素", "category": "heap", "difficulty": "medium", "companies": ["Amazon", "Facebook"], "description": "给你一个整数数组 nums 和一个整数 k,请你返回其中出现频率前 k 高的元素。", "solution_python": "import heapq\nfrom collections import Counter\ndef topKFrequent(nums, k):\n count = Counter(nums)\n heap = []\n for num, freq in count.items():\n heapq.heappush(heap, (freq, num))\n if len(heap) > k: heapq.heappop(heap)\n return [num for freq, num in heap]", "solution_java": "public int[] topKFrequent(int[] nums, int k) {\n Map count = new HashMap<>();\n for (int n : nums) count.put(n, count.getOrDefault(n, 0) + 1);\n PriorityQueue> heap = \n new PriorityQueue<>((a, b) -> a.getValue() - b.getValue());\n for (Map.Entry e : count.entrySet()) {\n heap.offer(e);\n if (heap.size() > k) heap.poll();\n }\n int[] res = new int[k];\n for (int i = k - 1; i >= 0; i--) res[i] = heap.poll().getKey();\n return res;\n}", "solution_cpp": "vector topKFrequent(vector& nums, int k) {\n unordered_map count;\n for (int n : nums) count[n]++;\n priority_queue, vector>, greater>> heap;\n for (auto& [num, freq] : count) {\n heap.push({freq, num});\n if (heap.size() > k) heap.pop();\n }\n vector res;\n while (!heap.empty()) { res.push_back(heap.top().second); heap.pop(); }\n reverse(res.begin(), res.end());\n return res;\n}", "test_cases": ["nums=[1,1,1,2,2,3], k=2 -> [1,2]", "nums=[1], k=1 -> [1]"], "key_points": ["小顶堆保持大小k", "时间复杂度O(nlogk)"], "tags": ["heap", "medium", "Amazon", "Facebook"]} {"problem_id": "algo_01196", "original_id": "3sum", "title": "三数之和", "category": "two-pointers", "difficulty": "medium", "companies": ["Google", "Amazon"], "description": "给你一个整数数组 nums,判断是否存在三元组满足和为0,返回所有不重复的三元组。", "solution_python": "def threeSum(nums):\n nums.sort()\n result = []\n for i in range(len(nums) - 2):\n if i > 0 and nums[i] == nums[i-1]: continue\n left, right = i + 1, len(nums) - 1\n while left < right:\n total = nums[i] + nums[left] + nums[right]\n if total < 0: left += 1\n elif total > 0: right -= 1\n else:\n result.append([nums[i], nums[left], nums[right]])\n while left < right and nums[left] == nums[left+1]: left += 1\n while left < right and nums[right] == nums[right-1]: right -= 1\n left += 1; right -= 1\n return result", "solution_java": "public List> threeSum(int[] nums) {\n Arrays.sort(nums);\n List> result = new ArrayList<>();\n for (int i = 0; i < nums.length - 2; i++) {\n if (i > 0 && nums[i] == nums[i-1]) continue;\n int left = i + 1, right = nums.length - 1;\n while (left < right) {\n int total = nums[i] + nums[left] + nums[right];\n if (total < 0) left++;\n else if (total > 0) right--;\n else {\n result.add(Arrays.asList(nums[i], nums[left], nums[right]));\n while (left < right && nums[left] == nums[left+1]) left++;\n while (left < right && nums[right] == nums[right-1]) right--;\n left++; right--;\n }\n }\n }\n return result;\n}", "solution_cpp": "vector> threeSum(vector& nums) {\n sort(nums.begin(), nums.end());\n vector> result;\n for (int i = 0; i < nums.size() - 2; i++) {\n if (i > 0 && nums[i] == nums[i-1]) continue;\n int left = i + 1, right = nums.size() - 1;\n while (left < right) {\n int total = nums[i] + nums[left] + nums[right];\n if (total < 0) left++;\n else if (total > 0) right--;\n else {\n result.push_back({nums[i], nums[left], nums[right]});\n while (left < right && nums[left] == nums[left+1]) left++;\n while (left < right && nums[right] == nums[right-1]) right--;\n left++; right--;\n }\n }\n }\n return result;\n}", "test_cases": ["nums=[-1,0,1,2,-1,-4] -> [[-1,-1,2],[-1,0,1]]"], "key_points": ["排序+双指针", "去重是关键"], "tags": ["two-pointers", "medium", "Google", "Amazon"]} {"problem_id": "algo_01197", "original_id": "container-water", "title": "盛最多水的容器", "category": "two-pointers", "difficulty": "medium", "companies": ["Google", "Uber"], "description": "给定一个长度为 n 的整数数组 height,找出其中的两条线,使得它们与 x 轴共同构成的容器可以容纳最多的水。", "solution_python": "def maxArea(height):\n left, right = 0, len(height) - 1\n max_area = 0\n while left < right:\n h = min(height[left], height[right])\n max_area = max(max_area, h * (right - left))\n if height[left] < height[right]: left += 1\n else: right -= 1\n return max_area", "solution_java": "public int maxArea(int[] height) {\n int left = 0, right = height.length - 1, maxArea = 0;\n while (left < right) {\n int h = Math.min(height[left], height[right]);\n maxArea = Math.max(maxArea, h * (right - left));\n if (height[left] < height[right]) left++;\n else right--;\n }\n return maxArea;\n}", "solution_cpp": "int maxArea(vector& height) {\n int left = 0, right = height.size() - 1, maxArea = 0;\n while (left < right) {\n int h = min(height[left], height[right]);\n maxArea = max(maxArea, h * (right - left));\n if (height[left] < height[right]) left++;\n else right--;\n }\n return maxArea;\n}", "test_cases": ["height=[1,8,6,2,5,4,8,3,7] -> 49"], "key_points": ["移动短边指针", "面积=min(h1,h2)*width"], "tags": ["two-pointers", "medium", "Google", "Uber"]} {"problem_id": "algo_01198", "original_id": "min-stack", "title": "最小栈", "category": "stack", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "设计一个支持 push,pop,top 操作,并能在常数时间内检索到最小元素的栈。", "solution_python": "class MinStack:\n def __init__(self):\n self.stack = []\n self.min_stack = []\n def push(self, val):\n self.stack.append(val)\n self.min_stack.append(min(val, self.min_stack[-1] if self.min_stack else val))\n def pop(self):\n self.stack.pop(); self.min_stack.pop()\n def top(self): return self.stack[-1]\n def getMin(self): return self.min_stack[-1]", "solution_java": "class MinStack {\n Stack stack = new Stack<>();\n Stack minStack = new Stack<>();\n public void push(int val) { stack.push(val); minStack.push(Math.min(val, minStack.isEmpty() ? val : minStack.peek())); }\n public void pop() { stack.pop(); minStack.pop(); }\n public int top() { return stack.peek(); }\n public int getMin() { return minStack.peek(); }\n}", "solution_cpp": "class MinStack {\n stack st, minSt;\npublic:\n void push(int val) { st.push(val); minSt.push(min(val, minSt.empty() ? val : minSt.top())); }\n void pop() { st.pop(); minSt.pop(); }\n int top() { return st.top(); }\n int getMin() { return minSt.top(); }\n};", "test_cases": ["push(-2), push(0), push(-3) -> getMin() returns -3"], "key_points": ["辅助栈记录最小值", "O(1)时间获取最小值"], "tags": ["stack", "medium", "Google", "Microsoft"]} {"problem_id": "algo_01199", "original_id": "lru-cache", "title": "LRU缓存", "category": "design", "difficulty": "hard", "companies": ["Google", "Amazon"], "description": "设计和实现一个 LRU(最近最少使用)缓存机制。", "solution_python": "class LRUCache:\n def __init__(self, capacity):\n self.capacity = capacity\n self.cache = {}\n self.order = []\n def get(self, key):\n if key not in self.cache: return -1\n self.order.remove(key); self.order.append(key)\n return self.cache[key]\n def put(self, key, value):\n if key in self.cache:\n self.order.remove(key)\n elif len(self.cache) >= self.capacity:\n del self.cache[self.order.pop(0)]\n self.cache[key] = value; self.order.append(key)", "solution_java": "class LRUCache {\n int capacity;\n LinkedHashMap cache = new LinkedHashMap<>();\n public LRUCache(int cap) { capacity = cap; }\n public int get(int key) { return cache.containsKey(key) ? cache.remove(key) : -1; }\n public void put(int key, int val) {\n if (cache.containsKey(key)) cache.remove(key);\n else if (cache.size() >= capacity) cache.remove(cache.keySet().iterator().next());\n cache.put(key, val);\n }\n}", "solution_cpp": "class LRUCache {\n int cap;\n list> dll;\n unordered_map>::iterator> cache;\npublic:\n LRUCache(int capacity) : cap(capacity) {}\n int get(int key) {\n auto it = cache.find(key);\n if (it == cache.end()) return -1;\n dll.splice(dll.end(), dll, it->second);\n return it->second->second;\n }\n void put(int key, int value) {\n auto it = cache.find(key);\n if (it != cache.end()) dll.erase(it->second);\n else if (cache.size() >= cap) { cache.erase(dll.front().first); dll.pop_front(); }\n dll.push_back({key, value});\n cache[key] = --dll.end();\n }\n};", "test_cases": ["put(1,1), put(2,2), get(1) -> 1"], "key_points": ["HashMap + 双向链表", "O(1)时间操作"], "tags": ["design", "hard", "Google", "Amazon"]} {"problem_id": "algo_01200", "original_id": "num-islands", "title": "岛屿数量", "category": "graph", "difficulty": "medium", "companies": ["Google", "Facebook"], "description": "给你一个由 '1'(陆地)和 '0'(水)组成的二维网格,请你计算网格中岛屿的数量。岛屿总是被水包围,且只能由水平或垂直方向相邻的陆地连接形成。", "solution_python": "def numIslands(grid):\n if not grid: return 0\n rows, cols = len(grid), len(grid[0])\n count = 0\n def dfs(r, c):\n if r < 0 or r >= rows or c < 0 or c >= cols or grid[r][c] != '1': return\n grid[r][c] = '0'\n dfs(r+1, c); dfs(r-1, c); dfs(r, c+1); dfs(r, c-1)\n for r in range(rows):\n for c in range(cols):\n if grid[r][c] == '1': count += 1; dfs(r, c)\n return count", "solution_java": "public int numIslands(char[][] grid) {\n if (grid.length == 0) return 0;\n int count = 0;\n for (int i = 0; i < grid.length; i++)\n for (int j = 0; j < grid[0].length; j++)\n if (grid[i][j] == '1') { count++; dfs(grid, i, j); }\n return count;\n}\nprivate void dfs(char[][] grid, int r, int c) {\n if (r < 0 || r >= grid.length || c < 0 || c >= grid[0].length || grid[r][c] != '1') return;\n grid[r][c] = '0';\n dfs(grid, r+1, c); dfs(grid, r-1, c); dfs(grid, r, c+1); dfs(grid, r, c-1);\n}", "solution_cpp": "int numIslands(vector>& grid) {\n if (grid.empty()) return 0;\n int count = 0;\n for (int i = 0; i < grid.size(); i++)\n for (int j = 0; j < grid[0].size(); j++)\n if (grid[i][j] == '1') { count++; dfs(grid, i, j); }\n return count;\n}\nvoid dfs(vector>& grid, int r, int c) {\n if (r < 0 || r >= grid.size() || c < 0 || c >= grid[0].size() || grid[r][c] != '1') return;\n grid[r][c] = '0';\n dfs(grid, r+1, c); dfs(grid, r-1, c); dfs(grid, r, c+1); dfs(grid, r, c-1);\n}", "test_cases": ["grid=[[1,1,1,1,0],[1,1,0,1,0],[1,1,0,0,0],[0,0,0,0,0]] -> 1"], "key_points": ["DFS/BFS遍历", "访问后标记为0避免重复"], "tags": ["graph", "medium", "Google", "Facebook"]} {"problem_id": "algo_01201", "original_id": "two-sum", "title": "两数之和", "category": "array", "difficulty": "easy", "companies": ["Amazon", "Google"], "description": "给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那两个整数,并返回他们的数组下标。", "solution_python": "def twoSum(nums, target):\n hashmap = {}\n for i, num in enumerate(nums):\n complement = target - num\n if complement in hashmap:\n return [hashmap[complement], i]\n hashmap[num] = i\n return []", "solution_java": "public int[] twoSum(int[] nums, int target) {\n Map map = new HashMap<>();\n for (int i = 0; i < nums.length; i++) {\n int complement = target - nums[i];\n if (map.containsKey(complement)) return new int[]{map.get(complement), i};\n map.put(nums[i], i);\n }\n return new int[]{};\n}", "solution_cpp": "vector twoSum(vector& nums, int target) {\n unordered_map m;\n for (int i = 0; i < nums.size(); i++) {\n if (m.count(target - nums[i])) return {m[target - nums[i]], i};\n m[nums[i]] = i;\n }\n return {};\n}", "test_cases": ["nums=[2,7,11,15], target=9 -> [0,1]", "nums=[3,2,4], target=6 -> [1,2]"], "key_points": ["哈希表一次遍历", "空间换时间"], "tags": ["array", "easy", "Amazon", "Google"]} {"problem_id": "algo_01202", "original_id": "merge-sorted", "title": "合并两个有序数组", "category": "array", "difficulty": "easy", "companies": ["Microsoft", "Uber"], "description": "给你两个按非递减顺序排列的整数数组 nums1 和 nums2,另有两个整数 m 和 n,分别表示 nums1 和 nums2 中的元素数目。请你合并 nums2 到 nums1 中。", "solution_python": "def merge(nums1, m, nums2, n):\n p1, p2, p = m-1, n-1, m+n-1\n while p1 >= 0 and p2 >= 0:\n if nums1[p1] > nums2[p2]: nums1[p] = nums1[p1]; p1 -= 1\n else: nums1[p] = nums2[p2]; p2 -= 1\n p -= 1\n while p2 >= 0: nums1[p] = nums2[p2]; p2 -= 1; p -= 1", "solution_java": "public void merge(int[] nums1, int m, int[] nums2, int n) {\n int p1 = m-1, p2 = n-1, p = m+n-1;\n while (p1 >= 0 && p2 >= 0) {\n nums1[p--] = nums1[p1] > nums2[p2] ? nums1[p1--] : nums2[p2--];\n }\n while (p2 >= 0) nums1[p--] = nums2[p2--];\n}", "solution_cpp": "void merge(vector& nums1, int m, vector& nums2, int n) {\n int p1 = m-1, p2 = n-1, p = m+n-1;\n while (p1 >= 0 && p2 >= 0) nums1[p--] = nums1[p1] > nums2[p2] ? nums1[p1--] : nums2[p2--];\n while (p2 >= 0) nums1[p--] = nums2[p2--];\n}", "test_cases": ["nums1=[1,2,3], m=3, nums2=[2,5,6], n=3 -> [1,2,2,3,5,6]", "nums1=[], m=0, nums2=[1], n=1 -> [1]"], "key_points": ["从后往前合并", "三指针技巧"], "tags": ["array", "easy", "Microsoft", "Uber"]} {"problem_id": "algo_01203", "original_id": "max-subarray", "title": "最大子数组和", "category": "array", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "给你一个整数数组 nums ,请你找出一个具有最大和的连续子数组,返回其最大和。", "solution_python": "def maxSubArray(nums):\n max_sum = current = nums[0]\n for num in nums[1:]:\n current = max(num, current + num)\n max_sum = max(max_sum, current)\n return max_sum", "solution_java": "public int maxSubArray(int[] nums) {\n int maxSum = nums[0], curr = nums[0];\n for (int i = 1; i < nums.length; i++) {\n curr = Math.max(nums[i], curr + nums[i]);\n maxSum = Math.max(maxSum, curr);\n }\n return maxSum;\n}", "solution_cpp": "int maxSubArray(vector& nums) {\n int maxSum = nums[0], curr = nums[0];\n for (int i = 1; i < nums.size(); i++) {\n curr = max(nums[i], curr + nums[i]);\n maxSum = max(maxSum, curr);\n }\n return maxSum;\n}", "test_cases": ["nums=[-2,1,-3,4,-1,2,1,-5,4] -> 6", "nums=[1] -> 1"], "key_points": ["Kadane算法", "动态规划基础题"], "tags": ["array", "medium", "Google", "Microsoft"]} {"problem_id": "algo_01204", "original_id": "valid-parentheses", "title": "有效的括号", "category": "string", "difficulty": "easy", "companies": ["Google", "Uber"], "description": "给定一个只包括 '(',')','{','}','[',']' 的字符串 s,判断字符串是否有效。", "solution_python": "def isValid(s):\n stack = []\n mapping = {')': '(', ']': '[', '}': '{'}\n for c in s:\n if c in mapping:\n if not stack or stack[-1] != mapping[c]: return False\n stack.pop()\n else: stack.append(c)\n return not stack", "solution_java": "public boolean isValid(String s) {\n Stack stack = new Stack<>();\n Map map = Map.of(')', '(', ']', '[', '}', '{');\n for (char c : s.toCharArray()) {\n if (map.containsValue(c)) stack.push(c);\n else if (!stack.isEmpty() && stack.pop() != map.get(c)) return false;\n }\n return stack.isEmpty();\n}", "solution_cpp": "bool isValid(string s) {\n stack st;\n unordered_map m = {{')','('},{']','['},{'}','{'}};\n for (char c : s) {\n if (m.find(c) == m.end()) st.push(c);\n else if (st.empty() || st.top() != m[c]) return false;\n else st.pop();\n }\n return st.empty();\n}", "test_cases": ["s=\"()\" -> true", "s=\"()[]{}\" -> true", "s=\"(]\" -> false"], "key_points": ["栈匹配法", "注意空栈边界"], "tags": ["string", "easy", "Google", "Uber"]} {"problem_id": "algo_01205", "original_id": "longest-palindrome", "title": "最长回文子串", "category": "string", "difficulty": "medium", "companies": ["Google", "Amazon"], "description": "给你一个字符串 s,找到 s 中最长的回文子串。", "solution_python": "def longestPalindrome(s):\n def expand(l, r):\n while l >= 0 and r < len(s) and s[l] == s[r]: l -= 1; r += 1\n return l + 1, r - 1\n start = end = 0\n for i in range(len(s)):\n l1, r1 = expand(i, i)\n l2, r2 = expand(i, i + 1)\n if r1 - l1 > end - start: start, end = l1, r1\n if r2 - l2 > end - start: start, end = l2, r2\n return s[start:end+1]", "solution_java": "public String longestPalindrome(String s) {\n int start = 0, end = 0;\n for (int i = 0; i < s.length(); i++) {\n int len1 = expand(s, i, i), len2 = expand(s, i, i+1);\n int len = Math.max(len1, len2);\n if (len > end - start) { start = i - (len-1)/2; end = i + len/2; }\n }\n return s.substring(start, end + 1);\n}\nprivate int expand(String s, int l, int r) {\n while (l >= 0 && r < s.length() && s.charAt(l) == s.charAt(r)) { l--; r++; }\n return r - l - 1;\n}", "solution_cpp": "string longestPalindrome(string s) {\n int start = 0, end = 0;\n for (int i = 0; i < s.size(); i++) {\n int len1 = expand(s, i, i), len2 = expand(s, i, i+1);\n if (max(len1, len2) > end - start) { start = i - (max(len1,len2)-1)/2; end = i + max(len1,len2)/2; }\n }\n return s.substr(start, end - start + 1);\n}", "test_cases": ["s=\"babad\" -> bab或aba", "s=\"cbbd\" -> bb"], "key_points": ["中心扩展法", "处理奇偶长度"], "tags": ["string", "medium", "Google", "Amazon"]} {"problem_id": "algo_01206", "original_id": "reverse-list", "title": "反转链表", "category": "linkedlist", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "给你单链表的头节点 head,请你反转链表,并返回反转后的链表。", "solution_python": "def reverseList(head):\n prev = None\n curr = head\n while curr:\n nxt = curr.next\n curr.next = prev\n prev = curr\n curr = nxt\n return prev", "solution_java": "public ListNode reverseList(ListNode head) {\n ListNode prev = null, curr = head;\n while (curr != null) {\n ListNode next = curr.next;\n curr.next = prev;\n prev = curr;\n curr = next;\n }\n return prev;\n}", "solution_cpp": "ListNode* reverseList(ListNode* head) {\n ListNode* prev = nullptr, *curr = head;\n while (curr) {\n ListNode* next = curr->next;\n curr->next = prev;\n prev = curr;\n curr = next;\n }\n return prev;\n}", "test_cases": ["head=[1,2,3,4,5] -> [5,4,3,2,1]", "head=[1,2] -> [2,1]"], "key_points": ["迭代法 O(1)空间", "递归法 O(n)空间"], "tags": ["linkedlist", "medium", "Google", "Microsoft"]} {"problem_id": "algo_01207", "original_id": "middle-node", "title": "链表的中间结点", "category": "linkedlist", "difficulty": "easy", "companies": ["Amazon", "Facebook"], "description": "给你单链表的头节点 head,请你找出并返回链表的中间结点。如果有两个中间结点,则返回第二个中间结点。", "solution_python": "def middleNode(head):\n slow = fast = head\n while fast and fast.next:\n slow = slow.next\n fast = fast.next.next\n return slow", "solution_java": "public ListNode middleNode(ListNode head) {\n ListNode slow = head, fast = head;\n while (fast != null && fast.next != null) {\n slow = slow.next;\n fast = fast.next.next;\n }\n return slow;\n}", "solution_cpp": "ListNode* middleNode(ListNode* head) {\n ListNode* slow = head, *fast = head;\n while (fast && fast->next) { slow = slow->next; fast = fast->next->next; }\n return slow;\n}", "test_cases": ["head=[1,2,3,4,5] -> 3", "head=[1,2,3,4,5,6] -> 4"], "key_points": ["快慢指针", "O(n)时间O(1)空间"], "tags": ["linkedlist", "easy", "Amazon", "Facebook"]} {"problem_id": "algo_01208", "original_id": "max-depth", "title": "二叉树的最大深度", "category": "tree", "difficulty": "easy", "companies": ["Microsoft", "Apple"], "description": "给定一个二叉树 root,返回其最大深度。", "solution_python": "def maxDepth(root):\n if not root: return 0\n return max(maxDepth(root.left), maxDepth(root.right)) + 1", "solution_java": "public int maxDepth(TreeNode root) {\n if (root == null) return 0;\n return Math.max(maxDepth(root.left), maxDepth(root.right)) + 1;\n}", "solution_cpp": "int maxDepth(TreeNode* root) {\n if (!root) return 0;\n return max(maxDepth(root->left), maxDepth(root->right)) + 1;\n}", "test_cases": ["root=[3,9,20,null,null,15,7] -> 3", "root=[1,null,2] -> 2"], "key_points": ["DFS递归", "层序遍历也可"], "tags": ["tree", "easy", "Microsoft", "Apple"]} {"problem_id": "algo_01209", "original_id": "inorder-traversal", "title": "二叉树的中序遍历", "category": "tree", "difficulty": "easy", "companies": ["Google", "Microsoft"], "description": "给定一个二叉树的根节点 root,返回它的中序遍历结果。", "solution_python": "def inorderTraversal(root):\n result = []\n def dfs(node):\n if node:\n dfs(node.left)\n result.append(node.val)\n dfs(node.right)\n dfs(root)\n return result", "solution_java": "public List inorderTraversal(TreeNode root) {\n List res = new ArrayList<>();\n dfs(root, res);\n return res;\n}\nprivate void dfs(TreeNode node, List res) {\n if (node == null) return;\n dfs(node.left, res); res.add(node.val); dfs(node.right, res);\n}", "solution_cpp": "vector inorderTraversal(TreeNode* root) {\n vector res;\n dfs(root, res);\n return res;\n}\nvoid dfs(TreeNode* node, vector& res) {\n if (!node) return;\n dfs(node->left, res); res.push_back(node->val); dfs(node->right, res);\n}", "test_cases": ["root=[1,null,2,3] -> [1,3,2]", "root=[] -> []"], "key_points": ["左-根-右顺序", "递归最简洁"], "tags": ["tree", "easy", "Google", "Microsoft"]} {"problem_id": "algo_01210", "original_id": "binary-search", "title": "二分查找", "category": "binarysearch", "difficulty": "easy", "companies": ["Google", "Amazon"], "description": "给定一个 n 个元素有序的(升序)整型数组 nums 和一个目标值 target,写一个函数搜索 nums 中的 target,如果目标值存在返回下标,否则返回 -1。", "solution_python": "def search(nums, target):\n left, right = 0, len(nums) - 1\n while left <= right:\n mid = (left + right) // 2\n if nums[mid] == target: return mid\n elif nums[mid] < target: left = mid + 1\n else: right = mid - 1\n return -1", "solution_java": "public int search(int[] nums, int target) {\n int left = 0, right = nums.length - 1;\n while (left <= right) {\n int mid = left + (right - left) / 2;\n if (nums[mid] == target) return mid;\n else if (nums[mid] < target) left = mid + 1;\n else right = mid - 1;\n }\n return -1;\n}", "solution_cpp": "int search(vector& nums, int target) {\n int left = 0, right = nums.size() - 1;\n while (left <= right) {\n int mid = left + (right - left) / 2;\n if (nums[mid] == target) return mid;\n else if (nums[mid] < target) left = mid + 1;\n else right = mid - 1;\n }\n return -1;\n}", "test_cases": ["nums=[-1,0,3,5,9,12], target=9 -> 4", "nums=[-1,0,3,5,9,12], target=2 -> -1"], "key_points": ["标准模板", "注意防溢出写法"], "tags": ["binarysearch", "easy", "Google", "Amazon"]} {"problem_id": "algo_01211", "original_id": "climbing-stairs", "title": "爬楼梯", "category": "dp", "difficulty": "easy", "companies": ["Amazon", "Google"], "description": "假设你正在爬楼梯。需要 n 阶你才能到达楼顶。每次你可以爬 1 或 2 个台阶。你有多少种不同的方法可以爬到楼顶?", "solution_python": "def climbStairs(n):\n if n <= 2: return n\n a, b = 1, 2\n for _ in range(3, n+1):\n a, b = b, a + b\n return b", "solution_java": "public int climbStairs(int n) {\n if (n <= 2) return n;\n int a = 1, b = 2;\n for (int i = 3; i <= n; i++) { int temp = a + b; a = b; b = temp; }\n return b;\n}", "solution_cpp": "int climbStairs(int n) {\n if (n <= 2) return n;\n int a = 1, b = 2;\n for (int i = 3; i <= n; i++) { int temp = a + b; a = b; b = temp; }\n return b;\n}", "test_cases": ["n=2 -> 2", "n=3 -> 3", "n=5 -> 8"], "key_points": ["斐波那契数列", "滚动数组优化空间"], "tags": ["dp", "easy", "Amazon", "Google"]} {"problem_id": "algo_01212", "original_id": "coin-change", "title": "零钱兑换", "category": "dp", "difficulty": "medium", "companies": ["Google", "Amazon"], "description": "给你一个整数数组 coins 表示不同面额的硬币,以及一个整数 amount 表示总金额。计算并返回可以凑成总金额所需的最少的硬币个数。如果没有任何一种硬币组合能组成总金额,返回 -1。", "solution_python": "def coinChange(coins, amount):\n dp = [float('inf')] * (amount + 1)\n dp[0] = 0\n for coin in coins:\n for x in range(coin, amount + 1):\n dp[x] = min(dp[x], dp[x - coin] + 1)\n return dp[amount] if dp[amount] != float('inf') else -1", "solution_java": "public int coinChange(int[] coins, int amount) {\n int[] dp = new int[amount + 1];\n Arrays.fill(dp, amount + 1);\n dp[0] = 0;\n for (int coin : coins) {\n for (int x = coin; x <= amount; x++) {\n dp[x] = Math.min(dp[x], dp[x - coin] + 1);\n }\n }\n return dp[amount] > amount ? -1 : dp[amount];\n}", "solution_cpp": "int coinChange(vector& coins, int amount) {\n vector dp(amount + 1, amount + 1);\n dp[0] = 0;\n for (int coin : coins) {\n for (int x = coin; x <= amount; x++) {\n dp[x] = min(dp[x], dp[x - coin] + 1);\n }\n }\n return dp[amount] > amount ? -1 : dp[amount];\n}", "test_cases": ["coins=[1,2,5], amount=11 -> 3", "coins=[2], amount=3 -> -1"], "key_points": ["完全背包问题", "dp[x] = min(dp[x-coin]+1)"], "tags": ["dp", "medium", "Google", "Amazon"]} {"problem_id": "algo_01213", "original_id": "subsets", "title": "子集", "category": "backtracking", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "给你一个整数数组 nums ,数组中的元素 互不相同 。返回该数组所有可能的子集(幂集)。", "solution_python": "def subsets(nums):\n result = []\n def backtrack(start, path):\n result.append(path[:])\n for i in range(start, len(nums)):\n path.append(nums[i])\n backtrack(i + 1, path)\n path.pop()\n backtrack(0, [])\n return result", "solution_java": "public List> subsets(int[] nums) {\n List> result = new ArrayList<>();\n backtrack(nums, 0, new ArrayList<>(), result);\n return result;\n}\nprivate void backtrack(int[] nums, int start, List path, List> result) {\n result.add(new ArrayList<>(path));\n for (int i = start; i < nums.length; i++) {\n path.add(nums[i]);\n backtrack(nums, i + 1, path, result);\n path.remove(path.size() - 1);\n }\n}", "solution_cpp": "vector> subsets(vector& nums) {\n vector> result;\n vector path;\n backtrack(nums, 0, path, result);\n return result;\n}\nvoid backtrack(vector& nums, int start, vector& path, vector>& result) {\n result.push_back(path);\n for (int i = start; i < nums.size(); i++) {\n path.push_back(nums[i]);\n backtrack(nums, i + 1, path, result);\n path.pop_back();\n }\n}", "test_cases": ["nums=[1,2,3] -> [[],[1],[2],[1,2],[3],[1,3],[2,3],[1,2,3]]"], "key_points": ["选或不选", "DFS遍历子集树"], "tags": ["backtracking", "medium", "Google", "Microsoft"]} {"problem_id": "algo_01214", "original_id": "permutations", "title": "全排列", "category": "backtracking", "difficulty": "medium", "companies": ["Google", "Facebook"], "description": "给定一个不含重复数字的数组 nums,返回其所有可能的全排列。", "solution_python": "def permute(nums):\n result = []\n def backtrack(path, used):\n if len(path) == len(nums):\n result.append(path[:])\n return\n for i in range(len(nums)):\n if used[i]: continue\n used[i] = True\n path.append(nums[i])\n backtrack(path, used)\n path.pop()\n used[i] = False\n backtrack([], [False]*len(nums))\n return result", "solution_java": "public List> permute(int[] nums) {\n List> result = new ArrayList<>();\n boolean[] used = new boolean[nums.length];\n backtrack(nums, used, new ArrayList<>(), result);\n return result;\n}\nprivate void backtrack(int[] nums, boolean[] used, List path, List> result) {\n if (path.size() == nums.length) { result.add(new ArrayList<>(path)); return; }\n for (int i = 0; i < nums.length; i++) {\n if (used[i]) continue;\n used[i] = true;\n path.add(nums[i]);\n backtrack(nums, used, path, result);\n path.remove(path.size() - 1);\n used[i] = false;\n }\n}", "solution_cpp": "vector> permute(vector& nums) {\n vector> result;\n vector used(nums.size(), false);\n vector path;\n backtrack(nums, used, path, result);\n return result;\n}\nvoid backtrack(vector& nums, vector& used, vector& path, vector>& result) {\n if (path.size() == nums.size()) { result.push_back(path); return; }\n for (int i = 0; i < nums.size(); i++) {\n if (used[i]) continue;\n used[i] = true;\n path.push_back(nums[i]);\n backtrack(nums, used, path, result);\n path.pop_back();\n used[i] = false;\n }\n}", "test_cases": ["nums=[1,2,3] -> [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]"], "key_points": ["标记已使用元素", "回溯经典模板"], "tags": ["backtracking", "medium", "Google", "Facebook"]} {"problem_id": "algo_01215", "original_id": "top-k-frequent", "title": "前K个高频元素", "category": "heap", "difficulty": "medium", "companies": ["Amazon", "Facebook"], "description": "给你一个整数数组 nums 和一个整数 k,请你返回其中出现频率前 k 高的元素。", "solution_python": "import heapq\nfrom collections import Counter\ndef topKFrequent(nums, k):\n count = Counter(nums)\n heap = []\n for num, freq in count.items():\n heapq.heappush(heap, (freq, num))\n if len(heap) > k: heapq.heappop(heap)\n return [num for freq, num in heap]", "solution_java": "public int[] topKFrequent(int[] nums, int k) {\n Map count = new HashMap<>();\n for (int n : nums) count.put(n, count.getOrDefault(n, 0) + 1);\n PriorityQueue> heap = \n new PriorityQueue<>((a, b) -> a.getValue() - b.getValue());\n for (Map.Entry e : count.entrySet()) {\n heap.offer(e);\n if (heap.size() > k) heap.poll();\n }\n int[] res = new int[k];\n for (int i = k - 1; i >= 0; i--) res[i] = heap.poll().getKey();\n return res;\n}", "solution_cpp": "vector topKFrequent(vector& nums, int k) {\n unordered_map count;\n for (int n : nums) count[n]++;\n priority_queue, vector>, greater>> heap;\n for (auto& [num, freq] : count) {\n heap.push({freq, num});\n if (heap.size() > k) heap.pop();\n }\n vector res;\n while (!heap.empty()) { res.push_back(heap.top().second); heap.pop(); }\n reverse(res.begin(), res.end());\n return res;\n}", "test_cases": ["nums=[1,1,1,2,2,3], k=2 -> [1,2]", "nums=[1], k=1 -> [1]"], "key_points": ["小顶堆保持大小k", "时间复杂度O(nlogk)"], "tags": ["heap", "medium", "Amazon", "Facebook"]} {"problem_id": "algo_01216", "original_id": "3sum", "title": "三数之和", "category": "two-pointers", "difficulty": "medium", "companies": ["Google", "Amazon"], "description": "给你一个整数数组 nums,判断是否存在三元组满足和为0,返回所有不重复的三元组。", "solution_python": "def threeSum(nums):\n nums.sort()\n result = []\n for i in range(len(nums) - 2):\n if i > 0 and nums[i] == nums[i-1]: continue\n left, right = i + 1, len(nums) - 1\n while left < right:\n total = nums[i] + nums[left] + nums[right]\n if total < 0: left += 1\n elif total > 0: right -= 1\n else:\n result.append([nums[i], nums[left], nums[right]])\n while left < right and nums[left] == nums[left+1]: left += 1\n while left < right and nums[right] == nums[right-1]: right -= 1\n left += 1; right -= 1\n return result", "solution_java": "public List> threeSum(int[] nums) {\n Arrays.sort(nums);\n List> result = new ArrayList<>();\n for (int i = 0; i < nums.length - 2; i++) {\n if (i > 0 && nums[i] == nums[i-1]) continue;\n int left = i + 1, right = nums.length - 1;\n while (left < right) {\n int total = nums[i] + nums[left] + nums[right];\n if (total < 0) left++;\n else if (total > 0) right--;\n else {\n result.add(Arrays.asList(nums[i], nums[left], nums[right]));\n while (left < right && nums[left] == nums[left+1]) left++;\n while (left < right && nums[right] == nums[right-1]) right--;\n left++; right--;\n }\n }\n }\n return result;\n}", "solution_cpp": "vector> threeSum(vector& nums) {\n sort(nums.begin(), nums.end());\n vector> result;\n for (int i = 0; i < nums.size() - 2; i++) {\n if (i > 0 && nums[i] == nums[i-1]) continue;\n int left = i + 1, right = nums.size() - 1;\n while (left < right) {\n int total = nums[i] + nums[left] + nums[right];\n if (total < 0) left++;\n else if (total > 0) right--;\n else {\n result.push_back({nums[i], nums[left], nums[right]});\n while (left < right && nums[left] == nums[left+1]) left++;\n while (left < right && nums[right] == nums[right-1]) right--;\n left++; right--;\n }\n }\n }\n return result;\n}", "test_cases": ["nums=[-1,0,1,2,-1,-4] -> [[-1,-1,2],[-1,0,1]]"], "key_points": ["排序+双指针", "去重是关键"], "tags": ["two-pointers", "medium", "Google", "Amazon"]} {"problem_id": "algo_01217", "original_id": "container-water", "title": "盛最多水的容器", "category": "two-pointers", "difficulty": "medium", "companies": ["Google", "Uber"], "description": "给定一个长度为 n 的整数数组 height,找出其中的两条线,使得它们与 x 轴共同构成的容器可以容纳最多的水。", "solution_python": "def maxArea(height):\n left, right = 0, len(height) - 1\n max_area = 0\n while left < right:\n h = min(height[left], height[right])\n max_area = max(max_area, h * (right - left))\n if height[left] < height[right]: left += 1\n else: right -= 1\n return max_area", "solution_java": "public int maxArea(int[] height) {\n int left = 0, right = height.length - 1, maxArea = 0;\n while (left < right) {\n int h = Math.min(height[left], height[right]);\n maxArea = Math.max(maxArea, h * (right - left));\n if (height[left] < height[right]) left++;\n else right--;\n }\n return maxArea;\n}", "solution_cpp": "int maxArea(vector& height) {\n int left = 0, right = height.size() - 1, maxArea = 0;\n while (left < right) {\n int h = min(height[left], height[right]);\n maxArea = max(maxArea, h * (right - left));\n if (height[left] < height[right]) left++;\n else right--;\n }\n return maxArea;\n}", "test_cases": ["height=[1,8,6,2,5,4,8,3,7] -> 49"], "key_points": ["移动短边指针", "面积=min(h1,h2)*width"], "tags": ["two-pointers", "medium", "Google", "Uber"]} {"problem_id": "algo_01218", "original_id": "min-stack", "title": "最小栈", "category": "stack", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "设计一个支持 push,pop,top 操作,并能在常数时间内检索到最小元素的栈。", "solution_python": "class MinStack:\n def __init__(self):\n self.stack = []\n self.min_stack = []\n def push(self, val):\n self.stack.append(val)\n self.min_stack.append(min(val, self.min_stack[-1] if self.min_stack else val))\n def pop(self):\n self.stack.pop(); self.min_stack.pop()\n def top(self): return self.stack[-1]\n def getMin(self): return self.min_stack[-1]", "solution_java": "class MinStack {\n Stack stack = new Stack<>();\n Stack minStack = new Stack<>();\n public void push(int val) { stack.push(val); minStack.push(Math.min(val, minStack.isEmpty() ? val : minStack.peek())); }\n public void pop() { stack.pop(); minStack.pop(); }\n public int top() { return stack.peek(); }\n public int getMin() { return minStack.peek(); }\n}", "solution_cpp": "class MinStack {\n stack st, minSt;\npublic:\n void push(int val) { st.push(val); minSt.push(min(val, minSt.empty() ? val : minSt.top())); }\n void pop() { st.pop(); minSt.pop(); }\n int top() { return st.top(); }\n int getMin() { return minSt.top(); }\n};", "test_cases": ["push(-2), push(0), push(-3) -> getMin() returns -3"], "key_points": ["辅助栈记录最小值", "O(1)时间获取最小值"], "tags": ["stack", "medium", "Google", "Microsoft"]} {"problem_id": "algo_01219", "original_id": "lru-cache", "title": "LRU缓存", "category": "design", "difficulty": "hard", "companies": ["Google", "Amazon"], "description": "设计和实现一个 LRU(最近最少使用)缓存机制。", "solution_python": "class LRUCache:\n def __init__(self, capacity):\n self.capacity = capacity\n self.cache = {}\n self.order = []\n def get(self, key):\n if key not in self.cache: return -1\n self.order.remove(key); self.order.append(key)\n return self.cache[key]\n def put(self, key, value):\n if key in self.cache:\n self.order.remove(key)\n elif len(self.cache) >= self.capacity:\n del self.cache[self.order.pop(0)]\n self.cache[key] = value; self.order.append(key)", "solution_java": "class LRUCache {\n int capacity;\n LinkedHashMap cache = new LinkedHashMap<>();\n public LRUCache(int cap) { capacity = cap; }\n public int get(int key) { return cache.containsKey(key) ? cache.remove(key) : -1; }\n public void put(int key, int val) {\n if (cache.containsKey(key)) cache.remove(key);\n else if (cache.size() >= capacity) cache.remove(cache.keySet().iterator().next());\n cache.put(key, val);\n }\n}", "solution_cpp": "class LRUCache {\n int cap;\n list> dll;\n unordered_map>::iterator> cache;\npublic:\n LRUCache(int capacity) : cap(capacity) {}\n int get(int key) {\n auto it = cache.find(key);\n if (it == cache.end()) return -1;\n dll.splice(dll.end(), dll, it->second);\n return it->second->second;\n }\n void put(int key, int value) {\n auto it = cache.find(key);\n if (it != cache.end()) dll.erase(it->second);\n else if (cache.size() >= cap) { cache.erase(dll.front().first); dll.pop_front(); }\n dll.push_back({key, value});\n cache[key] = --dll.end();\n }\n};", "test_cases": ["put(1,1), put(2,2), get(1) -> 1"], "key_points": ["HashMap + 双向链表", "O(1)时间操作"], "tags": ["design", "hard", "Google", "Amazon"]} {"problem_id": "algo_01220", "original_id": "num-islands", "title": "岛屿数量", "category": "graph", "difficulty": "medium", "companies": ["Google", "Facebook"], "description": "给你一个由 '1'(陆地)和 '0'(水)组成的二维网格,请你计算网格中岛屿的数量。岛屿总是被水包围,且只能由水平或垂直方向相邻的陆地连接形成。", "solution_python": "def numIslands(grid):\n if not grid: return 0\n rows, cols = len(grid), len(grid[0])\n count = 0\n def dfs(r, c):\n if r < 0 or r >= rows or c < 0 or c >= cols or grid[r][c] != '1': return\n grid[r][c] = '0'\n dfs(r+1, c); dfs(r-1, c); dfs(r, c+1); dfs(r, c-1)\n for r in range(rows):\n for c in range(cols):\n if grid[r][c] == '1': count += 1; dfs(r, c)\n return count", "solution_java": "public int numIslands(char[][] grid) {\n if (grid.length == 0) return 0;\n int count = 0;\n for (int i = 0; i < grid.length; i++)\n for (int j = 0; j < grid[0].length; j++)\n if (grid[i][j] == '1') { count++; dfs(grid, i, j); }\n return count;\n}\nprivate void dfs(char[][] grid, int r, int c) {\n if (r < 0 || r >= grid.length || c < 0 || c >= grid[0].length || grid[r][c] != '1') return;\n grid[r][c] = '0';\n dfs(grid, r+1, c); dfs(grid, r-1, c); dfs(grid, r, c+1); dfs(grid, r, c-1);\n}", "solution_cpp": "int numIslands(vector>& grid) {\n if (grid.empty()) return 0;\n int count = 0;\n for (int i = 0; i < grid.size(); i++)\n for (int j = 0; j < grid[0].size(); j++)\n if (grid[i][j] == '1') { count++; dfs(grid, i, j); }\n return count;\n}\nvoid dfs(vector>& grid, int r, int c) {\n if (r < 0 || r >= grid.size() || c < 0 || c >= grid[0].size() || grid[r][c] != '1') return;\n grid[r][c] = '0';\n dfs(grid, r+1, c); dfs(grid, r-1, c); dfs(grid, r, c+1); dfs(grid, r, c-1);\n}", "test_cases": ["grid=[[1,1,1,1,0],[1,1,0,1,0],[1,1,0,0,0],[0,0,0,0,0]] -> 1"], "key_points": ["DFS/BFS遍历", "访问后标记为0避免重复"], "tags": ["graph", "medium", "Google", "Facebook"]} {"problem_id": "algo_01221", "original_id": "two-sum", "title": "两数之和", "category": "array", "difficulty": "easy", "companies": ["Amazon", "Google"], "description": "给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那两个整数,并返回他们的数组下标。", "solution_python": "def twoSum(nums, target):\n hashmap = {}\n for i, num in enumerate(nums):\n complement = target - num\n if complement in hashmap:\n return [hashmap[complement], i]\n hashmap[num] = i\n return []", "solution_java": "public int[] twoSum(int[] nums, int target) {\n Map map = new HashMap<>();\n for (int i = 0; i < nums.length; i++) {\n int complement = target - nums[i];\n if (map.containsKey(complement)) return new int[]{map.get(complement), i};\n map.put(nums[i], i);\n }\n return new int[]{};\n}", "solution_cpp": "vector twoSum(vector& nums, int target) {\n unordered_map m;\n for (int i = 0; i < nums.size(); i++) {\n if (m.count(target - nums[i])) return {m[target - nums[i]], i};\n m[nums[i]] = i;\n }\n return {};\n}", "test_cases": ["nums=[2,7,11,15], target=9 -> [0,1]", "nums=[3,2,4], target=6 -> [1,2]"], "key_points": ["哈希表一次遍历", "空间换时间"], "tags": ["array", "easy", "Amazon", "Google"]} {"problem_id": "algo_01222", "original_id": "merge-sorted", "title": "合并两个有序数组", "category": "array", "difficulty": "easy", "companies": ["Microsoft", "Uber"], "description": "给你两个按非递减顺序排列的整数数组 nums1 和 nums2,另有两个整数 m 和 n,分别表示 nums1 和 nums2 中的元素数目。请你合并 nums2 到 nums1 中。", "solution_python": "def merge(nums1, m, nums2, n):\n p1, p2, p = m-1, n-1, m+n-1\n while p1 >= 0 and p2 >= 0:\n if nums1[p1] > nums2[p2]: nums1[p] = nums1[p1]; p1 -= 1\n else: nums1[p] = nums2[p2]; p2 -= 1\n p -= 1\n while p2 >= 0: nums1[p] = nums2[p2]; p2 -= 1; p -= 1", "solution_java": "public void merge(int[] nums1, int m, int[] nums2, int n) {\n int p1 = m-1, p2 = n-1, p = m+n-1;\n while (p1 >= 0 && p2 >= 0) {\n nums1[p--] = nums1[p1] > nums2[p2] ? nums1[p1--] : nums2[p2--];\n }\n while (p2 >= 0) nums1[p--] = nums2[p2--];\n}", "solution_cpp": "void merge(vector& nums1, int m, vector& nums2, int n) {\n int p1 = m-1, p2 = n-1, p = m+n-1;\n while (p1 >= 0 && p2 >= 0) nums1[p--] = nums1[p1] > nums2[p2] ? nums1[p1--] : nums2[p2--];\n while (p2 >= 0) nums1[p--] = nums2[p2--];\n}", "test_cases": ["nums1=[1,2,3], m=3, nums2=[2,5,6], n=3 -> [1,2,2,3,5,6]", "nums1=[], m=0, nums2=[1], n=1 -> [1]"], "key_points": ["从后往前合并", "三指针技巧"], "tags": ["array", "easy", "Microsoft", "Uber"]} {"problem_id": "algo_01223", "original_id": "max-subarray", "title": "最大子数组和", "category": "array", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "给你一个整数数组 nums ,请你找出一个具有最大和的连续子数组,返回其最大和。", "solution_python": "def maxSubArray(nums):\n max_sum = current = nums[0]\n for num in nums[1:]:\n current = max(num, current + num)\n max_sum = max(max_sum, current)\n return max_sum", "solution_java": "public int maxSubArray(int[] nums) {\n int maxSum = nums[0], curr = nums[0];\n for (int i = 1; i < nums.length; i++) {\n curr = Math.max(nums[i], curr + nums[i]);\n maxSum = Math.max(maxSum, curr);\n }\n return maxSum;\n}", "solution_cpp": "int maxSubArray(vector& nums) {\n int maxSum = nums[0], curr = nums[0];\n for (int i = 1; i < nums.size(); i++) {\n curr = max(nums[i], curr + nums[i]);\n maxSum = max(maxSum, curr);\n }\n return maxSum;\n}", "test_cases": ["nums=[-2,1,-3,4,-1,2,1,-5,4] -> 6", "nums=[1] -> 1"], "key_points": ["Kadane算法", "动态规划基础题"], "tags": ["array", "medium", "Google", "Microsoft"]} {"problem_id": "algo_01224", "original_id": "valid-parentheses", "title": "有效的括号", "category": "string", "difficulty": "easy", "companies": ["Google", "Uber"], "description": "给定一个只包括 '(',')','{','}','[',']' 的字符串 s,判断字符串是否有效。", "solution_python": "def isValid(s):\n stack = []\n mapping = {')': '(', ']': '[', '}': '{'}\n for c in s:\n if c in mapping:\n if not stack or stack[-1] != mapping[c]: return False\n stack.pop()\n else: stack.append(c)\n return not stack", "solution_java": "public boolean isValid(String s) {\n Stack stack = new Stack<>();\n Map map = Map.of(')', '(', ']', '[', '}', '{');\n for (char c : s.toCharArray()) {\n if (map.containsValue(c)) stack.push(c);\n else if (!stack.isEmpty() && stack.pop() != map.get(c)) return false;\n }\n return stack.isEmpty();\n}", "solution_cpp": "bool isValid(string s) {\n stack st;\n unordered_map m = {{')','('},{']','['},{'}','{'}};\n for (char c : s) {\n if (m.find(c) == m.end()) st.push(c);\n else if (st.empty() || st.top() != m[c]) return false;\n else st.pop();\n }\n return st.empty();\n}", "test_cases": ["s=\"()\" -> true", "s=\"()[]{}\" -> true", "s=\"(]\" -> false"], "key_points": ["栈匹配法", "注意空栈边界"], "tags": ["string", "easy", "Google", "Uber"]} {"problem_id": "algo_01225", "original_id": "longest-palindrome", "title": "最长回文子串", "category": "string", "difficulty": "medium", "companies": ["Google", "Amazon"], "description": "给你一个字符串 s,找到 s 中最长的回文子串。", "solution_python": "def longestPalindrome(s):\n def expand(l, r):\n while l >= 0 and r < len(s) and s[l] == s[r]: l -= 1; r += 1\n return l + 1, r - 1\n start = end = 0\n for i in range(len(s)):\n l1, r1 = expand(i, i)\n l2, r2 = expand(i, i + 1)\n if r1 - l1 > end - start: start, end = l1, r1\n if r2 - l2 > end - start: start, end = l2, r2\n return s[start:end+1]", "solution_java": "public String longestPalindrome(String s) {\n int start = 0, end = 0;\n for (int i = 0; i < s.length(); i++) {\n int len1 = expand(s, i, i), len2 = expand(s, i, i+1);\n int len = Math.max(len1, len2);\n if (len > end - start) { start = i - (len-1)/2; end = i + len/2; }\n }\n return s.substring(start, end + 1);\n}\nprivate int expand(String s, int l, int r) {\n while (l >= 0 && r < s.length() && s.charAt(l) == s.charAt(r)) { l--; r++; }\n return r - l - 1;\n}", "solution_cpp": "string longestPalindrome(string s) {\n int start = 0, end = 0;\n for (int i = 0; i < s.size(); i++) {\n int len1 = expand(s, i, i), len2 = expand(s, i, i+1);\n if (max(len1, len2) > end - start) { start = i - (max(len1,len2)-1)/2; end = i + max(len1,len2)/2; }\n }\n return s.substr(start, end - start + 1);\n}", "test_cases": ["s=\"babad\" -> bab或aba", "s=\"cbbd\" -> bb"], "key_points": ["中心扩展法", "处理奇偶长度"], "tags": ["string", "medium", "Google", "Amazon"]} {"problem_id": "algo_01226", "original_id": "reverse-list", "title": "反转链表", "category": "linkedlist", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "给你单链表的头节点 head,请你反转链表,并返回反转后的链表。", "solution_python": "def reverseList(head):\n prev = None\n curr = head\n while curr:\n nxt = curr.next\n curr.next = prev\n prev = curr\n curr = nxt\n return prev", "solution_java": "public ListNode reverseList(ListNode head) {\n ListNode prev = null, curr = head;\n while (curr != null) {\n ListNode next = curr.next;\n curr.next = prev;\n prev = curr;\n curr = next;\n }\n return prev;\n}", "solution_cpp": "ListNode* reverseList(ListNode* head) {\n ListNode* prev = nullptr, *curr = head;\n while (curr) {\n ListNode* next = curr->next;\n curr->next = prev;\n prev = curr;\n curr = next;\n }\n return prev;\n}", "test_cases": ["head=[1,2,3,4,5] -> [5,4,3,2,1]", "head=[1,2] -> [2,1]"], "key_points": ["迭代法 O(1)空间", "递归法 O(n)空间"], "tags": ["linkedlist", "medium", "Google", "Microsoft"]} {"problem_id": "algo_01227", "original_id": "middle-node", "title": "链表的中间结点", "category": "linkedlist", "difficulty": "easy", "companies": ["Amazon", "Facebook"], "description": "给你单链表的头节点 head,请你找出并返回链表的中间结点。如果有两个中间结点,则返回第二个中间结点。", "solution_python": "def middleNode(head):\n slow = fast = head\n while fast and fast.next:\n slow = slow.next\n fast = fast.next.next\n return slow", "solution_java": "public ListNode middleNode(ListNode head) {\n ListNode slow = head, fast = head;\n while (fast != null && fast.next != null) {\n slow = slow.next;\n fast = fast.next.next;\n }\n return slow;\n}", "solution_cpp": "ListNode* middleNode(ListNode* head) {\n ListNode* slow = head, *fast = head;\n while (fast && fast->next) { slow = slow->next; fast = fast->next->next; }\n return slow;\n}", "test_cases": ["head=[1,2,3,4,5] -> 3", "head=[1,2,3,4,5,6] -> 4"], "key_points": ["快慢指针", "O(n)时间O(1)空间"], "tags": ["linkedlist", "easy", "Amazon", "Facebook"]} {"problem_id": "algo_01228", "original_id": "max-depth", "title": "二叉树的最大深度", "category": "tree", "difficulty": "easy", "companies": ["Microsoft", "Apple"], "description": "给定一个二叉树 root,返回其最大深度。", "solution_python": "def maxDepth(root):\n if not root: return 0\n return max(maxDepth(root.left), maxDepth(root.right)) + 1", "solution_java": "public int maxDepth(TreeNode root) {\n if (root == null) return 0;\n return Math.max(maxDepth(root.left), maxDepth(root.right)) + 1;\n}", "solution_cpp": "int maxDepth(TreeNode* root) {\n if (!root) return 0;\n return max(maxDepth(root->left), maxDepth(root->right)) + 1;\n}", "test_cases": ["root=[3,9,20,null,null,15,7] -> 3", "root=[1,null,2] -> 2"], "key_points": ["DFS递归", "层序遍历也可"], "tags": ["tree", "easy", "Microsoft", "Apple"]} {"problem_id": "algo_01229", "original_id": "inorder-traversal", "title": "二叉树的中序遍历", "category": "tree", "difficulty": "easy", "companies": ["Google", "Microsoft"], "description": "给定一个二叉树的根节点 root,返回它的中序遍历结果。", "solution_python": "def inorderTraversal(root):\n result = []\n def dfs(node):\n if node:\n dfs(node.left)\n result.append(node.val)\n dfs(node.right)\n dfs(root)\n return result", "solution_java": "public List inorderTraversal(TreeNode root) {\n List res = new ArrayList<>();\n dfs(root, res);\n return res;\n}\nprivate void dfs(TreeNode node, List res) {\n if (node == null) return;\n dfs(node.left, res); res.add(node.val); dfs(node.right, res);\n}", "solution_cpp": "vector inorderTraversal(TreeNode* root) {\n vector res;\n dfs(root, res);\n return res;\n}\nvoid dfs(TreeNode* node, vector& res) {\n if (!node) return;\n dfs(node->left, res); res.push_back(node->val); dfs(node->right, res);\n}", "test_cases": ["root=[1,null,2,3] -> [1,3,2]", "root=[] -> []"], "key_points": ["左-根-右顺序", "递归最简洁"], "tags": ["tree", "easy", "Google", "Microsoft"]} {"problem_id": "algo_01230", "original_id": "binary-search", "title": "二分查找", "category": "binarysearch", "difficulty": "easy", "companies": ["Google", "Amazon"], "description": "给定一个 n 个元素有序的(升序)整型数组 nums 和一个目标值 target,写一个函数搜索 nums 中的 target,如果目标值存在返回下标,否则返回 -1。", "solution_python": "def search(nums, target):\n left, right = 0, len(nums) - 1\n while left <= right:\n mid = (left + right) // 2\n if nums[mid] == target: return mid\n elif nums[mid] < target: left = mid + 1\n else: right = mid - 1\n return -1", "solution_java": "public int search(int[] nums, int target) {\n int left = 0, right = nums.length - 1;\n while (left <= right) {\n int mid = left + (right - left) / 2;\n if (nums[mid] == target) return mid;\n else if (nums[mid] < target) left = mid + 1;\n else right = mid - 1;\n }\n return -1;\n}", "solution_cpp": "int search(vector& nums, int target) {\n int left = 0, right = nums.size() - 1;\n while (left <= right) {\n int mid = left + (right - left) / 2;\n if (nums[mid] == target) return mid;\n else if (nums[mid] < target) left = mid + 1;\n else right = mid - 1;\n }\n return -1;\n}", "test_cases": ["nums=[-1,0,3,5,9,12], target=9 -> 4", "nums=[-1,0,3,5,9,12], target=2 -> -1"], "key_points": ["标准模板", "注意防溢出写法"], "tags": ["binarysearch", "easy", "Google", "Amazon"]} {"problem_id": "algo_01231", "original_id": "climbing-stairs", "title": "爬楼梯", "category": "dp", "difficulty": "easy", "companies": ["Amazon", "Google"], "description": "假设你正在爬楼梯。需要 n 阶你才能到达楼顶。每次你可以爬 1 或 2 个台阶。你有多少种不同的方法可以爬到楼顶?", "solution_python": "def climbStairs(n):\n if n <= 2: return n\n a, b = 1, 2\n for _ in range(3, n+1):\n a, b = b, a + b\n return b", "solution_java": "public int climbStairs(int n) {\n if (n <= 2) return n;\n int a = 1, b = 2;\n for (int i = 3; i <= n; i++) { int temp = a + b; a = b; b = temp; }\n return b;\n}", "solution_cpp": "int climbStairs(int n) {\n if (n <= 2) return n;\n int a = 1, b = 2;\n for (int i = 3; i <= n; i++) { int temp = a + b; a = b; b = temp; }\n return b;\n}", "test_cases": ["n=2 -> 2", "n=3 -> 3", "n=5 -> 8"], "key_points": ["斐波那契数列", "滚动数组优化空间"], "tags": ["dp", "easy", "Amazon", "Google"]} {"problem_id": "algo_01232", "original_id": "coin-change", "title": "零钱兑换", "category": "dp", "difficulty": "medium", "companies": ["Google", "Amazon"], "description": "给你一个整数数组 coins 表示不同面额的硬币,以及一个整数 amount 表示总金额。计算并返回可以凑成总金额所需的最少的硬币个数。如果没有任何一种硬币组合能组成总金额,返回 -1。", "solution_python": "def coinChange(coins, amount):\n dp = [float('inf')] * (amount + 1)\n dp[0] = 0\n for coin in coins:\n for x in range(coin, amount + 1):\n dp[x] = min(dp[x], dp[x - coin] + 1)\n return dp[amount] if dp[amount] != float('inf') else -1", "solution_java": "public int coinChange(int[] coins, int amount) {\n int[] dp = new int[amount + 1];\n Arrays.fill(dp, amount + 1);\n dp[0] = 0;\n for (int coin : coins) {\n for (int x = coin; x <= amount; x++) {\n dp[x] = Math.min(dp[x], dp[x - coin] + 1);\n }\n }\n return dp[amount] > amount ? -1 : dp[amount];\n}", "solution_cpp": "int coinChange(vector& coins, int amount) {\n vector dp(amount + 1, amount + 1);\n dp[0] = 0;\n for (int coin : coins) {\n for (int x = coin; x <= amount; x++) {\n dp[x] = min(dp[x], dp[x - coin] + 1);\n }\n }\n return dp[amount] > amount ? -1 : dp[amount];\n}", "test_cases": ["coins=[1,2,5], amount=11 -> 3", "coins=[2], amount=3 -> -1"], "key_points": ["完全背包问题", "dp[x] = min(dp[x-coin]+1)"], "tags": ["dp", "medium", "Google", "Amazon"]} {"problem_id": "algo_01233", "original_id": "subsets", "title": "子集", "category": "backtracking", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "给你一个整数数组 nums ,数组中的元素 互不相同 。返回该数组所有可能的子集(幂集)。", "solution_python": "def subsets(nums):\n result = []\n def backtrack(start, path):\n result.append(path[:])\n for i in range(start, len(nums)):\n path.append(nums[i])\n backtrack(i + 1, path)\n path.pop()\n backtrack(0, [])\n return result", "solution_java": "public List> subsets(int[] nums) {\n List> result = new ArrayList<>();\n backtrack(nums, 0, new ArrayList<>(), result);\n return result;\n}\nprivate void backtrack(int[] nums, int start, List path, List> result) {\n result.add(new ArrayList<>(path));\n for (int i = start; i < nums.length; i++) {\n path.add(nums[i]);\n backtrack(nums, i + 1, path, result);\n path.remove(path.size() - 1);\n }\n}", "solution_cpp": "vector> subsets(vector& nums) {\n vector> result;\n vector path;\n backtrack(nums, 0, path, result);\n return result;\n}\nvoid backtrack(vector& nums, int start, vector& path, vector>& result) {\n result.push_back(path);\n for (int i = start; i < nums.size(); i++) {\n path.push_back(nums[i]);\n backtrack(nums, i + 1, path, result);\n path.pop_back();\n }\n}", "test_cases": ["nums=[1,2,3] -> [[],[1],[2],[1,2],[3],[1,3],[2,3],[1,2,3]]"], "key_points": ["选或不选", "DFS遍历子集树"], "tags": ["backtracking", "medium", "Google", "Microsoft"]} {"problem_id": "algo_01234", "original_id": "permutations", "title": "全排列", "category": "backtracking", "difficulty": "medium", "companies": ["Google", "Facebook"], "description": "给定一个不含重复数字的数组 nums,返回其所有可能的全排列。", "solution_python": "def permute(nums):\n result = []\n def backtrack(path, used):\n if len(path) == len(nums):\n result.append(path[:])\n return\n for i in range(len(nums)):\n if used[i]: continue\n used[i] = True\n path.append(nums[i])\n backtrack(path, used)\n path.pop()\n used[i] = False\n backtrack([], [False]*len(nums))\n return result", "solution_java": "public List> permute(int[] nums) {\n List> result = new ArrayList<>();\n boolean[] used = new boolean[nums.length];\n backtrack(nums, used, new ArrayList<>(), result);\n return result;\n}\nprivate void backtrack(int[] nums, boolean[] used, List path, List> result) {\n if (path.size() == nums.length) { result.add(new ArrayList<>(path)); return; }\n for (int i = 0; i < nums.length; i++) {\n if (used[i]) continue;\n used[i] = true;\n path.add(nums[i]);\n backtrack(nums, used, path, result);\n path.remove(path.size() - 1);\n used[i] = false;\n }\n}", "solution_cpp": "vector> permute(vector& nums) {\n vector> result;\n vector used(nums.size(), false);\n vector path;\n backtrack(nums, used, path, result);\n return result;\n}\nvoid backtrack(vector& nums, vector& used, vector& path, vector>& result) {\n if (path.size() == nums.size()) { result.push_back(path); return; }\n for (int i = 0; i < nums.size(); i++) {\n if (used[i]) continue;\n used[i] = true;\n path.push_back(nums[i]);\n backtrack(nums, used, path, result);\n path.pop_back();\n used[i] = false;\n }\n}", "test_cases": ["nums=[1,2,3] -> [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]"], "key_points": ["标记已使用元素", "回溯经典模板"], "tags": ["backtracking", "medium", "Google", "Facebook"]} {"problem_id": "algo_01235", "original_id": "top-k-frequent", "title": "前K个高频元素", "category": "heap", "difficulty": "medium", "companies": ["Amazon", "Facebook"], "description": "给你一个整数数组 nums 和一个整数 k,请你返回其中出现频率前 k 高的元素。", "solution_python": "import heapq\nfrom collections import Counter\ndef topKFrequent(nums, k):\n count = Counter(nums)\n heap = []\n for num, freq in count.items():\n heapq.heappush(heap, (freq, num))\n if len(heap) > k: heapq.heappop(heap)\n return [num for freq, num in heap]", "solution_java": "public int[] topKFrequent(int[] nums, int k) {\n Map count = new HashMap<>();\n for (int n : nums) count.put(n, count.getOrDefault(n, 0) + 1);\n PriorityQueue> heap = \n new PriorityQueue<>((a, b) -> a.getValue() - b.getValue());\n for (Map.Entry e : count.entrySet()) {\n heap.offer(e);\n if (heap.size() > k) heap.poll();\n }\n int[] res = new int[k];\n for (int i = k - 1; i >= 0; i--) res[i] = heap.poll().getKey();\n return res;\n}", "solution_cpp": "vector topKFrequent(vector& nums, int k) {\n unordered_map count;\n for (int n : nums) count[n]++;\n priority_queue, vector>, greater>> heap;\n for (auto& [num, freq] : count) {\n heap.push({freq, num});\n if (heap.size() > k) heap.pop();\n }\n vector res;\n while (!heap.empty()) { res.push_back(heap.top().second); heap.pop(); }\n reverse(res.begin(), res.end());\n return res;\n}", "test_cases": ["nums=[1,1,1,2,2,3], k=2 -> [1,2]", "nums=[1], k=1 -> [1]"], "key_points": ["小顶堆保持大小k", "时间复杂度O(nlogk)"], "tags": ["heap", "medium", "Amazon", "Facebook"]} {"problem_id": "algo_01236", "original_id": "3sum", "title": "三数之和", "category": "two-pointers", "difficulty": "medium", "companies": ["Google", "Amazon"], "description": "给你一个整数数组 nums,判断是否存在三元组满足和为0,返回所有不重复的三元组。", "solution_python": "def threeSum(nums):\n nums.sort()\n result = []\n for i in range(len(nums) - 2):\n if i > 0 and nums[i] == nums[i-1]: continue\n left, right = i + 1, len(nums) - 1\n while left < right:\n total = nums[i] + nums[left] + nums[right]\n if total < 0: left += 1\n elif total > 0: right -= 1\n else:\n result.append([nums[i], nums[left], nums[right]])\n while left < right and nums[left] == nums[left+1]: left += 1\n while left < right and nums[right] == nums[right-1]: right -= 1\n left += 1; right -= 1\n return result", "solution_java": "public List> threeSum(int[] nums) {\n Arrays.sort(nums);\n List> result = new ArrayList<>();\n for (int i = 0; i < nums.length - 2; i++) {\n if (i > 0 && nums[i] == nums[i-1]) continue;\n int left = i + 1, right = nums.length - 1;\n while (left < right) {\n int total = nums[i] + nums[left] + nums[right];\n if (total < 0) left++;\n else if (total > 0) right--;\n else {\n result.add(Arrays.asList(nums[i], nums[left], nums[right]));\n while (left < right && nums[left] == nums[left+1]) left++;\n while (left < right && nums[right] == nums[right-1]) right--;\n left++; right--;\n }\n }\n }\n return result;\n}", "solution_cpp": "vector> threeSum(vector& nums) {\n sort(nums.begin(), nums.end());\n vector> result;\n for (int i = 0; i < nums.size() - 2; i++) {\n if (i > 0 && nums[i] == nums[i-1]) continue;\n int left = i + 1, right = nums.size() - 1;\n while (left < right) {\n int total = nums[i] + nums[left] + nums[right];\n if (total < 0) left++;\n else if (total > 0) right--;\n else {\n result.push_back({nums[i], nums[left], nums[right]});\n while (left < right && nums[left] == nums[left+1]) left++;\n while (left < right && nums[right] == nums[right-1]) right--;\n left++; right--;\n }\n }\n }\n return result;\n}", "test_cases": ["nums=[-1,0,1,2,-1,-4] -> [[-1,-1,2],[-1,0,1]]"], "key_points": ["排序+双指针", "去重是关键"], "tags": ["two-pointers", "medium", "Google", "Amazon"]} {"problem_id": "algo_01237", "original_id": "container-water", "title": "盛最多水的容器", "category": "two-pointers", "difficulty": "medium", "companies": ["Google", "Uber"], "description": "给定一个长度为 n 的整数数组 height,找出其中的两条线,使得它们与 x 轴共同构成的容器可以容纳最多的水。", "solution_python": "def maxArea(height):\n left, right = 0, len(height) - 1\n max_area = 0\n while left < right:\n h = min(height[left], height[right])\n max_area = max(max_area, h * (right - left))\n if height[left] < height[right]: left += 1\n else: right -= 1\n return max_area", "solution_java": "public int maxArea(int[] height) {\n int left = 0, right = height.length - 1, maxArea = 0;\n while (left < right) {\n int h = Math.min(height[left], height[right]);\n maxArea = Math.max(maxArea, h * (right - left));\n if (height[left] < height[right]) left++;\n else right--;\n }\n return maxArea;\n}", "solution_cpp": "int maxArea(vector& height) {\n int left = 0, right = height.size() - 1, maxArea = 0;\n while (left < right) {\n int h = min(height[left], height[right]);\n maxArea = max(maxArea, h * (right - left));\n if (height[left] < height[right]) left++;\n else right--;\n }\n return maxArea;\n}", "test_cases": ["height=[1,8,6,2,5,4,8,3,7] -> 49"], "key_points": ["移动短边指针", "面积=min(h1,h2)*width"], "tags": ["two-pointers", "medium", "Google", "Uber"]} {"problem_id": "algo_01238", "original_id": "min-stack", "title": "最小栈", "category": "stack", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "设计一个支持 push,pop,top 操作,并能在常数时间内检索到最小元素的栈。", "solution_python": "class MinStack:\n def __init__(self):\n self.stack = []\n self.min_stack = []\n def push(self, val):\n self.stack.append(val)\n self.min_stack.append(min(val, self.min_stack[-1] if self.min_stack else val))\n def pop(self):\n self.stack.pop(); self.min_stack.pop()\n def top(self): return self.stack[-1]\n def getMin(self): return self.min_stack[-1]", "solution_java": "class MinStack {\n Stack stack = new Stack<>();\n Stack minStack = new Stack<>();\n public void push(int val) { stack.push(val); minStack.push(Math.min(val, minStack.isEmpty() ? val : minStack.peek())); }\n public void pop() { stack.pop(); minStack.pop(); }\n public int top() { return stack.peek(); }\n public int getMin() { return minStack.peek(); }\n}", "solution_cpp": "class MinStack {\n stack st, minSt;\npublic:\n void push(int val) { st.push(val); minSt.push(min(val, minSt.empty() ? val : minSt.top())); }\n void pop() { st.pop(); minSt.pop(); }\n int top() { return st.top(); }\n int getMin() { return minSt.top(); }\n};", "test_cases": ["push(-2), push(0), push(-3) -> getMin() returns -3"], "key_points": ["辅助栈记录最小值", "O(1)时间获取最小值"], "tags": ["stack", "medium", "Google", "Microsoft"]} {"problem_id": "algo_01239", "original_id": "lru-cache", "title": "LRU缓存", "category": "design", "difficulty": "hard", "companies": ["Google", "Amazon"], "description": "设计和实现一个 LRU(最近最少使用)缓存机制。", "solution_python": "class LRUCache:\n def __init__(self, capacity):\n self.capacity = capacity\n self.cache = {}\n self.order = []\n def get(self, key):\n if key not in self.cache: return -1\n self.order.remove(key); self.order.append(key)\n return self.cache[key]\n def put(self, key, value):\n if key in self.cache:\n self.order.remove(key)\n elif len(self.cache) >= self.capacity:\n del self.cache[self.order.pop(0)]\n self.cache[key] = value; self.order.append(key)", "solution_java": "class LRUCache {\n int capacity;\n LinkedHashMap cache = new LinkedHashMap<>();\n public LRUCache(int cap) { capacity = cap; }\n public int get(int key) { return cache.containsKey(key) ? cache.remove(key) : -1; }\n public void put(int key, int val) {\n if (cache.containsKey(key)) cache.remove(key);\n else if (cache.size() >= capacity) cache.remove(cache.keySet().iterator().next());\n cache.put(key, val);\n }\n}", "solution_cpp": "class LRUCache {\n int cap;\n list> dll;\n unordered_map>::iterator> cache;\npublic:\n LRUCache(int capacity) : cap(capacity) {}\n int get(int key) {\n auto it = cache.find(key);\n if (it == cache.end()) return -1;\n dll.splice(dll.end(), dll, it->second);\n return it->second->second;\n }\n void put(int key, int value) {\n auto it = cache.find(key);\n if (it != cache.end()) dll.erase(it->second);\n else if (cache.size() >= cap) { cache.erase(dll.front().first); dll.pop_front(); }\n dll.push_back({key, value});\n cache[key] = --dll.end();\n }\n};", "test_cases": ["put(1,1), put(2,2), get(1) -> 1"], "key_points": ["HashMap + 双向链表", "O(1)时间操作"], "tags": ["design", "hard", "Google", "Amazon"]} {"problem_id": "algo_01240", "original_id": "num-islands", "title": "岛屿数量", "category": "graph", "difficulty": "medium", "companies": ["Google", "Facebook"], "description": "给你一个由 '1'(陆地)和 '0'(水)组成的二维网格,请你计算网格中岛屿的数量。岛屿总是被水包围,且只能由水平或垂直方向相邻的陆地连接形成。", "solution_python": "def numIslands(grid):\n if not grid: return 0\n rows, cols = len(grid), len(grid[0])\n count = 0\n def dfs(r, c):\n if r < 0 or r >= rows or c < 0 or c >= cols or grid[r][c] != '1': return\n grid[r][c] = '0'\n dfs(r+1, c); dfs(r-1, c); dfs(r, c+1); dfs(r, c-1)\n for r in range(rows):\n for c in range(cols):\n if grid[r][c] == '1': count += 1; dfs(r, c)\n return count", "solution_java": "public int numIslands(char[][] grid) {\n if (grid.length == 0) return 0;\n int count = 0;\n for (int i = 0; i < grid.length; i++)\n for (int j = 0; j < grid[0].length; j++)\n if (grid[i][j] == '1') { count++; dfs(grid, i, j); }\n return count;\n}\nprivate void dfs(char[][] grid, int r, int c) {\n if (r < 0 || r >= grid.length || c < 0 || c >= grid[0].length || grid[r][c] != '1') return;\n grid[r][c] = '0';\n dfs(grid, r+1, c); dfs(grid, r-1, c); dfs(grid, r, c+1); dfs(grid, r, c-1);\n}", "solution_cpp": "int numIslands(vector>& grid) {\n if (grid.empty()) return 0;\n int count = 0;\n for (int i = 0; i < grid.size(); i++)\n for (int j = 0; j < grid[0].size(); j++)\n if (grid[i][j] == '1') { count++; dfs(grid, i, j); }\n return count;\n}\nvoid dfs(vector>& grid, int r, int c) {\n if (r < 0 || r >= grid.size() || c < 0 || c >= grid[0].size() || grid[r][c] != '1') return;\n grid[r][c] = '0';\n dfs(grid, r+1, c); dfs(grid, r-1, c); dfs(grid, r, c+1); dfs(grid, r, c-1);\n}", "test_cases": ["grid=[[1,1,1,1,0],[1,1,0,1,0],[1,1,0,0,0],[0,0,0,0,0]] -> 1"], "key_points": ["DFS/BFS遍历", "访问后标记为0避免重复"], "tags": ["graph", "medium", "Google", "Facebook"]} {"problem_id": "algo_01241", "original_id": "two-sum", "title": "两数之和", "category": "array", "difficulty": "easy", "companies": ["Amazon", "Google"], "description": "给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那两个整数,并返回他们的数组下标。", "solution_python": "def twoSum(nums, target):\n hashmap = {}\n for i, num in enumerate(nums):\n complement = target - num\n if complement in hashmap:\n return [hashmap[complement], i]\n hashmap[num] = i\n return []", "solution_java": "public int[] twoSum(int[] nums, int target) {\n Map map = new HashMap<>();\n for (int i = 0; i < nums.length; i++) {\n int complement = target - nums[i];\n if (map.containsKey(complement)) return new int[]{map.get(complement), i};\n map.put(nums[i], i);\n }\n return new int[]{};\n}", "solution_cpp": "vector twoSum(vector& nums, int target) {\n unordered_map m;\n for (int i = 0; i < nums.size(); i++) {\n if (m.count(target - nums[i])) return {m[target - nums[i]], i};\n m[nums[i]] = i;\n }\n return {};\n}", "test_cases": ["nums=[2,7,11,15], target=9 -> [0,1]", "nums=[3,2,4], target=6 -> [1,2]"], "key_points": ["哈希表一次遍历", "空间换时间"], "tags": ["array", "easy", "Amazon", "Google"]} {"problem_id": "algo_01242", "original_id": "merge-sorted", "title": "合并两个有序数组", "category": "array", "difficulty": "easy", "companies": ["Microsoft", "Uber"], "description": "给你两个按非递减顺序排列的整数数组 nums1 和 nums2,另有两个整数 m 和 n,分别表示 nums1 和 nums2 中的元素数目。请你合并 nums2 到 nums1 中。", "solution_python": "def merge(nums1, m, nums2, n):\n p1, p2, p = m-1, n-1, m+n-1\n while p1 >= 0 and p2 >= 0:\n if nums1[p1] > nums2[p2]: nums1[p] = nums1[p1]; p1 -= 1\n else: nums1[p] = nums2[p2]; p2 -= 1\n p -= 1\n while p2 >= 0: nums1[p] = nums2[p2]; p2 -= 1; p -= 1", "solution_java": "public void merge(int[] nums1, int m, int[] nums2, int n) {\n int p1 = m-1, p2 = n-1, p = m+n-1;\n while (p1 >= 0 && p2 >= 0) {\n nums1[p--] = nums1[p1] > nums2[p2] ? nums1[p1--] : nums2[p2--];\n }\n while (p2 >= 0) nums1[p--] = nums2[p2--];\n}", "solution_cpp": "void merge(vector& nums1, int m, vector& nums2, int n) {\n int p1 = m-1, p2 = n-1, p = m+n-1;\n while (p1 >= 0 && p2 >= 0) nums1[p--] = nums1[p1] > nums2[p2] ? nums1[p1--] : nums2[p2--];\n while (p2 >= 0) nums1[p--] = nums2[p2--];\n}", "test_cases": ["nums1=[1,2,3], m=3, nums2=[2,5,6], n=3 -> [1,2,2,3,5,6]", "nums1=[], m=0, nums2=[1], n=1 -> [1]"], "key_points": ["从后往前合并", "三指针技巧"], "tags": ["array", "easy", "Microsoft", "Uber"]} {"problem_id": "algo_01243", "original_id": "max-subarray", "title": "最大子数组和", "category": "array", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "给你一个整数数组 nums ,请你找出一个具有最大和的连续子数组,返回其最大和。", "solution_python": "def maxSubArray(nums):\n max_sum = current = nums[0]\n for num in nums[1:]:\n current = max(num, current + num)\n max_sum = max(max_sum, current)\n return max_sum", "solution_java": "public int maxSubArray(int[] nums) {\n int maxSum = nums[0], curr = nums[0];\n for (int i = 1; i < nums.length; i++) {\n curr = Math.max(nums[i], curr + nums[i]);\n maxSum = Math.max(maxSum, curr);\n }\n return maxSum;\n}", "solution_cpp": "int maxSubArray(vector& nums) {\n int maxSum = nums[0], curr = nums[0];\n for (int i = 1; i < nums.size(); i++) {\n curr = max(nums[i], curr + nums[i]);\n maxSum = max(maxSum, curr);\n }\n return maxSum;\n}", "test_cases": ["nums=[-2,1,-3,4,-1,2,1,-5,4] -> 6", "nums=[1] -> 1"], "key_points": ["Kadane算法", "动态规划基础题"], "tags": ["array", "medium", "Google", "Microsoft"]} {"problem_id": "algo_01244", "original_id": "valid-parentheses", "title": "有效的括号", "category": "string", "difficulty": "easy", "companies": ["Google", "Uber"], "description": "给定一个只包括 '(',')','{','}','[',']' 的字符串 s,判断字符串是否有效。", "solution_python": "def isValid(s):\n stack = []\n mapping = {')': '(', ']': '[', '}': '{'}\n for c in s:\n if c in mapping:\n if not stack or stack[-1] != mapping[c]: return False\n stack.pop()\n else: stack.append(c)\n return not stack", "solution_java": "public boolean isValid(String s) {\n Stack stack = new Stack<>();\n Map map = Map.of(')', '(', ']', '[', '}', '{');\n for (char c : s.toCharArray()) {\n if (map.containsValue(c)) stack.push(c);\n else if (!stack.isEmpty() && stack.pop() != map.get(c)) return false;\n }\n return stack.isEmpty();\n}", "solution_cpp": "bool isValid(string s) {\n stack st;\n unordered_map m = {{')','('},{']','['},{'}','{'}};\n for (char c : s) {\n if (m.find(c) == m.end()) st.push(c);\n else if (st.empty() || st.top() != m[c]) return false;\n else st.pop();\n }\n return st.empty();\n}", "test_cases": ["s=\"()\" -> true", "s=\"()[]{}\" -> true", "s=\"(]\" -> false"], "key_points": ["栈匹配法", "注意空栈边界"], "tags": ["string", "easy", "Google", "Uber"]} {"problem_id": "algo_01245", "original_id": "longest-palindrome", "title": "最长回文子串", "category": "string", "difficulty": "medium", "companies": ["Google", "Amazon"], "description": "给你一个字符串 s,找到 s 中最长的回文子串。", "solution_python": "def longestPalindrome(s):\n def expand(l, r):\n while l >= 0 and r < len(s) and s[l] == s[r]: l -= 1; r += 1\n return l + 1, r - 1\n start = end = 0\n for i in range(len(s)):\n l1, r1 = expand(i, i)\n l2, r2 = expand(i, i + 1)\n if r1 - l1 > end - start: start, end = l1, r1\n if r2 - l2 > end - start: start, end = l2, r2\n return s[start:end+1]", "solution_java": "public String longestPalindrome(String s) {\n int start = 0, end = 0;\n for (int i = 0; i < s.length(); i++) {\n int len1 = expand(s, i, i), len2 = expand(s, i, i+1);\n int len = Math.max(len1, len2);\n if (len > end - start) { start = i - (len-1)/2; end = i + len/2; }\n }\n return s.substring(start, end + 1);\n}\nprivate int expand(String s, int l, int r) {\n while (l >= 0 && r < s.length() && s.charAt(l) == s.charAt(r)) { l--; r++; }\n return r - l - 1;\n}", "solution_cpp": "string longestPalindrome(string s) {\n int start = 0, end = 0;\n for (int i = 0; i < s.size(); i++) {\n int len1 = expand(s, i, i), len2 = expand(s, i, i+1);\n if (max(len1, len2) > end - start) { start = i - (max(len1,len2)-1)/2; end = i + max(len1,len2)/2; }\n }\n return s.substr(start, end - start + 1);\n}", "test_cases": ["s=\"babad\" -> bab或aba", "s=\"cbbd\" -> bb"], "key_points": ["中心扩展法", "处理奇偶长度"], "tags": ["string", "medium", "Google", "Amazon"]} {"problem_id": "algo_01246", "original_id": "reverse-list", "title": "反转链表", "category": "linkedlist", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "给你单链表的头节点 head,请你反转链表,并返回反转后的链表。", "solution_python": "def reverseList(head):\n prev = None\n curr = head\n while curr:\n nxt = curr.next\n curr.next = prev\n prev = curr\n curr = nxt\n return prev", "solution_java": "public ListNode reverseList(ListNode head) {\n ListNode prev = null, curr = head;\n while (curr != null) {\n ListNode next = curr.next;\n curr.next = prev;\n prev = curr;\n curr = next;\n }\n return prev;\n}", "solution_cpp": "ListNode* reverseList(ListNode* head) {\n ListNode* prev = nullptr, *curr = head;\n while (curr) {\n ListNode* next = curr->next;\n curr->next = prev;\n prev = curr;\n curr = next;\n }\n return prev;\n}", "test_cases": ["head=[1,2,3,4,5] -> [5,4,3,2,1]", "head=[1,2] -> [2,1]"], "key_points": ["迭代法 O(1)空间", "递归法 O(n)空间"], "tags": ["linkedlist", "medium", "Google", "Microsoft"]} {"problem_id": "algo_01247", "original_id": "middle-node", "title": "链表的中间结点", "category": "linkedlist", "difficulty": "easy", "companies": ["Amazon", "Facebook"], "description": "给你单链表的头节点 head,请你找出并返回链表的中间结点。如果有两个中间结点,则返回第二个中间结点。", "solution_python": "def middleNode(head):\n slow = fast = head\n while fast and fast.next:\n slow = slow.next\n fast = fast.next.next\n return slow", "solution_java": "public ListNode middleNode(ListNode head) {\n ListNode slow = head, fast = head;\n while (fast != null && fast.next != null) {\n slow = slow.next;\n fast = fast.next.next;\n }\n return slow;\n}", "solution_cpp": "ListNode* middleNode(ListNode* head) {\n ListNode* slow = head, *fast = head;\n while (fast && fast->next) { slow = slow->next; fast = fast->next->next; }\n return slow;\n}", "test_cases": ["head=[1,2,3,4,5] -> 3", "head=[1,2,3,4,5,6] -> 4"], "key_points": ["快慢指针", "O(n)时间O(1)空间"], "tags": ["linkedlist", "easy", "Amazon", "Facebook"]} {"problem_id": "algo_01248", "original_id": "max-depth", "title": "二叉树的最大深度", "category": "tree", "difficulty": "easy", "companies": ["Microsoft", "Apple"], "description": "给定一个二叉树 root,返回其最大深度。", "solution_python": "def maxDepth(root):\n if not root: return 0\n return max(maxDepth(root.left), maxDepth(root.right)) + 1", "solution_java": "public int maxDepth(TreeNode root) {\n if (root == null) return 0;\n return Math.max(maxDepth(root.left), maxDepth(root.right)) + 1;\n}", "solution_cpp": "int maxDepth(TreeNode* root) {\n if (!root) return 0;\n return max(maxDepth(root->left), maxDepth(root->right)) + 1;\n}", "test_cases": ["root=[3,9,20,null,null,15,7] -> 3", "root=[1,null,2] -> 2"], "key_points": ["DFS递归", "层序遍历也可"], "tags": ["tree", "easy", "Microsoft", "Apple"]} {"problem_id": "algo_01249", "original_id": "inorder-traversal", "title": "二叉树的中序遍历", "category": "tree", "difficulty": "easy", "companies": ["Google", "Microsoft"], "description": "给定一个二叉树的根节点 root,返回它的中序遍历结果。", "solution_python": "def inorderTraversal(root):\n result = []\n def dfs(node):\n if node:\n dfs(node.left)\n result.append(node.val)\n dfs(node.right)\n dfs(root)\n return result", "solution_java": "public List inorderTraversal(TreeNode root) {\n List res = new ArrayList<>();\n dfs(root, res);\n return res;\n}\nprivate void dfs(TreeNode node, List res) {\n if (node == null) return;\n dfs(node.left, res); res.add(node.val); dfs(node.right, res);\n}", "solution_cpp": "vector inorderTraversal(TreeNode* root) {\n vector res;\n dfs(root, res);\n return res;\n}\nvoid dfs(TreeNode* node, vector& res) {\n if (!node) return;\n dfs(node->left, res); res.push_back(node->val); dfs(node->right, res);\n}", "test_cases": ["root=[1,null,2,3] -> [1,3,2]", "root=[] -> []"], "key_points": ["左-根-右顺序", "递归最简洁"], "tags": ["tree", "easy", "Google", "Microsoft"]} {"problem_id": "algo_01250", "original_id": "binary-search", "title": "二分查找", "category": "binarysearch", "difficulty": "easy", "companies": ["Google", "Amazon"], "description": "给定一个 n 个元素有序的(升序)整型数组 nums 和一个目标值 target,写一个函数搜索 nums 中的 target,如果目标值存在返回下标,否则返回 -1。", "solution_python": "def search(nums, target):\n left, right = 0, len(nums) - 1\n while left <= right:\n mid = (left + right) // 2\n if nums[mid] == target: return mid\n elif nums[mid] < target: left = mid + 1\n else: right = mid - 1\n return -1", "solution_java": "public int search(int[] nums, int target) {\n int left = 0, right = nums.length - 1;\n while (left <= right) {\n int mid = left + (right - left) / 2;\n if (nums[mid] == target) return mid;\n else if (nums[mid] < target) left = mid + 1;\n else right = mid - 1;\n }\n return -1;\n}", "solution_cpp": "int search(vector& nums, int target) {\n int left = 0, right = nums.size() - 1;\n while (left <= right) {\n int mid = left + (right - left) / 2;\n if (nums[mid] == target) return mid;\n else if (nums[mid] < target) left = mid + 1;\n else right = mid - 1;\n }\n return -1;\n}", "test_cases": ["nums=[-1,0,3,5,9,12], target=9 -> 4", "nums=[-1,0,3,5,9,12], target=2 -> -1"], "key_points": ["标准模板", "注意防溢出写法"], "tags": ["binarysearch", "easy", "Google", "Amazon"]} {"problem_id": "algo_01251", "original_id": "climbing-stairs", "title": "爬楼梯", "category": "dp", "difficulty": "easy", "companies": ["Amazon", "Google"], "description": "假设你正在爬楼梯。需要 n 阶你才能到达楼顶。每次你可以爬 1 或 2 个台阶。你有多少种不同的方法可以爬到楼顶?", "solution_python": "def climbStairs(n):\n if n <= 2: return n\n a, b = 1, 2\n for _ in range(3, n+1):\n a, b = b, a + b\n return b", "solution_java": "public int climbStairs(int n) {\n if (n <= 2) return n;\n int a = 1, b = 2;\n for (int i = 3; i <= n; i++) { int temp = a + b; a = b; b = temp; }\n return b;\n}", "solution_cpp": "int climbStairs(int n) {\n if (n <= 2) return n;\n int a = 1, b = 2;\n for (int i = 3; i <= n; i++) { int temp = a + b; a = b; b = temp; }\n return b;\n}", "test_cases": ["n=2 -> 2", "n=3 -> 3", "n=5 -> 8"], "key_points": ["斐波那契数列", "滚动数组优化空间"], "tags": ["dp", "easy", "Amazon", "Google"]} {"problem_id": "algo_01252", "original_id": "coin-change", "title": "零钱兑换", "category": "dp", "difficulty": "medium", "companies": ["Google", "Amazon"], "description": "给你一个整数数组 coins 表示不同面额的硬币,以及一个整数 amount 表示总金额。计算并返回可以凑成总金额所需的最少的硬币个数。如果没有任何一种硬币组合能组成总金额,返回 -1。", "solution_python": "def coinChange(coins, amount):\n dp = [float('inf')] * (amount + 1)\n dp[0] = 0\n for coin in coins:\n for x in range(coin, amount + 1):\n dp[x] = min(dp[x], dp[x - coin] + 1)\n return dp[amount] if dp[amount] != float('inf') else -1", "solution_java": "public int coinChange(int[] coins, int amount) {\n int[] dp = new int[amount + 1];\n Arrays.fill(dp, amount + 1);\n dp[0] = 0;\n for (int coin : coins) {\n for (int x = coin; x <= amount; x++) {\n dp[x] = Math.min(dp[x], dp[x - coin] + 1);\n }\n }\n return dp[amount] > amount ? -1 : dp[amount];\n}", "solution_cpp": "int coinChange(vector& coins, int amount) {\n vector dp(amount + 1, amount + 1);\n dp[0] = 0;\n for (int coin : coins) {\n for (int x = coin; x <= amount; x++) {\n dp[x] = min(dp[x], dp[x - coin] + 1);\n }\n }\n return dp[amount] > amount ? -1 : dp[amount];\n}", "test_cases": ["coins=[1,2,5], amount=11 -> 3", "coins=[2], amount=3 -> -1"], "key_points": ["完全背包问题", "dp[x] = min(dp[x-coin]+1)"], "tags": ["dp", "medium", "Google", "Amazon"]} {"problem_id": "algo_01253", "original_id": "subsets", "title": "子集", "category": "backtracking", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "给你一个整数数组 nums ,数组中的元素 互不相同 。返回该数组所有可能的子集(幂集)。", "solution_python": "def subsets(nums):\n result = []\n def backtrack(start, path):\n result.append(path[:])\n for i in range(start, len(nums)):\n path.append(nums[i])\n backtrack(i + 1, path)\n path.pop()\n backtrack(0, [])\n return result", "solution_java": "public List> subsets(int[] nums) {\n List> result = new ArrayList<>();\n backtrack(nums, 0, new ArrayList<>(), result);\n return result;\n}\nprivate void backtrack(int[] nums, int start, List path, List> result) {\n result.add(new ArrayList<>(path));\n for (int i = start; i < nums.length; i++) {\n path.add(nums[i]);\n backtrack(nums, i + 1, path, result);\n path.remove(path.size() - 1);\n }\n}", "solution_cpp": "vector> subsets(vector& nums) {\n vector> result;\n vector path;\n backtrack(nums, 0, path, result);\n return result;\n}\nvoid backtrack(vector& nums, int start, vector& path, vector>& result) {\n result.push_back(path);\n for (int i = start; i < nums.size(); i++) {\n path.push_back(nums[i]);\n backtrack(nums, i + 1, path, result);\n path.pop_back();\n }\n}", "test_cases": ["nums=[1,2,3] -> [[],[1],[2],[1,2],[3],[1,3],[2,3],[1,2,3]]"], "key_points": ["选或不选", "DFS遍历子集树"], "tags": ["backtracking", "medium", "Google", "Microsoft"]} {"problem_id": "algo_01254", "original_id": "permutations", "title": "全排列", "category": "backtracking", "difficulty": "medium", "companies": ["Google", "Facebook"], "description": "给定一个不含重复数字的数组 nums,返回其所有可能的全排列。", "solution_python": "def permute(nums):\n result = []\n def backtrack(path, used):\n if len(path) == len(nums):\n result.append(path[:])\n return\n for i in range(len(nums)):\n if used[i]: continue\n used[i] = True\n path.append(nums[i])\n backtrack(path, used)\n path.pop()\n used[i] = False\n backtrack([], [False]*len(nums))\n return result", "solution_java": "public List> permute(int[] nums) {\n List> result = new ArrayList<>();\n boolean[] used = new boolean[nums.length];\n backtrack(nums, used, new ArrayList<>(), result);\n return result;\n}\nprivate void backtrack(int[] nums, boolean[] used, List path, List> result) {\n if (path.size() == nums.length) { result.add(new ArrayList<>(path)); return; }\n for (int i = 0; i < nums.length; i++) {\n if (used[i]) continue;\n used[i] = true;\n path.add(nums[i]);\n backtrack(nums, used, path, result);\n path.remove(path.size() - 1);\n used[i] = false;\n }\n}", "solution_cpp": "vector> permute(vector& nums) {\n vector> result;\n vector used(nums.size(), false);\n vector path;\n backtrack(nums, used, path, result);\n return result;\n}\nvoid backtrack(vector& nums, vector& used, vector& path, vector>& result) {\n if (path.size() == nums.size()) { result.push_back(path); return; }\n for (int i = 0; i < nums.size(); i++) {\n if (used[i]) continue;\n used[i] = true;\n path.push_back(nums[i]);\n backtrack(nums, used, path, result);\n path.pop_back();\n used[i] = false;\n }\n}", "test_cases": ["nums=[1,2,3] -> [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]"], "key_points": ["标记已使用元素", "回溯经典模板"], "tags": ["backtracking", "medium", "Google", "Facebook"]} {"problem_id": "algo_01255", "original_id": "top-k-frequent", "title": "前K个高频元素", "category": "heap", "difficulty": "medium", "companies": ["Amazon", "Facebook"], "description": "给你一个整数数组 nums 和一个整数 k,请你返回其中出现频率前 k 高的元素。", "solution_python": "import heapq\nfrom collections import Counter\ndef topKFrequent(nums, k):\n count = Counter(nums)\n heap = []\n for num, freq in count.items():\n heapq.heappush(heap, (freq, num))\n if len(heap) > k: heapq.heappop(heap)\n return [num for freq, num in heap]", "solution_java": "public int[] topKFrequent(int[] nums, int k) {\n Map count = new HashMap<>();\n for (int n : nums) count.put(n, count.getOrDefault(n, 0) + 1);\n PriorityQueue> heap = \n new PriorityQueue<>((a, b) -> a.getValue() - b.getValue());\n for (Map.Entry e : count.entrySet()) {\n heap.offer(e);\n if (heap.size() > k) heap.poll();\n }\n int[] res = new int[k];\n for (int i = k - 1; i >= 0; i--) res[i] = heap.poll().getKey();\n return res;\n}", "solution_cpp": "vector topKFrequent(vector& nums, int k) {\n unordered_map count;\n for (int n : nums) count[n]++;\n priority_queue, vector>, greater>> heap;\n for (auto& [num, freq] : count) {\n heap.push({freq, num});\n if (heap.size() > k) heap.pop();\n }\n vector res;\n while (!heap.empty()) { res.push_back(heap.top().second); heap.pop(); }\n reverse(res.begin(), res.end());\n return res;\n}", "test_cases": ["nums=[1,1,1,2,2,3], k=2 -> [1,2]", "nums=[1], k=1 -> [1]"], "key_points": ["小顶堆保持大小k", "时间复杂度O(nlogk)"], "tags": ["heap", "medium", "Amazon", "Facebook"]} {"problem_id": "algo_01256", "original_id": "3sum", "title": "三数之和", "category": "two-pointers", "difficulty": "medium", "companies": ["Google", "Amazon"], "description": "给你一个整数数组 nums,判断是否存在三元组满足和为0,返回所有不重复的三元组。", "solution_python": "def threeSum(nums):\n nums.sort()\n result = []\n for i in range(len(nums) - 2):\n if i > 0 and nums[i] == nums[i-1]: continue\n left, right = i + 1, len(nums) - 1\n while left < right:\n total = nums[i] + nums[left] + nums[right]\n if total < 0: left += 1\n elif total > 0: right -= 1\n else:\n result.append([nums[i], nums[left], nums[right]])\n while left < right and nums[left] == nums[left+1]: left += 1\n while left < right and nums[right] == nums[right-1]: right -= 1\n left += 1; right -= 1\n return result", "solution_java": "public List> threeSum(int[] nums) {\n Arrays.sort(nums);\n List> result = new ArrayList<>();\n for (int i = 0; i < nums.length - 2; i++) {\n if (i > 0 && nums[i] == nums[i-1]) continue;\n int left = i + 1, right = nums.length - 1;\n while (left < right) {\n int total = nums[i] + nums[left] + nums[right];\n if (total < 0) left++;\n else if (total > 0) right--;\n else {\n result.add(Arrays.asList(nums[i], nums[left], nums[right]));\n while (left < right && nums[left] == nums[left+1]) left++;\n while (left < right && nums[right] == nums[right-1]) right--;\n left++; right--;\n }\n }\n }\n return result;\n}", "solution_cpp": "vector> threeSum(vector& nums) {\n sort(nums.begin(), nums.end());\n vector> result;\n for (int i = 0; i < nums.size() - 2; i++) {\n if (i > 0 && nums[i] == nums[i-1]) continue;\n int left = i + 1, right = nums.size() - 1;\n while (left < right) {\n int total = nums[i] + nums[left] + nums[right];\n if (total < 0) left++;\n else if (total > 0) right--;\n else {\n result.push_back({nums[i], nums[left], nums[right]});\n while (left < right && nums[left] == nums[left+1]) left++;\n while (left < right && nums[right] == nums[right-1]) right--;\n left++; right--;\n }\n }\n }\n return result;\n}", "test_cases": ["nums=[-1,0,1,2,-1,-4] -> [[-1,-1,2],[-1,0,1]]"], "key_points": ["排序+双指针", "去重是关键"], "tags": ["two-pointers", "medium", "Google", "Amazon"]} {"problem_id": "algo_01257", "original_id": "container-water", "title": "盛最多水的容器", "category": "two-pointers", "difficulty": "medium", "companies": ["Google", "Uber"], "description": "给定一个长度为 n 的整数数组 height,找出其中的两条线,使得它们与 x 轴共同构成的容器可以容纳最多的水。", "solution_python": "def maxArea(height):\n left, right = 0, len(height) - 1\n max_area = 0\n while left < right:\n h = min(height[left], height[right])\n max_area = max(max_area, h * (right - left))\n if height[left] < height[right]: left += 1\n else: right -= 1\n return max_area", "solution_java": "public int maxArea(int[] height) {\n int left = 0, right = height.length - 1, maxArea = 0;\n while (left < right) {\n int h = Math.min(height[left], height[right]);\n maxArea = Math.max(maxArea, h * (right - left));\n if (height[left] < height[right]) left++;\n else right--;\n }\n return maxArea;\n}", "solution_cpp": "int maxArea(vector& height) {\n int left = 0, right = height.size() - 1, maxArea = 0;\n while (left < right) {\n int h = min(height[left], height[right]);\n maxArea = max(maxArea, h * (right - left));\n if (height[left] < height[right]) left++;\n else right--;\n }\n return maxArea;\n}", "test_cases": ["height=[1,8,6,2,5,4,8,3,7] -> 49"], "key_points": ["移动短边指针", "面积=min(h1,h2)*width"], "tags": ["two-pointers", "medium", "Google", "Uber"]} {"problem_id": "algo_01258", "original_id": "min-stack", "title": "最小栈", "category": "stack", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "设计一个支持 push,pop,top 操作,并能在常数时间内检索到最小元素的栈。", "solution_python": "class MinStack:\n def __init__(self):\n self.stack = []\n self.min_stack = []\n def push(self, val):\n self.stack.append(val)\n self.min_stack.append(min(val, self.min_stack[-1] if self.min_stack else val))\n def pop(self):\n self.stack.pop(); self.min_stack.pop()\n def top(self): return self.stack[-1]\n def getMin(self): return self.min_stack[-1]", "solution_java": "class MinStack {\n Stack stack = new Stack<>();\n Stack minStack = new Stack<>();\n public void push(int val) { stack.push(val); minStack.push(Math.min(val, minStack.isEmpty() ? val : minStack.peek())); }\n public void pop() { stack.pop(); minStack.pop(); }\n public int top() { return stack.peek(); }\n public int getMin() { return minStack.peek(); }\n}", "solution_cpp": "class MinStack {\n stack st, minSt;\npublic:\n void push(int val) { st.push(val); minSt.push(min(val, minSt.empty() ? val : minSt.top())); }\n void pop() { st.pop(); minSt.pop(); }\n int top() { return st.top(); }\n int getMin() { return minSt.top(); }\n};", "test_cases": ["push(-2), push(0), push(-3) -> getMin() returns -3"], "key_points": ["辅助栈记录最小值", "O(1)时间获取最小值"], "tags": ["stack", "medium", "Google", "Microsoft"]} {"problem_id": "algo_01259", "original_id": "lru-cache", "title": "LRU缓存", "category": "design", "difficulty": "hard", "companies": ["Google", "Amazon"], "description": "设计和实现一个 LRU(最近最少使用)缓存机制。", "solution_python": "class LRUCache:\n def __init__(self, capacity):\n self.capacity = capacity\n self.cache = {}\n self.order = []\n def get(self, key):\n if key not in self.cache: return -1\n self.order.remove(key); self.order.append(key)\n return self.cache[key]\n def put(self, key, value):\n if key in self.cache:\n self.order.remove(key)\n elif len(self.cache) >= self.capacity:\n del self.cache[self.order.pop(0)]\n self.cache[key] = value; self.order.append(key)", "solution_java": "class LRUCache {\n int capacity;\n LinkedHashMap cache = new LinkedHashMap<>();\n public LRUCache(int cap) { capacity = cap; }\n public int get(int key) { return cache.containsKey(key) ? cache.remove(key) : -1; }\n public void put(int key, int val) {\n if (cache.containsKey(key)) cache.remove(key);\n else if (cache.size() >= capacity) cache.remove(cache.keySet().iterator().next());\n cache.put(key, val);\n }\n}", "solution_cpp": "class LRUCache {\n int cap;\n list> dll;\n unordered_map>::iterator> cache;\npublic:\n LRUCache(int capacity) : cap(capacity) {}\n int get(int key) {\n auto it = cache.find(key);\n if (it == cache.end()) return -1;\n dll.splice(dll.end(), dll, it->second);\n return it->second->second;\n }\n void put(int key, int value) {\n auto it = cache.find(key);\n if (it != cache.end()) dll.erase(it->second);\n else if (cache.size() >= cap) { cache.erase(dll.front().first); dll.pop_front(); }\n dll.push_back({key, value});\n cache[key] = --dll.end();\n }\n};", "test_cases": ["put(1,1), put(2,2), get(1) -> 1"], "key_points": ["HashMap + 双向链表", "O(1)时间操作"], "tags": ["design", "hard", "Google", "Amazon"]} {"problem_id": "algo_01260", "original_id": "num-islands", "title": "岛屿数量", "category": "graph", "difficulty": "medium", "companies": ["Google", "Facebook"], "description": "给你一个由 '1'(陆地)和 '0'(水)组成的二维网格,请你计算网格中岛屿的数量。岛屿总是被水包围,且只能由水平或垂直方向相邻的陆地连接形成。", "solution_python": "def numIslands(grid):\n if not grid: return 0\n rows, cols = len(grid), len(grid[0])\n count = 0\n def dfs(r, c):\n if r < 0 or r >= rows or c < 0 or c >= cols or grid[r][c] != '1': return\n grid[r][c] = '0'\n dfs(r+1, c); dfs(r-1, c); dfs(r, c+1); dfs(r, c-1)\n for r in range(rows):\n for c in range(cols):\n if grid[r][c] == '1': count += 1; dfs(r, c)\n return count", "solution_java": "public int numIslands(char[][] grid) {\n if (grid.length == 0) return 0;\n int count = 0;\n for (int i = 0; i < grid.length; i++)\n for (int j = 0; j < grid[0].length; j++)\n if (grid[i][j] == '1') { count++; dfs(grid, i, j); }\n return count;\n}\nprivate void dfs(char[][] grid, int r, int c) {\n if (r < 0 || r >= grid.length || c < 0 || c >= grid[0].length || grid[r][c] != '1') return;\n grid[r][c] = '0';\n dfs(grid, r+1, c); dfs(grid, r-1, c); dfs(grid, r, c+1); dfs(grid, r, c-1);\n}", "solution_cpp": "int numIslands(vector>& grid) {\n if (grid.empty()) return 0;\n int count = 0;\n for (int i = 0; i < grid.size(); i++)\n for (int j = 0; j < grid[0].size(); j++)\n if (grid[i][j] == '1') { count++; dfs(grid, i, j); }\n return count;\n}\nvoid dfs(vector>& grid, int r, int c) {\n if (r < 0 || r >= grid.size() || c < 0 || c >= grid[0].size() || grid[r][c] != '1') return;\n grid[r][c] = '0';\n dfs(grid, r+1, c); dfs(grid, r-1, c); dfs(grid, r, c+1); dfs(grid, r, c-1);\n}", "test_cases": ["grid=[[1,1,1,1,0],[1,1,0,1,0],[1,1,0,0,0],[0,0,0,0,0]] -> 1"], "key_points": ["DFS/BFS遍历", "访问后标记为0避免重复"], "tags": ["graph", "medium", "Google", "Facebook"]} {"problem_id": "algo_01261", "original_id": "two-sum", "title": "两数之和", "category": "array", "difficulty": "easy", "companies": ["Amazon", "Google"], "description": "给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那两个整数,并返回他们的数组下标。", "solution_python": "def twoSum(nums, target):\n hashmap = {}\n for i, num in enumerate(nums):\n complement = target - num\n if complement in hashmap:\n return [hashmap[complement], i]\n hashmap[num] = i\n return []", "solution_java": "public int[] twoSum(int[] nums, int target) {\n Map map = new HashMap<>();\n for (int i = 0; i < nums.length; i++) {\n int complement = target - nums[i];\n if (map.containsKey(complement)) return new int[]{map.get(complement), i};\n map.put(nums[i], i);\n }\n return new int[]{};\n}", "solution_cpp": "vector twoSum(vector& nums, int target) {\n unordered_map m;\n for (int i = 0; i < nums.size(); i++) {\n if (m.count(target - nums[i])) return {m[target - nums[i]], i};\n m[nums[i]] = i;\n }\n return {};\n}", "test_cases": ["nums=[2,7,11,15], target=9 -> [0,1]", "nums=[3,2,4], target=6 -> [1,2]"], "key_points": ["哈希表一次遍历", "空间换时间"], "tags": ["array", "easy", "Amazon", "Google"]} {"problem_id": "algo_01262", "original_id": "merge-sorted", "title": "合并两个有序数组", "category": "array", "difficulty": "easy", "companies": ["Microsoft", "Uber"], "description": "给你两个按非递减顺序排列的整数数组 nums1 和 nums2,另有两个整数 m 和 n,分别表示 nums1 和 nums2 中的元素数目。请你合并 nums2 到 nums1 中。", "solution_python": "def merge(nums1, m, nums2, n):\n p1, p2, p = m-1, n-1, m+n-1\n while p1 >= 0 and p2 >= 0:\n if nums1[p1] > nums2[p2]: nums1[p] = nums1[p1]; p1 -= 1\n else: nums1[p] = nums2[p2]; p2 -= 1\n p -= 1\n while p2 >= 0: nums1[p] = nums2[p2]; p2 -= 1; p -= 1", "solution_java": "public void merge(int[] nums1, int m, int[] nums2, int n) {\n int p1 = m-1, p2 = n-1, p = m+n-1;\n while (p1 >= 0 && p2 >= 0) {\n nums1[p--] = nums1[p1] > nums2[p2] ? nums1[p1--] : nums2[p2--];\n }\n while (p2 >= 0) nums1[p--] = nums2[p2--];\n}", "solution_cpp": "void merge(vector& nums1, int m, vector& nums2, int n) {\n int p1 = m-1, p2 = n-1, p = m+n-1;\n while (p1 >= 0 && p2 >= 0) nums1[p--] = nums1[p1] > nums2[p2] ? nums1[p1--] : nums2[p2--];\n while (p2 >= 0) nums1[p--] = nums2[p2--];\n}", "test_cases": ["nums1=[1,2,3], m=3, nums2=[2,5,6], n=3 -> [1,2,2,3,5,6]", "nums1=[], m=0, nums2=[1], n=1 -> [1]"], "key_points": ["从后往前合并", "三指针技巧"], "tags": ["array", "easy", "Microsoft", "Uber"]} {"problem_id": "algo_01263", "original_id": "max-subarray", "title": "最大子数组和", "category": "array", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "给你一个整数数组 nums ,请你找出一个具有最大和的连续子数组,返回其最大和。", "solution_python": "def maxSubArray(nums):\n max_sum = current = nums[0]\n for num in nums[1:]:\n current = max(num, current + num)\n max_sum = max(max_sum, current)\n return max_sum", "solution_java": "public int maxSubArray(int[] nums) {\n int maxSum = nums[0], curr = nums[0];\n for (int i = 1; i < nums.length; i++) {\n curr = Math.max(nums[i], curr + nums[i]);\n maxSum = Math.max(maxSum, curr);\n }\n return maxSum;\n}", "solution_cpp": "int maxSubArray(vector& nums) {\n int maxSum = nums[0], curr = nums[0];\n for (int i = 1; i < nums.size(); i++) {\n curr = max(nums[i], curr + nums[i]);\n maxSum = max(maxSum, curr);\n }\n return maxSum;\n}", "test_cases": ["nums=[-2,1,-3,4,-1,2,1,-5,4] -> 6", "nums=[1] -> 1"], "key_points": ["Kadane算法", "动态规划基础题"], "tags": ["array", "medium", "Google", "Microsoft"]} {"problem_id": "algo_01264", "original_id": "valid-parentheses", "title": "有效的括号", "category": "string", "difficulty": "easy", "companies": ["Google", "Uber"], "description": "给定一个只包括 '(',')','{','}','[',']' 的字符串 s,判断字符串是否有效。", "solution_python": "def isValid(s):\n stack = []\n mapping = {')': '(', ']': '[', '}': '{'}\n for c in s:\n if c in mapping:\n if not stack or stack[-1] != mapping[c]: return False\n stack.pop()\n else: stack.append(c)\n return not stack", "solution_java": "public boolean isValid(String s) {\n Stack stack = new Stack<>();\n Map map = Map.of(')', '(', ']', '[', '}', '{');\n for (char c : s.toCharArray()) {\n if (map.containsValue(c)) stack.push(c);\n else if (!stack.isEmpty() && stack.pop() != map.get(c)) return false;\n }\n return stack.isEmpty();\n}", "solution_cpp": "bool isValid(string s) {\n stack st;\n unordered_map m = {{')','('},{']','['},{'}','{'}};\n for (char c : s) {\n if (m.find(c) == m.end()) st.push(c);\n else if (st.empty() || st.top() != m[c]) return false;\n else st.pop();\n }\n return st.empty();\n}", "test_cases": ["s=\"()\" -> true", "s=\"()[]{}\" -> true", "s=\"(]\" -> false"], "key_points": ["栈匹配法", "注意空栈边界"], "tags": ["string", "easy", "Google", "Uber"]} {"problem_id": "algo_01265", "original_id": "longest-palindrome", "title": "最长回文子串", "category": "string", "difficulty": "medium", "companies": ["Google", "Amazon"], "description": "给你一个字符串 s,找到 s 中最长的回文子串。", "solution_python": "def longestPalindrome(s):\n def expand(l, r):\n while l >= 0 and r < len(s) and s[l] == s[r]: l -= 1; r += 1\n return l + 1, r - 1\n start = end = 0\n for i in range(len(s)):\n l1, r1 = expand(i, i)\n l2, r2 = expand(i, i + 1)\n if r1 - l1 > end - start: start, end = l1, r1\n if r2 - l2 > end - start: start, end = l2, r2\n return s[start:end+1]", "solution_java": "public String longestPalindrome(String s) {\n int start = 0, end = 0;\n for (int i = 0; i < s.length(); i++) {\n int len1 = expand(s, i, i), len2 = expand(s, i, i+1);\n int len = Math.max(len1, len2);\n if (len > end - start) { start = i - (len-1)/2; end = i + len/2; }\n }\n return s.substring(start, end + 1);\n}\nprivate int expand(String s, int l, int r) {\n while (l >= 0 && r < s.length() && s.charAt(l) == s.charAt(r)) { l--; r++; }\n return r - l - 1;\n}", "solution_cpp": "string longestPalindrome(string s) {\n int start = 0, end = 0;\n for (int i = 0; i < s.size(); i++) {\n int len1 = expand(s, i, i), len2 = expand(s, i, i+1);\n if (max(len1, len2) > end - start) { start = i - (max(len1,len2)-1)/2; end = i + max(len1,len2)/2; }\n }\n return s.substr(start, end - start + 1);\n}", "test_cases": ["s=\"babad\" -> bab或aba", "s=\"cbbd\" -> bb"], "key_points": ["中心扩展法", "处理奇偶长度"], "tags": ["string", "medium", "Google", "Amazon"]} {"problem_id": "algo_01266", "original_id": "reverse-list", "title": "反转链表", "category": "linkedlist", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "给你单链表的头节点 head,请你反转链表,并返回反转后的链表。", "solution_python": "def reverseList(head):\n prev = None\n curr = head\n while curr:\n nxt = curr.next\n curr.next = prev\n prev = curr\n curr = nxt\n return prev", "solution_java": "public ListNode reverseList(ListNode head) {\n ListNode prev = null, curr = head;\n while (curr != null) {\n ListNode next = curr.next;\n curr.next = prev;\n prev = curr;\n curr = next;\n }\n return prev;\n}", "solution_cpp": "ListNode* reverseList(ListNode* head) {\n ListNode* prev = nullptr, *curr = head;\n while (curr) {\n ListNode* next = curr->next;\n curr->next = prev;\n prev = curr;\n curr = next;\n }\n return prev;\n}", "test_cases": ["head=[1,2,3,4,5] -> [5,4,3,2,1]", "head=[1,2] -> [2,1]"], "key_points": ["迭代法 O(1)空间", "递归法 O(n)空间"], "tags": ["linkedlist", "medium", "Google", "Microsoft"]} {"problem_id": "algo_01267", "original_id": "middle-node", "title": "链表的中间结点", "category": "linkedlist", "difficulty": "easy", "companies": ["Amazon", "Facebook"], "description": "给你单链表的头节点 head,请你找出并返回链表的中间结点。如果有两个中间结点,则返回第二个中间结点。", "solution_python": "def middleNode(head):\n slow = fast = head\n while fast and fast.next:\n slow = slow.next\n fast = fast.next.next\n return slow", "solution_java": "public ListNode middleNode(ListNode head) {\n ListNode slow = head, fast = head;\n while (fast != null && fast.next != null) {\n slow = slow.next;\n fast = fast.next.next;\n }\n return slow;\n}", "solution_cpp": "ListNode* middleNode(ListNode* head) {\n ListNode* slow = head, *fast = head;\n while (fast && fast->next) { slow = slow->next; fast = fast->next->next; }\n return slow;\n}", "test_cases": ["head=[1,2,3,4,5] -> 3", "head=[1,2,3,4,5,6] -> 4"], "key_points": ["快慢指针", "O(n)时间O(1)空间"], "tags": ["linkedlist", "easy", "Amazon", "Facebook"]} {"problem_id": "algo_01268", "original_id": "max-depth", "title": "二叉树的最大深度", "category": "tree", "difficulty": "easy", "companies": ["Microsoft", "Apple"], "description": "给定一个二叉树 root,返回其最大深度。", "solution_python": "def maxDepth(root):\n if not root: return 0\n return max(maxDepth(root.left), maxDepth(root.right)) + 1", "solution_java": "public int maxDepth(TreeNode root) {\n if (root == null) return 0;\n return Math.max(maxDepth(root.left), maxDepth(root.right)) + 1;\n}", "solution_cpp": "int maxDepth(TreeNode* root) {\n if (!root) return 0;\n return max(maxDepth(root->left), maxDepth(root->right)) + 1;\n}", "test_cases": ["root=[3,9,20,null,null,15,7] -> 3", "root=[1,null,2] -> 2"], "key_points": ["DFS递归", "层序遍历也可"], "tags": ["tree", "easy", "Microsoft", "Apple"]} {"problem_id": "algo_01269", "original_id": "inorder-traversal", "title": "二叉树的中序遍历", "category": "tree", "difficulty": "easy", "companies": ["Google", "Microsoft"], "description": "给定一个二叉树的根节点 root,返回它的中序遍历结果。", "solution_python": "def inorderTraversal(root):\n result = []\n def dfs(node):\n if node:\n dfs(node.left)\n result.append(node.val)\n dfs(node.right)\n dfs(root)\n return result", "solution_java": "public List inorderTraversal(TreeNode root) {\n List res = new ArrayList<>();\n dfs(root, res);\n return res;\n}\nprivate void dfs(TreeNode node, List res) {\n if (node == null) return;\n dfs(node.left, res); res.add(node.val); dfs(node.right, res);\n}", "solution_cpp": "vector inorderTraversal(TreeNode* root) {\n vector res;\n dfs(root, res);\n return res;\n}\nvoid dfs(TreeNode* node, vector& res) {\n if (!node) return;\n dfs(node->left, res); res.push_back(node->val); dfs(node->right, res);\n}", "test_cases": ["root=[1,null,2,3] -> [1,3,2]", "root=[] -> []"], "key_points": ["左-根-右顺序", "递归最简洁"], "tags": ["tree", "easy", "Google", "Microsoft"]} {"problem_id": "algo_01270", "original_id": "binary-search", "title": "二分查找", "category": "binarysearch", "difficulty": "easy", "companies": ["Google", "Amazon"], "description": "给定一个 n 个元素有序的(升序)整型数组 nums 和一个目标值 target,写一个函数搜索 nums 中的 target,如果目标值存在返回下标,否则返回 -1。", "solution_python": "def search(nums, target):\n left, right = 0, len(nums) - 1\n while left <= right:\n mid = (left + right) // 2\n if nums[mid] == target: return mid\n elif nums[mid] < target: left = mid + 1\n else: right = mid - 1\n return -1", "solution_java": "public int search(int[] nums, int target) {\n int left = 0, right = nums.length - 1;\n while (left <= right) {\n int mid = left + (right - left) / 2;\n if (nums[mid] == target) return mid;\n else if (nums[mid] < target) left = mid + 1;\n else right = mid - 1;\n }\n return -1;\n}", "solution_cpp": "int search(vector& nums, int target) {\n int left = 0, right = nums.size() - 1;\n while (left <= right) {\n int mid = left + (right - left) / 2;\n if (nums[mid] == target) return mid;\n else if (nums[mid] < target) left = mid + 1;\n else right = mid - 1;\n }\n return -1;\n}", "test_cases": ["nums=[-1,0,3,5,9,12], target=9 -> 4", "nums=[-1,0,3,5,9,12], target=2 -> -1"], "key_points": ["标准模板", "注意防溢出写法"], "tags": ["binarysearch", "easy", "Google", "Amazon"]} {"problem_id": "algo_01271", "original_id": "climbing-stairs", "title": "爬楼梯", "category": "dp", "difficulty": "easy", "companies": ["Amazon", "Google"], "description": "假设你正在爬楼梯。需要 n 阶你才能到达楼顶。每次你可以爬 1 或 2 个台阶。你有多少种不同的方法可以爬到楼顶?", "solution_python": "def climbStairs(n):\n if n <= 2: return n\n a, b = 1, 2\n for _ in range(3, n+1):\n a, b = b, a + b\n return b", "solution_java": "public int climbStairs(int n) {\n if (n <= 2) return n;\n int a = 1, b = 2;\n for (int i = 3; i <= n; i++) { int temp = a + b; a = b; b = temp; }\n return b;\n}", "solution_cpp": "int climbStairs(int n) {\n if (n <= 2) return n;\n int a = 1, b = 2;\n for (int i = 3; i <= n; i++) { int temp = a + b; a = b; b = temp; }\n return b;\n}", "test_cases": ["n=2 -> 2", "n=3 -> 3", "n=5 -> 8"], "key_points": ["斐波那契数列", "滚动数组优化空间"], "tags": ["dp", "easy", "Amazon", "Google"]} {"problem_id": "algo_01272", "original_id": "coin-change", "title": "零钱兑换", "category": "dp", "difficulty": "medium", "companies": ["Google", "Amazon"], "description": "给你一个整数数组 coins 表示不同面额的硬币,以及一个整数 amount 表示总金额。计算并返回可以凑成总金额所需的最少的硬币个数。如果没有任何一种硬币组合能组成总金额,返回 -1。", "solution_python": "def coinChange(coins, amount):\n dp = [float('inf')] * (amount + 1)\n dp[0] = 0\n for coin in coins:\n for x in range(coin, amount + 1):\n dp[x] = min(dp[x], dp[x - coin] + 1)\n return dp[amount] if dp[amount] != float('inf') else -1", "solution_java": "public int coinChange(int[] coins, int amount) {\n int[] dp = new int[amount + 1];\n Arrays.fill(dp, amount + 1);\n dp[0] = 0;\n for (int coin : coins) {\n for (int x = coin; x <= amount; x++) {\n dp[x] = Math.min(dp[x], dp[x - coin] + 1);\n }\n }\n return dp[amount] > amount ? -1 : dp[amount];\n}", "solution_cpp": "int coinChange(vector& coins, int amount) {\n vector dp(amount + 1, amount + 1);\n dp[0] = 0;\n for (int coin : coins) {\n for (int x = coin; x <= amount; x++) {\n dp[x] = min(dp[x], dp[x - coin] + 1);\n }\n }\n return dp[amount] > amount ? -1 : dp[amount];\n}", "test_cases": ["coins=[1,2,5], amount=11 -> 3", "coins=[2], amount=3 -> -1"], "key_points": ["完全背包问题", "dp[x] = min(dp[x-coin]+1)"], "tags": ["dp", "medium", "Google", "Amazon"]} {"problem_id": "algo_01273", "original_id": "subsets", "title": "子集", "category": "backtracking", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "给你一个整数数组 nums ,数组中的元素 互不相同 。返回该数组所有可能的子集(幂集)。", "solution_python": "def subsets(nums):\n result = []\n def backtrack(start, path):\n result.append(path[:])\n for i in range(start, len(nums)):\n path.append(nums[i])\n backtrack(i + 1, path)\n path.pop()\n backtrack(0, [])\n return result", "solution_java": "public List> subsets(int[] nums) {\n List> result = new ArrayList<>();\n backtrack(nums, 0, new ArrayList<>(), result);\n return result;\n}\nprivate void backtrack(int[] nums, int start, List path, List> result) {\n result.add(new ArrayList<>(path));\n for (int i = start; i < nums.length; i++) {\n path.add(nums[i]);\n backtrack(nums, i + 1, path, result);\n path.remove(path.size() - 1);\n }\n}", "solution_cpp": "vector> subsets(vector& nums) {\n vector> result;\n vector path;\n backtrack(nums, 0, path, result);\n return result;\n}\nvoid backtrack(vector& nums, int start, vector& path, vector>& result) {\n result.push_back(path);\n for (int i = start; i < nums.size(); i++) {\n path.push_back(nums[i]);\n backtrack(nums, i + 1, path, result);\n path.pop_back();\n }\n}", "test_cases": ["nums=[1,2,3] -> [[],[1],[2],[1,2],[3],[1,3],[2,3],[1,2,3]]"], "key_points": ["选或不选", "DFS遍历子集树"], "tags": ["backtracking", "medium", "Google", "Microsoft"]} {"problem_id": "algo_01274", "original_id": "permutations", "title": "全排列", "category": "backtracking", "difficulty": "medium", "companies": ["Google", "Facebook"], "description": "给定一个不含重复数字的数组 nums,返回其所有可能的全排列。", "solution_python": "def permute(nums):\n result = []\n def backtrack(path, used):\n if len(path) == len(nums):\n result.append(path[:])\n return\n for i in range(len(nums)):\n if used[i]: continue\n used[i] = True\n path.append(nums[i])\n backtrack(path, used)\n path.pop()\n used[i] = False\n backtrack([], [False]*len(nums))\n return result", "solution_java": "public List> permute(int[] nums) {\n List> result = new ArrayList<>();\n boolean[] used = new boolean[nums.length];\n backtrack(nums, used, new ArrayList<>(), result);\n return result;\n}\nprivate void backtrack(int[] nums, boolean[] used, List path, List> result) {\n if (path.size() == nums.length) { result.add(new ArrayList<>(path)); return; }\n for (int i = 0; i < nums.length; i++) {\n if (used[i]) continue;\n used[i] = true;\n path.add(nums[i]);\n backtrack(nums, used, path, result);\n path.remove(path.size() - 1);\n used[i] = false;\n }\n}", "solution_cpp": "vector> permute(vector& nums) {\n vector> result;\n vector used(nums.size(), false);\n vector path;\n backtrack(nums, used, path, result);\n return result;\n}\nvoid backtrack(vector& nums, vector& used, vector& path, vector>& result) {\n if (path.size() == nums.size()) { result.push_back(path); return; }\n for (int i = 0; i < nums.size(); i++) {\n if (used[i]) continue;\n used[i] = true;\n path.push_back(nums[i]);\n backtrack(nums, used, path, result);\n path.pop_back();\n used[i] = false;\n }\n}", "test_cases": ["nums=[1,2,3] -> [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]"], "key_points": ["标记已使用元素", "回溯经典模板"], "tags": ["backtracking", "medium", "Google", "Facebook"]} {"problem_id": "algo_01275", "original_id": "top-k-frequent", "title": "前K个高频元素", "category": "heap", "difficulty": "medium", "companies": ["Amazon", "Facebook"], "description": "给你一个整数数组 nums 和一个整数 k,请你返回其中出现频率前 k 高的元素。", "solution_python": "import heapq\nfrom collections import Counter\ndef topKFrequent(nums, k):\n count = Counter(nums)\n heap = []\n for num, freq in count.items():\n heapq.heappush(heap, (freq, num))\n if len(heap) > k: heapq.heappop(heap)\n return [num for freq, num in heap]", "solution_java": "public int[] topKFrequent(int[] nums, int k) {\n Map count = new HashMap<>();\n for (int n : nums) count.put(n, count.getOrDefault(n, 0) + 1);\n PriorityQueue> heap = \n new PriorityQueue<>((a, b) -> a.getValue() - b.getValue());\n for (Map.Entry e : count.entrySet()) {\n heap.offer(e);\n if (heap.size() > k) heap.poll();\n }\n int[] res = new int[k];\n for (int i = k - 1; i >= 0; i--) res[i] = heap.poll().getKey();\n return res;\n}", "solution_cpp": "vector topKFrequent(vector& nums, int k) {\n unordered_map count;\n for (int n : nums) count[n]++;\n priority_queue, vector>, greater>> heap;\n for (auto& [num, freq] : count) {\n heap.push({freq, num});\n if (heap.size() > k) heap.pop();\n }\n vector res;\n while (!heap.empty()) { res.push_back(heap.top().second); heap.pop(); }\n reverse(res.begin(), res.end());\n return res;\n}", "test_cases": ["nums=[1,1,1,2,2,3], k=2 -> [1,2]", "nums=[1], k=1 -> [1]"], "key_points": ["小顶堆保持大小k", "时间复杂度O(nlogk)"], "tags": ["heap", "medium", "Amazon", "Facebook"]} {"problem_id": "algo_01276", "original_id": "3sum", "title": "三数之和", "category": "two-pointers", "difficulty": "medium", "companies": ["Google", "Amazon"], "description": "给你一个整数数组 nums,判断是否存在三元组满足和为0,返回所有不重复的三元组。", "solution_python": "def threeSum(nums):\n nums.sort()\n result = []\n for i in range(len(nums) - 2):\n if i > 0 and nums[i] == nums[i-1]: continue\n left, right = i + 1, len(nums) - 1\n while left < right:\n total = nums[i] + nums[left] + nums[right]\n if total < 0: left += 1\n elif total > 0: right -= 1\n else:\n result.append([nums[i], nums[left], nums[right]])\n while left < right and nums[left] == nums[left+1]: left += 1\n while left < right and nums[right] == nums[right-1]: right -= 1\n left += 1; right -= 1\n return result", "solution_java": "public List> threeSum(int[] nums) {\n Arrays.sort(nums);\n List> result = new ArrayList<>();\n for (int i = 0; i < nums.length - 2; i++) {\n if (i > 0 && nums[i] == nums[i-1]) continue;\n int left = i + 1, right = nums.length - 1;\n while (left < right) {\n int total = nums[i] + nums[left] + nums[right];\n if (total < 0) left++;\n else if (total > 0) right--;\n else {\n result.add(Arrays.asList(nums[i], nums[left], nums[right]));\n while (left < right && nums[left] == nums[left+1]) left++;\n while (left < right && nums[right] == nums[right-1]) right--;\n left++; right--;\n }\n }\n }\n return result;\n}", "solution_cpp": "vector> threeSum(vector& nums) {\n sort(nums.begin(), nums.end());\n vector> result;\n for (int i = 0; i < nums.size() - 2; i++) {\n if (i > 0 && nums[i] == nums[i-1]) continue;\n int left = i + 1, right = nums.size() - 1;\n while (left < right) {\n int total = nums[i] + nums[left] + nums[right];\n if (total < 0) left++;\n else if (total > 0) right--;\n else {\n result.push_back({nums[i], nums[left], nums[right]});\n while (left < right && nums[left] == nums[left+1]) left++;\n while (left < right && nums[right] == nums[right-1]) right--;\n left++; right--;\n }\n }\n }\n return result;\n}", "test_cases": ["nums=[-1,0,1,2,-1,-4] -> [[-1,-1,2],[-1,0,1]]"], "key_points": ["排序+双指针", "去重是关键"], "tags": ["two-pointers", "medium", "Google", "Amazon"]} {"problem_id": "algo_01277", "original_id": "container-water", "title": "盛最多水的容器", "category": "two-pointers", "difficulty": "medium", "companies": ["Google", "Uber"], "description": "给定一个长度为 n 的整数数组 height,找出其中的两条线,使得它们与 x 轴共同构成的容器可以容纳最多的水。", "solution_python": "def maxArea(height):\n left, right = 0, len(height) - 1\n max_area = 0\n while left < right:\n h = min(height[left], height[right])\n max_area = max(max_area, h * (right - left))\n if height[left] < height[right]: left += 1\n else: right -= 1\n return max_area", "solution_java": "public int maxArea(int[] height) {\n int left = 0, right = height.length - 1, maxArea = 0;\n while (left < right) {\n int h = Math.min(height[left], height[right]);\n maxArea = Math.max(maxArea, h * (right - left));\n if (height[left] < height[right]) left++;\n else right--;\n }\n return maxArea;\n}", "solution_cpp": "int maxArea(vector& height) {\n int left = 0, right = height.size() - 1, maxArea = 0;\n while (left < right) {\n int h = min(height[left], height[right]);\n maxArea = max(maxArea, h * (right - left));\n if (height[left] < height[right]) left++;\n else right--;\n }\n return maxArea;\n}", "test_cases": ["height=[1,8,6,2,5,4,8,3,7] -> 49"], "key_points": ["移动短边指针", "面积=min(h1,h2)*width"], "tags": ["two-pointers", "medium", "Google", "Uber"]} {"problem_id": "algo_01278", "original_id": "min-stack", "title": "最小栈", "category": "stack", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "设计一个支持 push,pop,top 操作,并能在常数时间内检索到最小元素的栈。", "solution_python": "class MinStack:\n def __init__(self):\n self.stack = []\n self.min_stack = []\n def push(self, val):\n self.stack.append(val)\n self.min_stack.append(min(val, self.min_stack[-1] if self.min_stack else val))\n def pop(self):\n self.stack.pop(); self.min_stack.pop()\n def top(self): return self.stack[-1]\n def getMin(self): return self.min_stack[-1]", "solution_java": "class MinStack {\n Stack stack = new Stack<>();\n Stack minStack = new Stack<>();\n public void push(int val) { stack.push(val); minStack.push(Math.min(val, minStack.isEmpty() ? val : minStack.peek())); }\n public void pop() { stack.pop(); minStack.pop(); }\n public int top() { return stack.peek(); }\n public int getMin() { return minStack.peek(); }\n}", "solution_cpp": "class MinStack {\n stack st, minSt;\npublic:\n void push(int val) { st.push(val); minSt.push(min(val, minSt.empty() ? val : minSt.top())); }\n void pop() { st.pop(); minSt.pop(); }\n int top() { return st.top(); }\n int getMin() { return minSt.top(); }\n};", "test_cases": ["push(-2), push(0), push(-3) -> getMin() returns -3"], "key_points": ["辅助栈记录最小值", "O(1)时间获取最小值"], "tags": ["stack", "medium", "Google", "Microsoft"]} {"problem_id": "algo_01279", "original_id": "lru-cache", "title": "LRU缓存", "category": "design", "difficulty": "hard", "companies": ["Google", "Amazon"], "description": "设计和实现一个 LRU(最近最少使用)缓存机制。", "solution_python": "class LRUCache:\n def __init__(self, capacity):\n self.capacity = capacity\n self.cache = {}\n self.order = []\n def get(self, key):\n if key not in self.cache: return -1\n self.order.remove(key); self.order.append(key)\n return self.cache[key]\n def put(self, key, value):\n if key in self.cache:\n self.order.remove(key)\n elif len(self.cache) >= self.capacity:\n del self.cache[self.order.pop(0)]\n self.cache[key] = value; self.order.append(key)", "solution_java": "class LRUCache {\n int capacity;\n LinkedHashMap cache = new LinkedHashMap<>();\n public LRUCache(int cap) { capacity = cap; }\n public int get(int key) { return cache.containsKey(key) ? cache.remove(key) : -1; }\n public void put(int key, int val) {\n if (cache.containsKey(key)) cache.remove(key);\n else if (cache.size() >= capacity) cache.remove(cache.keySet().iterator().next());\n cache.put(key, val);\n }\n}", "solution_cpp": "class LRUCache {\n int cap;\n list> dll;\n unordered_map>::iterator> cache;\npublic:\n LRUCache(int capacity) : cap(capacity) {}\n int get(int key) {\n auto it = cache.find(key);\n if (it == cache.end()) return -1;\n dll.splice(dll.end(), dll, it->second);\n return it->second->second;\n }\n void put(int key, int value) {\n auto it = cache.find(key);\n if (it != cache.end()) dll.erase(it->second);\n else if (cache.size() >= cap) { cache.erase(dll.front().first); dll.pop_front(); }\n dll.push_back({key, value});\n cache[key] = --dll.end();\n }\n};", "test_cases": ["put(1,1), put(2,2), get(1) -> 1"], "key_points": ["HashMap + 双向链表", "O(1)时间操作"], "tags": ["design", "hard", "Google", "Amazon"]} {"problem_id": "algo_01280", "original_id": "num-islands", "title": "岛屿数量", "category": "graph", "difficulty": "medium", "companies": ["Google", "Facebook"], "description": "给你一个由 '1'(陆地)和 '0'(水)组成的二维网格,请你计算网格中岛屿的数量。岛屿总是被水包围,且只能由水平或垂直方向相邻的陆地连接形成。", "solution_python": "def numIslands(grid):\n if not grid: return 0\n rows, cols = len(grid), len(grid[0])\n count = 0\n def dfs(r, c):\n if r < 0 or r >= rows or c < 0 or c >= cols or grid[r][c] != '1': return\n grid[r][c] = '0'\n dfs(r+1, c); dfs(r-1, c); dfs(r, c+1); dfs(r, c-1)\n for r in range(rows):\n for c in range(cols):\n if grid[r][c] == '1': count += 1; dfs(r, c)\n return count", "solution_java": "public int numIslands(char[][] grid) {\n if (grid.length == 0) return 0;\n int count = 0;\n for (int i = 0; i < grid.length; i++)\n for (int j = 0; j < grid[0].length; j++)\n if (grid[i][j] == '1') { count++; dfs(grid, i, j); }\n return count;\n}\nprivate void dfs(char[][] grid, int r, int c) {\n if (r < 0 || r >= grid.length || c < 0 || c >= grid[0].length || grid[r][c] != '1') return;\n grid[r][c] = '0';\n dfs(grid, r+1, c); dfs(grid, r-1, c); dfs(grid, r, c+1); dfs(grid, r, c-1);\n}", "solution_cpp": "int numIslands(vector>& grid) {\n if (grid.empty()) return 0;\n int count = 0;\n for (int i = 0; i < grid.size(); i++)\n for (int j = 0; j < grid[0].size(); j++)\n if (grid[i][j] == '1') { count++; dfs(grid, i, j); }\n return count;\n}\nvoid dfs(vector>& grid, int r, int c) {\n if (r < 0 || r >= grid.size() || c < 0 || c >= grid[0].size() || grid[r][c] != '1') return;\n grid[r][c] = '0';\n dfs(grid, r+1, c); dfs(grid, r-1, c); dfs(grid, r, c+1); dfs(grid, r, c-1);\n}", "test_cases": ["grid=[[1,1,1,1,0],[1,1,0,1,0],[1,1,0,0,0],[0,0,0,0,0]] -> 1"], "key_points": ["DFS/BFS遍历", "访问后标记为0避免重复"], "tags": ["graph", "medium", "Google", "Facebook"]} {"problem_id": "algo_01281", "original_id": "two-sum", "title": "两数之和", "category": "array", "difficulty": "easy", "companies": ["Amazon", "Google"], "description": "给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那两个整数,并返回他们的数组下标。", "solution_python": "def twoSum(nums, target):\n hashmap = {}\n for i, num in enumerate(nums):\n complement = target - num\n if complement in hashmap:\n return [hashmap[complement], i]\n hashmap[num] = i\n return []", "solution_java": "public int[] twoSum(int[] nums, int target) {\n Map map = new HashMap<>();\n for (int i = 0; i < nums.length; i++) {\n int complement = target - nums[i];\n if (map.containsKey(complement)) return new int[]{map.get(complement), i};\n map.put(nums[i], i);\n }\n return new int[]{};\n}", "solution_cpp": "vector twoSum(vector& nums, int target) {\n unordered_map m;\n for (int i = 0; i < nums.size(); i++) {\n if (m.count(target - nums[i])) return {m[target - nums[i]], i};\n m[nums[i]] = i;\n }\n return {};\n}", "test_cases": ["nums=[2,7,11,15], target=9 -> [0,1]", "nums=[3,2,4], target=6 -> [1,2]"], "key_points": ["哈希表一次遍历", "空间换时间"], "tags": ["array", "easy", "Amazon", "Google"]} {"problem_id": "algo_01282", "original_id": "merge-sorted", "title": "合并两个有序数组", "category": "array", "difficulty": "easy", "companies": ["Microsoft", "Uber"], "description": "给你两个按非递减顺序排列的整数数组 nums1 和 nums2,另有两个整数 m 和 n,分别表示 nums1 和 nums2 中的元素数目。请你合并 nums2 到 nums1 中。", "solution_python": "def merge(nums1, m, nums2, n):\n p1, p2, p = m-1, n-1, m+n-1\n while p1 >= 0 and p2 >= 0:\n if nums1[p1] > nums2[p2]: nums1[p] = nums1[p1]; p1 -= 1\n else: nums1[p] = nums2[p2]; p2 -= 1\n p -= 1\n while p2 >= 0: nums1[p] = nums2[p2]; p2 -= 1; p -= 1", "solution_java": "public void merge(int[] nums1, int m, int[] nums2, int n) {\n int p1 = m-1, p2 = n-1, p = m+n-1;\n while (p1 >= 0 && p2 >= 0) {\n nums1[p--] = nums1[p1] > nums2[p2] ? nums1[p1--] : nums2[p2--];\n }\n while (p2 >= 0) nums1[p--] = nums2[p2--];\n}", "solution_cpp": "void merge(vector& nums1, int m, vector& nums2, int n) {\n int p1 = m-1, p2 = n-1, p = m+n-1;\n while (p1 >= 0 && p2 >= 0) nums1[p--] = nums1[p1] > nums2[p2] ? nums1[p1--] : nums2[p2--];\n while (p2 >= 0) nums1[p--] = nums2[p2--];\n}", "test_cases": ["nums1=[1,2,3], m=3, nums2=[2,5,6], n=3 -> [1,2,2,3,5,6]", "nums1=[], m=0, nums2=[1], n=1 -> [1]"], "key_points": ["从后往前合并", "三指针技巧"], "tags": ["array", "easy", "Microsoft", "Uber"]} {"problem_id": "algo_01283", "original_id": "max-subarray", "title": "最大子数组和", "category": "array", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "给你一个整数数组 nums ,请你找出一个具有最大和的连续子数组,返回其最大和。", "solution_python": "def maxSubArray(nums):\n max_sum = current = nums[0]\n for num in nums[1:]:\n current = max(num, current + num)\n max_sum = max(max_sum, current)\n return max_sum", "solution_java": "public int maxSubArray(int[] nums) {\n int maxSum = nums[0], curr = nums[0];\n for (int i = 1; i < nums.length; i++) {\n curr = Math.max(nums[i], curr + nums[i]);\n maxSum = Math.max(maxSum, curr);\n }\n return maxSum;\n}", "solution_cpp": "int maxSubArray(vector& nums) {\n int maxSum = nums[0], curr = nums[0];\n for (int i = 1; i < nums.size(); i++) {\n curr = max(nums[i], curr + nums[i]);\n maxSum = max(maxSum, curr);\n }\n return maxSum;\n}", "test_cases": ["nums=[-2,1,-3,4,-1,2,1,-5,4] -> 6", "nums=[1] -> 1"], "key_points": ["Kadane算法", "动态规划基础题"], "tags": ["array", "medium", "Google", "Microsoft"]} {"problem_id": "algo_01284", "original_id": "valid-parentheses", "title": "有效的括号", "category": "string", "difficulty": "easy", "companies": ["Google", "Uber"], "description": "给定一个只包括 '(',')','{','}','[',']' 的字符串 s,判断字符串是否有效。", "solution_python": "def isValid(s):\n stack = []\n mapping = {')': '(', ']': '[', '}': '{'}\n for c in s:\n if c in mapping:\n if not stack or stack[-1] != mapping[c]: return False\n stack.pop()\n else: stack.append(c)\n return not stack", "solution_java": "public boolean isValid(String s) {\n Stack stack = new Stack<>();\n Map map = Map.of(')', '(', ']', '[', '}', '{');\n for (char c : s.toCharArray()) {\n if (map.containsValue(c)) stack.push(c);\n else if (!stack.isEmpty() && stack.pop() != map.get(c)) return false;\n }\n return stack.isEmpty();\n}", "solution_cpp": "bool isValid(string s) {\n stack st;\n unordered_map m = {{')','('},{']','['},{'}','{'}};\n for (char c : s) {\n if (m.find(c) == m.end()) st.push(c);\n else if (st.empty() || st.top() != m[c]) return false;\n else st.pop();\n }\n return st.empty();\n}", "test_cases": ["s=\"()\" -> true", "s=\"()[]{}\" -> true", "s=\"(]\" -> false"], "key_points": ["栈匹配法", "注意空栈边界"], "tags": ["string", "easy", "Google", "Uber"]} {"problem_id": "algo_01285", "original_id": "longest-palindrome", "title": "最长回文子串", "category": "string", "difficulty": "medium", "companies": ["Google", "Amazon"], "description": "给你一个字符串 s,找到 s 中最长的回文子串。", "solution_python": "def longestPalindrome(s):\n def expand(l, r):\n while l >= 0 and r < len(s) and s[l] == s[r]: l -= 1; r += 1\n return l + 1, r - 1\n start = end = 0\n for i in range(len(s)):\n l1, r1 = expand(i, i)\n l2, r2 = expand(i, i + 1)\n if r1 - l1 > end - start: start, end = l1, r1\n if r2 - l2 > end - start: start, end = l2, r2\n return s[start:end+1]", "solution_java": "public String longestPalindrome(String s) {\n int start = 0, end = 0;\n for (int i = 0; i < s.length(); i++) {\n int len1 = expand(s, i, i), len2 = expand(s, i, i+1);\n int len = Math.max(len1, len2);\n if (len > end - start) { start = i - (len-1)/2; end = i + len/2; }\n }\n return s.substring(start, end + 1);\n}\nprivate int expand(String s, int l, int r) {\n while (l >= 0 && r < s.length() && s.charAt(l) == s.charAt(r)) { l--; r++; }\n return r - l - 1;\n}", "solution_cpp": "string longestPalindrome(string s) {\n int start = 0, end = 0;\n for (int i = 0; i < s.size(); i++) {\n int len1 = expand(s, i, i), len2 = expand(s, i, i+1);\n if (max(len1, len2) > end - start) { start = i - (max(len1,len2)-1)/2; end = i + max(len1,len2)/2; }\n }\n return s.substr(start, end - start + 1);\n}", "test_cases": ["s=\"babad\" -> bab或aba", "s=\"cbbd\" -> bb"], "key_points": ["中心扩展法", "处理奇偶长度"], "tags": ["string", "medium", "Google", "Amazon"]} {"problem_id": "algo_01286", "original_id": "reverse-list", "title": "反转链表", "category": "linkedlist", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "给你单链表的头节点 head,请你反转链表,并返回反转后的链表。", "solution_python": "def reverseList(head):\n prev = None\n curr = head\n while curr:\n nxt = curr.next\n curr.next = prev\n prev = curr\n curr = nxt\n return prev", "solution_java": "public ListNode reverseList(ListNode head) {\n ListNode prev = null, curr = head;\n while (curr != null) {\n ListNode next = curr.next;\n curr.next = prev;\n prev = curr;\n curr = next;\n }\n return prev;\n}", "solution_cpp": "ListNode* reverseList(ListNode* head) {\n ListNode* prev = nullptr, *curr = head;\n while (curr) {\n ListNode* next = curr->next;\n curr->next = prev;\n prev = curr;\n curr = next;\n }\n return prev;\n}", "test_cases": ["head=[1,2,3,4,5] -> [5,4,3,2,1]", "head=[1,2] -> [2,1]"], "key_points": ["迭代法 O(1)空间", "递归法 O(n)空间"], "tags": ["linkedlist", "medium", "Google", "Microsoft"]} {"problem_id": "algo_01287", "original_id": "middle-node", "title": "链表的中间结点", "category": "linkedlist", "difficulty": "easy", "companies": ["Amazon", "Facebook"], "description": "给你单链表的头节点 head,请你找出并返回链表的中间结点。如果有两个中间结点,则返回第二个中间结点。", "solution_python": "def middleNode(head):\n slow = fast = head\n while fast and fast.next:\n slow = slow.next\n fast = fast.next.next\n return slow", "solution_java": "public ListNode middleNode(ListNode head) {\n ListNode slow = head, fast = head;\n while (fast != null && fast.next != null) {\n slow = slow.next;\n fast = fast.next.next;\n }\n return slow;\n}", "solution_cpp": "ListNode* middleNode(ListNode* head) {\n ListNode* slow = head, *fast = head;\n while (fast && fast->next) { slow = slow->next; fast = fast->next->next; }\n return slow;\n}", "test_cases": ["head=[1,2,3,4,5] -> 3", "head=[1,2,3,4,5,6] -> 4"], "key_points": ["快慢指针", "O(n)时间O(1)空间"], "tags": ["linkedlist", "easy", "Amazon", "Facebook"]} {"problem_id": "algo_01288", "original_id": "max-depth", "title": "二叉树的最大深度", "category": "tree", "difficulty": "easy", "companies": ["Microsoft", "Apple"], "description": "给定一个二叉树 root,返回其最大深度。", "solution_python": "def maxDepth(root):\n if not root: return 0\n return max(maxDepth(root.left), maxDepth(root.right)) + 1", "solution_java": "public int maxDepth(TreeNode root) {\n if (root == null) return 0;\n return Math.max(maxDepth(root.left), maxDepth(root.right)) + 1;\n}", "solution_cpp": "int maxDepth(TreeNode* root) {\n if (!root) return 0;\n return max(maxDepth(root->left), maxDepth(root->right)) + 1;\n}", "test_cases": ["root=[3,9,20,null,null,15,7] -> 3", "root=[1,null,2] -> 2"], "key_points": ["DFS递归", "层序遍历也可"], "tags": ["tree", "easy", "Microsoft", "Apple"]} {"problem_id": "algo_01289", "original_id": "inorder-traversal", "title": "二叉树的中序遍历", "category": "tree", "difficulty": "easy", "companies": ["Google", "Microsoft"], "description": "给定一个二叉树的根节点 root,返回它的中序遍历结果。", "solution_python": "def inorderTraversal(root):\n result = []\n def dfs(node):\n if node:\n dfs(node.left)\n result.append(node.val)\n dfs(node.right)\n dfs(root)\n return result", "solution_java": "public List inorderTraversal(TreeNode root) {\n List res = new ArrayList<>();\n dfs(root, res);\n return res;\n}\nprivate void dfs(TreeNode node, List res) {\n if (node == null) return;\n dfs(node.left, res); res.add(node.val); dfs(node.right, res);\n}", "solution_cpp": "vector inorderTraversal(TreeNode* root) {\n vector res;\n dfs(root, res);\n return res;\n}\nvoid dfs(TreeNode* node, vector& res) {\n if (!node) return;\n dfs(node->left, res); res.push_back(node->val); dfs(node->right, res);\n}", "test_cases": ["root=[1,null,2,3] -> [1,3,2]", "root=[] -> []"], "key_points": ["左-根-右顺序", "递归最简洁"], "tags": ["tree", "easy", "Google", "Microsoft"]} {"problem_id": "algo_01290", "original_id": "binary-search", "title": "二分查找", "category": "binarysearch", "difficulty": "easy", "companies": ["Google", "Amazon"], "description": "给定一个 n 个元素有序的(升序)整型数组 nums 和一个目标值 target,写一个函数搜索 nums 中的 target,如果目标值存在返回下标,否则返回 -1。", "solution_python": "def search(nums, target):\n left, right = 0, len(nums) - 1\n while left <= right:\n mid = (left + right) // 2\n if nums[mid] == target: return mid\n elif nums[mid] < target: left = mid + 1\n else: right = mid - 1\n return -1", "solution_java": "public int search(int[] nums, int target) {\n int left = 0, right = nums.length - 1;\n while (left <= right) {\n int mid = left + (right - left) / 2;\n if (nums[mid] == target) return mid;\n else if (nums[mid] < target) left = mid + 1;\n else right = mid - 1;\n }\n return -1;\n}", "solution_cpp": "int search(vector& nums, int target) {\n int left = 0, right = nums.size() - 1;\n while (left <= right) {\n int mid = left + (right - left) / 2;\n if (nums[mid] == target) return mid;\n else if (nums[mid] < target) left = mid + 1;\n else right = mid - 1;\n }\n return -1;\n}", "test_cases": ["nums=[-1,0,3,5,9,12], target=9 -> 4", "nums=[-1,0,3,5,9,12], target=2 -> -1"], "key_points": ["标准模板", "注意防溢出写法"], "tags": ["binarysearch", "easy", "Google", "Amazon"]} {"problem_id": "algo_01291", "original_id": "climbing-stairs", "title": "爬楼梯", "category": "dp", "difficulty": "easy", "companies": ["Amazon", "Google"], "description": "假设你正在爬楼梯。需要 n 阶你才能到达楼顶。每次你可以爬 1 或 2 个台阶。你有多少种不同的方法可以爬到楼顶?", "solution_python": "def climbStairs(n):\n if n <= 2: return n\n a, b = 1, 2\n for _ in range(3, n+1):\n a, b = b, a + b\n return b", "solution_java": "public int climbStairs(int n) {\n if (n <= 2) return n;\n int a = 1, b = 2;\n for (int i = 3; i <= n; i++) { int temp = a + b; a = b; b = temp; }\n return b;\n}", "solution_cpp": "int climbStairs(int n) {\n if (n <= 2) return n;\n int a = 1, b = 2;\n for (int i = 3; i <= n; i++) { int temp = a + b; a = b; b = temp; }\n return b;\n}", "test_cases": ["n=2 -> 2", "n=3 -> 3", "n=5 -> 8"], "key_points": ["斐波那契数列", "滚动数组优化空间"], "tags": ["dp", "easy", "Amazon", "Google"]} {"problem_id": "algo_01292", "original_id": "coin-change", "title": "零钱兑换", "category": "dp", "difficulty": "medium", "companies": ["Google", "Amazon"], "description": "给你一个整数数组 coins 表示不同面额的硬币,以及一个整数 amount 表示总金额。计算并返回可以凑成总金额所需的最少的硬币个数。如果没有任何一种硬币组合能组成总金额,返回 -1。", "solution_python": "def coinChange(coins, amount):\n dp = [float('inf')] * (amount + 1)\n dp[0] = 0\n for coin in coins:\n for x in range(coin, amount + 1):\n dp[x] = min(dp[x], dp[x - coin] + 1)\n return dp[amount] if dp[amount] != float('inf') else -1", "solution_java": "public int coinChange(int[] coins, int amount) {\n int[] dp = new int[amount + 1];\n Arrays.fill(dp, amount + 1);\n dp[0] = 0;\n for (int coin : coins) {\n for (int x = coin; x <= amount; x++) {\n dp[x] = Math.min(dp[x], dp[x - coin] + 1);\n }\n }\n return dp[amount] > amount ? -1 : dp[amount];\n}", "solution_cpp": "int coinChange(vector& coins, int amount) {\n vector dp(amount + 1, amount + 1);\n dp[0] = 0;\n for (int coin : coins) {\n for (int x = coin; x <= amount; x++) {\n dp[x] = min(dp[x], dp[x - coin] + 1);\n }\n }\n return dp[amount] > amount ? -1 : dp[amount];\n}", "test_cases": ["coins=[1,2,5], amount=11 -> 3", "coins=[2], amount=3 -> -1"], "key_points": ["完全背包问题", "dp[x] = min(dp[x-coin]+1)"], "tags": ["dp", "medium", "Google", "Amazon"]} {"problem_id": "algo_01293", "original_id": "subsets", "title": "子集", "category": "backtracking", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "给你一个整数数组 nums ,数组中的元素 互不相同 。返回该数组所有可能的子集(幂集)。", "solution_python": "def subsets(nums):\n result = []\n def backtrack(start, path):\n result.append(path[:])\n for i in range(start, len(nums)):\n path.append(nums[i])\n backtrack(i + 1, path)\n path.pop()\n backtrack(0, [])\n return result", "solution_java": "public List> subsets(int[] nums) {\n List> result = new ArrayList<>();\n backtrack(nums, 0, new ArrayList<>(), result);\n return result;\n}\nprivate void backtrack(int[] nums, int start, List path, List> result) {\n result.add(new ArrayList<>(path));\n for (int i = start; i < nums.length; i++) {\n path.add(nums[i]);\n backtrack(nums, i + 1, path, result);\n path.remove(path.size() - 1);\n }\n}", "solution_cpp": "vector> subsets(vector& nums) {\n vector> result;\n vector path;\n backtrack(nums, 0, path, result);\n return result;\n}\nvoid backtrack(vector& nums, int start, vector& path, vector>& result) {\n result.push_back(path);\n for (int i = start; i < nums.size(); i++) {\n path.push_back(nums[i]);\n backtrack(nums, i + 1, path, result);\n path.pop_back();\n }\n}", "test_cases": ["nums=[1,2,3] -> [[],[1],[2],[1,2],[3],[1,3],[2,3],[1,2,3]]"], "key_points": ["选或不选", "DFS遍历子集树"], "tags": ["backtracking", "medium", "Google", "Microsoft"]} {"problem_id": "algo_01294", "original_id": "permutations", "title": "全排列", "category": "backtracking", "difficulty": "medium", "companies": ["Google", "Facebook"], "description": "给定一个不含重复数字的数组 nums,返回其所有可能的全排列。", "solution_python": "def permute(nums):\n result = []\n def backtrack(path, used):\n if len(path) == len(nums):\n result.append(path[:])\n return\n for i in range(len(nums)):\n if used[i]: continue\n used[i] = True\n path.append(nums[i])\n backtrack(path, used)\n path.pop()\n used[i] = False\n backtrack([], [False]*len(nums))\n return result", "solution_java": "public List> permute(int[] nums) {\n List> result = new ArrayList<>();\n boolean[] used = new boolean[nums.length];\n backtrack(nums, used, new ArrayList<>(), result);\n return result;\n}\nprivate void backtrack(int[] nums, boolean[] used, List path, List> result) {\n if (path.size() == nums.length) { result.add(new ArrayList<>(path)); return; }\n for (int i = 0; i < nums.length; i++) {\n if (used[i]) continue;\n used[i] = true;\n path.add(nums[i]);\n backtrack(nums, used, path, result);\n path.remove(path.size() - 1);\n used[i] = false;\n }\n}", "solution_cpp": "vector> permute(vector& nums) {\n vector> result;\n vector used(nums.size(), false);\n vector path;\n backtrack(nums, used, path, result);\n return result;\n}\nvoid backtrack(vector& nums, vector& used, vector& path, vector>& result) {\n if (path.size() == nums.size()) { result.push_back(path); return; }\n for (int i = 0; i < nums.size(); i++) {\n if (used[i]) continue;\n used[i] = true;\n path.push_back(nums[i]);\n backtrack(nums, used, path, result);\n path.pop_back();\n used[i] = false;\n }\n}", "test_cases": ["nums=[1,2,3] -> [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]"], "key_points": ["标记已使用元素", "回溯经典模板"], "tags": ["backtracking", "medium", "Google", "Facebook"]} {"problem_id": "algo_01295", "original_id": "top-k-frequent", "title": "前K个高频元素", "category": "heap", "difficulty": "medium", "companies": ["Amazon", "Facebook"], "description": "给你一个整数数组 nums 和一个整数 k,请你返回其中出现频率前 k 高的元素。", "solution_python": "import heapq\nfrom collections import Counter\ndef topKFrequent(nums, k):\n count = Counter(nums)\n heap = []\n for num, freq in count.items():\n heapq.heappush(heap, (freq, num))\n if len(heap) > k: heapq.heappop(heap)\n return [num for freq, num in heap]", "solution_java": "public int[] topKFrequent(int[] nums, int k) {\n Map count = new HashMap<>();\n for (int n : nums) count.put(n, count.getOrDefault(n, 0) + 1);\n PriorityQueue> heap = \n new PriorityQueue<>((a, b) -> a.getValue() - b.getValue());\n for (Map.Entry e : count.entrySet()) {\n heap.offer(e);\n if (heap.size() > k) heap.poll();\n }\n int[] res = new int[k];\n for (int i = k - 1; i >= 0; i--) res[i] = heap.poll().getKey();\n return res;\n}", "solution_cpp": "vector topKFrequent(vector& nums, int k) {\n unordered_map count;\n for (int n : nums) count[n]++;\n priority_queue, vector>, greater>> heap;\n for (auto& [num, freq] : count) {\n heap.push({freq, num});\n if (heap.size() > k) heap.pop();\n }\n vector res;\n while (!heap.empty()) { res.push_back(heap.top().second); heap.pop(); }\n reverse(res.begin(), res.end());\n return res;\n}", "test_cases": ["nums=[1,1,1,2,2,3], k=2 -> [1,2]", "nums=[1], k=1 -> [1]"], "key_points": ["小顶堆保持大小k", "时间复杂度O(nlogk)"], "tags": ["heap", "medium", "Amazon", "Facebook"]} {"problem_id": "algo_01296", "original_id": "3sum", "title": "三数之和", "category": "two-pointers", "difficulty": "medium", "companies": ["Google", "Amazon"], "description": "给你一个整数数组 nums,判断是否存在三元组满足和为0,返回所有不重复的三元组。", "solution_python": "def threeSum(nums):\n nums.sort()\n result = []\n for i in range(len(nums) - 2):\n if i > 0 and nums[i] == nums[i-1]: continue\n left, right = i + 1, len(nums) - 1\n while left < right:\n total = nums[i] + nums[left] + nums[right]\n if total < 0: left += 1\n elif total > 0: right -= 1\n else:\n result.append([nums[i], nums[left], nums[right]])\n while left < right and nums[left] == nums[left+1]: left += 1\n while left < right and nums[right] == nums[right-1]: right -= 1\n left += 1; right -= 1\n return result", "solution_java": "public List> threeSum(int[] nums) {\n Arrays.sort(nums);\n List> result = new ArrayList<>();\n for (int i = 0; i < nums.length - 2; i++) {\n if (i > 0 && nums[i] == nums[i-1]) continue;\n int left = i + 1, right = nums.length - 1;\n while (left < right) {\n int total = nums[i] + nums[left] + nums[right];\n if (total < 0) left++;\n else if (total > 0) right--;\n else {\n result.add(Arrays.asList(nums[i], nums[left], nums[right]));\n while (left < right && nums[left] == nums[left+1]) left++;\n while (left < right && nums[right] == nums[right-1]) right--;\n left++; right--;\n }\n }\n }\n return result;\n}", "solution_cpp": "vector> threeSum(vector& nums) {\n sort(nums.begin(), nums.end());\n vector> result;\n for (int i = 0; i < nums.size() - 2; i++) {\n if (i > 0 && nums[i] == nums[i-1]) continue;\n int left = i + 1, right = nums.size() - 1;\n while (left < right) {\n int total = nums[i] + nums[left] + nums[right];\n if (total < 0) left++;\n else if (total > 0) right--;\n else {\n result.push_back({nums[i], nums[left], nums[right]});\n while (left < right && nums[left] == nums[left+1]) left++;\n while (left < right && nums[right] == nums[right-1]) right--;\n left++; right--;\n }\n }\n }\n return result;\n}", "test_cases": ["nums=[-1,0,1,2,-1,-4] -> [[-1,-1,2],[-1,0,1]]"], "key_points": ["排序+双指针", "去重是关键"], "tags": ["two-pointers", "medium", "Google", "Amazon"]} {"problem_id": "algo_01297", "original_id": "container-water", "title": "盛最多水的容器", "category": "two-pointers", "difficulty": "medium", "companies": ["Google", "Uber"], "description": "给定一个长度为 n 的整数数组 height,找出其中的两条线,使得它们与 x 轴共同构成的容器可以容纳最多的水。", "solution_python": "def maxArea(height):\n left, right = 0, len(height) - 1\n max_area = 0\n while left < right:\n h = min(height[left], height[right])\n max_area = max(max_area, h * (right - left))\n if height[left] < height[right]: left += 1\n else: right -= 1\n return max_area", "solution_java": "public int maxArea(int[] height) {\n int left = 0, right = height.length - 1, maxArea = 0;\n while (left < right) {\n int h = Math.min(height[left], height[right]);\n maxArea = Math.max(maxArea, h * (right - left));\n if (height[left] < height[right]) left++;\n else right--;\n }\n return maxArea;\n}", "solution_cpp": "int maxArea(vector& height) {\n int left = 0, right = height.size() - 1, maxArea = 0;\n while (left < right) {\n int h = min(height[left], height[right]);\n maxArea = max(maxArea, h * (right - left));\n if (height[left] < height[right]) left++;\n else right--;\n }\n return maxArea;\n}", "test_cases": ["height=[1,8,6,2,5,4,8,3,7] -> 49"], "key_points": ["移动短边指针", "面积=min(h1,h2)*width"], "tags": ["two-pointers", "medium", "Google", "Uber"]} {"problem_id": "algo_01298", "original_id": "min-stack", "title": "最小栈", "category": "stack", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "设计一个支持 push,pop,top 操作,并能在常数时间内检索到最小元素的栈。", "solution_python": "class MinStack:\n def __init__(self):\n self.stack = []\n self.min_stack = []\n def push(self, val):\n self.stack.append(val)\n self.min_stack.append(min(val, self.min_stack[-1] if self.min_stack else val))\n def pop(self):\n self.stack.pop(); self.min_stack.pop()\n def top(self): return self.stack[-1]\n def getMin(self): return self.min_stack[-1]", "solution_java": "class MinStack {\n Stack stack = new Stack<>();\n Stack minStack = new Stack<>();\n public void push(int val) { stack.push(val); minStack.push(Math.min(val, minStack.isEmpty() ? val : minStack.peek())); }\n public void pop() { stack.pop(); minStack.pop(); }\n public int top() { return stack.peek(); }\n public int getMin() { return minStack.peek(); }\n}", "solution_cpp": "class MinStack {\n stack st, minSt;\npublic:\n void push(int val) { st.push(val); minSt.push(min(val, minSt.empty() ? val : minSt.top())); }\n void pop() { st.pop(); minSt.pop(); }\n int top() { return st.top(); }\n int getMin() { return minSt.top(); }\n};", "test_cases": ["push(-2), push(0), push(-3) -> getMin() returns -3"], "key_points": ["辅助栈记录最小值", "O(1)时间获取最小值"], "tags": ["stack", "medium", "Google", "Microsoft"]} {"problem_id": "algo_01299", "original_id": "lru-cache", "title": "LRU缓存", "category": "design", "difficulty": "hard", "companies": ["Google", "Amazon"], "description": "设计和实现一个 LRU(最近最少使用)缓存机制。", "solution_python": "class LRUCache:\n def __init__(self, capacity):\n self.capacity = capacity\n self.cache = {}\n self.order = []\n def get(self, key):\n if key not in self.cache: return -1\n self.order.remove(key); self.order.append(key)\n return self.cache[key]\n def put(self, key, value):\n if key in self.cache:\n self.order.remove(key)\n elif len(self.cache) >= self.capacity:\n del self.cache[self.order.pop(0)]\n self.cache[key] = value; self.order.append(key)", "solution_java": "class LRUCache {\n int capacity;\n LinkedHashMap cache = new LinkedHashMap<>();\n public LRUCache(int cap) { capacity = cap; }\n public int get(int key) { return cache.containsKey(key) ? cache.remove(key) : -1; }\n public void put(int key, int val) {\n if (cache.containsKey(key)) cache.remove(key);\n else if (cache.size() >= capacity) cache.remove(cache.keySet().iterator().next());\n cache.put(key, val);\n }\n}", "solution_cpp": "class LRUCache {\n int cap;\n list> dll;\n unordered_map>::iterator> cache;\npublic:\n LRUCache(int capacity) : cap(capacity) {}\n int get(int key) {\n auto it = cache.find(key);\n if (it == cache.end()) return -1;\n dll.splice(dll.end(), dll, it->second);\n return it->second->second;\n }\n void put(int key, int value) {\n auto it = cache.find(key);\n if (it != cache.end()) dll.erase(it->second);\n else if (cache.size() >= cap) { cache.erase(dll.front().first); dll.pop_front(); }\n dll.push_back({key, value});\n cache[key] = --dll.end();\n }\n};", "test_cases": ["put(1,1), put(2,2), get(1) -> 1"], "key_points": ["HashMap + 双向链表", "O(1)时间操作"], "tags": ["design", "hard", "Google", "Amazon"]} {"problem_id": "algo_01300", "original_id": "num-islands", "title": "岛屿数量", "category": "graph", "difficulty": "medium", "companies": ["Google", "Facebook"], "description": "给你一个由 '1'(陆地)和 '0'(水)组成的二维网格,请你计算网格中岛屿的数量。岛屿总是被水包围,且只能由水平或垂直方向相邻的陆地连接形成。", "solution_python": "def numIslands(grid):\n if not grid: return 0\n rows, cols = len(grid), len(grid[0])\n count = 0\n def dfs(r, c):\n if r < 0 or r >= rows or c < 0 or c >= cols or grid[r][c] != '1': return\n grid[r][c] = '0'\n dfs(r+1, c); dfs(r-1, c); dfs(r, c+1); dfs(r, c-1)\n for r in range(rows):\n for c in range(cols):\n if grid[r][c] == '1': count += 1; dfs(r, c)\n return count", "solution_java": "public int numIslands(char[][] grid) {\n if (grid.length == 0) return 0;\n int count = 0;\n for (int i = 0; i < grid.length; i++)\n for (int j = 0; j < grid[0].length; j++)\n if (grid[i][j] == '1') { count++; dfs(grid, i, j); }\n return count;\n}\nprivate void dfs(char[][] grid, int r, int c) {\n if (r < 0 || r >= grid.length || c < 0 || c >= grid[0].length || grid[r][c] != '1') return;\n grid[r][c] = '0';\n dfs(grid, r+1, c); dfs(grid, r-1, c); dfs(grid, r, c+1); dfs(grid, r, c-1);\n}", "solution_cpp": "int numIslands(vector>& grid) {\n if (grid.empty()) return 0;\n int count = 0;\n for (int i = 0; i < grid.size(); i++)\n for (int j = 0; j < grid[0].size(); j++)\n if (grid[i][j] == '1') { count++; dfs(grid, i, j); }\n return count;\n}\nvoid dfs(vector>& grid, int r, int c) {\n if (r < 0 || r >= grid.size() || c < 0 || c >= grid[0].size() || grid[r][c] != '1') return;\n grid[r][c] = '0';\n dfs(grid, r+1, c); dfs(grid, r-1, c); dfs(grid, r, c+1); dfs(grid, r, c-1);\n}", "test_cases": ["grid=[[1,1,1,1,0],[1,1,0,1,0],[1,1,0,0,0],[0,0,0,0,0]] -> 1"], "key_points": ["DFS/BFS遍历", "访问后标记为0避免重复"], "tags": ["graph", "medium", "Google", "Facebook"]} {"problem_id": "algo_01301", "original_id": "two-sum", "title": "两数之和", "category": "array", "difficulty": "easy", "companies": ["Amazon", "Google"], "description": "给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那两个整数,并返回他们的数组下标。", "solution_python": "def twoSum(nums, target):\n hashmap = {}\n for i, num in enumerate(nums):\n complement = target - num\n if complement in hashmap:\n return [hashmap[complement], i]\n hashmap[num] = i\n return []", "solution_java": "public int[] twoSum(int[] nums, int target) {\n Map map = new HashMap<>();\n for (int i = 0; i < nums.length; i++) {\n int complement = target - nums[i];\n if (map.containsKey(complement)) return new int[]{map.get(complement), i};\n map.put(nums[i], i);\n }\n return new int[]{};\n}", "solution_cpp": "vector twoSum(vector& nums, int target) {\n unordered_map m;\n for (int i = 0; i < nums.size(); i++) {\n if (m.count(target - nums[i])) return {m[target - nums[i]], i};\n m[nums[i]] = i;\n }\n return {};\n}", "test_cases": ["nums=[2,7,11,15], target=9 -> [0,1]", "nums=[3,2,4], target=6 -> [1,2]"], "key_points": ["哈希表一次遍历", "空间换时间"], "tags": ["array", "easy", "Amazon", "Google"]} {"problem_id": "algo_01302", "original_id": "merge-sorted", "title": "合并两个有序数组", "category": "array", "difficulty": "easy", "companies": ["Microsoft", "Uber"], "description": "给你两个按非递减顺序排列的整数数组 nums1 和 nums2,另有两个整数 m 和 n,分别表示 nums1 和 nums2 中的元素数目。请你合并 nums2 到 nums1 中。", "solution_python": "def merge(nums1, m, nums2, n):\n p1, p2, p = m-1, n-1, m+n-1\n while p1 >= 0 and p2 >= 0:\n if nums1[p1] > nums2[p2]: nums1[p] = nums1[p1]; p1 -= 1\n else: nums1[p] = nums2[p2]; p2 -= 1\n p -= 1\n while p2 >= 0: nums1[p] = nums2[p2]; p2 -= 1; p -= 1", "solution_java": "public void merge(int[] nums1, int m, int[] nums2, int n) {\n int p1 = m-1, p2 = n-1, p = m+n-1;\n while (p1 >= 0 && p2 >= 0) {\n nums1[p--] = nums1[p1] > nums2[p2] ? nums1[p1--] : nums2[p2--];\n }\n while (p2 >= 0) nums1[p--] = nums2[p2--];\n}", "solution_cpp": "void merge(vector& nums1, int m, vector& nums2, int n) {\n int p1 = m-1, p2 = n-1, p = m+n-1;\n while (p1 >= 0 && p2 >= 0) nums1[p--] = nums1[p1] > nums2[p2] ? nums1[p1--] : nums2[p2--];\n while (p2 >= 0) nums1[p--] = nums2[p2--];\n}", "test_cases": ["nums1=[1,2,3], m=3, nums2=[2,5,6], n=3 -> [1,2,2,3,5,6]", "nums1=[], m=0, nums2=[1], n=1 -> [1]"], "key_points": ["从后往前合并", "三指针技巧"], "tags": ["array", "easy", "Microsoft", "Uber"]} {"problem_id": "algo_01303", "original_id": "max-subarray", "title": "最大子数组和", "category": "array", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "给你一个整数数组 nums ,请你找出一个具有最大和的连续子数组,返回其最大和。", "solution_python": "def maxSubArray(nums):\n max_sum = current = nums[0]\n for num in nums[1:]:\n current = max(num, current + num)\n max_sum = max(max_sum, current)\n return max_sum", "solution_java": "public int maxSubArray(int[] nums) {\n int maxSum = nums[0], curr = nums[0];\n for (int i = 1; i < nums.length; i++) {\n curr = Math.max(nums[i], curr + nums[i]);\n maxSum = Math.max(maxSum, curr);\n }\n return maxSum;\n}", "solution_cpp": "int maxSubArray(vector& nums) {\n int maxSum = nums[0], curr = nums[0];\n for (int i = 1; i < nums.size(); i++) {\n curr = max(nums[i], curr + nums[i]);\n maxSum = max(maxSum, curr);\n }\n return maxSum;\n}", "test_cases": ["nums=[-2,1,-3,4,-1,2,1,-5,4] -> 6", "nums=[1] -> 1"], "key_points": ["Kadane算法", "动态规划基础题"], "tags": ["array", "medium", "Google", "Microsoft"]} {"problem_id": "algo_01304", "original_id": "valid-parentheses", "title": "有效的括号", "category": "string", "difficulty": "easy", "companies": ["Google", "Uber"], "description": "给定一个只包括 '(',')','{','}','[',']' 的字符串 s,判断字符串是否有效。", "solution_python": "def isValid(s):\n stack = []\n mapping = {')': '(', ']': '[', '}': '{'}\n for c in s:\n if c in mapping:\n if not stack or stack[-1] != mapping[c]: return False\n stack.pop()\n else: stack.append(c)\n return not stack", "solution_java": "public boolean isValid(String s) {\n Stack stack = new Stack<>();\n Map map = Map.of(')', '(', ']', '[', '}', '{');\n for (char c : s.toCharArray()) {\n if (map.containsValue(c)) stack.push(c);\n else if (!stack.isEmpty() && stack.pop() != map.get(c)) return false;\n }\n return stack.isEmpty();\n}", "solution_cpp": "bool isValid(string s) {\n stack st;\n unordered_map m = {{')','('},{']','['},{'}','{'}};\n for (char c : s) {\n if (m.find(c) == m.end()) st.push(c);\n else if (st.empty() || st.top() != m[c]) return false;\n else st.pop();\n }\n return st.empty();\n}", "test_cases": ["s=\"()\" -> true", "s=\"()[]{}\" -> true", "s=\"(]\" -> false"], "key_points": ["栈匹配法", "注意空栈边界"], "tags": ["string", "easy", "Google", "Uber"]} {"problem_id": "algo_01305", "original_id": "longest-palindrome", "title": "最长回文子串", "category": "string", "difficulty": "medium", "companies": ["Google", "Amazon"], "description": "给你一个字符串 s,找到 s 中最长的回文子串。", "solution_python": "def longestPalindrome(s):\n def expand(l, r):\n while l >= 0 and r < len(s) and s[l] == s[r]: l -= 1; r += 1\n return l + 1, r - 1\n start = end = 0\n for i in range(len(s)):\n l1, r1 = expand(i, i)\n l2, r2 = expand(i, i + 1)\n if r1 - l1 > end - start: start, end = l1, r1\n if r2 - l2 > end - start: start, end = l2, r2\n return s[start:end+1]", "solution_java": "public String longestPalindrome(String s) {\n int start = 0, end = 0;\n for (int i = 0; i < s.length(); i++) {\n int len1 = expand(s, i, i), len2 = expand(s, i, i+1);\n int len = Math.max(len1, len2);\n if (len > end - start) { start = i - (len-1)/2; end = i + len/2; }\n }\n return s.substring(start, end + 1);\n}\nprivate int expand(String s, int l, int r) {\n while (l >= 0 && r < s.length() && s.charAt(l) == s.charAt(r)) { l--; r++; }\n return r - l - 1;\n}", "solution_cpp": "string longestPalindrome(string s) {\n int start = 0, end = 0;\n for (int i = 0; i < s.size(); i++) {\n int len1 = expand(s, i, i), len2 = expand(s, i, i+1);\n if (max(len1, len2) > end - start) { start = i - (max(len1,len2)-1)/2; end = i + max(len1,len2)/2; }\n }\n return s.substr(start, end - start + 1);\n}", "test_cases": ["s=\"babad\" -> bab或aba", "s=\"cbbd\" -> bb"], "key_points": ["中心扩展法", "处理奇偶长度"], "tags": ["string", "medium", "Google", "Amazon"]} {"problem_id": "algo_01306", "original_id": "reverse-list", "title": "反转链表", "category": "linkedlist", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "给你单链表的头节点 head,请你反转链表,并返回反转后的链表。", "solution_python": "def reverseList(head):\n prev = None\n curr = head\n while curr:\n nxt = curr.next\n curr.next = prev\n prev = curr\n curr = nxt\n return prev", "solution_java": "public ListNode reverseList(ListNode head) {\n ListNode prev = null, curr = head;\n while (curr != null) {\n ListNode next = curr.next;\n curr.next = prev;\n prev = curr;\n curr = next;\n }\n return prev;\n}", "solution_cpp": "ListNode* reverseList(ListNode* head) {\n ListNode* prev = nullptr, *curr = head;\n while (curr) {\n ListNode* next = curr->next;\n curr->next = prev;\n prev = curr;\n curr = next;\n }\n return prev;\n}", "test_cases": ["head=[1,2,3,4,5] -> [5,4,3,2,1]", "head=[1,2] -> [2,1]"], "key_points": ["迭代法 O(1)空间", "递归法 O(n)空间"], "tags": ["linkedlist", "medium", "Google", "Microsoft"]} {"problem_id": "algo_01307", "original_id": "middle-node", "title": "链表的中间结点", "category": "linkedlist", "difficulty": "easy", "companies": ["Amazon", "Facebook"], "description": "给你单链表的头节点 head,请你找出并返回链表的中间结点。如果有两个中间结点,则返回第二个中间结点。", "solution_python": "def middleNode(head):\n slow = fast = head\n while fast and fast.next:\n slow = slow.next\n fast = fast.next.next\n return slow", "solution_java": "public ListNode middleNode(ListNode head) {\n ListNode slow = head, fast = head;\n while (fast != null && fast.next != null) {\n slow = slow.next;\n fast = fast.next.next;\n }\n return slow;\n}", "solution_cpp": "ListNode* middleNode(ListNode* head) {\n ListNode* slow = head, *fast = head;\n while (fast && fast->next) { slow = slow->next; fast = fast->next->next; }\n return slow;\n}", "test_cases": ["head=[1,2,3,4,5] -> 3", "head=[1,2,3,4,5,6] -> 4"], "key_points": ["快慢指针", "O(n)时间O(1)空间"], "tags": ["linkedlist", "easy", "Amazon", "Facebook"]} {"problem_id": "algo_01308", "original_id": "max-depth", "title": "二叉树的最大深度", "category": "tree", "difficulty": "easy", "companies": ["Microsoft", "Apple"], "description": "给定一个二叉树 root,返回其最大深度。", "solution_python": "def maxDepth(root):\n if not root: return 0\n return max(maxDepth(root.left), maxDepth(root.right)) + 1", "solution_java": "public int maxDepth(TreeNode root) {\n if (root == null) return 0;\n return Math.max(maxDepth(root.left), maxDepth(root.right)) + 1;\n}", "solution_cpp": "int maxDepth(TreeNode* root) {\n if (!root) return 0;\n return max(maxDepth(root->left), maxDepth(root->right)) + 1;\n}", "test_cases": ["root=[3,9,20,null,null,15,7] -> 3", "root=[1,null,2] -> 2"], "key_points": ["DFS递归", "层序遍历也可"], "tags": ["tree", "easy", "Microsoft", "Apple"]} {"problem_id": "algo_01309", "original_id": "inorder-traversal", "title": "二叉树的中序遍历", "category": "tree", "difficulty": "easy", "companies": ["Google", "Microsoft"], "description": "给定一个二叉树的根节点 root,返回它的中序遍历结果。", "solution_python": "def inorderTraversal(root):\n result = []\n def dfs(node):\n if node:\n dfs(node.left)\n result.append(node.val)\n dfs(node.right)\n dfs(root)\n return result", "solution_java": "public List inorderTraversal(TreeNode root) {\n List res = new ArrayList<>();\n dfs(root, res);\n return res;\n}\nprivate void dfs(TreeNode node, List res) {\n if (node == null) return;\n dfs(node.left, res); res.add(node.val); dfs(node.right, res);\n}", "solution_cpp": "vector inorderTraversal(TreeNode* root) {\n vector res;\n dfs(root, res);\n return res;\n}\nvoid dfs(TreeNode* node, vector& res) {\n if (!node) return;\n dfs(node->left, res); res.push_back(node->val); dfs(node->right, res);\n}", "test_cases": ["root=[1,null,2,3] -> [1,3,2]", "root=[] -> []"], "key_points": ["左-根-右顺序", "递归最简洁"], "tags": ["tree", "easy", "Google", "Microsoft"]} {"problem_id": "algo_01310", "original_id": "binary-search", "title": "二分查找", "category": "binarysearch", "difficulty": "easy", "companies": ["Google", "Amazon"], "description": "给定一个 n 个元素有序的(升序)整型数组 nums 和一个目标值 target,写一个函数搜索 nums 中的 target,如果目标值存在返回下标,否则返回 -1。", "solution_python": "def search(nums, target):\n left, right = 0, len(nums) - 1\n while left <= right:\n mid = (left + right) // 2\n if nums[mid] == target: return mid\n elif nums[mid] < target: left = mid + 1\n else: right = mid - 1\n return -1", "solution_java": "public int search(int[] nums, int target) {\n int left = 0, right = nums.length - 1;\n while (left <= right) {\n int mid = left + (right - left) / 2;\n if (nums[mid] == target) return mid;\n else if (nums[mid] < target) left = mid + 1;\n else right = mid - 1;\n }\n return -1;\n}", "solution_cpp": "int search(vector& nums, int target) {\n int left = 0, right = nums.size() - 1;\n while (left <= right) {\n int mid = left + (right - left) / 2;\n if (nums[mid] == target) return mid;\n else if (nums[mid] < target) left = mid + 1;\n else right = mid - 1;\n }\n return -1;\n}", "test_cases": ["nums=[-1,0,3,5,9,12], target=9 -> 4", "nums=[-1,0,3,5,9,12], target=2 -> -1"], "key_points": ["标准模板", "注意防溢出写法"], "tags": ["binarysearch", "easy", "Google", "Amazon"]} {"problem_id": "algo_01311", "original_id": "climbing-stairs", "title": "爬楼梯", "category": "dp", "difficulty": "easy", "companies": ["Amazon", "Google"], "description": "假设你正在爬楼梯。需要 n 阶你才能到达楼顶。每次你可以爬 1 或 2 个台阶。你有多少种不同的方法可以爬到楼顶?", "solution_python": "def climbStairs(n):\n if n <= 2: return n\n a, b = 1, 2\n for _ in range(3, n+1):\n a, b = b, a + b\n return b", "solution_java": "public int climbStairs(int n) {\n if (n <= 2) return n;\n int a = 1, b = 2;\n for (int i = 3; i <= n; i++) { int temp = a + b; a = b; b = temp; }\n return b;\n}", "solution_cpp": "int climbStairs(int n) {\n if (n <= 2) return n;\n int a = 1, b = 2;\n for (int i = 3; i <= n; i++) { int temp = a + b; a = b; b = temp; }\n return b;\n}", "test_cases": ["n=2 -> 2", "n=3 -> 3", "n=5 -> 8"], "key_points": ["斐波那契数列", "滚动数组优化空间"], "tags": ["dp", "easy", "Amazon", "Google"]} {"problem_id": "algo_01312", "original_id": "coin-change", "title": "零钱兑换", "category": "dp", "difficulty": "medium", "companies": ["Google", "Amazon"], "description": "给你一个整数数组 coins 表示不同面额的硬币,以及一个整数 amount 表示总金额。计算并返回可以凑成总金额所需的最少的硬币个数。如果没有任何一种硬币组合能组成总金额,返回 -1。", "solution_python": "def coinChange(coins, amount):\n dp = [float('inf')] * (amount + 1)\n dp[0] = 0\n for coin in coins:\n for x in range(coin, amount + 1):\n dp[x] = min(dp[x], dp[x - coin] + 1)\n return dp[amount] if dp[amount] != float('inf') else -1", "solution_java": "public int coinChange(int[] coins, int amount) {\n int[] dp = new int[amount + 1];\n Arrays.fill(dp, amount + 1);\n dp[0] = 0;\n for (int coin : coins) {\n for (int x = coin; x <= amount; x++) {\n dp[x] = Math.min(dp[x], dp[x - coin] + 1);\n }\n }\n return dp[amount] > amount ? -1 : dp[amount];\n}", "solution_cpp": "int coinChange(vector& coins, int amount) {\n vector dp(amount + 1, amount + 1);\n dp[0] = 0;\n for (int coin : coins) {\n for (int x = coin; x <= amount; x++) {\n dp[x] = min(dp[x], dp[x - coin] + 1);\n }\n }\n return dp[amount] > amount ? -1 : dp[amount];\n}", "test_cases": ["coins=[1,2,5], amount=11 -> 3", "coins=[2], amount=3 -> -1"], "key_points": ["完全背包问题", "dp[x] = min(dp[x-coin]+1)"], "tags": ["dp", "medium", "Google", "Amazon"]} {"problem_id": "algo_01313", "original_id": "subsets", "title": "子集", "category": "backtracking", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "给你一个整数数组 nums ,数组中的元素 互不相同 。返回该数组所有可能的子集(幂集)。", "solution_python": "def subsets(nums):\n result = []\n def backtrack(start, path):\n result.append(path[:])\n for i in range(start, len(nums)):\n path.append(nums[i])\n backtrack(i + 1, path)\n path.pop()\n backtrack(0, [])\n return result", "solution_java": "public List> subsets(int[] nums) {\n List> result = new ArrayList<>();\n backtrack(nums, 0, new ArrayList<>(), result);\n return result;\n}\nprivate void backtrack(int[] nums, int start, List path, List> result) {\n result.add(new ArrayList<>(path));\n for (int i = start; i < nums.length; i++) {\n path.add(nums[i]);\n backtrack(nums, i + 1, path, result);\n path.remove(path.size() - 1);\n }\n}", "solution_cpp": "vector> subsets(vector& nums) {\n vector> result;\n vector path;\n backtrack(nums, 0, path, result);\n return result;\n}\nvoid backtrack(vector& nums, int start, vector& path, vector>& result) {\n result.push_back(path);\n for (int i = start; i < nums.size(); i++) {\n path.push_back(nums[i]);\n backtrack(nums, i + 1, path, result);\n path.pop_back();\n }\n}", "test_cases": ["nums=[1,2,3] -> [[],[1],[2],[1,2],[3],[1,3],[2,3],[1,2,3]]"], "key_points": ["选或不选", "DFS遍历子集树"], "tags": ["backtracking", "medium", "Google", "Microsoft"]} {"problem_id": "algo_01314", "original_id": "permutations", "title": "全排列", "category": "backtracking", "difficulty": "medium", "companies": ["Google", "Facebook"], "description": "给定一个不含重复数字的数组 nums,返回其所有可能的全排列。", "solution_python": "def permute(nums):\n result = []\n def backtrack(path, used):\n if len(path) == len(nums):\n result.append(path[:])\n return\n for i in range(len(nums)):\n if used[i]: continue\n used[i] = True\n path.append(nums[i])\n backtrack(path, used)\n path.pop()\n used[i] = False\n backtrack([], [False]*len(nums))\n return result", "solution_java": "public List> permute(int[] nums) {\n List> result = new ArrayList<>();\n boolean[] used = new boolean[nums.length];\n backtrack(nums, used, new ArrayList<>(), result);\n return result;\n}\nprivate void backtrack(int[] nums, boolean[] used, List path, List> result) {\n if (path.size() == nums.length) { result.add(new ArrayList<>(path)); return; }\n for (int i = 0; i < nums.length; i++) {\n if (used[i]) continue;\n used[i] = true;\n path.add(nums[i]);\n backtrack(nums, used, path, result);\n path.remove(path.size() - 1);\n used[i] = false;\n }\n}", "solution_cpp": "vector> permute(vector& nums) {\n vector> result;\n vector used(nums.size(), false);\n vector path;\n backtrack(nums, used, path, result);\n return result;\n}\nvoid backtrack(vector& nums, vector& used, vector& path, vector>& result) {\n if (path.size() == nums.size()) { result.push_back(path); return; }\n for (int i = 0; i < nums.size(); i++) {\n if (used[i]) continue;\n used[i] = true;\n path.push_back(nums[i]);\n backtrack(nums, used, path, result);\n path.pop_back();\n used[i] = false;\n }\n}", "test_cases": ["nums=[1,2,3] -> [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]"], "key_points": ["标记已使用元素", "回溯经典模板"], "tags": ["backtracking", "medium", "Google", "Facebook"]} {"problem_id": "algo_01315", "original_id": "top-k-frequent", "title": "前K个高频元素", "category": "heap", "difficulty": "medium", "companies": ["Amazon", "Facebook"], "description": "给你一个整数数组 nums 和一个整数 k,请你返回其中出现频率前 k 高的元素。", "solution_python": "import heapq\nfrom collections import Counter\ndef topKFrequent(nums, k):\n count = Counter(nums)\n heap = []\n for num, freq in count.items():\n heapq.heappush(heap, (freq, num))\n if len(heap) > k: heapq.heappop(heap)\n return [num for freq, num in heap]", "solution_java": "public int[] topKFrequent(int[] nums, int k) {\n Map count = new HashMap<>();\n for (int n : nums) count.put(n, count.getOrDefault(n, 0) + 1);\n PriorityQueue> heap = \n new PriorityQueue<>((a, b) -> a.getValue() - b.getValue());\n for (Map.Entry e : count.entrySet()) {\n heap.offer(e);\n if (heap.size() > k) heap.poll();\n }\n int[] res = new int[k];\n for (int i = k - 1; i >= 0; i--) res[i] = heap.poll().getKey();\n return res;\n}", "solution_cpp": "vector topKFrequent(vector& nums, int k) {\n unordered_map count;\n for (int n : nums) count[n]++;\n priority_queue, vector>, greater>> heap;\n for (auto& [num, freq] : count) {\n heap.push({freq, num});\n if (heap.size() > k) heap.pop();\n }\n vector res;\n while (!heap.empty()) { res.push_back(heap.top().second); heap.pop(); }\n reverse(res.begin(), res.end());\n return res;\n}", "test_cases": ["nums=[1,1,1,2,2,3], k=2 -> [1,2]", "nums=[1], k=1 -> [1]"], "key_points": ["小顶堆保持大小k", "时间复杂度O(nlogk)"], "tags": ["heap", "medium", "Amazon", "Facebook"]} {"problem_id": "algo_01316", "original_id": "3sum", "title": "三数之和", "category": "two-pointers", "difficulty": "medium", "companies": ["Google", "Amazon"], "description": "给你一个整数数组 nums,判断是否存在三元组满足和为0,返回所有不重复的三元组。", "solution_python": "def threeSum(nums):\n nums.sort()\n result = []\n for i in range(len(nums) - 2):\n if i > 0 and nums[i] == nums[i-1]: continue\n left, right = i + 1, len(nums) - 1\n while left < right:\n total = nums[i] + nums[left] + nums[right]\n if total < 0: left += 1\n elif total > 0: right -= 1\n else:\n result.append([nums[i], nums[left], nums[right]])\n while left < right and nums[left] == nums[left+1]: left += 1\n while left < right and nums[right] == nums[right-1]: right -= 1\n left += 1; right -= 1\n return result", "solution_java": "public List> threeSum(int[] nums) {\n Arrays.sort(nums);\n List> result = new ArrayList<>();\n for (int i = 0; i < nums.length - 2; i++) {\n if (i > 0 && nums[i] == nums[i-1]) continue;\n int left = i + 1, right = nums.length - 1;\n while (left < right) {\n int total = nums[i] + nums[left] + nums[right];\n if (total < 0) left++;\n else if (total > 0) right--;\n else {\n result.add(Arrays.asList(nums[i], nums[left], nums[right]));\n while (left < right && nums[left] == nums[left+1]) left++;\n while (left < right && nums[right] == nums[right-1]) right--;\n left++; right--;\n }\n }\n }\n return result;\n}", "solution_cpp": "vector> threeSum(vector& nums) {\n sort(nums.begin(), nums.end());\n vector> result;\n for (int i = 0; i < nums.size() - 2; i++) {\n if (i > 0 && nums[i] == nums[i-1]) continue;\n int left = i + 1, right = nums.size() - 1;\n while (left < right) {\n int total = nums[i] + nums[left] + nums[right];\n if (total < 0) left++;\n else if (total > 0) right--;\n else {\n result.push_back({nums[i], nums[left], nums[right]});\n while (left < right && nums[left] == nums[left+1]) left++;\n while (left < right && nums[right] == nums[right-1]) right--;\n left++; right--;\n }\n }\n }\n return result;\n}", "test_cases": ["nums=[-1,0,1,2,-1,-4] -> [[-1,-1,2],[-1,0,1]]"], "key_points": ["排序+双指针", "去重是关键"], "tags": ["two-pointers", "medium", "Google", "Amazon"]} {"problem_id": "algo_01317", "original_id": "container-water", "title": "盛最多水的容器", "category": "two-pointers", "difficulty": "medium", "companies": ["Google", "Uber"], "description": "给定一个长度为 n 的整数数组 height,找出其中的两条线,使得它们与 x 轴共同构成的容器可以容纳最多的水。", "solution_python": "def maxArea(height):\n left, right = 0, len(height) - 1\n max_area = 0\n while left < right:\n h = min(height[left], height[right])\n max_area = max(max_area, h * (right - left))\n if height[left] < height[right]: left += 1\n else: right -= 1\n return max_area", "solution_java": "public int maxArea(int[] height) {\n int left = 0, right = height.length - 1, maxArea = 0;\n while (left < right) {\n int h = Math.min(height[left], height[right]);\n maxArea = Math.max(maxArea, h * (right - left));\n if (height[left] < height[right]) left++;\n else right--;\n }\n return maxArea;\n}", "solution_cpp": "int maxArea(vector& height) {\n int left = 0, right = height.size() - 1, maxArea = 0;\n while (left < right) {\n int h = min(height[left], height[right]);\n maxArea = max(maxArea, h * (right - left));\n if (height[left] < height[right]) left++;\n else right--;\n }\n return maxArea;\n}", "test_cases": ["height=[1,8,6,2,5,4,8,3,7] -> 49"], "key_points": ["移动短边指针", "面积=min(h1,h2)*width"], "tags": ["two-pointers", "medium", "Google", "Uber"]} {"problem_id": "algo_01318", "original_id": "min-stack", "title": "最小栈", "category": "stack", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "设计一个支持 push,pop,top 操作,并能在常数时间内检索到最小元素的栈。", "solution_python": "class MinStack:\n def __init__(self):\n self.stack = []\n self.min_stack = []\n def push(self, val):\n self.stack.append(val)\n self.min_stack.append(min(val, self.min_stack[-1] if self.min_stack else val))\n def pop(self):\n self.stack.pop(); self.min_stack.pop()\n def top(self): return self.stack[-1]\n def getMin(self): return self.min_stack[-1]", "solution_java": "class MinStack {\n Stack stack = new Stack<>();\n Stack minStack = new Stack<>();\n public void push(int val) { stack.push(val); minStack.push(Math.min(val, minStack.isEmpty() ? val : minStack.peek())); }\n public void pop() { stack.pop(); minStack.pop(); }\n public int top() { return stack.peek(); }\n public int getMin() { return minStack.peek(); }\n}", "solution_cpp": "class MinStack {\n stack st, minSt;\npublic:\n void push(int val) { st.push(val); minSt.push(min(val, minSt.empty() ? val : minSt.top())); }\n void pop() { st.pop(); minSt.pop(); }\n int top() { return st.top(); }\n int getMin() { return minSt.top(); }\n};", "test_cases": ["push(-2), push(0), push(-3) -> getMin() returns -3"], "key_points": ["辅助栈记录最小值", "O(1)时间获取最小值"], "tags": ["stack", "medium", "Google", "Microsoft"]} {"problem_id": "algo_01319", "original_id": "lru-cache", "title": "LRU缓存", "category": "design", "difficulty": "hard", "companies": ["Google", "Amazon"], "description": "设计和实现一个 LRU(最近最少使用)缓存机制。", "solution_python": "class LRUCache:\n def __init__(self, capacity):\n self.capacity = capacity\n self.cache = {}\n self.order = []\n def get(self, key):\n if key not in self.cache: return -1\n self.order.remove(key); self.order.append(key)\n return self.cache[key]\n def put(self, key, value):\n if key in self.cache:\n self.order.remove(key)\n elif len(self.cache) >= self.capacity:\n del self.cache[self.order.pop(0)]\n self.cache[key] = value; self.order.append(key)", "solution_java": "class LRUCache {\n int capacity;\n LinkedHashMap cache = new LinkedHashMap<>();\n public LRUCache(int cap) { capacity = cap; }\n public int get(int key) { return cache.containsKey(key) ? cache.remove(key) : -1; }\n public void put(int key, int val) {\n if (cache.containsKey(key)) cache.remove(key);\n else if (cache.size() >= capacity) cache.remove(cache.keySet().iterator().next());\n cache.put(key, val);\n }\n}", "solution_cpp": "class LRUCache {\n int cap;\n list> dll;\n unordered_map>::iterator> cache;\npublic:\n LRUCache(int capacity) : cap(capacity) {}\n int get(int key) {\n auto it = cache.find(key);\n if (it == cache.end()) return -1;\n dll.splice(dll.end(), dll, it->second);\n return it->second->second;\n }\n void put(int key, int value) {\n auto it = cache.find(key);\n if (it != cache.end()) dll.erase(it->second);\n else if (cache.size() >= cap) { cache.erase(dll.front().first); dll.pop_front(); }\n dll.push_back({key, value});\n cache[key] = --dll.end();\n }\n};", "test_cases": ["put(1,1), put(2,2), get(1) -> 1"], "key_points": ["HashMap + 双向链表", "O(1)时间操作"], "tags": ["design", "hard", "Google", "Amazon"]} {"problem_id": "algo_01320", "original_id": "num-islands", "title": "岛屿数量", "category": "graph", "difficulty": "medium", "companies": ["Google", "Facebook"], "description": "给你一个由 '1'(陆地)和 '0'(水)组成的二维网格,请你计算网格中岛屿的数量。岛屿总是被水包围,且只能由水平或垂直方向相邻的陆地连接形成。", "solution_python": "def numIslands(grid):\n if not grid: return 0\n rows, cols = len(grid), len(grid[0])\n count = 0\n def dfs(r, c):\n if r < 0 or r >= rows or c < 0 or c >= cols or grid[r][c] != '1': return\n grid[r][c] = '0'\n dfs(r+1, c); dfs(r-1, c); dfs(r, c+1); dfs(r, c-1)\n for r in range(rows):\n for c in range(cols):\n if grid[r][c] == '1': count += 1; dfs(r, c)\n return count", "solution_java": "public int numIslands(char[][] grid) {\n if (grid.length == 0) return 0;\n int count = 0;\n for (int i = 0; i < grid.length; i++)\n for (int j = 0; j < grid[0].length; j++)\n if (grid[i][j] == '1') { count++; dfs(grid, i, j); }\n return count;\n}\nprivate void dfs(char[][] grid, int r, int c) {\n if (r < 0 || r >= grid.length || c < 0 || c >= grid[0].length || grid[r][c] != '1') return;\n grid[r][c] = '0';\n dfs(grid, r+1, c); dfs(grid, r-1, c); dfs(grid, r, c+1); dfs(grid, r, c-1);\n}", "solution_cpp": "int numIslands(vector>& grid) {\n if (grid.empty()) return 0;\n int count = 0;\n for (int i = 0; i < grid.size(); i++)\n for (int j = 0; j < grid[0].size(); j++)\n if (grid[i][j] == '1') { count++; dfs(grid, i, j); }\n return count;\n}\nvoid dfs(vector>& grid, int r, int c) {\n if (r < 0 || r >= grid.size() || c < 0 || c >= grid[0].size() || grid[r][c] != '1') return;\n grid[r][c] = '0';\n dfs(grid, r+1, c); dfs(grid, r-1, c); dfs(grid, r, c+1); dfs(grid, r, c-1);\n}", "test_cases": ["grid=[[1,1,1,1,0],[1,1,0,1,0],[1,1,0,0,0],[0,0,0,0,0]] -> 1"], "key_points": ["DFS/BFS遍历", "访问后标记为0避免重复"], "tags": ["graph", "medium", "Google", "Facebook"]} {"problem_id": "algo_01321", "original_id": "two-sum", "title": "两数之和", "category": "array", "difficulty": "easy", "companies": ["Amazon", "Google"], "description": "给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那两个整数,并返回他们的数组下标。", "solution_python": "def twoSum(nums, target):\n hashmap = {}\n for i, num in enumerate(nums):\n complement = target - num\n if complement in hashmap:\n return [hashmap[complement], i]\n hashmap[num] = i\n return []", "solution_java": "public int[] twoSum(int[] nums, int target) {\n Map map = new HashMap<>();\n for (int i = 0; i < nums.length; i++) {\n int complement = target - nums[i];\n if (map.containsKey(complement)) return new int[]{map.get(complement), i};\n map.put(nums[i], i);\n }\n return new int[]{};\n}", "solution_cpp": "vector twoSum(vector& nums, int target) {\n unordered_map m;\n for (int i = 0; i < nums.size(); i++) {\n if (m.count(target - nums[i])) return {m[target - nums[i]], i};\n m[nums[i]] = i;\n }\n return {};\n}", "test_cases": ["nums=[2,7,11,15], target=9 -> [0,1]", "nums=[3,2,4], target=6 -> [1,2]"], "key_points": ["哈希表一次遍历", "空间换时间"], "tags": ["array", "easy", "Amazon", "Google"]} {"problem_id": "algo_01322", "original_id": "merge-sorted", "title": "合并两个有序数组", "category": "array", "difficulty": "easy", "companies": ["Microsoft", "Uber"], "description": "给你两个按非递减顺序排列的整数数组 nums1 和 nums2,另有两个整数 m 和 n,分别表示 nums1 和 nums2 中的元素数目。请你合并 nums2 到 nums1 中。", "solution_python": "def merge(nums1, m, nums2, n):\n p1, p2, p = m-1, n-1, m+n-1\n while p1 >= 0 and p2 >= 0:\n if nums1[p1] > nums2[p2]: nums1[p] = nums1[p1]; p1 -= 1\n else: nums1[p] = nums2[p2]; p2 -= 1\n p -= 1\n while p2 >= 0: nums1[p] = nums2[p2]; p2 -= 1; p -= 1", "solution_java": "public void merge(int[] nums1, int m, int[] nums2, int n) {\n int p1 = m-1, p2 = n-1, p = m+n-1;\n while (p1 >= 0 && p2 >= 0) {\n nums1[p--] = nums1[p1] > nums2[p2] ? nums1[p1--] : nums2[p2--];\n }\n while (p2 >= 0) nums1[p--] = nums2[p2--];\n}", "solution_cpp": "void merge(vector& nums1, int m, vector& nums2, int n) {\n int p1 = m-1, p2 = n-1, p = m+n-1;\n while (p1 >= 0 && p2 >= 0) nums1[p--] = nums1[p1] > nums2[p2] ? nums1[p1--] : nums2[p2--];\n while (p2 >= 0) nums1[p--] = nums2[p2--];\n}", "test_cases": ["nums1=[1,2,3], m=3, nums2=[2,5,6], n=3 -> [1,2,2,3,5,6]", "nums1=[], m=0, nums2=[1], n=1 -> [1]"], "key_points": ["从后往前合并", "三指针技巧"], "tags": ["array", "easy", "Microsoft", "Uber"]} {"problem_id": "algo_01323", "original_id": "max-subarray", "title": "最大子数组和", "category": "array", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "给你一个整数数组 nums ,请你找出一个具有最大和的连续子数组,返回其最大和。", "solution_python": "def maxSubArray(nums):\n max_sum = current = nums[0]\n for num in nums[1:]:\n current = max(num, current + num)\n max_sum = max(max_sum, current)\n return max_sum", "solution_java": "public int maxSubArray(int[] nums) {\n int maxSum = nums[0], curr = nums[0];\n for (int i = 1; i < nums.length; i++) {\n curr = Math.max(nums[i], curr + nums[i]);\n maxSum = Math.max(maxSum, curr);\n }\n return maxSum;\n}", "solution_cpp": "int maxSubArray(vector& nums) {\n int maxSum = nums[0], curr = nums[0];\n for (int i = 1; i < nums.size(); i++) {\n curr = max(nums[i], curr + nums[i]);\n maxSum = max(maxSum, curr);\n }\n return maxSum;\n}", "test_cases": ["nums=[-2,1,-3,4,-1,2,1,-5,4] -> 6", "nums=[1] -> 1"], "key_points": ["Kadane算法", "动态规划基础题"], "tags": ["array", "medium", "Google", "Microsoft"]} {"problem_id": "algo_01324", "original_id": "valid-parentheses", "title": "有效的括号", "category": "string", "difficulty": "easy", "companies": ["Google", "Uber"], "description": "给定一个只包括 '(',')','{','}','[',']' 的字符串 s,判断字符串是否有效。", "solution_python": "def isValid(s):\n stack = []\n mapping = {')': '(', ']': '[', '}': '{'}\n for c in s:\n if c in mapping:\n if not stack or stack[-1] != mapping[c]: return False\n stack.pop()\n else: stack.append(c)\n return not stack", "solution_java": "public boolean isValid(String s) {\n Stack stack = new Stack<>();\n Map map = Map.of(')', '(', ']', '[', '}', '{');\n for (char c : s.toCharArray()) {\n if (map.containsValue(c)) stack.push(c);\n else if (!stack.isEmpty() && stack.pop() != map.get(c)) return false;\n }\n return stack.isEmpty();\n}", "solution_cpp": "bool isValid(string s) {\n stack st;\n unordered_map m = {{')','('},{']','['},{'}','{'}};\n for (char c : s) {\n if (m.find(c) == m.end()) st.push(c);\n else if (st.empty() || st.top() != m[c]) return false;\n else st.pop();\n }\n return st.empty();\n}", "test_cases": ["s=\"()\" -> true", "s=\"()[]{}\" -> true", "s=\"(]\" -> false"], "key_points": ["栈匹配法", "注意空栈边界"], "tags": ["string", "easy", "Google", "Uber"]} {"problem_id": "algo_01325", "original_id": "longest-palindrome", "title": "最长回文子串", "category": "string", "difficulty": "medium", "companies": ["Google", "Amazon"], "description": "给你一个字符串 s,找到 s 中最长的回文子串。", "solution_python": "def longestPalindrome(s):\n def expand(l, r):\n while l >= 0 and r < len(s) and s[l] == s[r]: l -= 1; r += 1\n return l + 1, r - 1\n start = end = 0\n for i in range(len(s)):\n l1, r1 = expand(i, i)\n l2, r2 = expand(i, i + 1)\n if r1 - l1 > end - start: start, end = l1, r1\n if r2 - l2 > end - start: start, end = l2, r2\n return s[start:end+1]", "solution_java": "public String longestPalindrome(String s) {\n int start = 0, end = 0;\n for (int i = 0; i < s.length(); i++) {\n int len1 = expand(s, i, i), len2 = expand(s, i, i+1);\n int len = Math.max(len1, len2);\n if (len > end - start) { start = i - (len-1)/2; end = i + len/2; }\n }\n return s.substring(start, end + 1);\n}\nprivate int expand(String s, int l, int r) {\n while (l >= 0 && r < s.length() && s.charAt(l) == s.charAt(r)) { l--; r++; }\n return r - l - 1;\n}", "solution_cpp": "string longestPalindrome(string s) {\n int start = 0, end = 0;\n for (int i = 0; i < s.size(); i++) {\n int len1 = expand(s, i, i), len2 = expand(s, i, i+1);\n if (max(len1, len2) > end - start) { start = i - (max(len1,len2)-1)/2; end = i + max(len1,len2)/2; }\n }\n return s.substr(start, end - start + 1);\n}", "test_cases": ["s=\"babad\" -> bab或aba", "s=\"cbbd\" -> bb"], "key_points": ["中心扩展法", "处理奇偶长度"], "tags": ["string", "medium", "Google", "Amazon"]} {"problem_id": "algo_01326", "original_id": "reverse-list", "title": "反转链表", "category": "linkedlist", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "给你单链表的头节点 head,请你反转链表,并返回反转后的链表。", "solution_python": "def reverseList(head):\n prev = None\n curr = head\n while curr:\n nxt = curr.next\n curr.next = prev\n prev = curr\n curr = nxt\n return prev", "solution_java": "public ListNode reverseList(ListNode head) {\n ListNode prev = null, curr = head;\n while (curr != null) {\n ListNode next = curr.next;\n curr.next = prev;\n prev = curr;\n curr = next;\n }\n return prev;\n}", "solution_cpp": "ListNode* reverseList(ListNode* head) {\n ListNode* prev = nullptr, *curr = head;\n while (curr) {\n ListNode* next = curr->next;\n curr->next = prev;\n prev = curr;\n curr = next;\n }\n return prev;\n}", "test_cases": ["head=[1,2,3,4,5] -> [5,4,3,2,1]", "head=[1,2] -> [2,1]"], "key_points": ["迭代法 O(1)空间", "递归法 O(n)空间"], "tags": ["linkedlist", "medium", "Google", "Microsoft"]} {"problem_id": "algo_01327", "original_id": "middle-node", "title": "链表的中间结点", "category": "linkedlist", "difficulty": "easy", "companies": ["Amazon", "Facebook"], "description": "给你单链表的头节点 head,请你找出并返回链表的中间结点。如果有两个中间结点,则返回第二个中间结点。", "solution_python": "def middleNode(head):\n slow = fast = head\n while fast and fast.next:\n slow = slow.next\n fast = fast.next.next\n return slow", "solution_java": "public ListNode middleNode(ListNode head) {\n ListNode slow = head, fast = head;\n while (fast != null && fast.next != null) {\n slow = slow.next;\n fast = fast.next.next;\n }\n return slow;\n}", "solution_cpp": "ListNode* middleNode(ListNode* head) {\n ListNode* slow = head, *fast = head;\n while (fast && fast->next) { slow = slow->next; fast = fast->next->next; }\n return slow;\n}", "test_cases": ["head=[1,2,3,4,5] -> 3", "head=[1,2,3,4,5,6] -> 4"], "key_points": ["快慢指针", "O(n)时间O(1)空间"], "tags": ["linkedlist", "easy", "Amazon", "Facebook"]} {"problem_id": "algo_01328", "original_id": "max-depth", "title": "二叉树的最大深度", "category": "tree", "difficulty": "easy", "companies": ["Microsoft", "Apple"], "description": "给定一个二叉树 root,返回其最大深度。", "solution_python": "def maxDepth(root):\n if not root: return 0\n return max(maxDepth(root.left), maxDepth(root.right)) + 1", "solution_java": "public int maxDepth(TreeNode root) {\n if (root == null) return 0;\n return Math.max(maxDepth(root.left), maxDepth(root.right)) + 1;\n}", "solution_cpp": "int maxDepth(TreeNode* root) {\n if (!root) return 0;\n return max(maxDepth(root->left), maxDepth(root->right)) + 1;\n}", "test_cases": ["root=[3,9,20,null,null,15,7] -> 3", "root=[1,null,2] -> 2"], "key_points": ["DFS递归", "层序遍历也可"], "tags": ["tree", "easy", "Microsoft", "Apple"]} {"problem_id": "algo_01329", "original_id": "inorder-traversal", "title": "二叉树的中序遍历", "category": "tree", "difficulty": "easy", "companies": ["Google", "Microsoft"], "description": "给定一个二叉树的根节点 root,返回它的中序遍历结果。", "solution_python": "def inorderTraversal(root):\n result = []\n def dfs(node):\n if node:\n dfs(node.left)\n result.append(node.val)\n dfs(node.right)\n dfs(root)\n return result", "solution_java": "public List inorderTraversal(TreeNode root) {\n List res = new ArrayList<>();\n dfs(root, res);\n return res;\n}\nprivate void dfs(TreeNode node, List res) {\n if (node == null) return;\n dfs(node.left, res); res.add(node.val); dfs(node.right, res);\n}", "solution_cpp": "vector inorderTraversal(TreeNode* root) {\n vector res;\n dfs(root, res);\n return res;\n}\nvoid dfs(TreeNode* node, vector& res) {\n if (!node) return;\n dfs(node->left, res); res.push_back(node->val); dfs(node->right, res);\n}", "test_cases": ["root=[1,null,2,3] -> [1,3,2]", "root=[] -> []"], "key_points": ["左-根-右顺序", "递归最简洁"], "tags": ["tree", "easy", "Google", "Microsoft"]} {"problem_id": "algo_01330", "original_id": "binary-search", "title": "二分查找", "category": "binarysearch", "difficulty": "easy", "companies": ["Google", "Amazon"], "description": "给定一个 n 个元素有序的(升序)整型数组 nums 和一个目标值 target,写一个函数搜索 nums 中的 target,如果目标值存在返回下标,否则返回 -1。", "solution_python": "def search(nums, target):\n left, right = 0, len(nums) - 1\n while left <= right:\n mid = (left + right) // 2\n if nums[mid] == target: return mid\n elif nums[mid] < target: left = mid + 1\n else: right = mid - 1\n return -1", "solution_java": "public int search(int[] nums, int target) {\n int left = 0, right = nums.length - 1;\n while (left <= right) {\n int mid = left + (right - left) / 2;\n if (nums[mid] == target) return mid;\n else if (nums[mid] < target) left = mid + 1;\n else right = mid - 1;\n }\n return -1;\n}", "solution_cpp": "int search(vector& nums, int target) {\n int left = 0, right = nums.size() - 1;\n while (left <= right) {\n int mid = left + (right - left) / 2;\n if (nums[mid] == target) return mid;\n else if (nums[mid] < target) left = mid + 1;\n else right = mid - 1;\n }\n return -1;\n}", "test_cases": ["nums=[-1,0,3,5,9,12], target=9 -> 4", "nums=[-1,0,3,5,9,12], target=2 -> -1"], "key_points": ["标准模板", "注意防溢出写法"], "tags": ["binarysearch", "easy", "Google", "Amazon"]} {"problem_id": "algo_01331", "original_id": "climbing-stairs", "title": "爬楼梯", "category": "dp", "difficulty": "easy", "companies": ["Amazon", "Google"], "description": "假设你正在爬楼梯。需要 n 阶你才能到达楼顶。每次你可以爬 1 或 2 个台阶。你有多少种不同的方法可以爬到楼顶?", "solution_python": "def climbStairs(n):\n if n <= 2: return n\n a, b = 1, 2\n for _ in range(3, n+1):\n a, b = b, a + b\n return b", "solution_java": "public int climbStairs(int n) {\n if (n <= 2) return n;\n int a = 1, b = 2;\n for (int i = 3; i <= n; i++) { int temp = a + b; a = b; b = temp; }\n return b;\n}", "solution_cpp": "int climbStairs(int n) {\n if (n <= 2) return n;\n int a = 1, b = 2;\n for (int i = 3; i <= n; i++) { int temp = a + b; a = b; b = temp; }\n return b;\n}", "test_cases": ["n=2 -> 2", "n=3 -> 3", "n=5 -> 8"], "key_points": ["斐波那契数列", "滚动数组优化空间"], "tags": ["dp", "easy", "Amazon", "Google"]} {"problem_id": "algo_01332", "original_id": "coin-change", "title": "零钱兑换", "category": "dp", "difficulty": "medium", "companies": ["Google", "Amazon"], "description": "给你一个整数数组 coins 表示不同面额的硬币,以及一个整数 amount 表示总金额。计算并返回可以凑成总金额所需的最少的硬币个数。如果没有任何一种硬币组合能组成总金额,返回 -1。", "solution_python": "def coinChange(coins, amount):\n dp = [float('inf')] * (amount + 1)\n dp[0] = 0\n for coin in coins:\n for x in range(coin, amount + 1):\n dp[x] = min(dp[x], dp[x - coin] + 1)\n return dp[amount] if dp[amount] != float('inf') else -1", "solution_java": "public int coinChange(int[] coins, int amount) {\n int[] dp = new int[amount + 1];\n Arrays.fill(dp, amount + 1);\n dp[0] = 0;\n for (int coin : coins) {\n for (int x = coin; x <= amount; x++) {\n dp[x] = Math.min(dp[x], dp[x - coin] + 1);\n }\n }\n return dp[amount] > amount ? -1 : dp[amount];\n}", "solution_cpp": "int coinChange(vector& coins, int amount) {\n vector dp(amount + 1, amount + 1);\n dp[0] = 0;\n for (int coin : coins) {\n for (int x = coin; x <= amount; x++) {\n dp[x] = min(dp[x], dp[x - coin] + 1);\n }\n }\n return dp[amount] > amount ? -1 : dp[amount];\n}", "test_cases": ["coins=[1,2,5], amount=11 -> 3", "coins=[2], amount=3 -> -1"], "key_points": ["完全背包问题", "dp[x] = min(dp[x-coin]+1)"], "tags": ["dp", "medium", "Google", "Amazon"]} {"problem_id": "algo_01333", "original_id": "subsets", "title": "子集", "category": "backtracking", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "给你一个整数数组 nums ,数组中的元素 互不相同 。返回该数组所有可能的子集(幂集)。", "solution_python": "def subsets(nums):\n result = []\n def backtrack(start, path):\n result.append(path[:])\n for i in range(start, len(nums)):\n path.append(nums[i])\n backtrack(i + 1, path)\n path.pop()\n backtrack(0, [])\n return result", "solution_java": "public List> subsets(int[] nums) {\n List> result = new ArrayList<>();\n backtrack(nums, 0, new ArrayList<>(), result);\n return result;\n}\nprivate void backtrack(int[] nums, int start, List path, List> result) {\n result.add(new ArrayList<>(path));\n for (int i = start; i < nums.length; i++) {\n path.add(nums[i]);\n backtrack(nums, i + 1, path, result);\n path.remove(path.size() - 1);\n }\n}", "solution_cpp": "vector> subsets(vector& nums) {\n vector> result;\n vector path;\n backtrack(nums, 0, path, result);\n return result;\n}\nvoid backtrack(vector& nums, int start, vector& path, vector>& result) {\n result.push_back(path);\n for (int i = start; i < nums.size(); i++) {\n path.push_back(nums[i]);\n backtrack(nums, i + 1, path, result);\n path.pop_back();\n }\n}", "test_cases": ["nums=[1,2,3] -> [[],[1],[2],[1,2],[3],[1,3],[2,3],[1,2,3]]"], "key_points": ["选或不选", "DFS遍历子集树"], "tags": ["backtracking", "medium", "Google", "Microsoft"]} {"problem_id": "algo_01334", "original_id": "permutations", "title": "全排列", "category": "backtracking", "difficulty": "medium", "companies": ["Google", "Facebook"], "description": "给定一个不含重复数字的数组 nums,返回其所有可能的全排列。", "solution_python": "def permute(nums):\n result = []\n def backtrack(path, used):\n if len(path) == len(nums):\n result.append(path[:])\n return\n for i in range(len(nums)):\n if used[i]: continue\n used[i] = True\n path.append(nums[i])\n backtrack(path, used)\n path.pop()\n used[i] = False\n backtrack([], [False]*len(nums))\n return result", "solution_java": "public List> permute(int[] nums) {\n List> result = new ArrayList<>();\n boolean[] used = new boolean[nums.length];\n backtrack(nums, used, new ArrayList<>(), result);\n return result;\n}\nprivate void backtrack(int[] nums, boolean[] used, List path, List> result) {\n if (path.size() == nums.length) { result.add(new ArrayList<>(path)); return; }\n for (int i = 0; i < nums.length; i++) {\n if (used[i]) continue;\n used[i] = true;\n path.add(nums[i]);\n backtrack(nums, used, path, result);\n path.remove(path.size() - 1);\n used[i] = false;\n }\n}", "solution_cpp": "vector> permute(vector& nums) {\n vector> result;\n vector used(nums.size(), false);\n vector path;\n backtrack(nums, used, path, result);\n return result;\n}\nvoid backtrack(vector& nums, vector& used, vector& path, vector>& result) {\n if (path.size() == nums.size()) { result.push_back(path); return; }\n for (int i = 0; i < nums.size(); i++) {\n if (used[i]) continue;\n used[i] = true;\n path.push_back(nums[i]);\n backtrack(nums, used, path, result);\n path.pop_back();\n used[i] = false;\n }\n}", "test_cases": ["nums=[1,2,3] -> [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]"], "key_points": ["标记已使用元素", "回溯经典模板"], "tags": ["backtracking", "medium", "Google", "Facebook"]} {"problem_id": "algo_01335", "original_id": "top-k-frequent", "title": "前K个高频元素", "category": "heap", "difficulty": "medium", "companies": ["Amazon", "Facebook"], "description": "给你一个整数数组 nums 和一个整数 k,请你返回其中出现频率前 k 高的元素。", "solution_python": "import heapq\nfrom collections import Counter\ndef topKFrequent(nums, k):\n count = Counter(nums)\n heap = []\n for num, freq in count.items():\n heapq.heappush(heap, (freq, num))\n if len(heap) > k: heapq.heappop(heap)\n return [num for freq, num in heap]", "solution_java": "public int[] topKFrequent(int[] nums, int k) {\n Map count = new HashMap<>();\n for (int n : nums) count.put(n, count.getOrDefault(n, 0) + 1);\n PriorityQueue> heap = \n new PriorityQueue<>((a, b) -> a.getValue() - b.getValue());\n for (Map.Entry e : count.entrySet()) {\n heap.offer(e);\n if (heap.size() > k) heap.poll();\n }\n int[] res = new int[k];\n for (int i = k - 1; i >= 0; i--) res[i] = heap.poll().getKey();\n return res;\n}", "solution_cpp": "vector topKFrequent(vector& nums, int k) {\n unordered_map count;\n for (int n : nums) count[n]++;\n priority_queue, vector>, greater>> heap;\n for (auto& [num, freq] : count) {\n heap.push({freq, num});\n if (heap.size() > k) heap.pop();\n }\n vector res;\n while (!heap.empty()) { res.push_back(heap.top().second); heap.pop(); }\n reverse(res.begin(), res.end());\n return res;\n}", "test_cases": ["nums=[1,1,1,2,2,3], k=2 -> [1,2]", "nums=[1], k=1 -> [1]"], "key_points": ["小顶堆保持大小k", "时间复杂度O(nlogk)"], "tags": ["heap", "medium", "Amazon", "Facebook"]} {"problem_id": "algo_01336", "original_id": "3sum", "title": "三数之和", "category": "two-pointers", "difficulty": "medium", "companies": ["Google", "Amazon"], "description": "给你一个整数数组 nums,判断是否存在三元组满足和为0,返回所有不重复的三元组。", "solution_python": "def threeSum(nums):\n nums.sort()\n result = []\n for i in range(len(nums) - 2):\n if i > 0 and nums[i] == nums[i-1]: continue\n left, right = i + 1, len(nums) - 1\n while left < right:\n total = nums[i] + nums[left] + nums[right]\n if total < 0: left += 1\n elif total > 0: right -= 1\n else:\n result.append([nums[i], nums[left], nums[right]])\n while left < right and nums[left] == nums[left+1]: left += 1\n while left < right and nums[right] == nums[right-1]: right -= 1\n left += 1; right -= 1\n return result", "solution_java": "public List> threeSum(int[] nums) {\n Arrays.sort(nums);\n List> result = new ArrayList<>();\n for (int i = 0; i < nums.length - 2; i++) {\n if (i > 0 && nums[i] == nums[i-1]) continue;\n int left = i + 1, right = nums.length - 1;\n while (left < right) {\n int total = nums[i] + nums[left] + nums[right];\n if (total < 0) left++;\n else if (total > 0) right--;\n else {\n result.add(Arrays.asList(nums[i], nums[left], nums[right]));\n while (left < right && nums[left] == nums[left+1]) left++;\n while (left < right && nums[right] == nums[right-1]) right--;\n left++; right--;\n }\n }\n }\n return result;\n}", "solution_cpp": "vector> threeSum(vector& nums) {\n sort(nums.begin(), nums.end());\n vector> result;\n for (int i = 0; i < nums.size() - 2; i++) {\n if (i > 0 && nums[i] == nums[i-1]) continue;\n int left = i + 1, right = nums.size() - 1;\n while (left < right) {\n int total = nums[i] + nums[left] + nums[right];\n if (total < 0) left++;\n else if (total > 0) right--;\n else {\n result.push_back({nums[i], nums[left], nums[right]});\n while (left < right && nums[left] == nums[left+1]) left++;\n while (left < right && nums[right] == nums[right-1]) right--;\n left++; right--;\n }\n }\n }\n return result;\n}", "test_cases": ["nums=[-1,0,1,2,-1,-4] -> [[-1,-1,2],[-1,0,1]]"], "key_points": ["排序+双指针", "去重是关键"], "tags": ["two-pointers", "medium", "Google", "Amazon"]} {"problem_id": "algo_01337", "original_id": "container-water", "title": "盛最多水的容器", "category": "two-pointers", "difficulty": "medium", "companies": ["Google", "Uber"], "description": "给定一个长度为 n 的整数数组 height,找出其中的两条线,使得它们与 x 轴共同构成的容器可以容纳最多的水。", "solution_python": "def maxArea(height):\n left, right = 0, len(height) - 1\n max_area = 0\n while left < right:\n h = min(height[left], height[right])\n max_area = max(max_area, h * (right - left))\n if height[left] < height[right]: left += 1\n else: right -= 1\n return max_area", "solution_java": "public int maxArea(int[] height) {\n int left = 0, right = height.length - 1, maxArea = 0;\n while (left < right) {\n int h = Math.min(height[left], height[right]);\n maxArea = Math.max(maxArea, h * (right - left));\n if (height[left] < height[right]) left++;\n else right--;\n }\n return maxArea;\n}", "solution_cpp": "int maxArea(vector& height) {\n int left = 0, right = height.size() - 1, maxArea = 0;\n while (left < right) {\n int h = min(height[left], height[right]);\n maxArea = max(maxArea, h * (right - left));\n if (height[left] < height[right]) left++;\n else right--;\n }\n return maxArea;\n}", "test_cases": ["height=[1,8,6,2,5,4,8,3,7] -> 49"], "key_points": ["移动短边指针", "面积=min(h1,h2)*width"], "tags": ["two-pointers", "medium", "Google", "Uber"]} {"problem_id": "algo_01338", "original_id": "min-stack", "title": "最小栈", "category": "stack", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "设计一个支持 push,pop,top 操作,并能在常数时间内检索到最小元素的栈。", "solution_python": "class MinStack:\n def __init__(self):\n self.stack = []\n self.min_stack = []\n def push(self, val):\n self.stack.append(val)\n self.min_stack.append(min(val, self.min_stack[-1] if self.min_stack else val))\n def pop(self):\n self.stack.pop(); self.min_stack.pop()\n def top(self): return self.stack[-1]\n def getMin(self): return self.min_stack[-1]", "solution_java": "class MinStack {\n Stack stack = new Stack<>();\n Stack minStack = new Stack<>();\n public void push(int val) { stack.push(val); minStack.push(Math.min(val, minStack.isEmpty() ? val : minStack.peek())); }\n public void pop() { stack.pop(); minStack.pop(); }\n public int top() { return stack.peek(); }\n public int getMin() { return minStack.peek(); }\n}", "solution_cpp": "class MinStack {\n stack st, minSt;\npublic:\n void push(int val) { st.push(val); minSt.push(min(val, minSt.empty() ? val : minSt.top())); }\n void pop() { st.pop(); minSt.pop(); }\n int top() { return st.top(); }\n int getMin() { return minSt.top(); }\n};", "test_cases": ["push(-2), push(0), push(-3) -> getMin() returns -3"], "key_points": ["辅助栈记录最小值", "O(1)时间获取最小值"], "tags": ["stack", "medium", "Google", "Microsoft"]} {"problem_id": "algo_01339", "original_id": "lru-cache", "title": "LRU缓存", "category": "design", "difficulty": "hard", "companies": ["Google", "Amazon"], "description": "设计和实现一个 LRU(最近最少使用)缓存机制。", "solution_python": "class LRUCache:\n def __init__(self, capacity):\n self.capacity = capacity\n self.cache = {}\n self.order = []\n def get(self, key):\n if key not in self.cache: return -1\n self.order.remove(key); self.order.append(key)\n return self.cache[key]\n def put(self, key, value):\n if key in self.cache:\n self.order.remove(key)\n elif len(self.cache) >= self.capacity:\n del self.cache[self.order.pop(0)]\n self.cache[key] = value; self.order.append(key)", "solution_java": "class LRUCache {\n int capacity;\n LinkedHashMap cache = new LinkedHashMap<>();\n public LRUCache(int cap) { capacity = cap; }\n public int get(int key) { return cache.containsKey(key) ? cache.remove(key) : -1; }\n public void put(int key, int val) {\n if (cache.containsKey(key)) cache.remove(key);\n else if (cache.size() >= capacity) cache.remove(cache.keySet().iterator().next());\n cache.put(key, val);\n }\n}", "solution_cpp": "class LRUCache {\n int cap;\n list> dll;\n unordered_map>::iterator> cache;\npublic:\n LRUCache(int capacity) : cap(capacity) {}\n int get(int key) {\n auto it = cache.find(key);\n if (it == cache.end()) return -1;\n dll.splice(dll.end(), dll, it->second);\n return it->second->second;\n }\n void put(int key, int value) {\n auto it = cache.find(key);\n if (it != cache.end()) dll.erase(it->second);\n else if (cache.size() >= cap) { cache.erase(dll.front().first); dll.pop_front(); }\n dll.push_back({key, value});\n cache[key] = --dll.end();\n }\n};", "test_cases": ["put(1,1), put(2,2), get(1) -> 1"], "key_points": ["HashMap + 双向链表", "O(1)时间操作"], "tags": ["design", "hard", "Google", "Amazon"]} {"problem_id": "algo_01340", "original_id": "num-islands", "title": "岛屿数量", "category": "graph", "difficulty": "medium", "companies": ["Google", "Facebook"], "description": "给你一个由 '1'(陆地)和 '0'(水)组成的二维网格,请你计算网格中岛屿的数量。岛屿总是被水包围,且只能由水平或垂直方向相邻的陆地连接形成。", "solution_python": "def numIslands(grid):\n if not grid: return 0\n rows, cols = len(grid), len(grid[0])\n count = 0\n def dfs(r, c):\n if r < 0 or r >= rows or c < 0 or c >= cols or grid[r][c] != '1': return\n grid[r][c] = '0'\n dfs(r+1, c); dfs(r-1, c); dfs(r, c+1); dfs(r, c-1)\n for r in range(rows):\n for c in range(cols):\n if grid[r][c] == '1': count += 1; dfs(r, c)\n return count", "solution_java": "public int numIslands(char[][] grid) {\n if (grid.length == 0) return 0;\n int count = 0;\n for (int i = 0; i < grid.length; i++)\n for (int j = 0; j < grid[0].length; j++)\n if (grid[i][j] == '1') { count++; dfs(grid, i, j); }\n return count;\n}\nprivate void dfs(char[][] grid, int r, int c) {\n if (r < 0 || r >= grid.length || c < 0 || c >= grid[0].length || grid[r][c] != '1') return;\n grid[r][c] = '0';\n dfs(grid, r+1, c); dfs(grid, r-1, c); dfs(grid, r, c+1); dfs(grid, r, c-1);\n}", "solution_cpp": "int numIslands(vector>& grid) {\n if (grid.empty()) return 0;\n int count = 0;\n for (int i = 0; i < grid.size(); i++)\n for (int j = 0; j < grid[0].size(); j++)\n if (grid[i][j] == '1') { count++; dfs(grid, i, j); }\n return count;\n}\nvoid dfs(vector>& grid, int r, int c) {\n if (r < 0 || r >= grid.size() || c < 0 || c >= grid[0].size() || grid[r][c] != '1') return;\n grid[r][c] = '0';\n dfs(grid, r+1, c); dfs(grid, r-1, c); dfs(grid, r, c+1); dfs(grid, r, c-1);\n}", "test_cases": ["grid=[[1,1,1,1,0],[1,1,0,1,0],[1,1,0,0,0],[0,0,0,0,0]] -> 1"], "key_points": ["DFS/BFS遍历", "访问后标记为0避免重复"], "tags": ["graph", "medium", "Google", "Facebook"]} {"problem_id": "algo_01341", "original_id": "two-sum", "title": "两数之和", "category": "array", "difficulty": "easy", "companies": ["Amazon", "Google"], "description": "给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那两个整数,并返回他们的数组下标。", "solution_python": "def twoSum(nums, target):\n hashmap = {}\n for i, num in enumerate(nums):\n complement = target - num\n if complement in hashmap:\n return [hashmap[complement], i]\n hashmap[num] = i\n return []", "solution_java": "public int[] twoSum(int[] nums, int target) {\n Map map = new HashMap<>();\n for (int i = 0; i < nums.length; i++) {\n int complement = target - nums[i];\n if (map.containsKey(complement)) return new int[]{map.get(complement), i};\n map.put(nums[i], i);\n }\n return new int[]{};\n}", "solution_cpp": "vector twoSum(vector& nums, int target) {\n unordered_map m;\n for (int i = 0; i < nums.size(); i++) {\n if (m.count(target - nums[i])) return {m[target - nums[i]], i};\n m[nums[i]] = i;\n }\n return {};\n}", "test_cases": ["nums=[2,7,11,15], target=9 -> [0,1]", "nums=[3,2,4], target=6 -> [1,2]"], "key_points": ["哈希表一次遍历", "空间换时间"], "tags": ["array", "easy", "Amazon", "Google"]} {"problem_id": "algo_01342", "original_id": "merge-sorted", "title": "合并两个有序数组", "category": "array", "difficulty": "easy", "companies": ["Microsoft", "Uber"], "description": "给你两个按非递减顺序排列的整数数组 nums1 和 nums2,另有两个整数 m 和 n,分别表示 nums1 和 nums2 中的元素数目。请你合并 nums2 到 nums1 中。", "solution_python": "def merge(nums1, m, nums2, n):\n p1, p2, p = m-1, n-1, m+n-1\n while p1 >= 0 and p2 >= 0:\n if nums1[p1] > nums2[p2]: nums1[p] = nums1[p1]; p1 -= 1\n else: nums1[p] = nums2[p2]; p2 -= 1\n p -= 1\n while p2 >= 0: nums1[p] = nums2[p2]; p2 -= 1; p -= 1", "solution_java": "public void merge(int[] nums1, int m, int[] nums2, int n) {\n int p1 = m-1, p2 = n-1, p = m+n-1;\n while (p1 >= 0 && p2 >= 0) {\n nums1[p--] = nums1[p1] > nums2[p2] ? nums1[p1--] : nums2[p2--];\n }\n while (p2 >= 0) nums1[p--] = nums2[p2--];\n}", "solution_cpp": "void merge(vector& nums1, int m, vector& nums2, int n) {\n int p1 = m-1, p2 = n-1, p = m+n-1;\n while (p1 >= 0 && p2 >= 0) nums1[p--] = nums1[p1] > nums2[p2] ? nums1[p1--] : nums2[p2--];\n while (p2 >= 0) nums1[p--] = nums2[p2--];\n}", "test_cases": ["nums1=[1,2,3], m=3, nums2=[2,5,6], n=3 -> [1,2,2,3,5,6]", "nums1=[], m=0, nums2=[1], n=1 -> [1]"], "key_points": ["从后往前合并", "三指针技巧"], "tags": ["array", "easy", "Microsoft", "Uber"]} {"problem_id": "algo_01343", "original_id": "max-subarray", "title": "最大子数组和", "category": "array", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "给你一个整数数组 nums ,请你找出一个具有最大和的连续子数组,返回其最大和。", "solution_python": "def maxSubArray(nums):\n max_sum = current = nums[0]\n for num in nums[1:]:\n current = max(num, current + num)\n max_sum = max(max_sum, current)\n return max_sum", "solution_java": "public int maxSubArray(int[] nums) {\n int maxSum = nums[0], curr = nums[0];\n for (int i = 1; i < nums.length; i++) {\n curr = Math.max(nums[i], curr + nums[i]);\n maxSum = Math.max(maxSum, curr);\n }\n return maxSum;\n}", "solution_cpp": "int maxSubArray(vector& nums) {\n int maxSum = nums[0], curr = nums[0];\n for (int i = 1; i < nums.size(); i++) {\n curr = max(nums[i], curr + nums[i]);\n maxSum = max(maxSum, curr);\n }\n return maxSum;\n}", "test_cases": ["nums=[-2,1,-3,4,-1,2,1,-5,4] -> 6", "nums=[1] -> 1"], "key_points": ["Kadane算法", "动态规划基础题"], "tags": ["array", "medium", "Google", "Microsoft"]} {"problem_id": "algo_01344", "original_id": "valid-parentheses", "title": "有效的括号", "category": "string", "difficulty": "easy", "companies": ["Google", "Uber"], "description": "给定一个只包括 '(',')','{','}','[',']' 的字符串 s,判断字符串是否有效。", "solution_python": "def isValid(s):\n stack = []\n mapping = {')': '(', ']': '[', '}': '{'}\n for c in s:\n if c in mapping:\n if not stack or stack[-1] != mapping[c]: return False\n stack.pop()\n else: stack.append(c)\n return not stack", "solution_java": "public boolean isValid(String s) {\n Stack stack = new Stack<>();\n Map map = Map.of(')', '(', ']', '[', '}', '{');\n for (char c : s.toCharArray()) {\n if (map.containsValue(c)) stack.push(c);\n else if (!stack.isEmpty() && stack.pop() != map.get(c)) return false;\n }\n return stack.isEmpty();\n}", "solution_cpp": "bool isValid(string s) {\n stack st;\n unordered_map m = {{')','('},{']','['},{'}','{'}};\n for (char c : s) {\n if (m.find(c) == m.end()) st.push(c);\n else if (st.empty() || st.top() != m[c]) return false;\n else st.pop();\n }\n return st.empty();\n}", "test_cases": ["s=\"()\" -> true", "s=\"()[]{}\" -> true", "s=\"(]\" -> false"], "key_points": ["栈匹配法", "注意空栈边界"], "tags": ["string", "easy", "Google", "Uber"]} {"problem_id": "algo_01345", "original_id": "longest-palindrome", "title": "最长回文子串", "category": "string", "difficulty": "medium", "companies": ["Google", "Amazon"], "description": "给你一个字符串 s,找到 s 中最长的回文子串。", "solution_python": "def longestPalindrome(s):\n def expand(l, r):\n while l >= 0 and r < len(s) and s[l] == s[r]: l -= 1; r += 1\n return l + 1, r - 1\n start = end = 0\n for i in range(len(s)):\n l1, r1 = expand(i, i)\n l2, r2 = expand(i, i + 1)\n if r1 - l1 > end - start: start, end = l1, r1\n if r2 - l2 > end - start: start, end = l2, r2\n return s[start:end+1]", "solution_java": "public String longestPalindrome(String s) {\n int start = 0, end = 0;\n for (int i = 0; i < s.length(); i++) {\n int len1 = expand(s, i, i), len2 = expand(s, i, i+1);\n int len = Math.max(len1, len2);\n if (len > end - start) { start = i - (len-1)/2; end = i + len/2; }\n }\n return s.substring(start, end + 1);\n}\nprivate int expand(String s, int l, int r) {\n while (l >= 0 && r < s.length() && s.charAt(l) == s.charAt(r)) { l--; r++; }\n return r - l - 1;\n}", "solution_cpp": "string longestPalindrome(string s) {\n int start = 0, end = 0;\n for (int i = 0; i < s.size(); i++) {\n int len1 = expand(s, i, i), len2 = expand(s, i, i+1);\n if (max(len1, len2) > end - start) { start = i - (max(len1,len2)-1)/2; end = i + max(len1,len2)/2; }\n }\n return s.substr(start, end - start + 1);\n}", "test_cases": ["s=\"babad\" -> bab或aba", "s=\"cbbd\" -> bb"], "key_points": ["中心扩展法", "处理奇偶长度"], "tags": ["string", "medium", "Google", "Amazon"]} {"problem_id": "algo_01346", "original_id": "reverse-list", "title": "反转链表", "category": "linkedlist", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "给你单链表的头节点 head,请你反转链表,并返回反转后的链表。", "solution_python": "def reverseList(head):\n prev = None\n curr = head\n while curr:\n nxt = curr.next\n curr.next = prev\n prev = curr\n curr = nxt\n return prev", "solution_java": "public ListNode reverseList(ListNode head) {\n ListNode prev = null, curr = head;\n while (curr != null) {\n ListNode next = curr.next;\n curr.next = prev;\n prev = curr;\n curr = next;\n }\n return prev;\n}", "solution_cpp": "ListNode* reverseList(ListNode* head) {\n ListNode* prev = nullptr, *curr = head;\n while (curr) {\n ListNode* next = curr->next;\n curr->next = prev;\n prev = curr;\n curr = next;\n }\n return prev;\n}", "test_cases": ["head=[1,2,3,4,5] -> [5,4,3,2,1]", "head=[1,2] -> [2,1]"], "key_points": ["迭代法 O(1)空间", "递归法 O(n)空间"], "tags": ["linkedlist", "medium", "Google", "Microsoft"]} {"problem_id": "algo_01347", "original_id": "middle-node", "title": "链表的中间结点", "category": "linkedlist", "difficulty": "easy", "companies": ["Amazon", "Facebook"], "description": "给你单链表的头节点 head,请你找出并返回链表的中间结点。如果有两个中间结点,则返回第二个中间结点。", "solution_python": "def middleNode(head):\n slow = fast = head\n while fast and fast.next:\n slow = slow.next\n fast = fast.next.next\n return slow", "solution_java": "public ListNode middleNode(ListNode head) {\n ListNode slow = head, fast = head;\n while (fast != null && fast.next != null) {\n slow = slow.next;\n fast = fast.next.next;\n }\n return slow;\n}", "solution_cpp": "ListNode* middleNode(ListNode* head) {\n ListNode* slow = head, *fast = head;\n while (fast && fast->next) { slow = slow->next; fast = fast->next->next; }\n return slow;\n}", "test_cases": ["head=[1,2,3,4,5] -> 3", "head=[1,2,3,4,5,6] -> 4"], "key_points": ["快慢指针", "O(n)时间O(1)空间"], "tags": ["linkedlist", "easy", "Amazon", "Facebook"]} {"problem_id": "algo_01348", "original_id": "max-depth", "title": "二叉树的最大深度", "category": "tree", "difficulty": "easy", "companies": ["Microsoft", "Apple"], "description": "给定一个二叉树 root,返回其最大深度。", "solution_python": "def maxDepth(root):\n if not root: return 0\n return max(maxDepth(root.left), maxDepth(root.right)) + 1", "solution_java": "public int maxDepth(TreeNode root) {\n if (root == null) return 0;\n return Math.max(maxDepth(root.left), maxDepth(root.right)) + 1;\n}", "solution_cpp": "int maxDepth(TreeNode* root) {\n if (!root) return 0;\n return max(maxDepth(root->left), maxDepth(root->right)) + 1;\n}", "test_cases": ["root=[3,9,20,null,null,15,7] -> 3", "root=[1,null,2] -> 2"], "key_points": ["DFS递归", "层序遍历也可"], "tags": ["tree", "easy", "Microsoft", "Apple"]} {"problem_id": "algo_01349", "original_id": "inorder-traversal", "title": "二叉树的中序遍历", "category": "tree", "difficulty": "easy", "companies": ["Google", "Microsoft"], "description": "给定一个二叉树的根节点 root,返回它的中序遍历结果。", "solution_python": "def inorderTraversal(root):\n result = []\n def dfs(node):\n if node:\n dfs(node.left)\n result.append(node.val)\n dfs(node.right)\n dfs(root)\n return result", "solution_java": "public List inorderTraversal(TreeNode root) {\n List res = new ArrayList<>();\n dfs(root, res);\n return res;\n}\nprivate void dfs(TreeNode node, List res) {\n if (node == null) return;\n dfs(node.left, res); res.add(node.val); dfs(node.right, res);\n}", "solution_cpp": "vector inorderTraversal(TreeNode* root) {\n vector res;\n dfs(root, res);\n return res;\n}\nvoid dfs(TreeNode* node, vector& res) {\n if (!node) return;\n dfs(node->left, res); res.push_back(node->val); dfs(node->right, res);\n}", "test_cases": ["root=[1,null,2,3] -> [1,3,2]", "root=[] -> []"], "key_points": ["左-根-右顺序", "递归最简洁"], "tags": ["tree", "easy", "Google", "Microsoft"]} {"problem_id": "algo_01350", "original_id": "binary-search", "title": "二分查找", "category": "binarysearch", "difficulty": "easy", "companies": ["Google", "Amazon"], "description": "给定一个 n 个元素有序的(升序)整型数组 nums 和一个目标值 target,写一个函数搜索 nums 中的 target,如果目标值存在返回下标,否则返回 -1。", "solution_python": "def search(nums, target):\n left, right = 0, len(nums) - 1\n while left <= right:\n mid = (left + right) // 2\n if nums[mid] == target: return mid\n elif nums[mid] < target: left = mid + 1\n else: right = mid - 1\n return -1", "solution_java": "public int search(int[] nums, int target) {\n int left = 0, right = nums.length - 1;\n while (left <= right) {\n int mid = left + (right - left) / 2;\n if (nums[mid] == target) return mid;\n else if (nums[mid] < target) left = mid + 1;\n else right = mid - 1;\n }\n return -1;\n}", "solution_cpp": "int search(vector& nums, int target) {\n int left = 0, right = nums.size() - 1;\n while (left <= right) {\n int mid = left + (right - left) / 2;\n if (nums[mid] == target) return mid;\n else if (nums[mid] < target) left = mid + 1;\n else right = mid - 1;\n }\n return -1;\n}", "test_cases": ["nums=[-1,0,3,5,9,12], target=9 -> 4", "nums=[-1,0,3,5,9,12], target=2 -> -1"], "key_points": ["标准模板", "注意防溢出写法"], "tags": ["binarysearch", "easy", "Google", "Amazon"]} {"problem_id": "algo_01351", "original_id": "climbing-stairs", "title": "爬楼梯", "category": "dp", "difficulty": "easy", "companies": ["Amazon", "Google"], "description": "假设你正在爬楼梯。需要 n 阶你才能到达楼顶。每次你可以爬 1 或 2 个台阶。你有多少种不同的方法可以爬到楼顶?", "solution_python": "def climbStairs(n):\n if n <= 2: return n\n a, b = 1, 2\n for _ in range(3, n+1):\n a, b = b, a + b\n return b", "solution_java": "public int climbStairs(int n) {\n if (n <= 2) return n;\n int a = 1, b = 2;\n for (int i = 3; i <= n; i++) { int temp = a + b; a = b; b = temp; }\n return b;\n}", "solution_cpp": "int climbStairs(int n) {\n if (n <= 2) return n;\n int a = 1, b = 2;\n for (int i = 3; i <= n; i++) { int temp = a + b; a = b; b = temp; }\n return b;\n}", "test_cases": ["n=2 -> 2", "n=3 -> 3", "n=5 -> 8"], "key_points": ["斐波那契数列", "滚动数组优化空间"], "tags": ["dp", "easy", "Amazon", "Google"]} {"problem_id": "algo_01352", "original_id": "coin-change", "title": "零钱兑换", "category": "dp", "difficulty": "medium", "companies": ["Google", "Amazon"], "description": "给你一个整数数组 coins 表示不同面额的硬币,以及一个整数 amount 表示总金额。计算并返回可以凑成总金额所需的最少的硬币个数。如果没有任何一种硬币组合能组成总金额,返回 -1。", "solution_python": "def coinChange(coins, amount):\n dp = [float('inf')] * (amount + 1)\n dp[0] = 0\n for coin in coins:\n for x in range(coin, amount + 1):\n dp[x] = min(dp[x], dp[x - coin] + 1)\n return dp[amount] if dp[amount] != float('inf') else -1", "solution_java": "public int coinChange(int[] coins, int amount) {\n int[] dp = new int[amount + 1];\n Arrays.fill(dp, amount + 1);\n dp[0] = 0;\n for (int coin : coins) {\n for (int x = coin; x <= amount; x++) {\n dp[x] = Math.min(dp[x], dp[x - coin] + 1);\n }\n }\n return dp[amount] > amount ? -1 : dp[amount];\n}", "solution_cpp": "int coinChange(vector& coins, int amount) {\n vector dp(amount + 1, amount + 1);\n dp[0] = 0;\n for (int coin : coins) {\n for (int x = coin; x <= amount; x++) {\n dp[x] = min(dp[x], dp[x - coin] + 1);\n }\n }\n return dp[amount] > amount ? -1 : dp[amount];\n}", "test_cases": ["coins=[1,2,5], amount=11 -> 3", "coins=[2], amount=3 -> -1"], "key_points": ["完全背包问题", "dp[x] = min(dp[x-coin]+1)"], "tags": ["dp", "medium", "Google", "Amazon"]} {"problem_id": "algo_01353", "original_id": "subsets", "title": "子集", "category": "backtracking", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "给你一个整数数组 nums ,数组中的元素 互不相同 。返回该数组所有可能的子集(幂集)。", "solution_python": "def subsets(nums):\n result = []\n def backtrack(start, path):\n result.append(path[:])\n for i in range(start, len(nums)):\n path.append(nums[i])\n backtrack(i + 1, path)\n path.pop()\n backtrack(0, [])\n return result", "solution_java": "public List> subsets(int[] nums) {\n List> result = new ArrayList<>();\n backtrack(nums, 0, new ArrayList<>(), result);\n return result;\n}\nprivate void backtrack(int[] nums, int start, List path, List> result) {\n result.add(new ArrayList<>(path));\n for (int i = start; i < nums.length; i++) {\n path.add(nums[i]);\n backtrack(nums, i + 1, path, result);\n path.remove(path.size() - 1);\n }\n}", "solution_cpp": "vector> subsets(vector& nums) {\n vector> result;\n vector path;\n backtrack(nums, 0, path, result);\n return result;\n}\nvoid backtrack(vector& nums, int start, vector& path, vector>& result) {\n result.push_back(path);\n for (int i = start; i < nums.size(); i++) {\n path.push_back(nums[i]);\n backtrack(nums, i + 1, path, result);\n path.pop_back();\n }\n}", "test_cases": ["nums=[1,2,3] -> [[],[1],[2],[1,2],[3],[1,3],[2,3],[1,2,3]]"], "key_points": ["选或不选", "DFS遍历子集树"], "tags": ["backtracking", "medium", "Google", "Microsoft"]} {"problem_id": "algo_01354", "original_id": "permutations", "title": "全排列", "category": "backtracking", "difficulty": "medium", "companies": ["Google", "Facebook"], "description": "给定一个不含重复数字的数组 nums,返回其所有可能的全排列。", "solution_python": "def permute(nums):\n result = []\n def backtrack(path, used):\n if len(path) == len(nums):\n result.append(path[:])\n return\n for i in range(len(nums)):\n if used[i]: continue\n used[i] = True\n path.append(nums[i])\n backtrack(path, used)\n path.pop()\n used[i] = False\n backtrack([], [False]*len(nums))\n return result", "solution_java": "public List> permute(int[] nums) {\n List> result = new ArrayList<>();\n boolean[] used = new boolean[nums.length];\n backtrack(nums, used, new ArrayList<>(), result);\n return result;\n}\nprivate void backtrack(int[] nums, boolean[] used, List path, List> result) {\n if (path.size() == nums.length) { result.add(new ArrayList<>(path)); return; }\n for (int i = 0; i < nums.length; i++) {\n if (used[i]) continue;\n used[i] = true;\n path.add(nums[i]);\n backtrack(nums, used, path, result);\n path.remove(path.size() - 1);\n used[i] = false;\n }\n}", "solution_cpp": "vector> permute(vector& nums) {\n vector> result;\n vector used(nums.size(), false);\n vector path;\n backtrack(nums, used, path, result);\n return result;\n}\nvoid backtrack(vector& nums, vector& used, vector& path, vector>& result) {\n if (path.size() == nums.size()) { result.push_back(path); return; }\n for (int i = 0; i < nums.size(); i++) {\n if (used[i]) continue;\n used[i] = true;\n path.push_back(nums[i]);\n backtrack(nums, used, path, result);\n path.pop_back();\n used[i] = false;\n }\n}", "test_cases": ["nums=[1,2,3] -> [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]"], "key_points": ["标记已使用元素", "回溯经典模板"], "tags": ["backtracking", "medium", "Google", "Facebook"]} {"problem_id": "algo_01355", "original_id": "top-k-frequent", "title": "前K个高频元素", "category": "heap", "difficulty": "medium", "companies": ["Amazon", "Facebook"], "description": "给你一个整数数组 nums 和一个整数 k,请你返回其中出现频率前 k 高的元素。", "solution_python": "import heapq\nfrom collections import Counter\ndef topKFrequent(nums, k):\n count = Counter(nums)\n heap = []\n for num, freq in count.items():\n heapq.heappush(heap, (freq, num))\n if len(heap) > k: heapq.heappop(heap)\n return [num for freq, num in heap]", "solution_java": "public int[] topKFrequent(int[] nums, int k) {\n Map count = new HashMap<>();\n for (int n : nums) count.put(n, count.getOrDefault(n, 0) + 1);\n PriorityQueue> heap = \n new PriorityQueue<>((a, b) -> a.getValue() - b.getValue());\n for (Map.Entry e : count.entrySet()) {\n heap.offer(e);\n if (heap.size() > k) heap.poll();\n }\n int[] res = new int[k];\n for (int i = k - 1; i >= 0; i--) res[i] = heap.poll().getKey();\n return res;\n}", "solution_cpp": "vector topKFrequent(vector& nums, int k) {\n unordered_map count;\n for (int n : nums) count[n]++;\n priority_queue, vector>, greater>> heap;\n for (auto& [num, freq] : count) {\n heap.push({freq, num});\n if (heap.size() > k) heap.pop();\n }\n vector res;\n while (!heap.empty()) { res.push_back(heap.top().second); heap.pop(); }\n reverse(res.begin(), res.end());\n return res;\n}", "test_cases": ["nums=[1,1,1,2,2,3], k=2 -> [1,2]", "nums=[1], k=1 -> [1]"], "key_points": ["小顶堆保持大小k", "时间复杂度O(nlogk)"], "tags": ["heap", "medium", "Amazon", "Facebook"]} {"problem_id": "algo_01356", "original_id": "3sum", "title": "三数之和", "category": "two-pointers", "difficulty": "medium", "companies": ["Google", "Amazon"], "description": "给你一个整数数组 nums,判断是否存在三元组满足和为0,返回所有不重复的三元组。", "solution_python": "def threeSum(nums):\n nums.sort()\n result = []\n for i in range(len(nums) - 2):\n if i > 0 and nums[i] == nums[i-1]: continue\n left, right = i + 1, len(nums) - 1\n while left < right:\n total = nums[i] + nums[left] + nums[right]\n if total < 0: left += 1\n elif total > 0: right -= 1\n else:\n result.append([nums[i], nums[left], nums[right]])\n while left < right and nums[left] == nums[left+1]: left += 1\n while left < right and nums[right] == nums[right-1]: right -= 1\n left += 1; right -= 1\n return result", "solution_java": "public List> threeSum(int[] nums) {\n Arrays.sort(nums);\n List> result = new ArrayList<>();\n for (int i = 0; i < nums.length - 2; i++) {\n if (i > 0 && nums[i] == nums[i-1]) continue;\n int left = i + 1, right = nums.length - 1;\n while (left < right) {\n int total = nums[i] + nums[left] + nums[right];\n if (total < 0) left++;\n else if (total > 0) right--;\n else {\n result.add(Arrays.asList(nums[i], nums[left], nums[right]));\n while (left < right && nums[left] == nums[left+1]) left++;\n while (left < right && nums[right] == nums[right-1]) right--;\n left++; right--;\n }\n }\n }\n return result;\n}", "solution_cpp": "vector> threeSum(vector& nums) {\n sort(nums.begin(), nums.end());\n vector> result;\n for (int i = 0; i < nums.size() - 2; i++) {\n if (i > 0 && nums[i] == nums[i-1]) continue;\n int left = i + 1, right = nums.size() - 1;\n while (left < right) {\n int total = nums[i] + nums[left] + nums[right];\n if (total < 0) left++;\n else if (total > 0) right--;\n else {\n result.push_back({nums[i], nums[left], nums[right]});\n while (left < right && nums[left] == nums[left+1]) left++;\n while (left < right && nums[right] == nums[right-1]) right--;\n left++; right--;\n }\n }\n }\n return result;\n}", "test_cases": ["nums=[-1,0,1,2,-1,-4] -> [[-1,-1,2],[-1,0,1]]"], "key_points": ["排序+双指针", "去重是关键"], "tags": ["two-pointers", "medium", "Google", "Amazon"]} {"problem_id": "algo_01357", "original_id": "container-water", "title": "盛最多水的容器", "category": "two-pointers", "difficulty": "medium", "companies": ["Google", "Uber"], "description": "给定一个长度为 n 的整数数组 height,找出其中的两条线,使得它们与 x 轴共同构成的容器可以容纳最多的水。", "solution_python": "def maxArea(height):\n left, right = 0, len(height) - 1\n max_area = 0\n while left < right:\n h = min(height[left], height[right])\n max_area = max(max_area, h * (right - left))\n if height[left] < height[right]: left += 1\n else: right -= 1\n return max_area", "solution_java": "public int maxArea(int[] height) {\n int left = 0, right = height.length - 1, maxArea = 0;\n while (left < right) {\n int h = Math.min(height[left], height[right]);\n maxArea = Math.max(maxArea, h * (right - left));\n if (height[left] < height[right]) left++;\n else right--;\n }\n return maxArea;\n}", "solution_cpp": "int maxArea(vector& height) {\n int left = 0, right = height.size() - 1, maxArea = 0;\n while (left < right) {\n int h = min(height[left], height[right]);\n maxArea = max(maxArea, h * (right - left));\n if (height[left] < height[right]) left++;\n else right--;\n }\n return maxArea;\n}", "test_cases": ["height=[1,8,6,2,5,4,8,3,7] -> 49"], "key_points": ["移动短边指针", "面积=min(h1,h2)*width"], "tags": ["two-pointers", "medium", "Google", "Uber"]} {"problem_id": "algo_01358", "original_id": "min-stack", "title": "最小栈", "category": "stack", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "设计一个支持 push,pop,top 操作,并能在常数时间内检索到最小元素的栈。", "solution_python": "class MinStack:\n def __init__(self):\n self.stack = []\n self.min_stack = []\n def push(self, val):\n self.stack.append(val)\n self.min_stack.append(min(val, self.min_stack[-1] if self.min_stack else val))\n def pop(self):\n self.stack.pop(); self.min_stack.pop()\n def top(self): return self.stack[-1]\n def getMin(self): return self.min_stack[-1]", "solution_java": "class MinStack {\n Stack stack = new Stack<>();\n Stack minStack = new Stack<>();\n public void push(int val) { stack.push(val); minStack.push(Math.min(val, minStack.isEmpty() ? val : minStack.peek())); }\n public void pop() { stack.pop(); minStack.pop(); }\n public int top() { return stack.peek(); }\n public int getMin() { return minStack.peek(); }\n}", "solution_cpp": "class MinStack {\n stack st, minSt;\npublic:\n void push(int val) { st.push(val); minSt.push(min(val, minSt.empty() ? val : minSt.top())); }\n void pop() { st.pop(); minSt.pop(); }\n int top() { return st.top(); }\n int getMin() { return minSt.top(); }\n};", "test_cases": ["push(-2), push(0), push(-3) -> getMin() returns -3"], "key_points": ["辅助栈记录最小值", "O(1)时间获取最小值"], "tags": ["stack", "medium", "Google", "Microsoft"]} {"problem_id": "algo_01359", "original_id": "lru-cache", "title": "LRU缓存", "category": "design", "difficulty": "hard", "companies": ["Google", "Amazon"], "description": "设计和实现一个 LRU(最近最少使用)缓存机制。", "solution_python": "class LRUCache:\n def __init__(self, capacity):\n self.capacity = capacity\n self.cache = {}\n self.order = []\n def get(self, key):\n if key not in self.cache: return -1\n self.order.remove(key); self.order.append(key)\n return self.cache[key]\n def put(self, key, value):\n if key in self.cache:\n self.order.remove(key)\n elif len(self.cache) >= self.capacity:\n del self.cache[self.order.pop(0)]\n self.cache[key] = value; self.order.append(key)", "solution_java": "class LRUCache {\n int capacity;\n LinkedHashMap cache = new LinkedHashMap<>();\n public LRUCache(int cap) { capacity = cap; }\n public int get(int key) { return cache.containsKey(key) ? cache.remove(key) : -1; }\n public void put(int key, int val) {\n if (cache.containsKey(key)) cache.remove(key);\n else if (cache.size() >= capacity) cache.remove(cache.keySet().iterator().next());\n cache.put(key, val);\n }\n}", "solution_cpp": "class LRUCache {\n int cap;\n list> dll;\n unordered_map>::iterator> cache;\npublic:\n LRUCache(int capacity) : cap(capacity) {}\n int get(int key) {\n auto it = cache.find(key);\n if (it == cache.end()) return -1;\n dll.splice(dll.end(), dll, it->second);\n return it->second->second;\n }\n void put(int key, int value) {\n auto it = cache.find(key);\n if (it != cache.end()) dll.erase(it->second);\n else if (cache.size() >= cap) { cache.erase(dll.front().first); dll.pop_front(); }\n dll.push_back({key, value});\n cache[key] = --dll.end();\n }\n};", "test_cases": ["put(1,1), put(2,2), get(1) -> 1"], "key_points": ["HashMap + 双向链表", "O(1)时间操作"], "tags": ["design", "hard", "Google", "Amazon"]} {"problem_id": "algo_01360", "original_id": "num-islands", "title": "岛屿数量", "category": "graph", "difficulty": "medium", "companies": ["Google", "Facebook"], "description": "给你一个由 '1'(陆地)和 '0'(水)组成的二维网格,请你计算网格中岛屿的数量。岛屿总是被水包围,且只能由水平或垂直方向相邻的陆地连接形成。", "solution_python": "def numIslands(grid):\n if not grid: return 0\n rows, cols = len(grid), len(grid[0])\n count = 0\n def dfs(r, c):\n if r < 0 or r >= rows or c < 0 or c >= cols or grid[r][c] != '1': return\n grid[r][c] = '0'\n dfs(r+1, c); dfs(r-1, c); dfs(r, c+1); dfs(r, c-1)\n for r in range(rows):\n for c in range(cols):\n if grid[r][c] == '1': count += 1; dfs(r, c)\n return count", "solution_java": "public int numIslands(char[][] grid) {\n if (grid.length == 0) return 0;\n int count = 0;\n for (int i = 0; i < grid.length; i++)\n for (int j = 0; j < grid[0].length; j++)\n if (grid[i][j] == '1') { count++; dfs(grid, i, j); }\n return count;\n}\nprivate void dfs(char[][] grid, int r, int c) {\n if (r < 0 || r >= grid.length || c < 0 || c >= grid[0].length || grid[r][c] != '1') return;\n grid[r][c] = '0';\n dfs(grid, r+1, c); dfs(grid, r-1, c); dfs(grid, r, c+1); dfs(grid, r, c-1);\n}", "solution_cpp": "int numIslands(vector>& grid) {\n if (grid.empty()) return 0;\n int count = 0;\n for (int i = 0; i < grid.size(); i++)\n for (int j = 0; j < grid[0].size(); j++)\n if (grid[i][j] == '1') { count++; dfs(grid, i, j); }\n return count;\n}\nvoid dfs(vector>& grid, int r, int c) {\n if (r < 0 || r >= grid.size() || c < 0 || c >= grid[0].size() || grid[r][c] != '1') return;\n grid[r][c] = '0';\n dfs(grid, r+1, c); dfs(grid, r-1, c); dfs(grid, r, c+1); dfs(grid, r, c-1);\n}", "test_cases": ["grid=[[1,1,1,1,0],[1,1,0,1,0],[1,1,0,0,0],[0,0,0,0,0]] -> 1"], "key_points": ["DFS/BFS遍历", "访问后标记为0避免重复"], "tags": ["graph", "medium", "Google", "Facebook"]} {"problem_id": "algo_01361", "original_id": "two-sum", "title": "两数之和", "category": "array", "difficulty": "easy", "companies": ["Amazon", "Google"], "description": "给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那两个整数,并返回他们的数组下标。", "solution_python": "def twoSum(nums, target):\n hashmap = {}\n for i, num in enumerate(nums):\n complement = target - num\n if complement in hashmap:\n return [hashmap[complement], i]\n hashmap[num] = i\n return []", "solution_java": "public int[] twoSum(int[] nums, int target) {\n Map map = new HashMap<>();\n for (int i = 0; i < nums.length; i++) {\n int complement = target - nums[i];\n if (map.containsKey(complement)) return new int[]{map.get(complement), i};\n map.put(nums[i], i);\n }\n return new int[]{};\n}", "solution_cpp": "vector twoSum(vector& nums, int target) {\n unordered_map m;\n for (int i = 0; i < nums.size(); i++) {\n if (m.count(target - nums[i])) return {m[target - nums[i]], i};\n m[nums[i]] = i;\n }\n return {};\n}", "test_cases": ["nums=[2,7,11,15], target=9 -> [0,1]", "nums=[3,2,4], target=6 -> [1,2]"], "key_points": ["哈希表一次遍历", "空间换时间"], "tags": ["array", "easy", "Amazon", "Google"]} {"problem_id": "algo_01362", "original_id": "merge-sorted", "title": "合并两个有序数组", "category": "array", "difficulty": "easy", "companies": ["Microsoft", "Uber"], "description": "给你两个按非递减顺序排列的整数数组 nums1 和 nums2,另有两个整数 m 和 n,分别表示 nums1 和 nums2 中的元素数目。请你合并 nums2 到 nums1 中。", "solution_python": "def merge(nums1, m, nums2, n):\n p1, p2, p = m-1, n-1, m+n-1\n while p1 >= 0 and p2 >= 0:\n if nums1[p1] > nums2[p2]: nums1[p] = nums1[p1]; p1 -= 1\n else: nums1[p] = nums2[p2]; p2 -= 1\n p -= 1\n while p2 >= 0: nums1[p] = nums2[p2]; p2 -= 1; p -= 1", "solution_java": "public void merge(int[] nums1, int m, int[] nums2, int n) {\n int p1 = m-1, p2 = n-1, p = m+n-1;\n while (p1 >= 0 && p2 >= 0) {\n nums1[p--] = nums1[p1] > nums2[p2] ? nums1[p1--] : nums2[p2--];\n }\n while (p2 >= 0) nums1[p--] = nums2[p2--];\n}", "solution_cpp": "void merge(vector& nums1, int m, vector& nums2, int n) {\n int p1 = m-1, p2 = n-1, p = m+n-1;\n while (p1 >= 0 && p2 >= 0) nums1[p--] = nums1[p1] > nums2[p2] ? nums1[p1--] : nums2[p2--];\n while (p2 >= 0) nums1[p--] = nums2[p2--];\n}", "test_cases": ["nums1=[1,2,3], m=3, nums2=[2,5,6], n=3 -> [1,2,2,3,5,6]", "nums1=[], m=0, nums2=[1], n=1 -> [1]"], "key_points": ["从后往前合并", "三指针技巧"], "tags": ["array", "easy", "Microsoft", "Uber"]} {"problem_id": "algo_01363", "original_id": "max-subarray", "title": "最大子数组和", "category": "array", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "给你一个整数数组 nums ,请你找出一个具有最大和的连续子数组,返回其最大和。", "solution_python": "def maxSubArray(nums):\n max_sum = current = nums[0]\n for num in nums[1:]:\n current = max(num, current + num)\n max_sum = max(max_sum, current)\n return max_sum", "solution_java": "public int maxSubArray(int[] nums) {\n int maxSum = nums[0], curr = nums[0];\n for (int i = 1; i < nums.length; i++) {\n curr = Math.max(nums[i], curr + nums[i]);\n maxSum = Math.max(maxSum, curr);\n }\n return maxSum;\n}", "solution_cpp": "int maxSubArray(vector& nums) {\n int maxSum = nums[0], curr = nums[0];\n for (int i = 1; i < nums.size(); i++) {\n curr = max(nums[i], curr + nums[i]);\n maxSum = max(maxSum, curr);\n }\n return maxSum;\n}", "test_cases": ["nums=[-2,1,-3,4,-1,2,1,-5,4] -> 6", "nums=[1] -> 1"], "key_points": ["Kadane算法", "动态规划基础题"], "tags": ["array", "medium", "Google", "Microsoft"]} {"problem_id": "algo_01364", "original_id": "valid-parentheses", "title": "有效的括号", "category": "string", "difficulty": "easy", "companies": ["Google", "Uber"], "description": "给定一个只包括 '(',')','{','}','[',']' 的字符串 s,判断字符串是否有效。", "solution_python": "def isValid(s):\n stack = []\n mapping = {')': '(', ']': '[', '}': '{'}\n for c in s:\n if c in mapping:\n if not stack or stack[-1] != mapping[c]: return False\n stack.pop()\n else: stack.append(c)\n return not stack", "solution_java": "public boolean isValid(String s) {\n Stack stack = new Stack<>();\n Map map = Map.of(')', '(', ']', '[', '}', '{');\n for (char c : s.toCharArray()) {\n if (map.containsValue(c)) stack.push(c);\n else if (!stack.isEmpty() && stack.pop() != map.get(c)) return false;\n }\n return stack.isEmpty();\n}", "solution_cpp": "bool isValid(string s) {\n stack st;\n unordered_map m = {{')','('},{']','['},{'}','{'}};\n for (char c : s) {\n if (m.find(c) == m.end()) st.push(c);\n else if (st.empty() || st.top() != m[c]) return false;\n else st.pop();\n }\n return st.empty();\n}", "test_cases": ["s=\"()\" -> true", "s=\"()[]{}\" -> true", "s=\"(]\" -> false"], "key_points": ["栈匹配法", "注意空栈边界"], "tags": ["string", "easy", "Google", "Uber"]} {"problem_id": "algo_01365", "original_id": "longest-palindrome", "title": "最长回文子串", "category": "string", "difficulty": "medium", "companies": ["Google", "Amazon"], "description": "给你一个字符串 s,找到 s 中最长的回文子串。", "solution_python": "def longestPalindrome(s):\n def expand(l, r):\n while l >= 0 and r < len(s) and s[l] == s[r]: l -= 1; r += 1\n return l + 1, r - 1\n start = end = 0\n for i in range(len(s)):\n l1, r1 = expand(i, i)\n l2, r2 = expand(i, i + 1)\n if r1 - l1 > end - start: start, end = l1, r1\n if r2 - l2 > end - start: start, end = l2, r2\n return s[start:end+1]", "solution_java": "public String longestPalindrome(String s) {\n int start = 0, end = 0;\n for (int i = 0; i < s.length(); i++) {\n int len1 = expand(s, i, i), len2 = expand(s, i, i+1);\n int len = Math.max(len1, len2);\n if (len > end - start) { start = i - (len-1)/2; end = i + len/2; }\n }\n return s.substring(start, end + 1);\n}\nprivate int expand(String s, int l, int r) {\n while (l >= 0 && r < s.length() && s.charAt(l) == s.charAt(r)) { l--; r++; }\n return r - l - 1;\n}", "solution_cpp": "string longestPalindrome(string s) {\n int start = 0, end = 0;\n for (int i = 0; i < s.size(); i++) {\n int len1 = expand(s, i, i), len2 = expand(s, i, i+1);\n if (max(len1, len2) > end - start) { start = i - (max(len1,len2)-1)/2; end = i + max(len1,len2)/2; }\n }\n return s.substr(start, end - start + 1);\n}", "test_cases": ["s=\"babad\" -> bab或aba", "s=\"cbbd\" -> bb"], "key_points": ["中心扩展法", "处理奇偶长度"], "tags": ["string", "medium", "Google", "Amazon"]} {"problem_id": "algo_01366", "original_id": "reverse-list", "title": "反转链表", "category": "linkedlist", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "给你单链表的头节点 head,请你反转链表,并返回反转后的链表。", "solution_python": "def reverseList(head):\n prev = None\n curr = head\n while curr:\n nxt = curr.next\n curr.next = prev\n prev = curr\n curr = nxt\n return prev", "solution_java": "public ListNode reverseList(ListNode head) {\n ListNode prev = null, curr = head;\n while (curr != null) {\n ListNode next = curr.next;\n curr.next = prev;\n prev = curr;\n curr = next;\n }\n return prev;\n}", "solution_cpp": "ListNode* reverseList(ListNode* head) {\n ListNode* prev = nullptr, *curr = head;\n while (curr) {\n ListNode* next = curr->next;\n curr->next = prev;\n prev = curr;\n curr = next;\n }\n return prev;\n}", "test_cases": ["head=[1,2,3,4,5] -> [5,4,3,2,1]", "head=[1,2] -> [2,1]"], "key_points": ["迭代法 O(1)空间", "递归法 O(n)空间"], "tags": ["linkedlist", "medium", "Google", "Microsoft"]} {"problem_id": "algo_01367", "original_id": "middle-node", "title": "链表的中间结点", "category": "linkedlist", "difficulty": "easy", "companies": ["Amazon", "Facebook"], "description": "给你单链表的头节点 head,请你找出并返回链表的中间结点。如果有两个中间结点,则返回第二个中间结点。", "solution_python": "def middleNode(head):\n slow = fast = head\n while fast and fast.next:\n slow = slow.next\n fast = fast.next.next\n return slow", "solution_java": "public ListNode middleNode(ListNode head) {\n ListNode slow = head, fast = head;\n while (fast != null && fast.next != null) {\n slow = slow.next;\n fast = fast.next.next;\n }\n return slow;\n}", "solution_cpp": "ListNode* middleNode(ListNode* head) {\n ListNode* slow = head, *fast = head;\n while (fast && fast->next) { slow = slow->next; fast = fast->next->next; }\n return slow;\n}", "test_cases": ["head=[1,2,3,4,5] -> 3", "head=[1,2,3,4,5,6] -> 4"], "key_points": ["快慢指针", "O(n)时间O(1)空间"], "tags": ["linkedlist", "easy", "Amazon", "Facebook"]} {"problem_id": "algo_01368", "original_id": "max-depth", "title": "二叉树的最大深度", "category": "tree", "difficulty": "easy", "companies": ["Microsoft", "Apple"], "description": "给定一个二叉树 root,返回其最大深度。", "solution_python": "def maxDepth(root):\n if not root: return 0\n return max(maxDepth(root.left), maxDepth(root.right)) + 1", "solution_java": "public int maxDepth(TreeNode root) {\n if (root == null) return 0;\n return Math.max(maxDepth(root.left), maxDepth(root.right)) + 1;\n}", "solution_cpp": "int maxDepth(TreeNode* root) {\n if (!root) return 0;\n return max(maxDepth(root->left), maxDepth(root->right)) + 1;\n}", "test_cases": ["root=[3,9,20,null,null,15,7] -> 3", "root=[1,null,2] -> 2"], "key_points": ["DFS递归", "层序遍历也可"], "tags": ["tree", "easy", "Microsoft", "Apple"]} {"problem_id": "algo_01369", "original_id": "inorder-traversal", "title": "二叉树的中序遍历", "category": "tree", "difficulty": "easy", "companies": ["Google", "Microsoft"], "description": "给定一个二叉树的根节点 root,返回它的中序遍历结果。", "solution_python": "def inorderTraversal(root):\n result = []\n def dfs(node):\n if node:\n dfs(node.left)\n result.append(node.val)\n dfs(node.right)\n dfs(root)\n return result", "solution_java": "public List inorderTraversal(TreeNode root) {\n List res = new ArrayList<>();\n dfs(root, res);\n return res;\n}\nprivate void dfs(TreeNode node, List res) {\n if (node == null) return;\n dfs(node.left, res); res.add(node.val); dfs(node.right, res);\n}", "solution_cpp": "vector inorderTraversal(TreeNode* root) {\n vector res;\n dfs(root, res);\n return res;\n}\nvoid dfs(TreeNode* node, vector& res) {\n if (!node) return;\n dfs(node->left, res); res.push_back(node->val); dfs(node->right, res);\n}", "test_cases": ["root=[1,null,2,3] -> [1,3,2]", "root=[] -> []"], "key_points": ["左-根-右顺序", "递归最简洁"], "tags": ["tree", "easy", "Google", "Microsoft"]} {"problem_id": "algo_01370", "original_id": "binary-search", "title": "二分查找", "category": "binarysearch", "difficulty": "easy", "companies": ["Google", "Amazon"], "description": "给定一个 n 个元素有序的(升序)整型数组 nums 和一个目标值 target,写一个函数搜索 nums 中的 target,如果目标值存在返回下标,否则返回 -1。", "solution_python": "def search(nums, target):\n left, right = 0, len(nums) - 1\n while left <= right:\n mid = (left + right) // 2\n if nums[mid] == target: return mid\n elif nums[mid] < target: left = mid + 1\n else: right = mid - 1\n return -1", "solution_java": "public int search(int[] nums, int target) {\n int left = 0, right = nums.length - 1;\n while (left <= right) {\n int mid = left + (right - left) / 2;\n if (nums[mid] == target) return mid;\n else if (nums[mid] < target) left = mid + 1;\n else right = mid - 1;\n }\n return -1;\n}", "solution_cpp": "int search(vector& nums, int target) {\n int left = 0, right = nums.size() - 1;\n while (left <= right) {\n int mid = left + (right - left) / 2;\n if (nums[mid] == target) return mid;\n else if (nums[mid] < target) left = mid + 1;\n else right = mid - 1;\n }\n return -1;\n}", "test_cases": ["nums=[-1,0,3,5,9,12], target=9 -> 4", "nums=[-1,0,3,5,9,12], target=2 -> -1"], "key_points": ["标准模板", "注意防溢出写法"], "tags": ["binarysearch", "easy", "Google", "Amazon"]} {"problem_id": "algo_01371", "original_id": "climbing-stairs", "title": "爬楼梯", "category": "dp", "difficulty": "easy", "companies": ["Amazon", "Google"], "description": "假设你正在爬楼梯。需要 n 阶你才能到达楼顶。每次你可以爬 1 或 2 个台阶。你有多少种不同的方法可以爬到楼顶?", "solution_python": "def climbStairs(n):\n if n <= 2: return n\n a, b = 1, 2\n for _ in range(3, n+1):\n a, b = b, a + b\n return b", "solution_java": "public int climbStairs(int n) {\n if (n <= 2) return n;\n int a = 1, b = 2;\n for (int i = 3; i <= n; i++) { int temp = a + b; a = b; b = temp; }\n return b;\n}", "solution_cpp": "int climbStairs(int n) {\n if (n <= 2) return n;\n int a = 1, b = 2;\n for (int i = 3; i <= n; i++) { int temp = a + b; a = b; b = temp; }\n return b;\n}", "test_cases": ["n=2 -> 2", "n=3 -> 3", "n=5 -> 8"], "key_points": ["斐波那契数列", "滚动数组优化空间"], "tags": ["dp", "easy", "Amazon", "Google"]} {"problem_id": "algo_01372", "original_id": "coin-change", "title": "零钱兑换", "category": "dp", "difficulty": "medium", "companies": ["Google", "Amazon"], "description": "给你一个整数数组 coins 表示不同面额的硬币,以及一个整数 amount 表示总金额。计算并返回可以凑成总金额所需的最少的硬币个数。如果没有任何一种硬币组合能组成总金额,返回 -1。", "solution_python": "def coinChange(coins, amount):\n dp = [float('inf')] * (amount + 1)\n dp[0] = 0\n for coin in coins:\n for x in range(coin, amount + 1):\n dp[x] = min(dp[x], dp[x - coin] + 1)\n return dp[amount] if dp[amount] != float('inf') else -1", "solution_java": "public int coinChange(int[] coins, int amount) {\n int[] dp = new int[amount + 1];\n Arrays.fill(dp, amount + 1);\n dp[0] = 0;\n for (int coin : coins) {\n for (int x = coin; x <= amount; x++) {\n dp[x] = Math.min(dp[x], dp[x - coin] + 1);\n }\n }\n return dp[amount] > amount ? -1 : dp[amount];\n}", "solution_cpp": "int coinChange(vector& coins, int amount) {\n vector dp(amount + 1, amount + 1);\n dp[0] = 0;\n for (int coin : coins) {\n for (int x = coin; x <= amount; x++) {\n dp[x] = min(dp[x], dp[x - coin] + 1);\n }\n }\n return dp[amount] > amount ? -1 : dp[amount];\n}", "test_cases": ["coins=[1,2,5], amount=11 -> 3", "coins=[2], amount=3 -> -1"], "key_points": ["完全背包问题", "dp[x] = min(dp[x-coin]+1)"], "tags": ["dp", "medium", "Google", "Amazon"]} {"problem_id": "algo_01373", "original_id": "subsets", "title": "子集", "category": "backtracking", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "给你一个整数数组 nums ,数组中的元素 互不相同 。返回该数组所有可能的子集(幂集)。", "solution_python": "def subsets(nums):\n result = []\n def backtrack(start, path):\n result.append(path[:])\n for i in range(start, len(nums)):\n path.append(nums[i])\n backtrack(i + 1, path)\n path.pop()\n backtrack(0, [])\n return result", "solution_java": "public List> subsets(int[] nums) {\n List> result = new ArrayList<>();\n backtrack(nums, 0, new ArrayList<>(), result);\n return result;\n}\nprivate void backtrack(int[] nums, int start, List path, List> result) {\n result.add(new ArrayList<>(path));\n for (int i = start; i < nums.length; i++) {\n path.add(nums[i]);\n backtrack(nums, i + 1, path, result);\n path.remove(path.size() - 1);\n }\n}", "solution_cpp": "vector> subsets(vector& nums) {\n vector> result;\n vector path;\n backtrack(nums, 0, path, result);\n return result;\n}\nvoid backtrack(vector& nums, int start, vector& path, vector>& result) {\n result.push_back(path);\n for (int i = start; i < nums.size(); i++) {\n path.push_back(nums[i]);\n backtrack(nums, i + 1, path, result);\n path.pop_back();\n }\n}", "test_cases": ["nums=[1,2,3] -> [[],[1],[2],[1,2],[3],[1,3],[2,3],[1,2,3]]"], "key_points": ["选或不选", "DFS遍历子集树"], "tags": ["backtracking", "medium", "Google", "Microsoft"]} {"problem_id": "algo_01374", "original_id": "permutations", "title": "全排列", "category": "backtracking", "difficulty": "medium", "companies": ["Google", "Facebook"], "description": "给定一个不含重复数字的数组 nums,返回其所有可能的全排列。", "solution_python": "def permute(nums):\n result = []\n def backtrack(path, used):\n if len(path) == len(nums):\n result.append(path[:])\n return\n for i in range(len(nums)):\n if used[i]: continue\n used[i] = True\n path.append(nums[i])\n backtrack(path, used)\n path.pop()\n used[i] = False\n backtrack([], [False]*len(nums))\n return result", "solution_java": "public List> permute(int[] nums) {\n List> result = new ArrayList<>();\n boolean[] used = new boolean[nums.length];\n backtrack(nums, used, new ArrayList<>(), result);\n return result;\n}\nprivate void backtrack(int[] nums, boolean[] used, List path, List> result) {\n if (path.size() == nums.length) { result.add(new ArrayList<>(path)); return; }\n for (int i = 0; i < nums.length; i++) {\n if (used[i]) continue;\n used[i] = true;\n path.add(nums[i]);\n backtrack(nums, used, path, result);\n path.remove(path.size() - 1);\n used[i] = false;\n }\n}", "solution_cpp": "vector> permute(vector& nums) {\n vector> result;\n vector used(nums.size(), false);\n vector path;\n backtrack(nums, used, path, result);\n return result;\n}\nvoid backtrack(vector& nums, vector& used, vector& path, vector>& result) {\n if (path.size() == nums.size()) { result.push_back(path); return; }\n for (int i = 0; i < nums.size(); i++) {\n if (used[i]) continue;\n used[i] = true;\n path.push_back(nums[i]);\n backtrack(nums, used, path, result);\n path.pop_back();\n used[i] = false;\n }\n}", "test_cases": ["nums=[1,2,3] -> [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]"], "key_points": ["标记已使用元素", "回溯经典模板"], "tags": ["backtracking", "medium", "Google", "Facebook"]} {"problem_id": "algo_01375", "original_id": "top-k-frequent", "title": "前K个高频元素", "category": "heap", "difficulty": "medium", "companies": ["Amazon", "Facebook"], "description": "给你一个整数数组 nums 和一个整数 k,请你返回其中出现频率前 k 高的元素。", "solution_python": "import heapq\nfrom collections import Counter\ndef topKFrequent(nums, k):\n count = Counter(nums)\n heap = []\n for num, freq in count.items():\n heapq.heappush(heap, (freq, num))\n if len(heap) > k: heapq.heappop(heap)\n return [num for freq, num in heap]", "solution_java": "public int[] topKFrequent(int[] nums, int k) {\n Map count = new HashMap<>();\n for (int n : nums) count.put(n, count.getOrDefault(n, 0) + 1);\n PriorityQueue> heap = \n new PriorityQueue<>((a, b) -> a.getValue() - b.getValue());\n for (Map.Entry e : count.entrySet()) {\n heap.offer(e);\n if (heap.size() > k) heap.poll();\n }\n int[] res = new int[k];\n for (int i = k - 1; i >= 0; i--) res[i] = heap.poll().getKey();\n return res;\n}", "solution_cpp": "vector topKFrequent(vector& nums, int k) {\n unordered_map count;\n for (int n : nums) count[n]++;\n priority_queue, vector>, greater>> heap;\n for (auto& [num, freq] : count) {\n heap.push({freq, num});\n if (heap.size() > k) heap.pop();\n }\n vector res;\n while (!heap.empty()) { res.push_back(heap.top().second); heap.pop(); }\n reverse(res.begin(), res.end());\n return res;\n}", "test_cases": ["nums=[1,1,1,2,2,3], k=2 -> [1,2]", "nums=[1], k=1 -> [1]"], "key_points": ["小顶堆保持大小k", "时间复杂度O(nlogk)"], "tags": ["heap", "medium", "Amazon", "Facebook"]} {"problem_id": "algo_01376", "original_id": "3sum", "title": "三数之和", "category": "two-pointers", "difficulty": "medium", "companies": ["Google", "Amazon"], "description": "给你一个整数数组 nums,判断是否存在三元组满足和为0,返回所有不重复的三元组。", "solution_python": "def threeSum(nums):\n nums.sort()\n result = []\n for i in range(len(nums) - 2):\n if i > 0 and nums[i] == nums[i-1]: continue\n left, right = i + 1, len(nums) - 1\n while left < right:\n total = nums[i] + nums[left] + nums[right]\n if total < 0: left += 1\n elif total > 0: right -= 1\n else:\n result.append([nums[i], nums[left], nums[right]])\n while left < right and nums[left] == nums[left+1]: left += 1\n while left < right and nums[right] == nums[right-1]: right -= 1\n left += 1; right -= 1\n return result", "solution_java": "public List> threeSum(int[] nums) {\n Arrays.sort(nums);\n List> result = new ArrayList<>();\n for (int i = 0; i < nums.length - 2; i++) {\n if (i > 0 && nums[i] == nums[i-1]) continue;\n int left = i + 1, right = nums.length - 1;\n while (left < right) {\n int total = nums[i] + nums[left] + nums[right];\n if (total < 0) left++;\n else if (total > 0) right--;\n else {\n result.add(Arrays.asList(nums[i], nums[left], nums[right]));\n while (left < right && nums[left] == nums[left+1]) left++;\n while (left < right && nums[right] == nums[right-1]) right--;\n left++; right--;\n }\n }\n }\n return result;\n}", "solution_cpp": "vector> threeSum(vector& nums) {\n sort(nums.begin(), nums.end());\n vector> result;\n for (int i = 0; i < nums.size() - 2; i++) {\n if (i > 0 && nums[i] == nums[i-1]) continue;\n int left = i + 1, right = nums.size() - 1;\n while (left < right) {\n int total = nums[i] + nums[left] + nums[right];\n if (total < 0) left++;\n else if (total > 0) right--;\n else {\n result.push_back({nums[i], nums[left], nums[right]});\n while (left < right && nums[left] == nums[left+1]) left++;\n while (left < right && nums[right] == nums[right-1]) right--;\n left++; right--;\n }\n }\n }\n return result;\n}", "test_cases": ["nums=[-1,0,1,2,-1,-4] -> [[-1,-1,2],[-1,0,1]]"], "key_points": ["排序+双指针", "去重是关键"], "tags": ["two-pointers", "medium", "Google", "Amazon"]} {"problem_id": "algo_01377", "original_id": "container-water", "title": "盛最多水的容器", "category": "two-pointers", "difficulty": "medium", "companies": ["Google", "Uber"], "description": "给定一个长度为 n 的整数数组 height,找出其中的两条线,使得它们与 x 轴共同构成的容器可以容纳最多的水。", "solution_python": "def maxArea(height):\n left, right = 0, len(height) - 1\n max_area = 0\n while left < right:\n h = min(height[left], height[right])\n max_area = max(max_area, h * (right - left))\n if height[left] < height[right]: left += 1\n else: right -= 1\n return max_area", "solution_java": "public int maxArea(int[] height) {\n int left = 0, right = height.length - 1, maxArea = 0;\n while (left < right) {\n int h = Math.min(height[left], height[right]);\n maxArea = Math.max(maxArea, h * (right - left));\n if (height[left] < height[right]) left++;\n else right--;\n }\n return maxArea;\n}", "solution_cpp": "int maxArea(vector& height) {\n int left = 0, right = height.size() - 1, maxArea = 0;\n while (left < right) {\n int h = min(height[left], height[right]);\n maxArea = max(maxArea, h * (right - left));\n if (height[left] < height[right]) left++;\n else right--;\n }\n return maxArea;\n}", "test_cases": ["height=[1,8,6,2,5,4,8,3,7] -> 49"], "key_points": ["移动短边指针", "面积=min(h1,h2)*width"], "tags": ["two-pointers", "medium", "Google", "Uber"]} {"problem_id": "algo_01378", "original_id": "min-stack", "title": "最小栈", "category": "stack", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "设计一个支持 push,pop,top 操作,并能在常数时间内检索到最小元素的栈。", "solution_python": "class MinStack:\n def __init__(self):\n self.stack = []\n self.min_stack = []\n def push(self, val):\n self.stack.append(val)\n self.min_stack.append(min(val, self.min_stack[-1] if self.min_stack else val))\n def pop(self):\n self.stack.pop(); self.min_stack.pop()\n def top(self): return self.stack[-1]\n def getMin(self): return self.min_stack[-1]", "solution_java": "class MinStack {\n Stack stack = new Stack<>();\n Stack minStack = new Stack<>();\n public void push(int val) { stack.push(val); minStack.push(Math.min(val, minStack.isEmpty() ? val : minStack.peek())); }\n public void pop() { stack.pop(); minStack.pop(); }\n public int top() { return stack.peek(); }\n public int getMin() { return minStack.peek(); }\n}", "solution_cpp": "class MinStack {\n stack st, minSt;\npublic:\n void push(int val) { st.push(val); minSt.push(min(val, minSt.empty() ? val : minSt.top())); }\n void pop() { st.pop(); minSt.pop(); }\n int top() { return st.top(); }\n int getMin() { return minSt.top(); }\n};", "test_cases": ["push(-2), push(0), push(-3) -> getMin() returns -3"], "key_points": ["辅助栈记录最小值", "O(1)时间获取最小值"], "tags": ["stack", "medium", "Google", "Microsoft"]} {"problem_id": "algo_01379", "original_id": "lru-cache", "title": "LRU缓存", "category": "design", "difficulty": "hard", "companies": ["Google", "Amazon"], "description": "设计和实现一个 LRU(最近最少使用)缓存机制。", "solution_python": "class LRUCache:\n def __init__(self, capacity):\n self.capacity = capacity\n self.cache = {}\n self.order = []\n def get(self, key):\n if key not in self.cache: return -1\n self.order.remove(key); self.order.append(key)\n return self.cache[key]\n def put(self, key, value):\n if key in self.cache:\n self.order.remove(key)\n elif len(self.cache) >= self.capacity:\n del self.cache[self.order.pop(0)]\n self.cache[key] = value; self.order.append(key)", "solution_java": "class LRUCache {\n int capacity;\n LinkedHashMap cache = new LinkedHashMap<>();\n public LRUCache(int cap) { capacity = cap; }\n public int get(int key) { return cache.containsKey(key) ? cache.remove(key) : -1; }\n public void put(int key, int val) {\n if (cache.containsKey(key)) cache.remove(key);\n else if (cache.size() >= capacity) cache.remove(cache.keySet().iterator().next());\n cache.put(key, val);\n }\n}", "solution_cpp": "class LRUCache {\n int cap;\n list> dll;\n unordered_map>::iterator> cache;\npublic:\n LRUCache(int capacity) : cap(capacity) {}\n int get(int key) {\n auto it = cache.find(key);\n if (it == cache.end()) return -1;\n dll.splice(dll.end(), dll, it->second);\n return it->second->second;\n }\n void put(int key, int value) {\n auto it = cache.find(key);\n if (it != cache.end()) dll.erase(it->second);\n else if (cache.size() >= cap) { cache.erase(dll.front().first); dll.pop_front(); }\n dll.push_back({key, value});\n cache[key] = --dll.end();\n }\n};", "test_cases": ["put(1,1), put(2,2), get(1) -> 1"], "key_points": ["HashMap + 双向链表", "O(1)时间操作"], "tags": ["design", "hard", "Google", "Amazon"]} {"problem_id": "algo_01380", "original_id": "num-islands", "title": "岛屿数量", "category": "graph", "difficulty": "medium", "companies": ["Google", "Facebook"], "description": "给你一个由 '1'(陆地)和 '0'(水)组成的二维网格,请你计算网格中岛屿的数量。岛屿总是被水包围,且只能由水平或垂直方向相邻的陆地连接形成。", "solution_python": "def numIslands(grid):\n if not grid: return 0\n rows, cols = len(grid), len(grid[0])\n count = 0\n def dfs(r, c):\n if r < 0 or r >= rows or c < 0 or c >= cols or grid[r][c] != '1': return\n grid[r][c] = '0'\n dfs(r+1, c); dfs(r-1, c); dfs(r, c+1); dfs(r, c-1)\n for r in range(rows):\n for c in range(cols):\n if grid[r][c] == '1': count += 1; dfs(r, c)\n return count", "solution_java": "public int numIslands(char[][] grid) {\n if (grid.length == 0) return 0;\n int count = 0;\n for (int i = 0; i < grid.length; i++)\n for (int j = 0; j < grid[0].length; j++)\n if (grid[i][j] == '1') { count++; dfs(grid, i, j); }\n return count;\n}\nprivate void dfs(char[][] grid, int r, int c) {\n if (r < 0 || r >= grid.length || c < 0 || c >= grid[0].length || grid[r][c] != '1') return;\n grid[r][c] = '0';\n dfs(grid, r+1, c); dfs(grid, r-1, c); dfs(grid, r, c+1); dfs(grid, r, c-1);\n}", "solution_cpp": "int numIslands(vector>& grid) {\n if (grid.empty()) return 0;\n int count = 0;\n for (int i = 0; i < grid.size(); i++)\n for (int j = 0; j < grid[0].size(); j++)\n if (grid[i][j] == '1') { count++; dfs(grid, i, j); }\n return count;\n}\nvoid dfs(vector>& grid, int r, int c) {\n if (r < 0 || r >= grid.size() || c < 0 || c >= grid[0].size() || grid[r][c] != '1') return;\n grid[r][c] = '0';\n dfs(grid, r+1, c); dfs(grid, r-1, c); dfs(grid, r, c+1); dfs(grid, r, c-1);\n}", "test_cases": ["grid=[[1,1,1,1,0],[1,1,0,1,0],[1,1,0,0,0],[0,0,0,0,0]] -> 1"], "key_points": ["DFS/BFS遍历", "访问后标记为0避免重复"], "tags": ["graph", "medium", "Google", "Facebook"]} {"problem_id": "algo_01381", "original_id": "two-sum", "title": "两数之和", "category": "array", "difficulty": "easy", "companies": ["Amazon", "Google"], "description": "给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那两个整数,并返回他们的数组下标。", "solution_python": "def twoSum(nums, target):\n hashmap = {}\n for i, num in enumerate(nums):\n complement = target - num\n if complement in hashmap:\n return [hashmap[complement], i]\n hashmap[num] = i\n return []", "solution_java": "public int[] twoSum(int[] nums, int target) {\n Map map = new HashMap<>();\n for (int i = 0; i < nums.length; i++) {\n int complement = target - nums[i];\n if (map.containsKey(complement)) return new int[]{map.get(complement), i};\n map.put(nums[i], i);\n }\n return new int[]{};\n}", "solution_cpp": "vector twoSum(vector& nums, int target) {\n unordered_map m;\n for (int i = 0; i < nums.size(); i++) {\n if (m.count(target - nums[i])) return {m[target - nums[i]], i};\n m[nums[i]] = i;\n }\n return {};\n}", "test_cases": ["nums=[2,7,11,15], target=9 -> [0,1]", "nums=[3,2,4], target=6 -> [1,2]"], "key_points": ["哈希表一次遍历", "空间换时间"], "tags": ["array", "easy", "Amazon", "Google"]} {"problem_id": "algo_01382", "original_id": "merge-sorted", "title": "合并两个有序数组", "category": "array", "difficulty": "easy", "companies": ["Microsoft", "Uber"], "description": "给你两个按非递减顺序排列的整数数组 nums1 和 nums2,另有两个整数 m 和 n,分别表示 nums1 和 nums2 中的元素数目。请你合并 nums2 到 nums1 中。", "solution_python": "def merge(nums1, m, nums2, n):\n p1, p2, p = m-1, n-1, m+n-1\n while p1 >= 0 and p2 >= 0:\n if nums1[p1] > nums2[p2]: nums1[p] = nums1[p1]; p1 -= 1\n else: nums1[p] = nums2[p2]; p2 -= 1\n p -= 1\n while p2 >= 0: nums1[p] = nums2[p2]; p2 -= 1; p -= 1", "solution_java": "public void merge(int[] nums1, int m, int[] nums2, int n) {\n int p1 = m-1, p2 = n-1, p = m+n-1;\n while (p1 >= 0 && p2 >= 0) {\n nums1[p--] = nums1[p1] > nums2[p2] ? nums1[p1--] : nums2[p2--];\n }\n while (p2 >= 0) nums1[p--] = nums2[p2--];\n}", "solution_cpp": "void merge(vector& nums1, int m, vector& nums2, int n) {\n int p1 = m-1, p2 = n-1, p = m+n-1;\n while (p1 >= 0 && p2 >= 0) nums1[p--] = nums1[p1] > nums2[p2] ? nums1[p1--] : nums2[p2--];\n while (p2 >= 0) nums1[p--] = nums2[p2--];\n}", "test_cases": ["nums1=[1,2,3], m=3, nums2=[2,5,6], n=3 -> [1,2,2,3,5,6]", "nums1=[], m=0, nums2=[1], n=1 -> [1]"], "key_points": ["从后往前合并", "三指针技巧"], "tags": ["array", "easy", "Microsoft", "Uber"]} {"problem_id": "algo_01383", "original_id": "max-subarray", "title": "最大子数组和", "category": "array", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "给你一个整数数组 nums ,请你找出一个具有最大和的连续子数组,返回其最大和。", "solution_python": "def maxSubArray(nums):\n max_sum = current = nums[0]\n for num in nums[1:]:\n current = max(num, current + num)\n max_sum = max(max_sum, current)\n return max_sum", "solution_java": "public int maxSubArray(int[] nums) {\n int maxSum = nums[0], curr = nums[0];\n for (int i = 1; i < nums.length; i++) {\n curr = Math.max(nums[i], curr + nums[i]);\n maxSum = Math.max(maxSum, curr);\n }\n return maxSum;\n}", "solution_cpp": "int maxSubArray(vector& nums) {\n int maxSum = nums[0], curr = nums[0];\n for (int i = 1; i < nums.size(); i++) {\n curr = max(nums[i], curr + nums[i]);\n maxSum = max(maxSum, curr);\n }\n return maxSum;\n}", "test_cases": ["nums=[-2,1,-3,4,-1,2,1,-5,4] -> 6", "nums=[1] -> 1"], "key_points": ["Kadane算法", "动态规划基础题"], "tags": ["array", "medium", "Google", "Microsoft"]} {"problem_id": "algo_01384", "original_id": "valid-parentheses", "title": "有效的括号", "category": "string", "difficulty": "easy", "companies": ["Google", "Uber"], "description": "给定一个只包括 '(',')','{','}','[',']' 的字符串 s,判断字符串是否有效。", "solution_python": "def isValid(s):\n stack = []\n mapping = {')': '(', ']': '[', '}': '{'}\n for c in s:\n if c in mapping:\n if not stack or stack[-1] != mapping[c]: return False\n stack.pop()\n else: stack.append(c)\n return not stack", "solution_java": "public boolean isValid(String s) {\n Stack stack = new Stack<>();\n Map map = Map.of(')', '(', ']', '[', '}', '{');\n for (char c : s.toCharArray()) {\n if (map.containsValue(c)) stack.push(c);\n else if (!stack.isEmpty() && stack.pop() != map.get(c)) return false;\n }\n return stack.isEmpty();\n}", "solution_cpp": "bool isValid(string s) {\n stack st;\n unordered_map m = {{')','('},{']','['},{'}','{'}};\n for (char c : s) {\n if (m.find(c) == m.end()) st.push(c);\n else if (st.empty() || st.top() != m[c]) return false;\n else st.pop();\n }\n return st.empty();\n}", "test_cases": ["s=\"()\" -> true", "s=\"()[]{}\" -> true", "s=\"(]\" -> false"], "key_points": ["栈匹配法", "注意空栈边界"], "tags": ["string", "easy", "Google", "Uber"]} {"problem_id": "algo_01385", "original_id": "longest-palindrome", "title": "最长回文子串", "category": "string", "difficulty": "medium", "companies": ["Google", "Amazon"], "description": "给你一个字符串 s,找到 s 中最长的回文子串。", "solution_python": "def longestPalindrome(s):\n def expand(l, r):\n while l >= 0 and r < len(s) and s[l] == s[r]: l -= 1; r += 1\n return l + 1, r - 1\n start = end = 0\n for i in range(len(s)):\n l1, r1 = expand(i, i)\n l2, r2 = expand(i, i + 1)\n if r1 - l1 > end - start: start, end = l1, r1\n if r2 - l2 > end - start: start, end = l2, r2\n return s[start:end+1]", "solution_java": "public String longestPalindrome(String s) {\n int start = 0, end = 0;\n for (int i = 0; i < s.length(); i++) {\n int len1 = expand(s, i, i), len2 = expand(s, i, i+1);\n int len = Math.max(len1, len2);\n if (len > end - start) { start = i - (len-1)/2; end = i + len/2; }\n }\n return s.substring(start, end + 1);\n}\nprivate int expand(String s, int l, int r) {\n while (l >= 0 && r < s.length() && s.charAt(l) == s.charAt(r)) { l--; r++; }\n return r - l - 1;\n}", "solution_cpp": "string longestPalindrome(string s) {\n int start = 0, end = 0;\n for (int i = 0; i < s.size(); i++) {\n int len1 = expand(s, i, i), len2 = expand(s, i, i+1);\n if (max(len1, len2) > end - start) { start = i - (max(len1,len2)-1)/2; end = i + max(len1,len2)/2; }\n }\n return s.substr(start, end - start + 1);\n}", "test_cases": ["s=\"babad\" -> bab或aba", "s=\"cbbd\" -> bb"], "key_points": ["中心扩展法", "处理奇偶长度"], "tags": ["string", "medium", "Google", "Amazon"]} {"problem_id": "algo_01386", "original_id": "reverse-list", "title": "反转链表", "category": "linkedlist", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "给你单链表的头节点 head,请你反转链表,并返回反转后的链表。", "solution_python": "def reverseList(head):\n prev = None\n curr = head\n while curr:\n nxt = curr.next\n curr.next = prev\n prev = curr\n curr = nxt\n return prev", "solution_java": "public ListNode reverseList(ListNode head) {\n ListNode prev = null, curr = head;\n while (curr != null) {\n ListNode next = curr.next;\n curr.next = prev;\n prev = curr;\n curr = next;\n }\n return prev;\n}", "solution_cpp": "ListNode* reverseList(ListNode* head) {\n ListNode* prev = nullptr, *curr = head;\n while (curr) {\n ListNode* next = curr->next;\n curr->next = prev;\n prev = curr;\n curr = next;\n }\n return prev;\n}", "test_cases": ["head=[1,2,3,4,5] -> [5,4,3,2,1]", "head=[1,2] -> [2,1]"], "key_points": ["迭代法 O(1)空间", "递归法 O(n)空间"], "tags": ["linkedlist", "medium", "Google", "Microsoft"]} {"problem_id": "algo_01387", "original_id": "middle-node", "title": "链表的中间结点", "category": "linkedlist", "difficulty": "easy", "companies": ["Amazon", "Facebook"], "description": "给你单链表的头节点 head,请你找出并返回链表的中间结点。如果有两个中间结点,则返回第二个中间结点。", "solution_python": "def middleNode(head):\n slow = fast = head\n while fast and fast.next:\n slow = slow.next\n fast = fast.next.next\n return slow", "solution_java": "public ListNode middleNode(ListNode head) {\n ListNode slow = head, fast = head;\n while (fast != null && fast.next != null) {\n slow = slow.next;\n fast = fast.next.next;\n }\n return slow;\n}", "solution_cpp": "ListNode* middleNode(ListNode* head) {\n ListNode* slow = head, *fast = head;\n while (fast && fast->next) { slow = slow->next; fast = fast->next->next; }\n return slow;\n}", "test_cases": ["head=[1,2,3,4,5] -> 3", "head=[1,2,3,4,5,6] -> 4"], "key_points": ["快慢指针", "O(n)时间O(1)空间"], "tags": ["linkedlist", "easy", "Amazon", "Facebook"]} {"problem_id": "algo_01388", "original_id": "max-depth", "title": "二叉树的最大深度", "category": "tree", "difficulty": "easy", "companies": ["Microsoft", "Apple"], "description": "给定一个二叉树 root,返回其最大深度。", "solution_python": "def maxDepth(root):\n if not root: return 0\n return max(maxDepth(root.left), maxDepth(root.right)) + 1", "solution_java": "public int maxDepth(TreeNode root) {\n if (root == null) return 0;\n return Math.max(maxDepth(root.left), maxDepth(root.right)) + 1;\n}", "solution_cpp": "int maxDepth(TreeNode* root) {\n if (!root) return 0;\n return max(maxDepth(root->left), maxDepth(root->right)) + 1;\n}", "test_cases": ["root=[3,9,20,null,null,15,7] -> 3", "root=[1,null,2] -> 2"], "key_points": ["DFS递归", "层序遍历也可"], "tags": ["tree", "easy", "Microsoft", "Apple"]} {"problem_id": "algo_01389", "original_id": "inorder-traversal", "title": "二叉树的中序遍历", "category": "tree", "difficulty": "easy", "companies": ["Google", "Microsoft"], "description": "给定一个二叉树的根节点 root,返回它的中序遍历结果。", "solution_python": "def inorderTraversal(root):\n result = []\n def dfs(node):\n if node:\n dfs(node.left)\n result.append(node.val)\n dfs(node.right)\n dfs(root)\n return result", "solution_java": "public List inorderTraversal(TreeNode root) {\n List res = new ArrayList<>();\n dfs(root, res);\n return res;\n}\nprivate void dfs(TreeNode node, List res) {\n if (node == null) return;\n dfs(node.left, res); res.add(node.val); dfs(node.right, res);\n}", "solution_cpp": "vector inorderTraversal(TreeNode* root) {\n vector res;\n dfs(root, res);\n return res;\n}\nvoid dfs(TreeNode* node, vector& res) {\n if (!node) return;\n dfs(node->left, res); res.push_back(node->val); dfs(node->right, res);\n}", "test_cases": ["root=[1,null,2,3] -> [1,3,2]", "root=[] -> []"], "key_points": ["左-根-右顺序", "递归最简洁"], "tags": ["tree", "easy", "Google", "Microsoft"]} {"problem_id": "algo_01390", "original_id": "binary-search", "title": "二分查找", "category": "binarysearch", "difficulty": "easy", "companies": ["Google", "Amazon"], "description": "给定一个 n 个元素有序的(升序)整型数组 nums 和一个目标值 target,写一个函数搜索 nums 中的 target,如果目标值存在返回下标,否则返回 -1。", "solution_python": "def search(nums, target):\n left, right = 0, len(nums) - 1\n while left <= right:\n mid = (left + right) // 2\n if nums[mid] == target: return mid\n elif nums[mid] < target: left = mid + 1\n else: right = mid - 1\n return -1", "solution_java": "public int search(int[] nums, int target) {\n int left = 0, right = nums.length - 1;\n while (left <= right) {\n int mid = left + (right - left) / 2;\n if (nums[mid] == target) return mid;\n else if (nums[mid] < target) left = mid + 1;\n else right = mid - 1;\n }\n return -1;\n}", "solution_cpp": "int search(vector& nums, int target) {\n int left = 0, right = nums.size() - 1;\n while (left <= right) {\n int mid = left + (right - left) / 2;\n if (nums[mid] == target) return mid;\n else if (nums[mid] < target) left = mid + 1;\n else right = mid - 1;\n }\n return -1;\n}", "test_cases": ["nums=[-1,0,3,5,9,12], target=9 -> 4", "nums=[-1,0,3,5,9,12], target=2 -> -1"], "key_points": ["标准模板", "注意防溢出写法"], "tags": ["binarysearch", "easy", "Google", "Amazon"]} {"problem_id": "algo_01391", "original_id": "climbing-stairs", "title": "爬楼梯", "category": "dp", "difficulty": "easy", "companies": ["Amazon", "Google"], "description": "假设你正在爬楼梯。需要 n 阶你才能到达楼顶。每次你可以爬 1 或 2 个台阶。你有多少种不同的方法可以爬到楼顶?", "solution_python": "def climbStairs(n):\n if n <= 2: return n\n a, b = 1, 2\n for _ in range(3, n+1):\n a, b = b, a + b\n return b", "solution_java": "public int climbStairs(int n) {\n if (n <= 2) return n;\n int a = 1, b = 2;\n for (int i = 3; i <= n; i++) { int temp = a + b; a = b; b = temp; }\n return b;\n}", "solution_cpp": "int climbStairs(int n) {\n if (n <= 2) return n;\n int a = 1, b = 2;\n for (int i = 3; i <= n; i++) { int temp = a + b; a = b; b = temp; }\n return b;\n}", "test_cases": ["n=2 -> 2", "n=3 -> 3", "n=5 -> 8"], "key_points": ["斐波那契数列", "滚动数组优化空间"], "tags": ["dp", "easy", "Amazon", "Google"]} {"problem_id": "algo_01392", "original_id": "coin-change", "title": "零钱兑换", "category": "dp", "difficulty": "medium", "companies": ["Google", "Amazon"], "description": "给你一个整数数组 coins 表示不同面额的硬币,以及一个整数 amount 表示总金额。计算并返回可以凑成总金额所需的最少的硬币个数。如果没有任何一种硬币组合能组成总金额,返回 -1。", "solution_python": "def coinChange(coins, amount):\n dp = [float('inf')] * (amount + 1)\n dp[0] = 0\n for coin in coins:\n for x in range(coin, amount + 1):\n dp[x] = min(dp[x], dp[x - coin] + 1)\n return dp[amount] if dp[amount] != float('inf') else -1", "solution_java": "public int coinChange(int[] coins, int amount) {\n int[] dp = new int[amount + 1];\n Arrays.fill(dp, amount + 1);\n dp[0] = 0;\n for (int coin : coins) {\n for (int x = coin; x <= amount; x++) {\n dp[x] = Math.min(dp[x], dp[x - coin] + 1);\n }\n }\n return dp[amount] > amount ? -1 : dp[amount];\n}", "solution_cpp": "int coinChange(vector& coins, int amount) {\n vector dp(amount + 1, amount + 1);\n dp[0] = 0;\n for (int coin : coins) {\n for (int x = coin; x <= amount; x++) {\n dp[x] = min(dp[x], dp[x - coin] + 1);\n }\n }\n return dp[amount] > amount ? -1 : dp[amount];\n}", "test_cases": ["coins=[1,2,5], amount=11 -> 3", "coins=[2], amount=3 -> -1"], "key_points": ["完全背包问题", "dp[x] = min(dp[x-coin]+1)"], "tags": ["dp", "medium", "Google", "Amazon"]} {"problem_id": "algo_01393", "original_id": "subsets", "title": "子集", "category": "backtracking", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "给你一个整数数组 nums ,数组中的元素 互不相同 。返回该数组所有可能的子集(幂集)。", "solution_python": "def subsets(nums):\n result = []\n def backtrack(start, path):\n result.append(path[:])\n for i in range(start, len(nums)):\n path.append(nums[i])\n backtrack(i + 1, path)\n path.pop()\n backtrack(0, [])\n return result", "solution_java": "public List> subsets(int[] nums) {\n List> result = new ArrayList<>();\n backtrack(nums, 0, new ArrayList<>(), result);\n return result;\n}\nprivate void backtrack(int[] nums, int start, List path, List> result) {\n result.add(new ArrayList<>(path));\n for (int i = start; i < nums.length; i++) {\n path.add(nums[i]);\n backtrack(nums, i + 1, path, result);\n path.remove(path.size() - 1);\n }\n}", "solution_cpp": "vector> subsets(vector& nums) {\n vector> result;\n vector path;\n backtrack(nums, 0, path, result);\n return result;\n}\nvoid backtrack(vector& nums, int start, vector& path, vector>& result) {\n result.push_back(path);\n for (int i = start; i < nums.size(); i++) {\n path.push_back(nums[i]);\n backtrack(nums, i + 1, path, result);\n path.pop_back();\n }\n}", "test_cases": ["nums=[1,2,3] -> [[],[1],[2],[1,2],[3],[1,3],[2,3],[1,2,3]]"], "key_points": ["选或不选", "DFS遍历子集树"], "tags": ["backtracking", "medium", "Google", "Microsoft"]} {"problem_id": "algo_01394", "original_id": "permutations", "title": "全排列", "category": "backtracking", "difficulty": "medium", "companies": ["Google", "Facebook"], "description": "给定一个不含重复数字的数组 nums,返回其所有可能的全排列。", "solution_python": "def permute(nums):\n result = []\n def backtrack(path, used):\n if len(path) == len(nums):\n result.append(path[:])\n return\n for i in range(len(nums)):\n if used[i]: continue\n used[i] = True\n path.append(nums[i])\n backtrack(path, used)\n path.pop()\n used[i] = False\n backtrack([], [False]*len(nums))\n return result", "solution_java": "public List> permute(int[] nums) {\n List> result = new ArrayList<>();\n boolean[] used = new boolean[nums.length];\n backtrack(nums, used, new ArrayList<>(), result);\n return result;\n}\nprivate void backtrack(int[] nums, boolean[] used, List path, List> result) {\n if (path.size() == nums.length) { result.add(new ArrayList<>(path)); return; }\n for (int i = 0; i < nums.length; i++) {\n if (used[i]) continue;\n used[i] = true;\n path.add(nums[i]);\n backtrack(nums, used, path, result);\n path.remove(path.size() - 1);\n used[i] = false;\n }\n}", "solution_cpp": "vector> permute(vector& nums) {\n vector> result;\n vector used(nums.size(), false);\n vector path;\n backtrack(nums, used, path, result);\n return result;\n}\nvoid backtrack(vector& nums, vector& used, vector& path, vector>& result) {\n if (path.size() == nums.size()) { result.push_back(path); return; }\n for (int i = 0; i < nums.size(); i++) {\n if (used[i]) continue;\n used[i] = true;\n path.push_back(nums[i]);\n backtrack(nums, used, path, result);\n path.pop_back();\n used[i] = false;\n }\n}", "test_cases": ["nums=[1,2,3] -> [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]"], "key_points": ["标记已使用元素", "回溯经典模板"], "tags": ["backtracking", "medium", "Google", "Facebook"]} {"problem_id": "algo_01395", "original_id": "top-k-frequent", "title": "前K个高频元素", "category": "heap", "difficulty": "medium", "companies": ["Amazon", "Facebook"], "description": "给你一个整数数组 nums 和一个整数 k,请你返回其中出现频率前 k 高的元素。", "solution_python": "import heapq\nfrom collections import Counter\ndef topKFrequent(nums, k):\n count = Counter(nums)\n heap = []\n for num, freq in count.items():\n heapq.heappush(heap, (freq, num))\n if len(heap) > k: heapq.heappop(heap)\n return [num for freq, num in heap]", "solution_java": "public int[] topKFrequent(int[] nums, int k) {\n Map count = new HashMap<>();\n for (int n : nums) count.put(n, count.getOrDefault(n, 0) + 1);\n PriorityQueue> heap = \n new PriorityQueue<>((a, b) -> a.getValue() - b.getValue());\n for (Map.Entry e : count.entrySet()) {\n heap.offer(e);\n if (heap.size() > k) heap.poll();\n }\n int[] res = new int[k];\n for (int i = k - 1; i >= 0; i--) res[i] = heap.poll().getKey();\n return res;\n}", "solution_cpp": "vector topKFrequent(vector& nums, int k) {\n unordered_map count;\n for (int n : nums) count[n]++;\n priority_queue, vector>, greater>> heap;\n for (auto& [num, freq] : count) {\n heap.push({freq, num});\n if (heap.size() > k) heap.pop();\n }\n vector res;\n while (!heap.empty()) { res.push_back(heap.top().second); heap.pop(); }\n reverse(res.begin(), res.end());\n return res;\n}", "test_cases": ["nums=[1,1,1,2,2,3], k=2 -> [1,2]", "nums=[1], k=1 -> [1]"], "key_points": ["小顶堆保持大小k", "时间复杂度O(nlogk)"], "tags": ["heap", "medium", "Amazon", "Facebook"]} {"problem_id": "algo_01396", "original_id": "3sum", "title": "三数之和", "category": "two-pointers", "difficulty": "medium", "companies": ["Google", "Amazon"], "description": "给你一个整数数组 nums,判断是否存在三元组满足和为0,返回所有不重复的三元组。", "solution_python": "def threeSum(nums):\n nums.sort()\n result = []\n for i in range(len(nums) - 2):\n if i > 0 and nums[i] == nums[i-1]: continue\n left, right = i + 1, len(nums) - 1\n while left < right:\n total = nums[i] + nums[left] + nums[right]\n if total < 0: left += 1\n elif total > 0: right -= 1\n else:\n result.append([nums[i], nums[left], nums[right]])\n while left < right and nums[left] == nums[left+1]: left += 1\n while left < right and nums[right] == nums[right-1]: right -= 1\n left += 1; right -= 1\n return result", "solution_java": "public List> threeSum(int[] nums) {\n Arrays.sort(nums);\n List> result = new ArrayList<>();\n for (int i = 0; i < nums.length - 2; i++) {\n if (i > 0 && nums[i] == nums[i-1]) continue;\n int left = i + 1, right = nums.length - 1;\n while (left < right) {\n int total = nums[i] + nums[left] + nums[right];\n if (total < 0) left++;\n else if (total > 0) right--;\n else {\n result.add(Arrays.asList(nums[i], nums[left], nums[right]));\n while (left < right && nums[left] == nums[left+1]) left++;\n while (left < right && nums[right] == nums[right-1]) right--;\n left++; right--;\n }\n }\n }\n return result;\n}", "solution_cpp": "vector> threeSum(vector& nums) {\n sort(nums.begin(), nums.end());\n vector> result;\n for (int i = 0; i < nums.size() - 2; i++) {\n if (i > 0 && nums[i] == nums[i-1]) continue;\n int left = i + 1, right = nums.size() - 1;\n while (left < right) {\n int total = nums[i] + nums[left] + nums[right];\n if (total < 0) left++;\n else if (total > 0) right--;\n else {\n result.push_back({nums[i], nums[left], nums[right]});\n while (left < right && nums[left] == nums[left+1]) left++;\n while (left < right && nums[right] == nums[right-1]) right--;\n left++; right--;\n }\n }\n }\n return result;\n}", "test_cases": ["nums=[-1,0,1,2,-1,-4] -> [[-1,-1,2],[-1,0,1]]"], "key_points": ["排序+双指针", "去重是关键"], "tags": ["two-pointers", "medium", "Google", "Amazon"]} {"problem_id": "algo_01397", "original_id": "container-water", "title": "盛最多水的容器", "category": "two-pointers", "difficulty": "medium", "companies": ["Google", "Uber"], "description": "给定一个长度为 n 的整数数组 height,找出其中的两条线,使得它们与 x 轴共同构成的容器可以容纳最多的水。", "solution_python": "def maxArea(height):\n left, right = 0, len(height) - 1\n max_area = 0\n while left < right:\n h = min(height[left], height[right])\n max_area = max(max_area, h * (right - left))\n if height[left] < height[right]: left += 1\n else: right -= 1\n return max_area", "solution_java": "public int maxArea(int[] height) {\n int left = 0, right = height.length - 1, maxArea = 0;\n while (left < right) {\n int h = Math.min(height[left], height[right]);\n maxArea = Math.max(maxArea, h * (right - left));\n if (height[left] < height[right]) left++;\n else right--;\n }\n return maxArea;\n}", "solution_cpp": "int maxArea(vector& height) {\n int left = 0, right = height.size() - 1, maxArea = 0;\n while (left < right) {\n int h = min(height[left], height[right]);\n maxArea = max(maxArea, h * (right - left));\n if (height[left] < height[right]) left++;\n else right--;\n }\n return maxArea;\n}", "test_cases": ["height=[1,8,6,2,5,4,8,3,7] -> 49"], "key_points": ["移动短边指针", "面积=min(h1,h2)*width"], "tags": ["two-pointers", "medium", "Google", "Uber"]} {"problem_id": "algo_01398", "original_id": "min-stack", "title": "最小栈", "category": "stack", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "设计一个支持 push,pop,top 操作,并能在常数时间内检索到最小元素的栈。", "solution_python": "class MinStack:\n def __init__(self):\n self.stack = []\n self.min_stack = []\n def push(self, val):\n self.stack.append(val)\n self.min_stack.append(min(val, self.min_stack[-1] if self.min_stack else val))\n def pop(self):\n self.stack.pop(); self.min_stack.pop()\n def top(self): return self.stack[-1]\n def getMin(self): return self.min_stack[-1]", "solution_java": "class MinStack {\n Stack stack = new Stack<>();\n Stack minStack = new Stack<>();\n public void push(int val) { stack.push(val); minStack.push(Math.min(val, minStack.isEmpty() ? val : minStack.peek())); }\n public void pop() { stack.pop(); minStack.pop(); }\n public int top() { return stack.peek(); }\n public int getMin() { return minStack.peek(); }\n}", "solution_cpp": "class MinStack {\n stack st, minSt;\npublic:\n void push(int val) { st.push(val); minSt.push(min(val, minSt.empty() ? val : minSt.top())); }\n void pop() { st.pop(); minSt.pop(); }\n int top() { return st.top(); }\n int getMin() { return minSt.top(); }\n};", "test_cases": ["push(-2), push(0), push(-3) -> getMin() returns -3"], "key_points": ["辅助栈记录最小值", "O(1)时间获取最小值"], "tags": ["stack", "medium", "Google", "Microsoft"]} {"problem_id": "algo_01399", "original_id": "lru-cache", "title": "LRU缓存", "category": "design", "difficulty": "hard", "companies": ["Google", "Amazon"], "description": "设计和实现一个 LRU(最近最少使用)缓存机制。", "solution_python": "class LRUCache:\n def __init__(self, capacity):\n self.capacity = capacity\n self.cache = {}\n self.order = []\n def get(self, key):\n if key not in self.cache: return -1\n self.order.remove(key); self.order.append(key)\n return self.cache[key]\n def put(self, key, value):\n if key in self.cache:\n self.order.remove(key)\n elif len(self.cache) >= self.capacity:\n del self.cache[self.order.pop(0)]\n self.cache[key] = value; self.order.append(key)", "solution_java": "class LRUCache {\n int capacity;\n LinkedHashMap cache = new LinkedHashMap<>();\n public LRUCache(int cap) { capacity = cap; }\n public int get(int key) { return cache.containsKey(key) ? cache.remove(key) : -1; }\n public void put(int key, int val) {\n if (cache.containsKey(key)) cache.remove(key);\n else if (cache.size() >= capacity) cache.remove(cache.keySet().iterator().next());\n cache.put(key, val);\n }\n}", "solution_cpp": "class LRUCache {\n int cap;\n list> dll;\n unordered_map>::iterator> cache;\npublic:\n LRUCache(int capacity) : cap(capacity) {}\n int get(int key) {\n auto it = cache.find(key);\n if (it == cache.end()) return -1;\n dll.splice(dll.end(), dll, it->second);\n return it->second->second;\n }\n void put(int key, int value) {\n auto it = cache.find(key);\n if (it != cache.end()) dll.erase(it->second);\n else if (cache.size() >= cap) { cache.erase(dll.front().first); dll.pop_front(); }\n dll.push_back({key, value});\n cache[key] = --dll.end();\n }\n};", "test_cases": ["put(1,1), put(2,2), get(1) -> 1"], "key_points": ["HashMap + 双向链表", "O(1)时间操作"], "tags": ["design", "hard", "Google", "Amazon"]} {"problem_id": "algo_01400", "original_id": "num-islands", "title": "岛屿数量", "category": "graph", "difficulty": "medium", "companies": ["Google", "Facebook"], "description": "给你一个由 '1'(陆地)和 '0'(水)组成的二维网格,请你计算网格中岛屿的数量。岛屿总是被水包围,且只能由水平或垂直方向相邻的陆地连接形成。", "solution_python": "def numIslands(grid):\n if not grid: return 0\n rows, cols = len(grid), len(grid[0])\n count = 0\n def dfs(r, c):\n if r < 0 or r >= rows or c < 0 or c >= cols or grid[r][c] != '1': return\n grid[r][c] = '0'\n dfs(r+1, c); dfs(r-1, c); dfs(r, c+1); dfs(r, c-1)\n for r in range(rows):\n for c in range(cols):\n if grid[r][c] == '1': count += 1; dfs(r, c)\n return count", "solution_java": "public int numIslands(char[][] grid) {\n if (grid.length == 0) return 0;\n int count = 0;\n for (int i = 0; i < grid.length; i++)\n for (int j = 0; j < grid[0].length; j++)\n if (grid[i][j] == '1') { count++; dfs(grid, i, j); }\n return count;\n}\nprivate void dfs(char[][] grid, int r, int c) {\n if (r < 0 || r >= grid.length || c < 0 || c >= grid[0].length || grid[r][c] != '1') return;\n grid[r][c] = '0';\n dfs(grid, r+1, c); dfs(grid, r-1, c); dfs(grid, r, c+1); dfs(grid, r, c-1);\n}", "solution_cpp": "int numIslands(vector>& grid) {\n if (grid.empty()) return 0;\n int count = 0;\n for (int i = 0; i < grid.size(); i++)\n for (int j = 0; j < grid[0].size(); j++)\n if (grid[i][j] == '1') { count++; dfs(grid, i, j); }\n return count;\n}\nvoid dfs(vector>& grid, int r, int c) {\n if (r < 0 || r >= grid.size() || c < 0 || c >= grid[0].size() || grid[r][c] != '1') return;\n grid[r][c] = '0';\n dfs(grid, r+1, c); dfs(grid, r-1, c); dfs(grid, r, c+1); dfs(grid, r, c-1);\n}", "test_cases": ["grid=[[1,1,1,1,0],[1,1,0,1,0],[1,1,0,0,0],[0,0,0,0,0]] -> 1"], "key_points": ["DFS/BFS遍历", "访问后标记为0避免重复"], "tags": ["graph", "medium", "Google", "Facebook"]} {"problem_id": "algo_01401", "original_id": "two-sum", "title": "两数之和", "category": "array", "difficulty": "easy", "companies": ["Amazon", "Google"], "description": "给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那两个整数,并返回他们的数组下标。", "solution_python": "def twoSum(nums, target):\n hashmap = {}\n for i, num in enumerate(nums):\n complement = target - num\n if complement in hashmap:\n return [hashmap[complement], i]\n hashmap[num] = i\n return []", "solution_java": "public int[] twoSum(int[] nums, int target) {\n Map map = new HashMap<>();\n for (int i = 0; i < nums.length; i++) {\n int complement = target - nums[i];\n if (map.containsKey(complement)) return new int[]{map.get(complement), i};\n map.put(nums[i], i);\n }\n return new int[]{};\n}", "solution_cpp": "vector twoSum(vector& nums, int target) {\n unordered_map m;\n for (int i = 0; i < nums.size(); i++) {\n if (m.count(target - nums[i])) return {m[target - nums[i]], i};\n m[nums[i]] = i;\n }\n return {};\n}", "test_cases": ["nums=[2,7,11,15], target=9 -> [0,1]", "nums=[3,2,4], target=6 -> [1,2]"], "key_points": ["哈希表一次遍历", "空间换时间"], "tags": ["array", "easy", "Amazon", "Google"]} {"problem_id": "algo_01402", "original_id": "merge-sorted", "title": "合并两个有序数组", "category": "array", "difficulty": "easy", "companies": ["Microsoft", "Uber"], "description": "给你两个按非递减顺序排列的整数数组 nums1 和 nums2,另有两个整数 m 和 n,分别表示 nums1 和 nums2 中的元素数目。请你合并 nums2 到 nums1 中。", "solution_python": "def merge(nums1, m, nums2, n):\n p1, p2, p = m-1, n-1, m+n-1\n while p1 >= 0 and p2 >= 0:\n if nums1[p1] > nums2[p2]: nums1[p] = nums1[p1]; p1 -= 1\n else: nums1[p] = nums2[p2]; p2 -= 1\n p -= 1\n while p2 >= 0: nums1[p] = nums2[p2]; p2 -= 1; p -= 1", "solution_java": "public void merge(int[] nums1, int m, int[] nums2, int n) {\n int p1 = m-1, p2 = n-1, p = m+n-1;\n while (p1 >= 0 && p2 >= 0) {\n nums1[p--] = nums1[p1] > nums2[p2] ? nums1[p1--] : nums2[p2--];\n }\n while (p2 >= 0) nums1[p--] = nums2[p2--];\n}", "solution_cpp": "void merge(vector& nums1, int m, vector& nums2, int n) {\n int p1 = m-1, p2 = n-1, p = m+n-1;\n while (p1 >= 0 && p2 >= 0) nums1[p--] = nums1[p1] > nums2[p2] ? nums1[p1--] : nums2[p2--];\n while (p2 >= 0) nums1[p--] = nums2[p2--];\n}", "test_cases": ["nums1=[1,2,3], m=3, nums2=[2,5,6], n=3 -> [1,2,2,3,5,6]", "nums1=[], m=0, nums2=[1], n=1 -> [1]"], "key_points": ["从后往前合并", "三指针技巧"], "tags": ["array", "easy", "Microsoft", "Uber"]} {"problem_id": "algo_01403", "original_id": "max-subarray", "title": "最大子数组和", "category": "array", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "给你一个整数数组 nums ,请你找出一个具有最大和的连续子数组,返回其最大和。", "solution_python": "def maxSubArray(nums):\n max_sum = current = nums[0]\n for num in nums[1:]:\n current = max(num, current + num)\n max_sum = max(max_sum, current)\n return max_sum", "solution_java": "public int maxSubArray(int[] nums) {\n int maxSum = nums[0], curr = nums[0];\n for (int i = 1; i < nums.length; i++) {\n curr = Math.max(nums[i], curr + nums[i]);\n maxSum = Math.max(maxSum, curr);\n }\n return maxSum;\n}", "solution_cpp": "int maxSubArray(vector& nums) {\n int maxSum = nums[0], curr = nums[0];\n for (int i = 1; i < nums.size(); i++) {\n curr = max(nums[i], curr + nums[i]);\n maxSum = max(maxSum, curr);\n }\n return maxSum;\n}", "test_cases": ["nums=[-2,1,-3,4,-1,2,1,-5,4] -> 6", "nums=[1] -> 1"], "key_points": ["Kadane算法", "动态规划基础题"], "tags": ["array", "medium", "Google", "Microsoft"]} {"problem_id": "algo_01404", "original_id": "valid-parentheses", "title": "有效的括号", "category": "string", "difficulty": "easy", "companies": ["Google", "Uber"], "description": "给定一个只包括 '(',')','{','}','[',']' 的字符串 s,判断字符串是否有效。", "solution_python": "def isValid(s):\n stack = []\n mapping = {')': '(', ']': '[', '}': '{'}\n for c in s:\n if c in mapping:\n if not stack or stack[-1] != mapping[c]: return False\n stack.pop()\n else: stack.append(c)\n return not stack", "solution_java": "public boolean isValid(String s) {\n Stack stack = new Stack<>();\n Map map = Map.of(')', '(', ']', '[', '}', '{');\n for (char c : s.toCharArray()) {\n if (map.containsValue(c)) stack.push(c);\n else if (!stack.isEmpty() && stack.pop() != map.get(c)) return false;\n }\n return stack.isEmpty();\n}", "solution_cpp": "bool isValid(string s) {\n stack st;\n unordered_map m = {{')','('},{']','['},{'}','{'}};\n for (char c : s) {\n if (m.find(c) == m.end()) st.push(c);\n else if (st.empty() || st.top() != m[c]) return false;\n else st.pop();\n }\n return st.empty();\n}", "test_cases": ["s=\"()\" -> true", "s=\"()[]{}\" -> true", "s=\"(]\" -> false"], "key_points": ["栈匹配法", "注意空栈边界"], "tags": ["string", "easy", "Google", "Uber"]} {"problem_id": "algo_01405", "original_id": "longest-palindrome", "title": "最长回文子串", "category": "string", "difficulty": "medium", "companies": ["Google", "Amazon"], "description": "给你一个字符串 s,找到 s 中最长的回文子串。", "solution_python": "def longestPalindrome(s):\n def expand(l, r):\n while l >= 0 and r < len(s) and s[l] == s[r]: l -= 1; r += 1\n return l + 1, r - 1\n start = end = 0\n for i in range(len(s)):\n l1, r1 = expand(i, i)\n l2, r2 = expand(i, i + 1)\n if r1 - l1 > end - start: start, end = l1, r1\n if r2 - l2 > end - start: start, end = l2, r2\n return s[start:end+1]", "solution_java": "public String longestPalindrome(String s) {\n int start = 0, end = 0;\n for (int i = 0; i < s.length(); i++) {\n int len1 = expand(s, i, i), len2 = expand(s, i, i+1);\n int len = Math.max(len1, len2);\n if (len > end - start) { start = i - (len-1)/2; end = i + len/2; }\n }\n return s.substring(start, end + 1);\n}\nprivate int expand(String s, int l, int r) {\n while (l >= 0 && r < s.length() && s.charAt(l) == s.charAt(r)) { l--; r++; }\n return r - l - 1;\n}", "solution_cpp": "string longestPalindrome(string s) {\n int start = 0, end = 0;\n for (int i = 0; i < s.size(); i++) {\n int len1 = expand(s, i, i), len2 = expand(s, i, i+1);\n if (max(len1, len2) > end - start) { start = i - (max(len1,len2)-1)/2; end = i + max(len1,len2)/2; }\n }\n return s.substr(start, end - start + 1);\n}", "test_cases": ["s=\"babad\" -> bab或aba", "s=\"cbbd\" -> bb"], "key_points": ["中心扩展法", "处理奇偶长度"], "tags": ["string", "medium", "Google", "Amazon"]} {"problem_id": "algo_01406", "original_id": "reverse-list", "title": "反转链表", "category": "linkedlist", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "给你单链表的头节点 head,请你反转链表,并返回反转后的链表。", "solution_python": "def reverseList(head):\n prev = None\n curr = head\n while curr:\n nxt = curr.next\n curr.next = prev\n prev = curr\n curr = nxt\n return prev", "solution_java": "public ListNode reverseList(ListNode head) {\n ListNode prev = null, curr = head;\n while (curr != null) {\n ListNode next = curr.next;\n curr.next = prev;\n prev = curr;\n curr = next;\n }\n return prev;\n}", "solution_cpp": "ListNode* reverseList(ListNode* head) {\n ListNode* prev = nullptr, *curr = head;\n while (curr) {\n ListNode* next = curr->next;\n curr->next = prev;\n prev = curr;\n curr = next;\n }\n return prev;\n}", "test_cases": ["head=[1,2,3,4,5] -> [5,4,3,2,1]", "head=[1,2] -> [2,1]"], "key_points": ["迭代法 O(1)空间", "递归法 O(n)空间"], "tags": ["linkedlist", "medium", "Google", "Microsoft"]} {"problem_id": "algo_01407", "original_id": "middle-node", "title": "链表的中间结点", "category": "linkedlist", "difficulty": "easy", "companies": ["Amazon", "Facebook"], "description": "给你单链表的头节点 head,请你找出并返回链表的中间结点。如果有两个中间结点,则返回第二个中间结点。", "solution_python": "def middleNode(head):\n slow = fast = head\n while fast and fast.next:\n slow = slow.next\n fast = fast.next.next\n return slow", "solution_java": "public ListNode middleNode(ListNode head) {\n ListNode slow = head, fast = head;\n while (fast != null && fast.next != null) {\n slow = slow.next;\n fast = fast.next.next;\n }\n return slow;\n}", "solution_cpp": "ListNode* middleNode(ListNode* head) {\n ListNode* slow = head, *fast = head;\n while (fast && fast->next) { slow = slow->next; fast = fast->next->next; }\n return slow;\n}", "test_cases": ["head=[1,2,3,4,5] -> 3", "head=[1,2,3,4,5,6] -> 4"], "key_points": ["快慢指针", "O(n)时间O(1)空间"], "tags": ["linkedlist", "easy", "Amazon", "Facebook"]} {"problem_id": "algo_01408", "original_id": "max-depth", "title": "二叉树的最大深度", "category": "tree", "difficulty": "easy", "companies": ["Microsoft", "Apple"], "description": "给定一个二叉树 root,返回其最大深度。", "solution_python": "def maxDepth(root):\n if not root: return 0\n return max(maxDepth(root.left), maxDepth(root.right)) + 1", "solution_java": "public int maxDepth(TreeNode root) {\n if (root == null) return 0;\n return Math.max(maxDepth(root.left), maxDepth(root.right)) + 1;\n}", "solution_cpp": "int maxDepth(TreeNode* root) {\n if (!root) return 0;\n return max(maxDepth(root->left), maxDepth(root->right)) + 1;\n}", "test_cases": ["root=[3,9,20,null,null,15,7] -> 3", "root=[1,null,2] -> 2"], "key_points": ["DFS递归", "层序遍历也可"], "tags": ["tree", "easy", "Microsoft", "Apple"]} {"problem_id": "algo_01409", "original_id": "inorder-traversal", "title": "二叉树的中序遍历", "category": "tree", "difficulty": "easy", "companies": ["Google", "Microsoft"], "description": "给定一个二叉树的根节点 root,返回它的中序遍历结果。", "solution_python": "def inorderTraversal(root):\n result = []\n def dfs(node):\n if node:\n dfs(node.left)\n result.append(node.val)\n dfs(node.right)\n dfs(root)\n return result", "solution_java": "public List inorderTraversal(TreeNode root) {\n List res = new ArrayList<>();\n dfs(root, res);\n return res;\n}\nprivate void dfs(TreeNode node, List res) {\n if (node == null) return;\n dfs(node.left, res); res.add(node.val); dfs(node.right, res);\n}", "solution_cpp": "vector inorderTraversal(TreeNode* root) {\n vector res;\n dfs(root, res);\n return res;\n}\nvoid dfs(TreeNode* node, vector& res) {\n if (!node) return;\n dfs(node->left, res); res.push_back(node->val); dfs(node->right, res);\n}", "test_cases": ["root=[1,null,2,3] -> [1,3,2]", "root=[] -> []"], "key_points": ["左-根-右顺序", "递归最简洁"], "tags": ["tree", "easy", "Google", "Microsoft"]} {"problem_id": "algo_01410", "original_id": "binary-search", "title": "二分查找", "category": "binarysearch", "difficulty": "easy", "companies": ["Google", "Amazon"], "description": "给定一个 n 个元素有序的(升序)整型数组 nums 和一个目标值 target,写一个函数搜索 nums 中的 target,如果目标值存在返回下标,否则返回 -1。", "solution_python": "def search(nums, target):\n left, right = 0, len(nums) - 1\n while left <= right:\n mid = (left + right) // 2\n if nums[mid] == target: return mid\n elif nums[mid] < target: left = mid + 1\n else: right = mid - 1\n return -1", "solution_java": "public int search(int[] nums, int target) {\n int left = 0, right = nums.length - 1;\n while (left <= right) {\n int mid = left + (right - left) / 2;\n if (nums[mid] == target) return mid;\n else if (nums[mid] < target) left = mid + 1;\n else right = mid - 1;\n }\n return -1;\n}", "solution_cpp": "int search(vector& nums, int target) {\n int left = 0, right = nums.size() - 1;\n while (left <= right) {\n int mid = left + (right - left) / 2;\n if (nums[mid] == target) return mid;\n else if (nums[mid] < target) left = mid + 1;\n else right = mid - 1;\n }\n return -1;\n}", "test_cases": ["nums=[-1,0,3,5,9,12], target=9 -> 4", "nums=[-1,0,3,5,9,12], target=2 -> -1"], "key_points": ["标准模板", "注意防溢出写法"], "tags": ["binarysearch", "easy", "Google", "Amazon"]} {"problem_id": "algo_01411", "original_id": "climbing-stairs", "title": "爬楼梯", "category": "dp", "difficulty": "easy", "companies": ["Amazon", "Google"], "description": "假设你正在爬楼梯。需要 n 阶你才能到达楼顶。每次你可以爬 1 或 2 个台阶。你有多少种不同的方法可以爬到楼顶?", "solution_python": "def climbStairs(n):\n if n <= 2: return n\n a, b = 1, 2\n for _ in range(3, n+1):\n a, b = b, a + b\n return b", "solution_java": "public int climbStairs(int n) {\n if (n <= 2) return n;\n int a = 1, b = 2;\n for (int i = 3; i <= n; i++) { int temp = a + b; a = b; b = temp; }\n return b;\n}", "solution_cpp": "int climbStairs(int n) {\n if (n <= 2) return n;\n int a = 1, b = 2;\n for (int i = 3; i <= n; i++) { int temp = a + b; a = b; b = temp; }\n return b;\n}", "test_cases": ["n=2 -> 2", "n=3 -> 3", "n=5 -> 8"], "key_points": ["斐波那契数列", "滚动数组优化空间"], "tags": ["dp", "easy", "Amazon", "Google"]} {"problem_id": "algo_01412", "original_id": "coin-change", "title": "零钱兑换", "category": "dp", "difficulty": "medium", "companies": ["Google", "Amazon"], "description": "给你一个整数数组 coins 表示不同面额的硬币,以及一个整数 amount 表示总金额。计算并返回可以凑成总金额所需的最少的硬币个数。如果没有任何一种硬币组合能组成总金额,返回 -1。", "solution_python": "def coinChange(coins, amount):\n dp = [float('inf')] * (amount + 1)\n dp[0] = 0\n for coin in coins:\n for x in range(coin, amount + 1):\n dp[x] = min(dp[x], dp[x - coin] + 1)\n return dp[amount] if dp[amount] != float('inf') else -1", "solution_java": "public int coinChange(int[] coins, int amount) {\n int[] dp = new int[amount + 1];\n Arrays.fill(dp, amount + 1);\n dp[0] = 0;\n for (int coin : coins) {\n for (int x = coin; x <= amount; x++) {\n dp[x] = Math.min(dp[x], dp[x - coin] + 1);\n }\n }\n return dp[amount] > amount ? -1 : dp[amount];\n}", "solution_cpp": "int coinChange(vector& coins, int amount) {\n vector dp(amount + 1, amount + 1);\n dp[0] = 0;\n for (int coin : coins) {\n for (int x = coin; x <= amount; x++) {\n dp[x] = min(dp[x], dp[x - coin] + 1);\n }\n }\n return dp[amount] > amount ? -1 : dp[amount];\n}", "test_cases": ["coins=[1,2,5], amount=11 -> 3", "coins=[2], amount=3 -> -1"], "key_points": ["完全背包问题", "dp[x] = min(dp[x-coin]+1)"], "tags": ["dp", "medium", "Google", "Amazon"]} {"problem_id": "algo_01413", "original_id": "subsets", "title": "子集", "category": "backtracking", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "给你一个整数数组 nums ,数组中的元素 互不相同 。返回该数组所有可能的子集(幂集)。", "solution_python": "def subsets(nums):\n result = []\n def backtrack(start, path):\n result.append(path[:])\n for i in range(start, len(nums)):\n path.append(nums[i])\n backtrack(i + 1, path)\n path.pop()\n backtrack(0, [])\n return result", "solution_java": "public List> subsets(int[] nums) {\n List> result = new ArrayList<>();\n backtrack(nums, 0, new ArrayList<>(), result);\n return result;\n}\nprivate void backtrack(int[] nums, int start, List path, List> result) {\n result.add(new ArrayList<>(path));\n for (int i = start; i < nums.length; i++) {\n path.add(nums[i]);\n backtrack(nums, i + 1, path, result);\n path.remove(path.size() - 1);\n }\n}", "solution_cpp": "vector> subsets(vector& nums) {\n vector> result;\n vector path;\n backtrack(nums, 0, path, result);\n return result;\n}\nvoid backtrack(vector& nums, int start, vector& path, vector>& result) {\n result.push_back(path);\n for (int i = start; i < nums.size(); i++) {\n path.push_back(nums[i]);\n backtrack(nums, i + 1, path, result);\n path.pop_back();\n }\n}", "test_cases": ["nums=[1,2,3] -> [[],[1],[2],[1,2],[3],[1,3],[2,3],[1,2,3]]"], "key_points": ["选或不选", "DFS遍历子集树"], "tags": ["backtracking", "medium", "Google", "Microsoft"]} {"problem_id": "algo_01414", "original_id": "permutations", "title": "全排列", "category": "backtracking", "difficulty": "medium", "companies": ["Google", "Facebook"], "description": "给定一个不含重复数字的数组 nums,返回其所有可能的全排列。", "solution_python": "def permute(nums):\n result = []\n def backtrack(path, used):\n if len(path) == len(nums):\n result.append(path[:])\n return\n for i in range(len(nums)):\n if used[i]: continue\n used[i] = True\n path.append(nums[i])\n backtrack(path, used)\n path.pop()\n used[i] = False\n backtrack([], [False]*len(nums))\n return result", "solution_java": "public List> permute(int[] nums) {\n List> result = new ArrayList<>();\n boolean[] used = new boolean[nums.length];\n backtrack(nums, used, new ArrayList<>(), result);\n return result;\n}\nprivate void backtrack(int[] nums, boolean[] used, List path, List> result) {\n if (path.size() == nums.length) { result.add(new ArrayList<>(path)); return; }\n for (int i = 0; i < nums.length; i++) {\n if (used[i]) continue;\n used[i] = true;\n path.add(nums[i]);\n backtrack(nums, used, path, result);\n path.remove(path.size() - 1);\n used[i] = false;\n }\n}", "solution_cpp": "vector> permute(vector& nums) {\n vector> result;\n vector used(nums.size(), false);\n vector path;\n backtrack(nums, used, path, result);\n return result;\n}\nvoid backtrack(vector& nums, vector& used, vector& path, vector>& result) {\n if (path.size() == nums.size()) { result.push_back(path); return; }\n for (int i = 0; i < nums.size(); i++) {\n if (used[i]) continue;\n used[i] = true;\n path.push_back(nums[i]);\n backtrack(nums, used, path, result);\n path.pop_back();\n used[i] = false;\n }\n}", "test_cases": ["nums=[1,2,3] -> [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]"], "key_points": ["标记已使用元素", "回溯经典模板"], "tags": ["backtracking", "medium", "Google", "Facebook"]} {"problem_id": "algo_01415", "original_id": "top-k-frequent", "title": "前K个高频元素", "category": "heap", "difficulty": "medium", "companies": ["Amazon", "Facebook"], "description": "给你一个整数数组 nums 和一个整数 k,请你返回其中出现频率前 k 高的元素。", "solution_python": "import heapq\nfrom collections import Counter\ndef topKFrequent(nums, k):\n count = Counter(nums)\n heap = []\n for num, freq in count.items():\n heapq.heappush(heap, (freq, num))\n if len(heap) > k: heapq.heappop(heap)\n return [num for freq, num in heap]", "solution_java": "public int[] topKFrequent(int[] nums, int k) {\n Map count = new HashMap<>();\n for (int n : nums) count.put(n, count.getOrDefault(n, 0) + 1);\n PriorityQueue> heap = \n new PriorityQueue<>((a, b) -> a.getValue() - b.getValue());\n for (Map.Entry e : count.entrySet()) {\n heap.offer(e);\n if (heap.size() > k) heap.poll();\n }\n int[] res = new int[k];\n for (int i = k - 1; i >= 0; i--) res[i] = heap.poll().getKey();\n return res;\n}", "solution_cpp": "vector topKFrequent(vector& nums, int k) {\n unordered_map count;\n for (int n : nums) count[n]++;\n priority_queue, vector>, greater>> heap;\n for (auto& [num, freq] : count) {\n heap.push({freq, num});\n if (heap.size() > k) heap.pop();\n }\n vector res;\n while (!heap.empty()) { res.push_back(heap.top().second); heap.pop(); }\n reverse(res.begin(), res.end());\n return res;\n}", "test_cases": ["nums=[1,1,1,2,2,3], k=2 -> [1,2]", "nums=[1], k=1 -> [1]"], "key_points": ["小顶堆保持大小k", "时间复杂度O(nlogk)"], "tags": ["heap", "medium", "Amazon", "Facebook"]} {"problem_id": "algo_01416", "original_id": "3sum", "title": "三数之和", "category": "two-pointers", "difficulty": "medium", "companies": ["Google", "Amazon"], "description": "给你一个整数数组 nums,判断是否存在三元组满足和为0,返回所有不重复的三元组。", "solution_python": "def threeSum(nums):\n nums.sort()\n result = []\n for i in range(len(nums) - 2):\n if i > 0 and nums[i] == nums[i-1]: continue\n left, right = i + 1, len(nums) - 1\n while left < right:\n total = nums[i] + nums[left] + nums[right]\n if total < 0: left += 1\n elif total > 0: right -= 1\n else:\n result.append([nums[i], nums[left], nums[right]])\n while left < right and nums[left] == nums[left+1]: left += 1\n while left < right and nums[right] == nums[right-1]: right -= 1\n left += 1; right -= 1\n return result", "solution_java": "public List> threeSum(int[] nums) {\n Arrays.sort(nums);\n List> result = new ArrayList<>();\n for (int i = 0; i < nums.length - 2; i++) {\n if (i > 0 && nums[i] == nums[i-1]) continue;\n int left = i + 1, right = nums.length - 1;\n while (left < right) {\n int total = nums[i] + nums[left] + nums[right];\n if (total < 0) left++;\n else if (total > 0) right--;\n else {\n result.add(Arrays.asList(nums[i], nums[left], nums[right]));\n while (left < right && nums[left] == nums[left+1]) left++;\n while (left < right && nums[right] == nums[right-1]) right--;\n left++; right--;\n }\n }\n }\n return result;\n}", "solution_cpp": "vector> threeSum(vector& nums) {\n sort(nums.begin(), nums.end());\n vector> result;\n for (int i = 0; i < nums.size() - 2; i++) {\n if (i > 0 && nums[i] == nums[i-1]) continue;\n int left = i + 1, right = nums.size() - 1;\n while (left < right) {\n int total = nums[i] + nums[left] + nums[right];\n if (total < 0) left++;\n else if (total > 0) right--;\n else {\n result.push_back({nums[i], nums[left], nums[right]});\n while (left < right && nums[left] == nums[left+1]) left++;\n while (left < right && nums[right] == nums[right-1]) right--;\n left++; right--;\n }\n }\n }\n return result;\n}", "test_cases": ["nums=[-1,0,1,2,-1,-4] -> [[-1,-1,2],[-1,0,1]]"], "key_points": ["排序+双指针", "去重是关键"], "tags": ["two-pointers", "medium", "Google", "Amazon"]} {"problem_id": "algo_01417", "original_id": "container-water", "title": "盛最多水的容器", "category": "two-pointers", "difficulty": "medium", "companies": ["Google", "Uber"], "description": "给定一个长度为 n 的整数数组 height,找出其中的两条线,使得它们与 x 轴共同构成的容器可以容纳最多的水。", "solution_python": "def maxArea(height):\n left, right = 0, len(height) - 1\n max_area = 0\n while left < right:\n h = min(height[left], height[right])\n max_area = max(max_area, h * (right - left))\n if height[left] < height[right]: left += 1\n else: right -= 1\n return max_area", "solution_java": "public int maxArea(int[] height) {\n int left = 0, right = height.length - 1, maxArea = 0;\n while (left < right) {\n int h = Math.min(height[left], height[right]);\n maxArea = Math.max(maxArea, h * (right - left));\n if (height[left] < height[right]) left++;\n else right--;\n }\n return maxArea;\n}", "solution_cpp": "int maxArea(vector& height) {\n int left = 0, right = height.size() - 1, maxArea = 0;\n while (left < right) {\n int h = min(height[left], height[right]);\n maxArea = max(maxArea, h * (right - left));\n if (height[left] < height[right]) left++;\n else right--;\n }\n return maxArea;\n}", "test_cases": ["height=[1,8,6,2,5,4,8,3,7] -> 49"], "key_points": ["移动短边指针", "面积=min(h1,h2)*width"], "tags": ["two-pointers", "medium", "Google", "Uber"]} {"problem_id": "algo_01418", "original_id": "min-stack", "title": "最小栈", "category": "stack", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "设计一个支持 push,pop,top 操作,并能在常数时间内检索到最小元素的栈。", "solution_python": "class MinStack:\n def __init__(self):\n self.stack = []\n self.min_stack = []\n def push(self, val):\n self.stack.append(val)\n self.min_stack.append(min(val, self.min_stack[-1] if self.min_stack else val))\n def pop(self):\n self.stack.pop(); self.min_stack.pop()\n def top(self): return self.stack[-1]\n def getMin(self): return self.min_stack[-1]", "solution_java": "class MinStack {\n Stack stack = new Stack<>();\n Stack minStack = new Stack<>();\n public void push(int val) { stack.push(val); minStack.push(Math.min(val, minStack.isEmpty() ? val : minStack.peek())); }\n public void pop() { stack.pop(); minStack.pop(); }\n public int top() { return stack.peek(); }\n public int getMin() { return minStack.peek(); }\n}", "solution_cpp": "class MinStack {\n stack st, minSt;\npublic:\n void push(int val) { st.push(val); minSt.push(min(val, minSt.empty() ? val : minSt.top())); }\n void pop() { st.pop(); minSt.pop(); }\n int top() { return st.top(); }\n int getMin() { return minSt.top(); }\n};", "test_cases": ["push(-2), push(0), push(-3) -> getMin() returns -3"], "key_points": ["辅助栈记录最小值", "O(1)时间获取最小值"], "tags": ["stack", "medium", "Google", "Microsoft"]} {"problem_id": "algo_01419", "original_id": "lru-cache", "title": "LRU缓存", "category": "design", "difficulty": "hard", "companies": ["Google", "Amazon"], "description": "设计和实现一个 LRU(最近最少使用)缓存机制。", "solution_python": "class LRUCache:\n def __init__(self, capacity):\n self.capacity = capacity\n self.cache = {}\n self.order = []\n def get(self, key):\n if key not in self.cache: return -1\n self.order.remove(key); self.order.append(key)\n return self.cache[key]\n def put(self, key, value):\n if key in self.cache:\n self.order.remove(key)\n elif len(self.cache) >= self.capacity:\n del self.cache[self.order.pop(0)]\n self.cache[key] = value; self.order.append(key)", "solution_java": "class LRUCache {\n int capacity;\n LinkedHashMap cache = new LinkedHashMap<>();\n public LRUCache(int cap) { capacity = cap; }\n public int get(int key) { return cache.containsKey(key) ? cache.remove(key) : -1; }\n public void put(int key, int val) {\n if (cache.containsKey(key)) cache.remove(key);\n else if (cache.size() >= capacity) cache.remove(cache.keySet().iterator().next());\n cache.put(key, val);\n }\n}", "solution_cpp": "class LRUCache {\n int cap;\n list> dll;\n unordered_map>::iterator> cache;\npublic:\n LRUCache(int capacity) : cap(capacity) {}\n int get(int key) {\n auto it = cache.find(key);\n if (it == cache.end()) return -1;\n dll.splice(dll.end(), dll, it->second);\n return it->second->second;\n }\n void put(int key, int value) {\n auto it = cache.find(key);\n if (it != cache.end()) dll.erase(it->second);\n else if (cache.size() >= cap) { cache.erase(dll.front().first); dll.pop_front(); }\n dll.push_back({key, value});\n cache[key] = --dll.end();\n }\n};", "test_cases": ["put(1,1), put(2,2), get(1) -> 1"], "key_points": ["HashMap + 双向链表", "O(1)时间操作"], "tags": ["design", "hard", "Google", "Amazon"]} {"problem_id": "algo_01420", "original_id": "num-islands", "title": "岛屿数量", "category": "graph", "difficulty": "medium", "companies": ["Google", "Facebook"], "description": "给你一个由 '1'(陆地)和 '0'(水)组成的二维网格,请你计算网格中岛屿的数量。岛屿总是被水包围,且只能由水平或垂直方向相邻的陆地连接形成。", "solution_python": "def numIslands(grid):\n if not grid: return 0\n rows, cols = len(grid), len(grid[0])\n count = 0\n def dfs(r, c):\n if r < 0 or r >= rows or c < 0 or c >= cols or grid[r][c] != '1': return\n grid[r][c] = '0'\n dfs(r+1, c); dfs(r-1, c); dfs(r, c+1); dfs(r, c-1)\n for r in range(rows):\n for c in range(cols):\n if grid[r][c] == '1': count += 1; dfs(r, c)\n return count", "solution_java": "public int numIslands(char[][] grid) {\n if (grid.length == 0) return 0;\n int count = 0;\n for (int i = 0; i < grid.length; i++)\n for (int j = 0; j < grid[0].length; j++)\n if (grid[i][j] == '1') { count++; dfs(grid, i, j); }\n return count;\n}\nprivate void dfs(char[][] grid, int r, int c) {\n if (r < 0 || r >= grid.length || c < 0 || c >= grid[0].length || grid[r][c] != '1') return;\n grid[r][c] = '0';\n dfs(grid, r+1, c); dfs(grid, r-1, c); dfs(grid, r, c+1); dfs(grid, r, c-1);\n}", "solution_cpp": "int numIslands(vector>& grid) {\n if (grid.empty()) return 0;\n int count = 0;\n for (int i = 0; i < grid.size(); i++)\n for (int j = 0; j < grid[0].size(); j++)\n if (grid[i][j] == '1') { count++; dfs(grid, i, j); }\n return count;\n}\nvoid dfs(vector>& grid, int r, int c) {\n if (r < 0 || r >= grid.size() || c < 0 || c >= grid[0].size() || grid[r][c] != '1') return;\n grid[r][c] = '0';\n dfs(grid, r+1, c); dfs(grid, r-1, c); dfs(grid, r, c+1); dfs(grid, r, c-1);\n}", "test_cases": ["grid=[[1,1,1,1,0],[1,1,0,1,0],[1,1,0,0,0],[0,0,0,0,0]] -> 1"], "key_points": ["DFS/BFS遍历", "访问后标记为0避免重复"], "tags": ["graph", "medium", "Google", "Facebook"]} {"problem_id": "algo_01421", "original_id": "two-sum", "title": "两数之和", "category": "array", "difficulty": "easy", "companies": ["Amazon", "Google"], "description": "给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那两个整数,并返回他们的数组下标。", "solution_python": "def twoSum(nums, target):\n hashmap = {}\n for i, num in enumerate(nums):\n complement = target - num\n if complement in hashmap:\n return [hashmap[complement], i]\n hashmap[num] = i\n return []", "solution_java": "public int[] twoSum(int[] nums, int target) {\n Map map = new HashMap<>();\n for (int i = 0; i < nums.length; i++) {\n int complement = target - nums[i];\n if (map.containsKey(complement)) return new int[]{map.get(complement), i};\n map.put(nums[i], i);\n }\n return new int[]{};\n}", "solution_cpp": "vector twoSum(vector& nums, int target) {\n unordered_map m;\n for (int i = 0; i < nums.size(); i++) {\n if (m.count(target - nums[i])) return {m[target - nums[i]], i};\n m[nums[i]] = i;\n }\n return {};\n}", "test_cases": ["nums=[2,7,11,15], target=9 -> [0,1]", "nums=[3,2,4], target=6 -> [1,2]"], "key_points": ["哈希表一次遍历", "空间换时间"], "tags": ["array", "easy", "Amazon", "Google"]} {"problem_id": "algo_01422", "original_id": "merge-sorted", "title": "合并两个有序数组", "category": "array", "difficulty": "easy", "companies": ["Microsoft", "Uber"], "description": "给你两个按非递减顺序排列的整数数组 nums1 和 nums2,另有两个整数 m 和 n,分别表示 nums1 和 nums2 中的元素数目。请你合并 nums2 到 nums1 中。", "solution_python": "def merge(nums1, m, nums2, n):\n p1, p2, p = m-1, n-1, m+n-1\n while p1 >= 0 and p2 >= 0:\n if nums1[p1] > nums2[p2]: nums1[p] = nums1[p1]; p1 -= 1\n else: nums1[p] = nums2[p2]; p2 -= 1\n p -= 1\n while p2 >= 0: nums1[p] = nums2[p2]; p2 -= 1; p -= 1", "solution_java": "public void merge(int[] nums1, int m, int[] nums2, int n) {\n int p1 = m-1, p2 = n-1, p = m+n-1;\n while (p1 >= 0 && p2 >= 0) {\n nums1[p--] = nums1[p1] > nums2[p2] ? nums1[p1--] : nums2[p2--];\n }\n while (p2 >= 0) nums1[p--] = nums2[p2--];\n}", "solution_cpp": "void merge(vector& nums1, int m, vector& nums2, int n) {\n int p1 = m-1, p2 = n-1, p = m+n-1;\n while (p1 >= 0 && p2 >= 0) nums1[p--] = nums1[p1] > nums2[p2] ? nums1[p1--] : nums2[p2--];\n while (p2 >= 0) nums1[p--] = nums2[p2--];\n}", "test_cases": ["nums1=[1,2,3], m=3, nums2=[2,5,6], n=3 -> [1,2,2,3,5,6]", "nums1=[], m=0, nums2=[1], n=1 -> [1]"], "key_points": ["从后往前合并", "三指针技巧"], "tags": ["array", "easy", "Microsoft", "Uber"]} {"problem_id": "algo_01423", "original_id": "max-subarray", "title": "最大子数组和", "category": "array", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "给你一个整数数组 nums ,请你找出一个具有最大和的连续子数组,返回其最大和。", "solution_python": "def maxSubArray(nums):\n max_sum = current = nums[0]\n for num in nums[1:]:\n current = max(num, current + num)\n max_sum = max(max_sum, current)\n return max_sum", "solution_java": "public int maxSubArray(int[] nums) {\n int maxSum = nums[0], curr = nums[0];\n for (int i = 1; i < nums.length; i++) {\n curr = Math.max(nums[i], curr + nums[i]);\n maxSum = Math.max(maxSum, curr);\n }\n return maxSum;\n}", "solution_cpp": "int maxSubArray(vector& nums) {\n int maxSum = nums[0], curr = nums[0];\n for (int i = 1; i < nums.size(); i++) {\n curr = max(nums[i], curr + nums[i]);\n maxSum = max(maxSum, curr);\n }\n return maxSum;\n}", "test_cases": ["nums=[-2,1,-3,4,-1,2,1,-5,4] -> 6", "nums=[1] -> 1"], "key_points": ["Kadane算法", "动态规划基础题"], "tags": ["array", "medium", "Google", "Microsoft"]} {"problem_id": "algo_01424", "original_id": "valid-parentheses", "title": "有效的括号", "category": "string", "difficulty": "easy", "companies": ["Google", "Uber"], "description": "给定一个只包括 '(',')','{','}','[',']' 的字符串 s,判断字符串是否有效。", "solution_python": "def isValid(s):\n stack = []\n mapping = {')': '(', ']': '[', '}': '{'}\n for c in s:\n if c in mapping:\n if not stack or stack[-1] != mapping[c]: return False\n stack.pop()\n else: stack.append(c)\n return not stack", "solution_java": "public boolean isValid(String s) {\n Stack stack = new Stack<>();\n Map map = Map.of(')', '(', ']', '[', '}', '{');\n for (char c : s.toCharArray()) {\n if (map.containsValue(c)) stack.push(c);\n else if (!stack.isEmpty() && stack.pop() != map.get(c)) return false;\n }\n return stack.isEmpty();\n}", "solution_cpp": "bool isValid(string s) {\n stack st;\n unordered_map m = {{')','('},{']','['},{'}','{'}};\n for (char c : s) {\n if (m.find(c) == m.end()) st.push(c);\n else if (st.empty() || st.top() != m[c]) return false;\n else st.pop();\n }\n return st.empty();\n}", "test_cases": ["s=\"()\" -> true", "s=\"()[]{}\" -> true", "s=\"(]\" -> false"], "key_points": ["栈匹配法", "注意空栈边界"], "tags": ["string", "easy", "Google", "Uber"]} {"problem_id": "algo_01425", "original_id": "longest-palindrome", "title": "最长回文子串", "category": "string", "difficulty": "medium", "companies": ["Google", "Amazon"], "description": "给你一个字符串 s,找到 s 中最长的回文子串。", "solution_python": "def longestPalindrome(s):\n def expand(l, r):\n while l >= 0 and r < len(s) and s[l] == s[r]: l -= 1; r += 1\n return l + 1, r - 1\n start = end = 0\n for i in range(len(s)):\n l1, r1 = expand(i, i)\n l2, r2 = expand(i, i + 1)\n if r1 - l1 > end - start: start, end = l1, r1\n if r2 - l2 > end - start: start, end = l2, r2\n return s[start:end+1]", "solution_java": "public String longestPalindrome(String s) {\n int start = 0, end = 0;\n for (int i = 0; i < s.length(); i++) {\n int len1 = expand(s, i, i), len2 = expand(s, i, i+1);\n int len = Math.max(len1, len2);\n if (len > end - start) { start = i - (len-1)/2; end = i + len/2; }\n }\n return s.substring(start, end + 1);\n}\nprivate int expand(String s, int l, int r) {\n while (l >= 0 && r < s.length() && s.charAt(l) == s.charAt(r)) { l--; r++; }\n return r - l - 1;\n}", "solution_cpp": "string longestPalindrome(string s) {\n int start = 0, end = 0;\n for (int i = 0; i < s.size(); i++) {\n int len1 = expand(s, i, i), len2 = expand(s, i, i+1);\n if (max(len1, len2) > end - start) { start = i - (max(len1,len2)-1)/2; end = i + max(len1,len2)/2; }\n }\n return s.substr(start, end - start + 1);\n}", "test_cases": ["s=\"babad\" -> bab或aba", "s=\"cbbd\" -> bb"], "key_points": ["中心扩展法", "处理奇偶长度"], "tags": ["string", "medium", "Google", "Amazon"]} {"problem_id": "algo_01426", "original_id": "reverse-list", "title": "反转链表", "category": "linkedlist", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "给你单链表的头节点 head,请你反转链表,并返回反转后的链表。", "solution_python": "def reverseList(head):\n prev = None\n curr = head\n while curr:\n nxt = curr.next\n curr.next = prev\n prev = curr\n curr = nxt\n return prev", "solution_java": "public ListNode reverseList(ListNode head) {\n ListNode prev = null, curr = head;\n while (curr != null) {\n ListNode next = curr.next;\n curr.next = prev;\n prev = curr;\n curr = next;\n }\n return prev;\n}", "solution_cpp": "ListNode* reverseList(ListNode* head) {\n ListNode* prev = nullptr, *curr = head;\n while (curr) {\n ListNode* next = curr->next;\n curr->next = prev;\n prev = curr;\n curr = next;\n }\n return prev;\n}", "test_cases": ["head=[1,2,3,4,5] -> [5,4,3,2,1]", "head=[1,2] -> [2,1]"], "key_points": ["迭代法 O(1)空间", "递归法 O(n)空间"], "tags": ["linkedlist", "medium", "Google", "Microsoft"]} {"problem_id": "algo_01427", "original_id": "middle-node", "title": "链表的中间结点", "category": "linkedlist", "difficulty": "easy", "companies": ["Amazon", "Facebook"], "description": "给你单链表的头节点 head,请你找出并返回链表的中间结点。如果有两个中间结点,则返回第二个中间结点。", "solution_python": "def middleNode(head):\n slow = fast = head\n while fast and fast.next:\n slow = slow.next\n fast = fast.next.next\n return slow", "solution_java": "public ListNode middleNode(ListNode head) {\n ListNode slow = head, fast = head;\n while (fast != null && fast.next != null) {\n slow = slow.next;\n fast = fast.next.next;\n }\n return slow;\n}", "solution_cpp": "ListNode* middleNode(ListNode* head) {\n ListNode* slow = head, *fast = head;\n while (fast && fast->next) { slow = slow->next; fast = fast->next->next; }\n return slow;\n}", "test_cases": ["head=[1,2,3,4,5] -> 3", "head=[1,2,3,4,5,6] -> 4"], "key_points": ["快慢指针", "O(n)时间O(1)空间"], "tags": ["linkedlist", "easy", "Amazon", "Facebook"]} {"problem_id": "algo_01428", "original_id": "max-depth", "title": "二叉树的最大深度", "category": "tree", "difficulty": "easy", "companies": ["Microsoft", "Apple"], "description": "给定一个二叉树 root,返回其最大深度。", "solution_python": "def maxDepth(root):\n if not root: return 0\n return max(maxDepth(root.left), maxDepth(root.right)) + 1", "solution_java": "public int maxDepth(TreeNode root) {\n if (root == null) return 0;\n return Math.max(maxDepth(root.left), maxDepth(root.right)) + 1;\n}", "solution_cpp": "int maxDepth(TreeNode* root) {\n if (!root) return 0;\n return max(maxDepth(root->left), maxDepth(root->right)) + 1;\n}", "test_cases": ["root=[3,9,20,null,null,15,7] -> 3", "root=[1,null,2] -> 2"], "key_points": ["DFS递归", "层序遍历也可"], "tags": ["tree", "easy", "Microsoft", "Apple"]} {"problem_id": "algo_01429", "original_id": "inorder-traversal", "title": "二叉树的中序遍历", "category": "tree", "difficulty": "easy", "companies": ["Google", "Microsoft"], "description": "给定一个二叉树的根节点 root,返回它的中序遍历结果。", "solution_python": "def inorderTraversal(root):\n result = []\n def dfs(node):\n if node:\n dfs(node.left)\n result.append(node.val)\n dfs(node.right)\n dfs(root)\n return result", "solution_java": "public List inorderTraversal(TreeNode root) {\n List res = new ArrayList<>();\n dfs(root, res);\n return res;\n}\nprivate void dfs(TreeNode node, List res) {\n if (node == null) return;\n dfs(node.left, res); res.add(node.val); dfs(node.right, res);\n}", "solution_cpp": "vector inorderTraversal(TreeNode* root) {\n vector res;\n dfs(root, res);\n return res;\n}\nvoid dfs(TreeNode* node, vector& res) {\n if (!node) return;\n dfs(node->left, res); res.push_back(node->val); dfs(node->right, res);\n}", "test_cases": ["root=[1,null,2,3] -> [1,3,2]", "root=[] -> []"], "key_points": ["左-根-右顺序", "递归最简洁"], "tags": ["tree", "easy", "Google", "Microsoft"]} {"problem_id": "algo_01430", "original_id": "binary-search", "title": "二分查找", "category": "binarysearch", "difficulty": "easy", "companies": ["Google", "Amazon"], "description": "给定一个 n 个元素有序的(升序)整型数组 nums 和一个目标值 target,写一个函数搜索 nums 中的 target,如果目标值存在返回下标,否则返回 -1。", "solution_python": "def search(nums, target):\n left, right = 0, len(nums) - 1\n while left <= right:\n mid = (left + right) // 2\n if nums[mid] == target: return mid\n elif nums[mid] < target: left = mid + 1\n else: right = mid - 1\n return -1", "solution_java": "public int search(int[] nums, int target) {\n int left = 0, right = nums.length - 1;\n while (left <= right) {\n int mid = left + (right - left) / 2;\n if (nums[mid] == target) return mid;\n else if (nums[mid] < target) left = mid + 1;\n else right = mid - 1;\n }\n return -1;\n}", "solution_cpp": "int search(vector& nums, int target) {\n int left = 0, right = nums.size() - 1;\n while (left <= right) {\n int mid = left + (right - left) / 2;\n if (nums[mid] == target) return mid;\n else if (nums[mid] < target) left = mid + 1;\n else right = mid - 1;\n }\n return -1;\n}", "test_cases": ["nums=[-1,0,3,5,9,12], target=9 -> 4", "nums=[-1,0,3,5,9,12], target=2 -> -1"], "key_points": ["标准模板", "注意防溢出写法"], "tags": ["binarysearch", "easy", "Google", "Amazon"]} {"problem_id": "algo_01431", "original_id": "climbing-stairs", "title": "爬楼梯", "category": "dp", "difficulty": "easy", "companies": ["Amazon", "Google"], "description": "假设你正在爬楼梯。需要 n 阶你才能到达楼顶。每次你可以爬 1 或 2 个台阶。你有多少种不同的方法可以爬到楼顶?", "solution_python": "def climbStairs(n):\n if n <= 2: return n\n a, b = 1, 2\n for _ in range(3, n+1):\n a, b = b, a + b\n return b", "solution_java": "public int climbStairs(int n) {\n if (n <= 2) return n;\n int a = 1, b = 2;\n for (int i = 3; i <= n; i++) { int temp = a + b; a = b; b = temp; }\n return b;\n}", "solution_cpp": "int climbStairs(int n) {\n if (n <= 2) return n;\n int a = 1, b = 2;\n for (int i = 3; i <= n; i++) { int temp = a + b; a = b; b = temp; }\n return b;\n}", "test_cases": ["n=2 -> 2", "n=3 -> 3", "n=5 -> 8"], "key_points": ["斐波那契数列", "滚动数组优化空间"], "tags": ["dp", "easy", "Amazon", "Google"]} {"problem_id": "algo_01432", "original_id": "coin-change", "title": "零钱兑换", "category": "dp", "difficulty": "medium", "companies": ["Google", "Amazon"], "description": "给你一个整数数组 coins 表示不同面额的硬币,以及一个整数 amount 表示总金额。计算并返回可以凑成总金额所需的最少的硬币个数。如果没有任何一种硬币组合能组成总金额,返回 -1。", "solution_python": "def coinChange(coins, amount):\n dp = [float('inf')] * (amount + 1)\n dp[0] = 0\n for coin in coins:\n for x in range(coin, amount + 1):\n dp[x] = min(dp[x], dp[x - coin] + 1)\n return dp[amount] if dp[amount] != float('inf') else -1", "solution_java": "public int coinChange(int[] coins, int amount) {\n int[] dp = new int[amount + 1];\n Arrays.fill(dp, amount + 1);\n dp[0] = 0;\n for (int coin : coins) {\n for (int x = coin; x <= amount; x++) {\n dp[x] = Math.min(dp[x], dp[x - coin] + 1);\n }\n }\n return dp[amount] > amount ? -1 : dp[amount];\n}", "solution_cpp": "int coinChange(vector& coins, int amount) {\n vector dp(amount + 1, amount + 1);\n dp[0] = 0;\n for (int coin : coins) {\n for (int x = coin; x <= amount; x++) {\n dp[x] = min(dp[x], dp[x - coin] + 1);\n }\n }\n return dp[amount] > amount ? -1 : dp[amount];\n}", "test_cases": ["coins=[1,2,5], amount=11 -> 3", "coins=[2], amount=3 -> -1"], "key_points": ["完全背包问题", "dp[x] = min(dp[x-coin]+1)"], "tags": ["dp", "medium", "Google", "Amazon"]} {"problem_id": "algo_01433", "original_id": "subsets", "title": "子集", "category": "backtracking", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "给你一个整数数组 nums ,数组中的元素 互不相同 。返回该数组所有可能的子集(幂集)。", "solution_python": "def subsets(nums):\n result = []\n def backtrack(start, path):\n result.append(path[:])\n for i in range(start, len(nums)):\n path.append(nums[i])\n backtrack(i + 1, path)\n path.pop()\n backtrack(0, [])\n return result", "solution_java": "public List> subsets(int[] nums) {\n List> result = new ArrayList<>();\n backtrack(nums, 0, new ArrayList<>(), result);\n return result;\n}\nprivate void backtrack(int[] nums, int start, List path, List> result) {\n result.add(new ArrayList<>(path));\n for (int i = start; i < nums.length; i++) {\n path.add(nums[i]);\n backtrack(nums, i + 1, path, result);\n path.remove(path.size() - 1);\n }\n}", "solution_cpp": "vector> subsets(vector& nums) {\n vector> result;\n vector path;\n backtrack(nums, 0, path, result);\n return result;\n}\nvoid backtrack(vector& nums, int start, vector& path, vector>& result) {\n result.push_back(path);\n for (int i = start; i < nums.size(); i++) {\n path.push_back(nums[i]);\n backtrack(nums, i + 1, path, result);\n path.pop_back();\n }\n}", "test_cases": ["nums=[1,2,3] -> [[],[1],[2],[1,2],[3],[1,3],[2,3],[1,2,3]]"], "key_points": ["选或不选", "DFS遍历子集树"], "tags": ["backtracking", "medium", "Google", "Microsoft"]} {"problem_id": "algo_01434", "original_id": "permutations", "title": "全排列", "category": "backtracking", "difficulty": "medium", "companies": ["Google", "Facebook"], "description": "给定一个不含重复数字的数组 nums,返回其所有可能的全排列。", "solution_python": "def permute(nums):\n result = []\n def backtrack(path, used):\n if len(path) == len(nums):\n result.append(path[:])\n return\n for i in range(len(nums)):\n if used[i]: continue\n used[i] = True\n path.append(nums[i])\n backtrack(path, used)\n path.pop()\n used[i] = False\n backtrack([], [False]*len(nums))\n return result", "solution_java": "public List> permute(int[] nums) {\n List> result = new ArrayList<>();\n boolean[] used = new boolean[nums.length];\n backtrack(nums, used, new ArrayList<>(), result);\n return result;\n}\nprivate void backtrack(int[] nums, boolean[] used, List path, List> result) {\n if (path.size() == nums.length) { result.add(new ArrayList<>(path)); return; }\n for (int i = 0; i < nums.length; i++) {\n if (used[i]) continue;\n used[i] = true;\n path.add(nums[i]);\n backtrack(nums, used, path, result);\n path.remove(path.size() - 1);\n used[i] = false;\n }\n}", "solution_cpp": "vector> permute(vector& nums) {\n vector> result;\n vector used(nums.size(), false);\n vector path;\n backtrack(nums, used, path, result);\n return result;\n}\nvoid backtrack(vector& nums, vector& used, vector& path, vector>& result) {\n if (path.size() == nums.size()) { result.push_back(path); return; }\n for (int i = 0; i < nums.size(); i++) {\n if (used[i]) continue;\n used[i] = true;\n path.push_back(nums[i]);\n backtrack(nums, used, path, result);\n path.pop_back();\n used[i] = false;\n }\n}", "test_cases": ["nums=[1,2,3] -> [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]"], "key_points": ["标记已使用元素", "回溯经典模板"], "tags": ["backtracking", "medium", "Google", "Facebook"]} {"problem_id": "algo_01435", "original_id": "top-k-frequent", "title": "前K个高频元素", "category": "heap", "difficulty": "medium", "companies": ["Amazon", "Facebook"], "description": "给你一个整数数组 nums 和一个整数 k,请你返回其中出现频率前 k 高的元素。", "solution_python": "import heapq\nfrom collections import Counter\ndef topKFrequent(nums, k):\n count = Counter(nums)\n heap = []\n for num, freq in count.items():\n heapq.heappush(heap, (freq, num))\n if len(heap) > k: heapq.heappop(heap)\n return [num for freq, num in heap]", "solution_java": "public int[] topKFrequent(int[] nums, int k) {\n Map count = new HashMap<>();\n for (int n : nums) count.put(n, count.getOrDefault(n, 0) + 1);\n PriorityQueue> heap = \n new PriorityQueue<>((a, b) -> a.getValue() - b.getValue());\n for (Map.Entry e : count.entrySet()) {\n heap.offer(e);\n if (heap.size() > k) heap.poll();\n }\n int[] res = new int[k];\n for (int i = k - 1; i >= 0; i--) res[i] = heap.poll().getKey();\n return res;\n}", "solution_cpp": "vector topKFrequent(vector& nums, int k) {\n unordered_map count;\n for (int n : nums) count[n]++;\n priority_queue, vector>, greater>> heap;\n for (auto& [num, freq] : count) {\n heap.push({freq, num});\n if (heap.size() > k) heap.pop();\n }\n vector res;\n while (!heap.empty()) { res.push_back(heap.top().second); heap.pop(); }\n reverse(res.begin(), res.end());\n return res;\n}", "test_cases": ["nums=[1,1,1,2,2,3], k=2 -> [1,2]", "nums=[1], k=1 -> [1]"], "key_points": ["小顶堆保持大小k", "时间复杂度O(nlogk)"], "tags": ["heap", "medium", "Amazon", "Facebook"]} {"problem_id": "algo_01436", "original_id": "3sum", "title": "三数之和", "category": "two-pointers", "difficulty": "medium", "companies": ["Google", "Amazon"], "description": "给你一个整数数组 nums,判断是否存在三元组满足和为0,返回所有不重复的三元组。", "solution_python": "def threeSum(nums):\n nums.sort()\n result = []\n for i in range(len(nums) - 2):\n if i > 0 and nums[i] == nums[i-1]: continue\n left, right = i + 1, len(nums) - 1\n while left < right:\n total = nums[i] + nums[left] + nums[right]\n if total < 0: left += 1\n elif total > 0: right -= 1\n else:\n result.append([nums[i], nums[left], nums[right]])\n while left < right and nums[left] == nums[left+1]: left += 1\n while left < right and nums[right] == nums[right-1]: right -= 1\n left += 1; right -= 1\n return result", "solution_java": "public List> threeSum(int[] nums) {\n Arrays.sort(nums);\n List> result = new ArrayList<>();\n for (int i = 0; i < nums.length - 2; i++) {\n if (i > 0 && nums[i] == nums[i-1]) continue;\n int left = i + 1, right = nums.length - 1;\n while (left < right) {\n int total = nums[i] + nums[left] + nums[right];\n if (total < 0) left++;\n else if (total > 0) right--;\n else {\n result.add(Arrays.asList(nums[i], nums[left], nums[right]));\n while (left < right && nums[left] == nums[left+1]) left++;\n while (left < right && nums[right] == nums[right-1]) right--;\n left++; right--;\n }\n }\n }\n return result;\n}", "solution_cpp": "vector> threeSum(vector& nums) {\n sort(nums.begin(), nums.end());\n vector> result;\n for (int i = 0; i < nums.size() - 2; i++) {\n if (i > 0 && nums[i] == nums[i-1]) continue;\n int left = i + 1, right = nums.size() - 1;\n while (left < right) {\n int total = nums[i] + nums[left] + nums[right];\n if (total < 0) left++;\n else if (total > 0) right--;\n else {\n result.push_back({nums[i], nums[left], nums[right]});\n while (left < right && nums[left] == nums[left+1]) left++;\n while (left < right && nums[right] == nums[right-1]) right--;\n left++; right--;\n }\n }\n }\n return result;\n}", "test_cases": ["nums=[-1,0,1,2,-1,-4] -> [[-1,-1,2],[-1,0,1]]"], "key_points": ["排序+双指针", "去重是关键"], "tags": ["two-pointers", "medium", "Google", "Amazon"]} {"problem_id": "algo_01437", "original_id": "container-water", "title": "盛最多水的容器", "category": "two-pointers", "difficulty": "medium", "companies": ["Google", "Uber"], "description": "给定一个长度为 n 的整数数组 height,找出其中的两条线,使得它们与 x 轴共同构成的容器可以容纳最多的水。", "solution_python": "def maxArea(height):\n left, right = 0, len(height) - 1\n max_area = 0\n while left < right:\n h = min(height[left], height[right])\n max_area = max(max_area, h * (right - left))\n if height[left] < height[right]: left += 1\n else: right -= 1\n return max_area", "solution_java": "public int maxArea(int[] height) {\n int left = 0, right = height.length - 1, maxArea = 0;\n while (left < right) {\n int h = Math.min(height[left], height[right]);\n maxArea = Math.max(maxArea, h * (right - left));\n if (height[left] < height[right]) left++;\n else right--;\n }\n return maxArea;\n}", "solution_cpp": "int maxArea(vector& height) {\n int left = 0, right = height.size() - 1, maxArea = 0;\n while (left < right) {\n int h = min(height[left], height[right]);\n maxArea = max(maxArea, h * (right - left));\n if (height[left] < height[right]) left++;\n else right--;\n }\n return maxArea;\n}", "test_cases": ["height=[1,8,6,2,5,4,8,3,7] -> 49"], "key_points": ["移动短边指针", "面积=min(h1,h2)*width"], "tags": ["two-pointers", "medium", "Google", "Uber"]} {"problem_id": "algo_01438", "original_id": "min-stack", "title": "最小栈", "category": "stack", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "设计一个支持 push,pop,top 操作,并能在常数时间内检索到最小元素的栈。", "solution_python": "class MinStack:\n def __init__(self):\n self.stack = []\n self.min_stack = []\n def push(self, val):\n self.stack.append(val)\n self.min_stack.append(min(val, self.min_stack[-1] if self.min_stack else val))\n def pop(self):\n self.stack.pop(); self.min_stack.pop()\n def top(self): return self.stack[-1]\n def getMin(self): return self.min_stack[-1]", "solution_java": "class MinStack {\n Stack stack = new Stack<>();\n Stack minStack = new Stack<>();\n public void push(int val) { stack.push(val); minStack.push(Math.min(val, minStack.isEmpty() ? val : minStack.peek())); }\n public void pop() { stack.pop(); minStack.pop(); }\n public int top() { return stack.peek(); }\n public int getMin() { return minStack.peek(); }\n}", "solution_cpp": "class MinStack {\n stack st, minSt;\npublic:\n void push(int val) { st.push(val); minSt.push(min(val, minSt.empty() ? val : minSt.top())); }\n void pop() { st.pop(); minSt.pop(); }\n int top() { return st.top(); }\n int getMin() { return minSt.top(); }\n};", "test_cases": ["push(-2), push(0), push(-3) -> getMin() returns -3"], "key_points": ["辅助栈记录最小值", "O(1)时间获取最小值"], "tags": ["stack", "medium", "Google", "Microsoft"]} {"problem_id": "algo_01439", "original_id": "lru-cache", "title": "LRU缓存", "category": "design", "difficulty": "hard", "companies": ["Google", "Amazon"], "description": "设计和实现一个 LRU(最近最少使用)缓存机制。", "solution_python": "class LRUCache:\n def __init__(self, capacity):\n self.capacity = capacity\n self.cache = {}\n self.order = []\n def get(self, key):\n if key not in self.cache: return -1\n self.order.remove(key); self.order.append(key)\n return self.cache[key]\n def put(self, key, value):\n if key in self.cache:\n self.order.remove(key)\n elif len(self.cache) >= self.capacity:\n del self.cache[self.order.pop(0)]\n self.cache[key] = value; self.order.append(key)", "solution_java": "class LRUCache {\n int capacity;\n LinkedHashMap cache = new LinkedHashMap<>();\n public LRUCache(int cap) { capacity = cap; }\n public int get(int key) { return cache.containsKey(key) ? cache.remove(key) : -1; }\n public void put(int key, int val) {\n if (cache.containsKey(key)) cache.remove(key);\n else if (cache.size() >= capacity) cache.remove(cache.keySet().iterator().next());\n cache.put(key, val);\n }\n}", "solution_cpp": "class LRUCache {\n int cap;\n list> dll;\n unordered_map>::iterator> cache;\npublic:\n LRUCache(int capacity) : cap(capacity) {}\n int get(int key) {\n auto it = cache.find(key);\n if (it == cache.end()) return -1;\n dll.splice(dll.end(), dll, it->second);\n return it->second->second;\n }\n void put(int key, int value) {\n auto it = cache.find(key);\n if (it != cache.end()) dll.erase(it->second);\n else if (cache.size() >= cap) { cache.erase(dll.front().first); dll.pop_front(); }\n dll.push_back({key, value});\n cache[key] = --dll.end();\n }\n};", "test_cases": ["put(1,1), put(2,2), get(1) -> 1"], "key_points": ["HashMap + 双向链表", "O(1)时间操作"], "tags": ["design", "hard", "Google", "Amazon"]} {"problem_id": "algo_01440", "original_id": "num-islands", "title": "岛屿数量", "category": "graph", "difficulty": "medium", "companies": ["Google", "Facebook"], "description": "给你一个由 '1'(陆地)和 '0'(水)组成的二维网格,请你计算网格中岛屿的数量。岛屿总是被水包围,且只能由水平或垂直方向相邻的陆地连接形成。", "solution_python": "def numIslands(grid):\n if not grid: return 0\n rows, cols = len(grid), len(grid[0])\n count = 0\n def dfs(r, c):\n if r < 0 or r >= rows or c < 0 or c >= cols or grid[r][c] != '1': return\n grid[r][c] = '0'\n dfs(r+1, c); dfs(r-1, c); dfs(r, c+1); dfs(r, c-1)\n for r in range(rows):\n for c in range(cols):\n if grid[r][c] == '1': count += 1; dfs(r, c)\n return count", "solution_java": "public int numIslands(char[][] grid) {\n if (grid.length == 0) return 0;\n int count = 0;\n for (int i = 0; i < grid.length; i++)\n for (int j = 0; j < grid[0].length; j++)\n if (grid[i][j] == '1') { count++; dfs(grid, i, j); }\n return count;\n}\nprivate void dfs(char[][] grid, int r, int c) {\n if (r < 0 || r >= grid.length || c < 0 || c >= grid[0].length || grid[r][c] != '1') return;\n grid[r][c] = '0';\n dfs(grid, r+1, c); dfs(grid, r-1, c); dfs(grid, r, c+1); dfs(grid, r, c-1);\n}", "solution_cpp": "int numIslands(vector>& grid) {\n if (grid.empty()) return 0;\n int count = 0;\n for (int i = 0; i < grid.size(); i++)\n for (int j = 0; j < grid[0].size(); j++)\n if (grid[i][j] == '1') { count++; dfs(grid, i, j); }\n return count;\n}\nvoid dfs(vector>& grid, int r, int c) {\n if (r < 0 || r >= grid.size() || c < 0 || c >= grid[0].size() || grid[r][c] != '1') return;\n grid[r][c] = '0';\n dfs(grid, r+1, c); dfs(grid, r-1, c); dfs(grid, r, c+1); dfs(grid, r, c-1);\n}", "test_cases": ["grid=[[1,1,1,1,0],[1,1,0,1,0],[1,1,0,0,0],[0,0,0,0,0]] -> 1"], "key_points": ["DFS/BFS遍历", "访问后标记为0避免重复"], "tags": ["graph", "medium", "Google", "Facebook"]} {"problem_id": "algo_01441", "original_id": "two-sum", "title": "两数之和", "category": "array", "difficulty": "easy", "companies": ["Amazon", "Google"], "description": "给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那两个整数,并返回他们的数组下标。", "solution_python": "def twoSum(nums, target):\n hashmap = {}\n for i, num in enumerate(nums):\n complement = target - num\n if complement in hashmap:\n return [hashmap[complement], i]\n hashmap[num] = i\n return []", "solution_java": "public int[] twoSum(int[] nums, int target) {\n Map map = new HashMap<>();\n for (int i = 0; i < nums.length; i++) {\n int complement = target - nums[i];\n if (map.containsKey(complement)) return new int[]{map.get(complement), i};\n map.put(nums[i], i);\n }\n return new int[]{};\n}", "solution_cpp": "vector twoSum(vector& nums, int target) {\n unordered_map m;\n for (int i = 0; i < nums.size(); i++) {\n if (m.count(target - nums[i])) return {m[target - nums[i]], i};\n m[nums[i]] = i;\n }\n return {};\n}", "test_cases": ["nums=[2,7,11,15], target=9 -> [0,1]", "nums=[3,2,4], target=6 -> [1,2]"], "key_points": ["哈希表一次遍历", "空间换时间"], "tags": ["array", "easy", "Amazon", "Google"]} {"problem_id": "algo_01442", "original_id": "merge-sorted", "title": "合并两个有序数组", "category": "array", "difficulty": "easy", "companies": ["Microsoft", "Uber"], "description": "给你两个按非递减顺序排列的整数数组 nums1 和 nums2,另有两个整数 m 和 n,分别表示 nums1 和 nums2 中的元素数目。请你合并 nums2 到 nums1 中。", "solution_python": "def merge(nums1, m, nums2, n):\n p1, p2, p = m-1, n-1, m+n-1\n while p1 >= 0 and p2 >= 0:\n if nums1[p1] > nums2[p2]: nums1[p] = nums1[p1]; p1 -= 1\n else: nums1[p] = nums2[p2]; p2 -= 1\n p -= 1\n while p2 >= 0: nums1[p] = nums2[p2]; p2 -= 1; p -= 1", "solution_java": "public void merge(int[] nums1, int m, int[] nums2, int n) {\n int p1 = m-1, p2 = n-1, p = m+n-1;\n while (p1 >= 0 && p2 >= 0) {\n nums1[p--] = nums1[p1] > nums2[p2] ? nums1[p1--] : nums2[p2--];\n }\n while (p2 >= 0) nums1[p--] = nums2[p2--];\n}", "solution_cpp": "void merge(vector& nums1, int m, vector& nums2, int n) {\n int p1 = m-1, p2 = n-1, p = m+n-1;\n while (p1 >= 0 && p2 >= 0) nums1[p--] = nums1[p1] > nums2[p2] ? nums1[p1--] : nums2[p2--];\n while (p2 >= 0) nums1[p--] = nums2[p2--];\n}", "test_cases": ["nums1=[1,2,3], m=3, nums2=[2,5,6], n=3 -> [1,2,2,3,5,6]", "nums1=[], m=0, nums2=[1], n=1 -> [1]"], "key_points": ["从后往前合并", "三指针技巧"], "tags": ["array", "easy", "Microsoft", "Uber"]} {"problem_id": "algo_01443", "original_id": "max-subarray", "title": "最大子数组和", "category": "array", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "给你一个整数数组 nums ,请你找出一个具有最大和的连续子数组,返回其最大和。", "solution_python": "def maxSubArray(nums):\n max_sum = current = nums[0]\n for num in nums[1:]:\n current = max(num, current + num)\n max_sum = max(max_sum, current)\n return max_sum", "solution_java": "public int maxSubArray(int[] nums) {\n int maxSum = nums[0], curr = nums[0];\n for (int i = 1; i < nums.length; i++) {\n curr = Math.max(nums[i], curr + nums[i]);\n maxSum = Math.max(maxSum, curr);\n }\n return maxSum;\n}", "solution_cpp": "int maxSubArray(vector& nums) {\n int maxSum = nums[0], curr = nums[0];\n for (int i = 1; i < nums.size(); i++) {\n curr = max(nums[i], curr + nums[i]);\n maxSum = max(maxSum, curr);\n }\n return maxSum;\n}", "test_cases": ["nums=[-2,1,-3,4,-1,2,1,-5,4] -> 6", "nums=[1] -> 1"], "key_points": ["Kadane算法", "动态规划基础题"], "tags": ["array", "medium", "Google", "Microsoft"]} {"problem_id": "algo_01444", "original_id": "valid-parentheses", "title": "有效的括号", "category": "string", "difficulty": "easy", "companies": ["Google", "Uber"], "description": "给定一个只包括 '(',')','{','}','[',']' 的字符串 s,判断字符串是否有效。", "solution_python": "def isValid(s):\n stack = []\n mapping = {')': '(', ']': '[', '}': '{'}\n for c in s:\n if c in mapping:\n if not stack or stack[-1] != mapping[c]: return False\n stack.pop()\n else: stack.append(c)\n return not stack", "solution_java": "public boolean isValid(String s) {\n Stack stack = new Stack<>();\n Map map = Map.of(')', '(', ']', '[', '}', '{');\n for (char c : s.toCharArray()) {\n if (map.containsValue(c)) stack.push(c);\n else if (!stack.isEmpty() && stack.pop() != map.get(c)) return false;\n }\n return stack.isEmpty();\n}", "solution_cpp": "bool isValid(string s) {\n stack st;\n unordered_map m = {{')','('},{']','['},{'}','{'}};\n for (char c : s) {\n if (m.find(c) == m.end()) st.push(c);\n else if (st.empty() || st.top() != m[c]) return false;\n else st.pop();\n }\n return st.empty();\n}", "test_cases": ["s=\"()\" -> true", "s=\"()[]{}\" -> true", "s=\"(]\" -> false"], "key_points": ["栈匹配法", "注意空栈边界"], "tags": ["string", "easy", "Google", "Uber"]} {"problem_id": "algo_01445", "original_id": "longest-palindrome", "title": "最长回文子串", "category": "string", "difficulty": "medium", "companies": ["Google", "Amazon"], "description": "给你一个字符串 s,找到 s 中最长的回文子串。", "solution_python": "def longestPalindrome(s):\n def expand(l, r):\n while l >= 0 and r < len(s) and s[l] == s[r]: l -= 1; r += 1\n return l + 1, r - 1\n start = end = 0\n for i in range(len(s)):\n l1, r1 = expand(i, i)\n l2, r2 = expand(i, i + 1)\n if r1 - l1 > end - start: start, end = l1, r1\n if r2 - l2 > end - start: start, end = l2, r2\n return s[start:end+1]", "solution_java": "public String longestPalindrome(String s) {\n int start = 0, end = 0;\n for (int i = 0; i < s.length(); i++) {\n int len1 = expand(s, i, i), len2 = expand(s, i, i+1);\n int len = Math.max(len1, len2);\n if (len > end - start) { start = i - (len-1)/2; end = i + len/2; }\n }\n return s.substring(start, end + 1);\n}\nprivate int expand(String s, int l, int r) {\n while (l >= 0 && r < s.length() && s.charAt(l) == s.charAt(r)) { l--; r++; }\n return r - l - 1;\n}", "solution_cpp": "string longestPalindrome(string s) {\n int start = 0, end = 0;\n for (int i = 0; i < s.size(); i++) {\n int len1 = expand(s, i, i), len2 = expand(s, i, i+1);\n if (max(len1, len2) > end - start) { start = i - (max(len1,len2)-1)/2; end = i + max(len1,len2)/2; }\n }\n return s.substr(start, end - start + 1);\n}", "test_cases": ["s=\"babad\" -> bab或aba", "s=\"cbbd\" -> bb"], "key_points": ["中心扩展法", "处理奇偶长度"], "tags": ["string", "medium", "Google", "Amazon"]} {"problem_id": "algo_01446", "original_id": "reverse-list", "title": "反转链表", "category": "linkedlist", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "给你单链表的头节点 head,请你反转链表,并返回反转后的链表。", "solution_python": "def reverseList(head):\n prev = None\n curr = head\n while curr:\n nxt = curr.next\n curr.next = prev\n prev = curr\n curr = nxt\n return prev", "solution_java": "public ListNode reverseList(ListNode head) {\n ListNode prev = null, curr = head;\n while (curr != null) {\n ListNode next = curr.next;\n curr.next = prev;\n prev = curr;\n curr = next;\n }\n return prev;\n}", "solution_cpp": "ListNode* reverseList(ListNode* head) {\n ListNode* prev = nullptr, *curr = head;\n while (curr) {\n ListNode* next = curr->next;\n curr->next = prev;\n prev = curr;\n curr = next;\n }\n return prev;\n}", "test_cases": ["head=[1,2,3,4,5] -> [5,4,3,2,1]", "head=[1,2] -> [2,1]"], "key_points": ["迭代法 O(1)空间", "递归法 O(n)空间"], "tags": ["linkedlist", "medium", "Google", "Microsoft"]} {"problem_id": "algo_01447", "original_id": "middle-node", "title": "链表的中间结点", "category": "linkedlist", "difficulty": "easy", "companies": ["Amazon", "Facebook"], "description": "给你单链表的头节点 head,请你找出并返回链表的中间结点。如果有两个中间结点,则返回第二个中间结点。", "solution_python": "def middleNode(head):\n slow = fast = head\n while fast and fast.next:\n slow = slow.next\n fast = fast.next.next\n return slow", "solution_java": "public ListNode middleNode(ListNode head) {\n ListNode slow = head, fast = head;\n while (fast != null && fast.next != null) {\n slow = slow.next;\n fast = fast.next.next;\n }\n return slow;\n}", "solution_cpp": "ListNode* middleNode(ListNode* head) {\n ListNode* slow = head, *fast = head;\n while (fast && fast->next) { slow = slow->next; fast = fast->next->next; }\n return slow;\n}", "test_cases": ["head=[1,2,3,4,5] -> 3", "head=[1,2,3,4,5,6] -> 4"], "key_points": ["快慢指针", "O(n)时间O(1)空间"], "tags": ["linkedlist", "easy", "Amazon", "Facebook"]} {"problem_id": "algo_01448", "original_id": "max-depth", "title": "二叉树的最大深度", "category": "tree", "difficulty": "easy", "companies": ["Microsoft", "Apple"], "description": "给定一个二叉树 root,返回其最大深度。", "solution_python": "def maxDepth(root):\n if not root: return 0\n return max(maxDepth(root.left), maxDepth(root.right)) + 1", "solution_java": "public int maxDepth(TreeNode root) {\n if (root == null) return 0;\n return Math.max(maxDepth(root.left), maxDepth(root.right)) + 1;\n}", "solution_cpp": "int maxDepth(TreeNode* root) {\n if (!root) return 0;\n return max(maxDepth(root->left), maxDepth(root->right)) + 1;\n}", "test_cases": ["root=[3,9,20,null,null,15,7] -> 3", "root=[1,null,2] -> 2"], "key_points": ["DFS递归", "层序遍历也可"], "tags": ["tree", "easy", "Microsoft", "Apple"]} {"problem_id": "algo_01449", "original_id": "inorder-traversal", "title": "二叉树的中序遍历", "category": "tree", "difficulty": "easy", "companies": ["Google", "Microsoft"], "description": "给定一个二叉树的根节点 root,返回它的中序遍历结果。", "solution_python": "def inorderTraversal(root):\n result = []\n def dfs(node):\n if node:\n dfs(node.left)\n result.append(node.val)\n dfs(node.right)\n dfs(root)\n return result", "solution_java": "public List inorderTraversal(TreeNode root) {\n List res = new ArrayList<>();\n dfs(root, res);\n return res;\n}\nprivate void dfs(TreeNode node, List res) {\n if (node == null) return;\n dfs(node.left, res); res.add(node.val); dfs(node.right, res);\n}", "solution_cpp": "vector inorderTraversal(TreeNode* root) {\n vector res;\n dfs(root, res);\n return res;\n}\nvoid dfs(TreeNode* node, vector& res) {\n if (!node) return;\n dfs(node->left, res); res.push_back(node->val); dfs(node->right, res);\n}", "test_cases": ["root=[1,null,2,3] -> [1,3,2]", "root=[] -> []"], "key_points": ["左-根-右顺序", "递归最简洁"], "tags": ["tree", "easy", "Google", "Microsoft"]} {"problem_id": "algo_01450", "original_id": "binary-search", "title": "二分查找", "category": "binarysearch", "difficulty": "easy", "companies": ["Google", "Amazon"], "description": "给定一个 n 个元素有序的(升序)整型数组 nums 和一个目标值 target,写一个函数搜索 nums 中的 target,如果目标值存在返回下标,否则返回 -1。", "solution_python": "def search(nums, target):\n left, right = 0, len(nums) - 1\n while left <= right:\n mid = (left + right) // 2\n if nums[mid] == target: return mid\n elif nums[mid] < target: left = mid + 1\n else: right = mid - 1\n return -1", "solution_java": "public int search(int[] nums, int target) {\n int left = 0, right = nums.length - 1;\n while (left <= right) {\n int mid = left + (right - left) / 2;\n if (nums[mid] == target) return mid;\n else if (nums[mid] < target) left = mid + 1;\n else right = mid - 1;\n }\n return -1;\n}", "solution_cpp": "int search(vector& nums, int target) {\n int left = 0, right = nums.size() - 1;\n while (left <= right) {\n int mid = left + (right - left) / 2;\n if (nums[mid] == target) return mid;\n else if (nums[mid] < target) left = mid + 1;\n else right = mid - 1;\n }\n return -1;\n}", "test_cases": ["nums=[-1,0,3,5,9,12], target=9 -> 4", "nums=[-1,0,3,5,9,12], target=2 -> -1"], "key_points": ["标准模板", "注意防溢出写法"], "tags": ["binarysearch", "easy", "Google", "Amazon"]} {"problem_id": "algo_01451", "original_id": "climbing-stairs", "title": "爬楼梯", "category": "dp", "difficulty": "easy", "companies": ["Amazon", "Google"], "description": "假设你正在爬楼梯。需要 n 阶你才能到达楼顶。每次你可以爬 1 或 2 个台阶。你有多少种不同的方法可以爬到楼顶?", "solution_python": "def climbStairs(n):\n if n <= 2: return n\n a, b = 1, 2\n for _ in range(3, n+1):\n a, b = b, a + b\n return b", "solution_java": "public int climbStairs(int n) {\n if (n <= 2) return n;\n int a = 1, b = 2;\n for (int i = 3; i <= n; i++) { int temp = a + b; a = b; b = temp; }\n return b;\n}", "solution_cpp": "int climbStairs(int n) {\n if (n <= 2) return n;\n int a = 1, b = 2;\n for (int i = 3; i <= n; i++) { int temp = a + b; a = b; b = temp; }\n return b;\n}", "test_cases": ["n=2 -> 2", "n=3 -> 3", "n=5 -> 8"], "key_points": ["斐波那契数列", "滚动数组优化空间"], "tags": ["dp", "easy", "Amazon", "Google"]} {"problem_id": "algo_01452", "original_id": "coin-change", "title": "零钱兑换", "category": "dp", "difficulty": "medium", "companies": ["Google", "Amazon"], "description": "给你一个整数数组 coins 表示不同面额的硬币,以及一个整数 amount 表示总金额。计算并返回可以凑成总金额所需的最少的硬币个数。如果没有任何一种硬币组合能组成总金额,返回 -1。", "solution_python": "def coinChange(coins, amount):\n dp = [float('inf')] * (amount + 1)\n dp[0] = 0\n for coin in coins:\n for x in range(coin, amount + 1):\n dp[x] = min(dp[x], dp[x - coin] + 1)\n return dp[amount] if dp[amount] != float('inf') else -1", "solution_java": "public int coinChange(int[] coins, int amount) {\n int[] dp = new int[amount + 1];\n Arrays.fill(dp, amount + 1);\n dp[0] = 0;\n for (int coin : coins) {\n for (int x = coin; x <= amount; x++) {\n dp[x] = Math.min(dp[x], dp[x - coin] + 1);\n }\n }\n return dp[amount] > amount ? -1 : dp[amount];\n}", "solution_cpp": "int coinChange(vector& coins, int amount) {\n vector dp(amount + 1, amount + 1);\n dp[0] = 0;\n for (int coin : coins) {\n for (int x = coin; x <= amount; x++) {\n dp[x] = min(dp[x], dp[x - coin] + 1);\n }\n }\n return dp[amount] > amount ? -1 : dp[amount];\n}", "test_cases": ["coins=[1,2,5], amount=11 -> 3", "coins=[2], amount=3 -> -1"], "key_points": ["完全背包问题", "dp[x] = min(dp[x-coin]+1)"], "tags": ["dp", "medium", "Google", "Amazon"]} {"problem_id": "algo_01453", "original_id": "subsets", "title": "子集", "category": "backtracking", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "给你一个整数数组 nums ,数组中的元素 互不相同 。返回该数组所有可能的子集(幂集)。", "solution_python": "def subsets(nums):\n result = []\n def backtrack(start, path):\n result.append(path[:])\n for i in range(start, len(nums)):\n path.append(nums[i])\n backtrack(i + 1, path)\n path.pop()\n backtrack(0, [])\n return result", "solution_java": "public List> subsets(int[] nums) {\n List> result = new ArrayList<>();\n backtrack(nums, 0, new ArrayList<>(), result);\n return result;\n}\nprivate void backtrack(int[] nums, int start, List path, List> result) {\n result.add(new ArrayList<>(path));\n for (int i = start; i < nums.length; i++) {\n path.add(nums[i]);\n backtrack(nums, i + 1, path, result);\n path.remove(path.size() - 1);\n }\n}", "solution_cpp": "vector> subsets(vector& nums) {\n vector> result;\n vector path;\n backtrack(nums, 0, path, result);\n return result;\n}\nvoid backtrack(vector& nums, int start, vector& path, vector>& result) {\n result.push_back(path);\n for (int i = start; i < nums.size(); i++) {\n path.push_back(nums[i]);\n backtrack(nums, i + 1, path, result);\n path.pop_back();\n }\n}", "test_cases": ["nums=[1,2,3] -> [[],[1],[2],[1,2],[3],[1,3],[2,3],[1,2,3]]"], "key_points": ["选或不选", "DFS遍历子集树"], "tags": ["backtracking", "medium", "Google", "Microsoft"]} {"problem_id": "algo_01454", "original_id": "permutations", "title": "全排列", "category": "backtracking", "difficulty": "medium", "companies": ["Google", "Facebook"], "description": "给定一个不含重复数字的数组 nums,返回其所有可能的全排列。", "solution_python": "def permute(nums):\n result = []\n def backtrack(path, used):\n if len(path) == len(nums):\n result.append(path[:])\n return\n for i in range(len(nums)):\n if used[i]: continue\n used[i] = True\n path.append(nums[i])\n backtrack(path, used)\n path.pop()\n used[i] = False\n backtrack([], [False]*len(nums))\n return result", "solution_java": "public List> permute(int[] nums) {\n List> result = new ArrayList<>();\n boolean[] used = new boolean[nums.length];\n backtrack(nums, used, new ArrayList<>(), result);\n return result;\n}\nprivate void backtrack(int[] nums, boolean[] used, List path, List> result) {\n if (path.size() == nums.length) { result.add(new ArrayList<>(path)); return; }\n for (int i = 0; i < nums.length; i++) {\n if (used[i]) continue;\n used[i] = true;\n path.add(nums[i]);\n backtrack(nums, used, path, result);\n path.remove(path.size() - 1);\n used[i] = false;\n }\n}", "solution_cpp": "vector> permute(vector& nums) {\n vector> result;\n vector used(nums.size(), false);\n vector path;\n backtrack(nums, used, path, result);\n return result;\n}\nvoid backtrack(vector& nums, vector& used, vector& path, vector>& result) {\n if (path.size() == nums.size()) { result.push_back(path); return; }\n for (int i = 0; i < nums.size(); i++) {\n if (used[i]) continue;\n used[i] = true;\n path.push_back(nums[i]);\n backtrack(nums, used, path, result);\n path.pop_back();\n used[i] = false;\n }\n}", "test_cases": ["nums=[1,2,3] -> [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]"], "key_points": ["标记已使用元素", "回溯经典模板"], "tags": ["backtracking", "medium", "Google", "Facebook"]} {"problem_id": "algo_01455", "original_id": "top-k-frequent", "title": "前K个高频元素", "category": "heap", "difficulty": "medium", "companies": ["Amazon", "Facebook"], "description": "给你一个整数数组 nums 和一个整数 k,请你返回其中出现频率前 k 高的元素。", "solution_python": "import heapq\nfrom collections import Counter\ndef topKFrequent(nums, k):\n count = Counter(nums)\n heap = []\n for num, freq in count.items():\n heapq.heappush(heap, (freq, num))\n if len(heap) > k: heapq.heappop(heap)\n return [num for freq, num in heap]", "solution_java": "public int[] topKFrequent(int[] nums, int k) {\n Map count = new HashMap<>();\n for (int n : nums) count.put(n, count.getOrDefault(n, 0) + 1);\n PriorityQueue> heap = \n new PriorityQueue<>((a, b) -> a.getValue() - b.getValue());\n for (Map.Entry e : count.entrySet()) {\n heap.offer(e);\n if (heap.size() > k) heap.poll();\n }\n int[] res = new int[k];\n for (int i = k - 1; i >= 0; i--) res[i] = heap.poll().getKey();\n return res;\n}", "solution_cpp": "vector topKFrequent(vector& nums, int k) {\n unordered_map count;\n for (int n : nums) count[n]++;\n priority_queue, vector>, greater>> heap;\n for (auto& [num, freq] : count) {\n heap.push({freq, num});\n if (heap.size() > k) heap.pop();\n }\n vector res;\n while (!heap.empty()) { res.push_back(heap.top().second); heap.pop(); }\n reverse(res.begin(), res.end());\n return res;\n}", "test_cases": ["nums=[1,1,1,2,2,3], k=2 -> [1,2]", "nums=[1], k=1 -> [1]"], "key_points": ["小顶堆保持大小k", "时间复杂度O(nlogk)"], "tags": ["heap", "medium", "Amazon", "Facebook"]} {"problem_id": "algo_01456", "original_id": "3sum", "title": "三数之和", "category": "two-pointers", "difficulty": "medium", "companies": ["Google", "Amazon"], "description": "给你一个整数数组 nums,判断是否存在三元组满足和为0,返回所有不重复的三元组。", "solution_python": "def threeSum(nums):\n nums.sort()\n result = []\n for i in range(len(nums) - 2):\n if i > 0 and nums[i] == nums[i-1]: continue\n left, right = i + 1, len(nums) - 1\n while left < right:\n total = nums[i] + nums[left] + nums[right]\n if total < 0: left += 1\n elif total > 0: right -= 1\n else:\n result.append([nums[i], nums[left], nums[right]])\n while left < right and nums[left] == nums[left+1]: left += 1\n while left < right and nums[right] == nums[right-1]: right -= 1\n left += 1; right -= 1\n return result", "solution_java": "public List> threeSum(int[] nums) {\n Arrays.sort(nums);\n List> result = new ArrayList<>();\n for (int i = 0; i < nums.length - 2; i++) {\n if (i > 0 && nums[i] == nums[i-1]) continue;\n int left = i + 1, right = nums.length - 1;\n while (left < right) {\n int total = nums[i] + nums[left] + nums[right];\n if (total < 0) left++;\n else if (total > 0) right--;\n else {\n result.add(Arrays.asList(nums[i], nums[left], nums[right]));\n while (left < right && nums[left] == nums[left+1]) left++;\n while (left < right && nums[right] == nums[right-1]) right--;\n left++; right--;\n }\n }\n }\n return result;\n}", "solution_cpp": "vector> threeSum(vector& nums) {\n sort(nums.begin(), nums.end());\n vector> result;\n for (int i = 0; i < nums.size() - 2; i++) {\n if (i > 0 && nums[i] == nums[i-1]) continue;\n int left = i + 1, right = nums.size() - 1;\n while (left < right) {\n int total = nums[i] + nums[left] + nums[right];\n if (total < 0) left++;\n else if (total > 0) right--;\n else {\n result.push_back({nums[i], nums[left], nums[right]});\n while (left < right && nums[left] == nums[left+1]) left++;\n while (left < right && nums[right] == nums[right-1]) right--;\n left++; right--;\n }\n }\n }\n return result;\n}", "test_cases": ["nums=[-1,0,1,2,-1,-4] -> [[-1,-1,2],[-1,0,1]]"], "key_points": ["排序+双指针", "去重是关键"], "tags": ["two-pointers", "medium", "Google", "Amazon"]} {"problem_id": "algo_01457", "original_id": "container-water", "title": "盛最多水的容器", "category": "two-pointers", "difficulty": "medium", "companies": ["Google", "Uber"], "description": "给定一个长度为 n 的整数数组 height,找出其中的两条线,使得它们与 x 轴共同构成的容器可以容纳最多的水。", "solution_python": "def maxArea(height):\n left, right = 0, len(height) - 1\n max_area = 0\n while left < right:\n h = min(height[left], height[right])\n max_area = max(max_area, h * (right - left))\n if height[left] < height[right]: left += 1\n else: right -= 1\n return max_area", "solution_java": "public int maxArea(int[] height) {\n int left = 0, right = height.length - 1, maxArea = 0;\n while (left < right) {\n int h = Math.min(height[left], height[right]);\n maxArea = Math.max(maxArea, h * (right - left));\n if (height[left] < height[right]) left++;\n else right--;\n }\n return maxArea;\n}", "solution_cpp": "int maxArea(vector& height) {\n int left = 0, right = height.size() - 1, maxArea = 0;\n while (left < right) {\n int h = min(height[left], height[right]);\n maxArea = max(maxArea, h * (right - left));\n if (height[left] < height[right]) left++;\n else right--;\n }\n return maxArea;\n}", "test_cases": ["height=[1,8,6,2,5,4,8,3,7] -> 49"], "key_points": ["移动短边指针", "面积=min(h1,h2)*width"], "tags": ["two-pointers", "medium", "Google", "Uber"]} {"problem_id": "algo_01458", "original_id": "min-stack", "title": "最小栈", "category": "stack", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "设计一个支持 push,pop,top 操作,并能在常数时间内检索到最小元素的栈。", "solution_python": "class MinStack:\n def __init__(self):\n self.stack = []\n self.min_stack = []\n def push(self, val):\n self.stack.append(val)\n self.min_stack.append(min(val, self.min_stack[-1] if self.min_stack else val))\n def pop(self):\n self.stack.pop(); self.min_stack.pop()\n def top(self): return self.stack[-1]\n def getMin(self): return self.min_stack[-1]", "solution_java": "class MinStack {\n Stack stack = new Stack<>();\n Stack minStack = new Stack<>();\n public void push(int val) { stack.push(val); minStack.push(Math.min(val, minStack.isEmpty() ? val : minStack.peek())); }\n public void pop() { stack.pop(); minStack.pop(); }\n public int top() { return stack.peek(); }\n public int getMin() { return minStack.peek(); }\n}", "solution_cpp": "class MinStack {\n stack st, minSt;\npublic:\n void push(int val) { st.push(val); minSt.push(min(val, minSt.empty() ? val : minSt.top())); }\n void pop() { st.pop(); minSt.pop(); }\n int top() { return st.top(); }\n int getMin() { return minSt.top(); }\n};", "test_cases": ["push(-2), push(0), push(-3) -> getMin() returns -3"], "key_points": ["辅助栈记录最小值", "O(1)时间获取最小值"], "tags": ["stack", "medium", "Google", "Microsoft"]} {"problem_id": "algo_01459", "original_id": "lru-cache", "title": "LRU缓存", "category": "design", "difficulty": "hard", "companies": ["Google", "Amazon"], "description": "设计和实现一个 LRU(最近最少使用)缓存机制。", "solution_python": "class LRUCache:\n def __init__(self, capacity):\n self.capacity = capacity\n self.cache = {}\n self.order = []\n def get(self, key):\n if key not in self.cache: return -1\n self.order.remove(key); self.order.append(key)\n return self.cache[key]\n def put(self, key, value):\n if key in self.cache:\n self.order.remove(key)\n elif len(self.cache) >= self.capacity:\n del self.cache[self.order.pop(0)]\n self.cache[key] = value; self.order.append(key)", "solution_java": "class LRUCache {\n int capacity;\n LinkedHashMap cache = new LinkedHashMap<>();\n public LRUCache(int cap) { capacity = cap; }\n public int get(int key) { return cache.containsKey(key) ? cache.remove(key) : -1; }\n public void put(int key, int val) {\n if (cache.containsKey(key)) cache.remove(key);\n else if (cache.size() >= capacity) cache.remove(cache.keySet().iterator().next());\n cache.put(key, val);\n }\n}", "solution_cpp": "class LRUCache {\n int cap;\n list> dll;\n unordered_map>::iterator> cache;\npublic:\n LRUCache(int capacity) : cap(capacity) {}\n int get(int key) {\n auto it = cache.find(key);\n if (it == cache.end()) return -1;\n dll.splice(dll.end(), dll, it->second);\n return it->second->second;\n }\n void put(int key, int value) {\n auto it = cache.find(key);\n if (it != cache.end()) dll.erase(it->second);\n else if (cache.size() >= cap) { cache.erase(dll.front().first); dll.pop_front(); }\n dll.push_back({key, value});\n cache[key] = --dll.end();\n }\n};", "test_cases": ["put(1,1), put(2,2), get(1) -> 1"], "key_points": ["HashMap + 双向链表", "O(1)时间操作"], "tags": ["design", "hard", "Google", "Amazon"]} {"problem_id": "algo_01460", "original_id": "num-islands", "title": "岛屿数量", "category": "graph", "difficulty": "medium", "companies": ["Google", "Facebook"], "description": "给你一个由 '1'(陆地)和 '0'(水)组成的二维网格,请你计算网格中岛屿的数量。岛屿总是被水包围,且只能由水平或垂直方向相邻的陆地连接形成。", "solution_python": "def numIslands(grid):\n if not grid: return 0\n rows, cols = len(grid), len(grid[0])\n count = 0\n def dfs(r, c):\n if r < 0 or r >= rows or c < 0 or c >= cols or grid[r][c] != '1': return\n grid[r][c] = '0'\n dfs(r+1, c); dfs(r-1, c); dfs(r, c+1); dfs(r, c-1)\n for r in range(rows):\n for c in range(cols):\n if grid[r][c] == '1': count += 1; dfs(r, c)\n return count", "solution_java": "public int numIslands(char[][] grid) {\n if (grid.length == 0) return 0;\n int count = 0;\n for (int i = 0; i < grid.length; i++)\n for (int j = 0; j < grid[0].length; j++)\n if (grid[i][j] == '1') { count++; dfs(grid, i, j); }\n return count;\n}\nprivate void dfs(char[][] grid, int r, int c) {\n if (r < 0 || r >= grid.length || c < 0 || c >= grid[0].length || grid[r][c] != '1') return;\n grid[r][c] = '0';\n dfs(grid, r+1, c); dfs(grid, r-1, c); dfs(grid, r, c+1); dfs(grid, r, c-1);\n}", "solution_cpp": "int numIslands(vector>& grid) {\n if (grid.empty()) return 0;\n int count = 0;\n for (int i = 0; i < grid.size(); i++)\n for (int j = 0; j < grid[0].size(); j++)\n if (grid[i][j] == '1') { count++; dfs(grid, i, j); }\n return count;\n}\nvoid dfs(vector>& grid, int r, int c) {\n if (r < 0 || r >= grid.size() || c < 0 || c >= grid[0].size() || grid[r][c] != '1') return;\n grid[r][c] = '0';\n dfs(grid, r+1, c); dfs(grid, r-1, c); dfs(grid, r, c+1); dfs(grid, r, c-1);\n}", "test_cases": ["grid=[[1,1,1,1,0],[1,1,0,1,0],[1,1,0,0,0],[0,0,0,0,0]] -> 1"], "key_points": ["DFS/BFS遍历", "访问后标记为0避免重复"], "tags": ["graph", "medium", "Google", "Facebook"]} {"problem_id": "algo_01461", "original_id": "two-sum", "title": "两数之和", "category": "array", "difficulty": "easy", "companies": ["Amazon", "Google"], "description": "给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那两个整数,并返回他们的数组下标。", "solution_python": "def twoSum(nums, target):\n hashmap = {}\n for i, num in enumerate(nums):\n complement = target - num\n if complement in hashmap:\n return [hashmap[complement], i]\n hashmap[num] = i\n return []", "solution_java": "public int[] twoSum(int[] nums, int target) {\n Map map = new HashMap<>();\n for (int i = 0; i < nums.length; i++) {\n int complement = target - nums[i];\n if (map.containsKey(complement)) return new int[]{map.get(complement), i};\n map.put(nums[i], i);\n }\n return new int[]{};\n}", "solution_cpp": "vector twoSum(vector& nums, int target) {\n unordered_map m;\n for (int i = 0; i < nums.size(); i++) {\n if (m.count(target - nums[i])) return {m[target - nums[i]], i};\n m[nums[i]] = i;\n }\n return {};\n}", "test_cases": ["nums=[2,7,11,15], target=9 -> [0,1]", "nums=[3,2,4], target=6 -> [1,2]"], "key_points": ["哈希表一次遍历", "空间换时间"], "tags": ["array", "easy", "Amazon", "Google"]} {"problem_id": "algo_01462", "original_id": "merge-sorted", "title": "合并两个有序数组", "category": "array", "difficulty": "easy", "companies": ["Microsoft", "Uber"], "description": "给你两个按非递减顺序排列的整数数组 nums1 和 nums2,另有两个整数 m 和 n,分别表示 nums1 和 nums2 中的元素数目。请你合并 nums2 到 nums1 中。", "solution_python": "def merge(nums1, m, nums2, n):\n p1, p2, p = m-1, n-1, m+n-1\n while p1 >= 0 and p2 >= 0:\n if nums1[p1] > nums2[p2]: nums1[p] = nums1[p1]; p1 -= 1\n else: nums1[p] = nums2[p2]; p2 -= 1\n p -= 1\n while p2 >= 0: nums1[p] = nums2[p2]; p2 -= 1; p -= 1", "solution_java": "public void merge(int[] nums1, int m, int[] nums2, int n) {\n int p1 = m-1, p2 = n-1, p = m+n-1;\n while (p1 >= 0 && p2 >= 0) {\n nums1[p--] = nums1[p1] > nums2[p2] ? nums1[p1--] : nums2[p2--];\n }\n while (p2 >= 0) nums1[p--] = nums2[p2--];\n}", "solution_cpp": "void merge(vector& nums1, int m, vector& nums2, int n) {\n int p1 = m-1, p2 = n-1, p = m+n-1;\n while (p1 >= 0 && p2 >= 0) nums1[p--] = nums1[p1] > nums2[p2] ? nums1[p1--] : nums2[p2--];\n while (p2 >= 0) nums1[p--] = nums2[p2--];\n}", "test_cases": ["nums1=[1,2,3], m=3, nums2=[2,5,6], n=3 -> [1,2,2,3,5,6]", "nums1=[], m=0, nums2=[1], n=1 -> [1]"], "key_points": ["从后往前合并", "三指针技巧"], "tags": ["array", "easy", "Microsoft", "Uber"]} {"problem_id": "algo_01463", "original_id": "max-subarray", "title": "最大子数组和", "category": "array", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "给你一个整数数组 nums ,请你找出一个具有最大和的连续子数组,返回其最大和。", "solution_python": "def maxSubArray(nums):\n max_sum = current = nums[0]\n for num in nums[1:]:\n current = max(num, current + num)\n max_sum = max(max_sum, current)\n return max_sum", "solution_java": "public int maxSubArray(int[] nums) {\n int maxSum = nums[0], curr = nums[0];\n for (int i = 1; i < nums.length; i++) {\n curr = Math.max(nums[i], curr + nums[i]);\n maxSum = Math.max(maxSum, curr);\n }\n return maxSum;\n}", "solution_cpp": "int maxSubArray(vector& nums) {\n int maxSum = nums[0], curr = nums[0];\n for (int i = 1; i < nums.size(); i++) {\n curr = max(nums[i], curr + nums[i]);\n maxSum = max(maxSum, curr);\n }\n return maxSum;\n}", "test_cases": ["nums=[-2,1,-3,4,-1,2,1,-5,4] -> 6", "nums=[1] -> 1"], "key_points": ["Kadane算法", "动态规划基础题"], "tags": ["array", "medium", "Google", "Microsoft"]} {"problem_id": "algo_01464", "original_id": "valid-parentheses", "title": "有效的括号", "category": "string", "difficulty": "easy", "companies": ["Google", "Uber"], "description": "给定一个只包括 '(',')','{','}','[',']' 的字符串 s,判断字符串是否有效。", "solution_python": "def isValid(s):\n stack = []\n mapping = {')': '(', ']': '[', '}': '{'}\n for c in s:\n if c in mapping:\n if not stack or stack[-1] != mapping[c]: return False\n stack.pop()\n else: stack.append(c)\n return not stack", "solution_java": "public boolean isValid(String s) {\n Stack stack = new Stack<>();\n Map map = Map.of(')', '(', ']', '[', '}', '{');\n for (char c : s.toCharArray()) {\n if (map.containsValue(c)) stack.push(c);\n else if (!stack.isEmpty() && stack.pop() != map.get(c)) return false;\n }\n return stack.isEmpty();\n}", "solution_cpp": "bool isValid(string s) {\n stack st;\n unordered_map m = {{')','('},{']','['},{'}','{'}};\n for (char c : s) {\n if (m.find(c) == m.end()) st.push(c);\n else if (st.empty() || st.top() != m[c]) return false;\n else st.pop();\n }\n return st.empty();\n}", "test_cases": ["s=\"()\" -> true", "s=\"()[]{}\" -> true", "s=\"(]\" -> false"], "key_points": ["栈匹配法", "注意空栈边界"], "tags": ["string", "easy", "Google", "Uber"]} {"problem_id": "algo_01465", "original_id": "longest-palindrome", "title": "最长回文子串", "category": "string", "difficulty": "medium", "companies": ["Google", "Amazon"], "description": "给你一个字符串 s,找到 s 中最长的回文子串。", "solution_python": "def longestPalindrome(s):\n def expand(l, r):\n while l >= 0 and r < len(s) and s[l] == s[r]: l -= 1; r += 1\n return l + 1, r - 1\n start = end = 0\n for i in range(len(s)):\n l1, r1 = expand(i, i)\n l2, r2 = expand(i, i + 1)\n if r1 - l1 > end - start: start, end = l1, r1\n if r2 - l2 > end - start: start, end = l2, r2\n return s[start:end+1]", "solution_java": "public String longestPalindrome(String s) {\n int start = 0, end = 0;\n for (int i = 0; i < s.length(); i++) {\n int len1 = expand(s, i, i), len2 = expand(s, i, i+1);\n int len = Math.max(len1, len2);\n if (len > end - start) { start = i - (len-1)/2; end = i + len/2; }\n }\n return s.substring(start, end + 1);\n}\nprivate int expand(String s, int l, int r) {\n while (l >= 0 && r < s.length() && s.charAt(l) == s.charAt(r)) { l--; r++; }\n return r - l - 1;\n}", "solution_cpp": "string longestPalindrome(string s) {\n int start = 0, end = 0;\n for (int i = 0; i < s.size(); i++) {\n int len1 = expand(s, i, i), len2 = expand(s, i, i+1);\n if (max(len1, len2) > end - start) { start = i - (max(len1,len2)-1)/2; end = i + max(len1,len2)/2; }\n }\n return s.substr(start, end - start + 1);\n}", "test_cases": ["s=\"babad\" -> bab或aba", "s=\"cbbd\" -> bb"], "key_points": ["中心扩展法", "处理奇偶长度"], "tags": ["string", "medium", "Google", "Amazon"]} {"problem_id": "algo_01466", "original_id": "reverse-list", "title": "反转链表", "category": "linkedlist", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "给你单链表的头节点 head,请你反转链表,并返回反转后的链表。", "solution_python": "def reverseList(head):\n prev = None\n curr = head\n while curr:\n nxt = curr.next\n curr.next = prev\n prev = curr\n curr = nxt\n return prev", "solution_java": "public ListNode reverseList(ListNode head) {\n ListNode prev = null, curr = head;\n while (curr != null) {\n ListNode next = curr.next;\n curr.next = prev;\n prev = curr;\n curr = next;\n }\n return prev;\n}", "solution_cpp": "ListNode* reverseList(ListNode* head) {\n ListNode* prev = nullptr, *curr = head;\n while (curr) {\n ListNode* next = curr->next;\n curr->next = prev;\n prev = curr;\n curr = next;\n }\n return prev;\n}", "test_cases": ["head=[1,2,3,4,5] -> [5,4,3,2,1]", "head=[1,2] -> [2,1]"], "key_points": ["迭代法 O(1)空间", "递归法 O(n)空间"], "tags": ["linkedlist", "medium", "Google", "Microsoft"]} {"problem_id": "algo_01467", "original_id": "middle-node", "title": "链表的中间结点", "category": "linkedlist", "difficulty": "easy", "companies": ["Amazon", "Facebook"], "description": "给你单链表的头节点 head,请你找出并返回链表的中间结点。如果有两个中间结点,则返回第二个中间结点。", "solution_python": "def middleNode(head):\n slow = fast = head\n while fast and fast.next:\n slow = slow.next\n fast = fast.next.next\n return slow", "solution_java": "public ListNode middleNode(ListNode head) {\n ListNode slow = head, fast = head;\n while (fast != null && fast.next != null) {\n slow = slow.next;\n fast = fast.next.next;\n }\n return slow;\n}", "solution_cpp": "ListNode* middleNode(ListNode* head) {\n ListNode* slow = head, *fast = head;\n while (fast && fast->next) { slow = slow->next; fast = fast->next->next; }\n return slow;\n}", "test_cases": ["head=[1,2,3,4,5] -> 3", "head=[1,2,3,4,5,6] -> 4"], "key_points": ["快慢指针", "O(n)时间O(1)空间"], "tags": ["linkedlist", "easy", "Amazon", "Facebook"]} {"problem_id": "algo_01468", "original_id": "max-depth", "title": "二叉树的最大深度", "category": "tree", "difficulty": "easy", "companies": ["Microsoft", "Apple"], "description": "给定一个二叉树 root,返回其最大深度。", "solution_python": "def maxDepth(root):\n if not root: return 0\n return max(maxDepth(root.left), maxDepth(root.right)) + 1", "solution_java": "public int maxDepth(TreeNode root) {\n if (root == null) return 0;\n return Math.max(maxDepth(root.left), maxDepth(root.right)) + 1;\n}", "solution_cpp": "int maxDepth(TreeNode* root) {\n if (!root) return 0;\n return max(maxDepth(root->left), maxDepth(root->right)) + 1;\n}", "test_cases": ["root=[3,9,20,null,null,15,7] -> 3", "root=[1,null,2] -> 2"], "key_points": ["DFS递归", "层序遍历也可"], "tags": ["tree", "easy", "Microsoft", "Apple"]} {"problem_id": "algo_01469", "original_id": "inorder-traversal", "title": "二叉树的中序遍历", "category": "tree", "difficulty": "easy", "companies": ["Google", "Microsoft"], "description": "给定一个二叉树的根节点 root,返回它的中序遍历结果。", "solution_python": "def inorderTraversal(root):\n result = []\n def dfs(node):\n if node:\n dfs(node.left)\n result.append(node.val)\n dfs(node.right)\n dfs(root)\n return result", "solution_java": "public List inorderTraversal(TreeNode root) {\n List res = new ArrayList<>();\n dfs(root, res);\n return res;\n}\nprivate void dfs(TreeNode node, List res) {\n if (node == null) return;\n dfs(node.left, res); res.add(node.val); dfs(node.right, res);\n}", "solution_cpp": "vector inorderTraversal(TreeNode* root) {\n vector res;\n dfs(root, res);\n return res;\n}\nvoid dfs(TreeNode* node, vector& res) {\n if (!node) return;\n dfs(node->left, res); res.push_back(node->val); dfs(node->right, res);\n}", "test_cases": ["root=[1,null,2,3] -> [1,3,2]", "root=[] -> []"], "key_points": ["左-根-右顺序", "递归最简洁"], "tags": ["tree", "easy", "Google", "Microsoft"]} {"problem_id": "algo_01470", "original_id": "binary-search", "title": "二分查找", "category": "binarysearch", "difficulty": "easy", "companies": ["Google", "Amazon"], "description": "给定一个 n 个元素有序的(升序)整型数组 nums 和一个目标值 target,写一个函数搜索 nums 中的 target,如果目标值存在返回下标,否则返回 -1。", "solution_python": "def search(nums, target):\n left, right = 0, len(nums) - 1\n while left <= right:\n mid = (left + right) // 2\n if nums[mid] == target: return mid\n elif nums[mid] < target: left = mid + 1\n else: right = mid - 1\n return -1", "solution_java": "public int search(int[] nums, int target) {\n int left = 0, right = nums.length - 1;\n while (left <= right) {\n int mid = left + (right - left) / 2;\n if (nums[mid] == target) return mid;\n else if (nums[mid] < target) left = mid + 1;\n else right = mid - 1;\n }\n return -1;\n}", "solution_cpp": "int search(vector& nums, int target) {\n int left = 0, right = nums.size() - 1;\n while (left <= right) {\n int mid = left + (right - left) / 2;\n if (nums[mid] == target) return mid;\n else if (nums[mid] < target) left = mid + 1;\n else right = mid - 1;\n }\n return -1;\n}", "test_cases": ["nums=[-1,0,3,5,9,12], target=9 -> 4", "nums=[-1,0,3,5,9,12], target=2 -> -1"], "key_points": ["标准模板", "注意防溢出写法"], "tags": ["binarysearch", "easy", "Google", "Amazon"]} {"problem_id": "algo_01471", "original_id": "climbing-stairs", "title": "爬楼梯", "category": "dp", "difficulty": "easy", "companies": ["Amazon", "Google"], "description": "假设你正在爬楼梯。需要 n 阶你才能到达楼顶。每次你可以爬 1 或 2 个台阶。你有多少种不同的方法可以爬到楼顶?", "solution_python": "def climbStairs(n):\n if n <= 2: return n\n a, b = 1, 2\n for _ in range(3, n+1):\n a, b = b, a + b\n return b", "solution_java": "public int climbStairs(int n) {\n if (n <= 2) return n;\n int a = 1, b = 2;\n for (int i = 3; i <= n; i++) { int temp = a + b; a = b; b = temp; }\n return b;\n}", "solution_cpp": "int climbStairs(int n) {\n if (n <= 2) return n;\n int a = 1, b = 2;\n for (int i = 3; i <= n; i++) { int temp = a + b; a = b; b = temp; }\n return b;\n}", "test_cases": ["n=2 -> 2", "n=3 -> 3", "n=5 -> 8"], "key_points": ["斐波那契数列", "滚动数组优化空间"], "tags": ["dp", "easy", "Amazon", "Google"]} {"problem_id": "algo_01472", "original_id": "coin-change", "title": "零钱兑换", "category": "dp", "difficulty": "medium", "companies": ["Google", "Amazon"], "description": "给你一个整数数组 coins 表示不同面额的硬币,以及一个整数 amount 表示总金额。计算并返回可以凑成总金额所需的最少的硬币个数。如果没有任何一种硬币组合能组成总金额,返回 -1。", "solution_python": "def coinChange(coins, amount):\n dp = [float('inf')] * (amount + 1)\n dp[0] = 0\n for coin in coins:\n for x in range(coin, amount + 1):\n dp[x] = min(dp[x], dp[x - coin] + 1)\n return dp[amount] if dp[amount] != float('inf') else -1", "solution_java": "public int coinChange(int[] coins, int amount) {\n int[] dp = new int[amount + 1];\n Arrays.fill(dp, amount + 1);\n dp[0] = 0;\n for (int coin : coins) {\n for (int x = coin; x <= amount; x++) {\n dp[x] = Math.min(dp[x], dp[x - coin] + 1);\n }\n }\n return dp[amount] > amount ? -1 : dp[amount];\n}", "solution_cpp": "int coinChange(vector& coins, int amount) {\n vector dp(amount + 1, amount + 1);\n dp[0] = 0;\n for (int coin : coins) {\n for (int x = coin; x <= amount; x++) {\n dp[x] = min(dp[x], dp[x - coin] + 1);\n }\n }\n return dp[amount] > amount ? -1 : dp[amount];\n}", "test_cases": ["coins=[1,2,5], amount=11 -> 3", "coins=[2], amount=3 -> -1"], "key_points": ["完全背包问题", "dp[x] = min(dp[x-coin]+1)"], "tags": ["dp", "medium", "Google", "Amazon"]} {"problem_id": "algo_01473", "original_id": "subsets", "title": "子集", "category": "backtracking", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "给你一个整数数组 nums ,数组中的元素 互不相同 。返回该数组所有可能的子集(幂集)。", "solution_python": "def subsets(nums):\n result = []\n def backtrack(start, path):\n result.append(path[:])\n for i in range(start, len(nums)):\n path.append(nums[i])\n backtrack(i + 1, path)\n path.pop()\n backtrack(0, [])\n return result", "solution_java": "public List> subsets(int[] nums) {\n List> result = new ArrayList<>();\n backtrack(nums, 0, new ArrayList<>(), result);\n return result;\n}\nprivate void backtrack(int[] nums, int start, List path, List> result) {\n result.add(new ArrayList<>(path));\n for (int i = start; i < nums.length; i++) {\n path.add(nums[i]);\n backtrack(nums, i + 1, path, result);\n path.remove(path.size() - 1);\n }\n}", "solution_cpp": "vector> subsets(vector& nums) {\n vector> result;\n vector path;\n backtrack(nums, 0, path, result);\n return result;\n}\nvoid backtrack(vector& nums, int start, vector& path, vector>& result) {\n result.push_back(path);\n for (int i = start; i < nums.size(); i++) {\n path.push_back(nums[i]);\n backtrack(nums, i + 1, path, result);\n path.pop_back();\n }\n}", "test_cases": ["nums=[1,2,3] -> [[],[1],[2],[1,2],[3],[1,3],[2,3],[1,2,3]]"], "key_points": ["选或不选", "DFS遍历子集树"], "tags": ["backtracking", "medium", "Google", "Microsoft"]} {"problem_id": "algo_01474", "original_id": "permutations", "title": "全排列", "category": "backtracking", "difficulty": "medium", "companies": ["Google", "Facebook"], "description": "给定一个不含重复数字的数组 nums,返回其所有可能的全排列。", "solution_python": "def permute(nums):\n result = []\n def backtrack(path, used):\n if len(path) == len(nums):\n result.append(path[:])\n return\n for i in range(len(nums)):\n if used[i]: continue\n used[i] = True\n path.append(nums[i])\n backtrack(path, used)\n path.pop()\n used[i] = False\n backtrack([], [False]*len(nums))\n return result", "solution_java": "public List> permute(int[] nums) {\n List> result = new ArrayList<>();\n boolean[] used = new boolean[nums.length];\n backtrack(nums, used, new ArrayList<>(), result);\n return result;\n}\nprivate void backtrack(int[] nums, boolean[] used, List path, List> result) {\n if (path.size() == nums.length) { result.add(new ArrayList<>(path)); return; }\n for (int i = 0; i < nums.length; i++) {\n if (used[i]) continue;\n used[i] = true;\n path.add(nums[i]);\n backtrack(nums, used, path, result);\n path.remove(path.size() - 1);\n used[i] = false;\n }\n}", "solution_cpp": "vector> permute(vector& nums) {\n vector> result;\n vector used(nums.size(), false);\n vector path;\n backtrack(nums, used, path, result);\n return result;\n}\nvoid backtrack(vector& nums, vector& used, vector& path, vector>& result) {\n if (path.size() == nums.size()) { result.push_back(path); return; }\n for (int i = 0; i < nums.size(); i++) {\n if (used[i]) continue;\n used[i] = true;\n path.push_back(nums[i]);\n backtrack(nums, used, path, result);\n path.pop_back();\n used[i] = false;\n }\n}", "test_cases": ["nums=[1,2,3] -> [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]"], "key_points": ["标记已使用元素", "回溯经典模板"], "tags": ["backtracking", "medium", "Google", "Facebook"]} {"problem_id": "algo_01475", "original_id": "top-k-frequent", "title": "前K个高频元素", "category": "heap", "difficulty": "medium", "companies": ["Amazon", "Facebook"], "description": "给你一个整数数组 nums 和一个整数 k,请你返回其中出现频率前 k 高的元素。", "solution_python": "import heapq\nfrom collections import Counter\ndef topKFrequent(nums, k):\n count = Counter(nums)\n heap = []\n for num, freq in count.items():\n heapq.heappush(heap, (freq, num))\n if len(heap) > k: heapq.heappop(heap)\n return [num for freq, num in heap]", "solution_java": "public int[] topKFrequent(int[] nums, int k) {\n Map count = new HashMap<>();\n for (int n : nums) count.put(n, count.getOrDefault(n, 0) + 1);\n PriorityQueue> heap = \n new PriorityQueue<>((a, b) -> a.getValue() - b.getValue());\n for (Map.Entry e : count.entrySet()) {\n heap.offer(e);\n if (heap.size() > k) heap.poll();\n }\n int[] res = new int[k];\n for (int i = k - 1; i >= 0; i--) res[i] = heap.poll().getKey();\n return res;\n}", "solution_cpp": "vector topKFrequent(vector& nums, int k) {\n unordered_map count;\n for (int n : nums) count[n]++;\n priority_queue, vector>, greater>> heap;\n for (auto& [num, freq] : count) {\n heap.push({freq, num});\n if (heap.size() > k) heap.pop();\n }\n vector res;\n while (!heap.empty()) { res.push_back(heap.top().second); heap.pop(); }\n reverse(res.begin(), res.end());\n return res;\n}", "test_cases": ["nums=[1,1,1,2,2,3], k=2 -> [1,2]", "nums=[1], k=1 -> [1]"], "key_points": ["小顶堆保持大小k", "时间复杂度O(nlogk)"], "tags": ["heap", "medium", "Amazon", "Facebook"]} {"problem_id": "algo_01476", "original_id": "3sum", "title": "三数之和", "category": "two-pointers", "difficulty": "medium", "companies": ["Google", "Amazon"], "description": "给你一个整数数组 nums,判断是否存在三元组满足和为0,返回所有不重复的三元组。", "solution_python": "def threeSum(nums):\n nums.sort()\n result = []\n for i in range(len(nums) - 2):\n if i > 0 and nums[i] == nums[i-1]: continue\n left, right = i + 1, len(nums) - 1\n while left < right:\n total = nums[i] + nums[left] + nums[right]\n if total < 0: left += 1\n elif total > 0: right -= 1\n else:\n result.append([nums[i], nums[left], nums[right]])\n while left < right and nums[left] == nums[left+1]: left += 1\n while left < right and nums[right] == nums[right-1]: right -= 1\n left += 1; right -= 1\n return result", "solution_java": "public List> threeSum(int[] nums) {\n Arrays.sort(nums);\n List> result = new ArrayList<>();\n for (int i = 0; i < nums.length - 2; i++) {\n if (i > 0 && nums[i] == nums[i-1]) continue;\n int left = i + 1, right = nums.length - 1;\n while (left < right) {\n int total = nums[i] + nums[left] + nums[right];\n if (total < 0) left++;\n else if (total > 0) right--;\n else {\n result.add(Arrays.asList(nums[i], nums[left], nums[right]));\n while (left < right && nums[left] == nums[left+1]) left++;\n while (left < right && nums[right] == nums[right-1]) right--;\n left++; right--;\n }\n }\n }\n return result;\n}", "solution_cpp": "vector> threeSum(vector& nums) {\n sort(nums.begin(), nums.end());\n vector> result;\n for (int i = 0; i < nums.size() - 2; i++) {\n if (i > 0 && nums[i] == nums[i-1]) continue;\n int left = i + 1, right = nums.size() - 1;\n while (left < right) {\n int total = nums[i] + nums[left] + nums[right];\n if (total < 0) left++;\n else if (total > 0) right--;\n else {\n result.push_back({nums[i], nums[left], nums[right]});\n while (left < right && nums[left] == nums[left+1]) left++;\n while (left < right && nums[right] == nums[right-1]) right--;\n left++; right--;\n }\n }\n }\n return result;\n}", "test_cases": ["nums=[-1,0,1,2,-1,-4] -> [[-1,-1,2],[-1,0,1]]"], "key_points": ["排序+双指针", "去重是关键"], "tags": ["two-pointers", "medium", "Google", "Amazon"]} {"problem_id": "algo_01477", "original_id": "container-water", "title": "盛最多水的容器", "category": "two-pointers", "difficulty": "medium", "companies": ["Google", "Uber"], "description": "给定一个长度为 n 的整数数组 height,找出其中的两条线,使得它们与 x 轴共同构成的容器可以容纳最多的水。", "solution_python": "def maxArea(height):\n left, right = 0, len(height) - 1\n max_area = 0\n while left < right:\n h = min(height[left], height[right])\n max_area = max(max_area, h * (right - left))\n if height[left] < height[right]: left += 1\n else: right -= 1\n return max_area", "solution_java": "public int maxArea(int[] height) {\n int left = 0, right = height.length - 1, maxArea = 0;\n while (left < right) {\n int h = Math.min(height[left], height[right]);\n maxArea = Math.max(maxArea, h * (right - left));\n if (height[left] < height[right]) left++;\n else right--;\n }\n return maxArea;\n}", "solution_cpp": "int maxArea(vector& height) {\n int left = 0, right = height.size() - 1, maxArea = 0;\n while (left < right) {\n int h = min(height[left], height[right]);\n maxArea = max(maxArea, h * (right - left));\n if (height[left] < height[right]) left++;\n else right--;\n }\n return maxArea;\n}", "test_cases": ["height=[1,8,6,2,5,4,8,3,7] -> 49"], "key_points": ["移动短边指针", "面积=min(h1,h2)*width"], "tags": ["two-pointers", "medium", "Google", "Uber"]} {"problem_id": "algo_01478", "original_id": "min-stack", "title": "最小栈", "category": "stack", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "设计一个支持 push,pop,top 操作,并能在常数时间内检索到最小元素的栈。", "solution_python": "class MinStack:\n def __init__(self):\n self.stack = []\n self.min_stack = []\n def push(self, val):\n self.stack.append(val)\n self.min_stack.append(min(val, self.min_stack[-1] if self.min_stack else val))\n def pop(self):\n self.stack.pop(); self.min_stack.pop()\n def top(self): return self.stack[-1]\n def getMin(self): return self.min_stack[-1]", "solution_java": "class MinStack {\n Stack stack = new Stack<>();\n Stack minStack = new Stack<>();\n public void push(int val) { stack.push(val); minStack.push(Math.min(val, minStack.isEmpty() ? val : minStack.peek())); }\n public void pop() { stack.pop(); minStack.pop(); }\n public int top() { return stack.peek(); }\n public int getMin() { return minStack.peek(); }\n}", "solution_cpp": "class MinStack {\n stack st, minSt;\npublic:\n void push(int val) { st.push(val); minSt.push(min(val, minSt.empty() ? val : minSt.top())); }\n void pop() { st.pop(); minSt.pop(); }\n int top() { return st.top(); }\n int getMin() { return minSt.top(); }\n};", "test_cases": ["push(-2), push(0), push(-3) -> getMin() returns -3"], "key_points": ["辅助栈记录最小值", "O(1)时间获取最小值"], "tags": ["stack", "medium", "Google", "Microsoft"]} {"problem_id": "algo_01479", "original_id": "lru-cache", "title": "LRU缓存", "category": "design", "difficulty": "hard", "companies": ["Google", "Amazon"], "description": "设计和实现一个 LRU(最近最少使用)缓存机制。", "solution_python": "class LRUCache:\n def __init__(self, capacity):\n self.capacity = capacity\n self.cache = {}\n self.order = []\n def get(self, key):\n if key not in self.cache: return -1\n self.order.remove(key); self.order.append(key)\n return self.cache[key]\n def put(self, key, value):\n if key in self.cache:\n self.order.remove(key)\n elif len(self.cache) >= self.capacity:\n del self.cache[self.order.pop(0)]\n self.cache[key] = value; self.order.append(key)", "solution_java": "class LRUCache {\n int capacity;\n LinkedHashMap cache = new LinkedHashMap<>();\n public LRUCache(int cap) { capacity = cap; }\n public int get(int key) { return cache.containsKey(key) ? cache.remove(key) : -1; }\n public void put(int key, int val) {\n if (cache.containsKey(key)) cache.remove(key);\n else if (cache.size() >= capacity) cache.remove(cache.keySet().iterator().next());\n cache.put(key, val);\n }\n}", "solution_cpp": "class LRUCache {\n int cap;\n list> dll;\n unordered_map>::iterator> cache;\npublic:\n LRUCache(int capacity) : cap(capacity) {}\n int get(int key) {\n auto it = cache.find(key);\n if (it == cache.end()) return -1;\n dll.splice(dll.end(), dll, it->second);\n return it->second->second;\n }\n void put(int key, int value) {\n auto it = cache.find(key);\n if (it != cache.end()) dll.erase(it->second);\n else if (cache.size() >= cap) { cache.erase(dll.front().first); dll.pop_front(); }\n dll.push_back({key, value});\n cache[key] = --dll.end();\n }\n};", "test_cases": ["put(1,1), put(2,2), get(1) -> 1"], "key_points": ["HashMap + 双向链表", "O(1)时间操作"], "tags": ["design", "hard", "Google", "Amazon"]} {"problem_id": "algo_01480", "original_id": "num-islands", "title": "岛屿数量", "category": "graph", "difficulty": "medium", "companies": ["Google", "Facebook"], "description": "给你一个由 '1'(陆地)和 '0'(水)组成的二维网格,请你计算网格中岛屿的数量。岛屿总是被水包围,且只能由水平或垂直方向相邻的陆地连接形成。", "solution_python": "def numIslands(grid):\n if not grid: return 0\n rows, cols = len(grid), len(grid[0])\n count = 0\n def dfs(r, c):\n if r < 0 or r >= rows or c < 0 or c >= cols or grid[r][c] != '1': return\n grid[r][c] = '0'\n dfs(r+1, c); dfs(r-1, c); dfs(r, c+1); dfs(r, c-1)\n for r in range(rows):\n for c in range(cols):\n if grid[r][c] == '1': count += 1; dfs(r, c)\n return count", "solution_java": "public int numIslands(char[][] grid) {\n if (grid.length == 0) return 0;\n int count = 0;\n for (int i = 0; i < grid.length; i++)\n for (int j = 0; j < grid[0].length; j++)\n if (grid[i][j] == '1') { count++; dfs(grid, i, j); }\n return count;\n}\nprivate void dfs(char[][] grid, int r, int c) {\n if (r < 0 || r >= grid.length || c < 0 || c >= grid[0].length || grid[r][c] != '1') return;\n grid[r][c] = '0';\n dfs(grid, r+1, c); dfs(grid, r-1, c); dfs(grid, r, c+1); dfs(grid, r, c-1);\n}", "solution_cpp": "int numIslands(vector>& grid) {\n if (grid.empty()) return 0;\n int count = 0;\n for (int i = 0; i < grid.size(); i++)\n for (int j = 0; j < grid[0].size(); j++)\n if (grid[i][j] == '1') { count++; dfs(grid, i, j); }\n return count;\n}\nvoid dfs(vector>& grid, int r, int c) {\n if (r < 0 || r >= grid.size() || c < 0 || c >= grid[0].size() || grid[r][c] != '1') return;\n grid[r][c] = '0';\n dfs(grid, r+1, c); dfs(grid, r-1, c); dfs(grid, r, c+1); dfs(grid, r, c-1);\n}", "test_cases": ["grid=[[1,1,1,1,0],[1,1,0,1,0],[1,1,0,0,0],[0,0,0,0,0]] -> 1"], "key_points": ["DFS/BFS遍历", "访问后标记为0避免重复"], "tags": ["graph", "medium", "Google", "Facebook"]} {"problem_id": "algo_01481", "original_id": "two-sum", "title": "两数之和", "category": "array", "difficulty": "easy", "companies": ["Amazon", "Google"], "description": "给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那两个整数,并返回他们的数组下标。", "solution_python": "def twoSum(nums, target):\n hashmap = {}\n for i, num in enumerate(nums):\n complement = target - num\n if complement in hashmap:\n return [hashmap[complement], i]\n hashmap[num] = i\n return []", "solution_java": "public int[] twoSum(int[] nums, int target) {\n Map map = new HashMap<>();\n for (int i = 0; i < nums.length; i++) {\n int complement = target - nums[i];\n if (map.containsKey(complement)) return new int[]{map.get(complement), i};\n map.put(nums[i], i);\n }\n return new int[]{};\n}", "solution_cpp": "vector twoSum(vector& nums, int target) {\n unordered_map m;\n for (int i = 0; i < nums.size(); i++) {\n if (m.count(target - nums[i])) return {m[target - nums[i]], i};\n m[nums[i]] = i;\n }\n return {};\n}", "test_cases": ["nums=[2,7,11,15], target=9 -> [0,1]", "nums=[3,2,4], target=6 -> [1,2]"], "key_points": ["哈希表一次遍历", "空间换时间"], "tags": ["array", "easy", "Amazon", "Google"]} {"problem_id": "algo_01482", "original_id": "merge-sorted", "title": "合并两个有序数组", "category": "array", "difficulty": "easy", "companies": ["Microsoft", "Uber"], "description": "给你两个按非递减顺序排列的整数数组 nums1 和 nums2,另有两个整数 m 和 n,分别表示 nums1 和 nums2 中的元素数目。请你合并 nums2 到 nums1 中。", "solution_python": "def merge(nums1, m, nums2, n):\n p1, p2, p = m-1, n-1, m+n-1\n while p1 >= 0 and p2 >= 0:\n if nums1[p1] > nums2[p2]: nums1[p] = nums1[p1]; p1 -= 1\n else: nums1[p] = nums2[p2]; p2 -= 1\n p -= 1\n while p2 >= 0: nums1[p] = nums2[p2]; p2 -= 1; p -= 1", "solution_java": "public void merge(int[] nums1, int m, int[] nums2, int n) {\n int p1 = m-1, p2 = n-1, p = m+n-1;\n while (p1 >= 0 && p2 >= 0) {\n nums1[p--] = nums1[p1] > nums2[p2] ? nums1[p1--] : nums2[p2--];\n }\n while (p2 >= 0) nums1[p--] = nums2[p2--];\n}", "solution_cpp": "void merge(vector& nums1, int m, vector& nums2, int n) {\n int p1 = m-1, p2 = n-1, p = m+n-1;\n while (p1 >= 0 && p2 >= 0) nums1[p--] = nums1[p1] > nums2[p2] ? nums1[p1--] : nums2[p2--];\n while (p2 >= 0) nums1[p--] = nums2[p2--];\n}", "test_cases": ["nums1=[1,2,3], m=3, nums2=[2,5,6], n=3 -> [1,2,2,3,5,6]", "nums1=[], m=0, nums2=[1], n=1 -> [1]"], "key_points": ["从后往前合并", "三指针技巧"], "tags": ["array", "easy", "Microsoft", "Uber"]} {"problem_id": "algo_01483", "original_id": "max-subarray", "title": "最大子数组和", "category": "array", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "给你一个整数数组 nums ,请你找出一个具有最大和的连续子数组,返回其最大和。", "solution_python": "def maxSubArray(nums):\n max_sum = current = nums[0]\n for num in nums[1:]:\n current = max(num, current + num)\n max_sum = max(max_sum, current)\n return max_sum", "solution_java": "public int maxSubArray(int[] nums) {\n int maxSum = nums[0], curr = nums[0];\n for (int i = 1; i < nums.length; i++) {\n curr = Math.max(nums[i], curr + nums[i]);\n maxSum = Math.max(maxSum, curr);\n }\n return maxSum;\n}", "solution_cpp": "int maxSubArray(vector& nums) {\n int maxSum = nums[0], curr = nums[0];\n for (int i = 1; i < nums.size(); i++) {\n curr = max(nums[i], curr + nums[i]);\n maxSum = max(maxSum, curr);\n }\n return maxSum;\n}", "test_cases": ["nums=[-2,1,-3,4,-1,2,1,-5,4] -> 6", "nums=[1] -> 1"], "key_points": ["Kadane算法", "动态规划基础题"], "tags": ["array", "medium", "Google", "Microsoft"]} {"problem_id": "algo_01484", "original_id": "valid-parentheses", "title": "有效的括号", "category": "string", "difficulty": "easy", "companies": ["Google", "Uber"], "description": "给定一个只包括 '(',')','{','}','[',']' 的字符串 s,判断字符串是否有效。", "solution_python": "def isValid(s):\n stack = []\n mapping = {')': '(', ']': '[', '}': '{'}\n for c in s:\n if c in mapping:\n if not stack or stack[-1] != mapping[c]: return False\n stack.pop()\n else: stack.append(c)\n return not stack", "solution_java": "public boolean isValid(String s) {\n Stack stack = new Stack<>();\n Map map = Map.of(')', '(', ']', '[', '}', '{');\n for (char c : s.toCharArray()) {\n if (map.containsValue(c)) stack.push(c);\n else if (!stack.isEmpty() && stack.pop() != map.get(c)) return false;\n }\n return stack.isEmpty();\n}", "solution_cpp": "bool isValid(string s) {\n stack st;\n unordered_map m = {{')','('},{']','['},{'}','{'}};\n for (char c : s) {\n if (m.find(c) == m.end()) st.push(c);\n else if (st.empty() || st.top() != m[c]) return false;\n else st.pop();\n }\n return st.empty();\n}", "test_cases": ["s=\"()\" -> true", "s=\"()[]{}\" -> true", "s=\"(]\" -> false"], "key_points": ["栈匹配法", "注意空栈边界"], "tags": ["string", "easy", "Google", "Uber"]} {"problem_id": "algo_01485", "original_id": "longest-palindrome", "title": "最长回文子串", "category": "string", "difficulty": "medium", "companies": ["Google", "Amazon"], "description": "给你一个字符串 s,找到 s 中最长的回文子串。", "solution_python": "def longestPalindrome(s):\n def expand(l, r):\n while l >= 0 and r < len(s) and s[l] == s[r]: l -= 1; r += 1\n return l + 1, r - 1\n start = end = 0\n for i in range(len(s)):\n l1, r1 = expand(i, i)\n l2, r2 = expand(i, i + 1)\n if r1 - l1 > end - start: start, end = l1, r1\n if r2 - l2 > end - start: start, end = l2, r2\n return s[start:end+1]", "solution_java": "public String longestPalindrome(String s) {\n int start = 0, end = 0;\n for (int i = 0; i < s.length(); i++) {\n int len1 = expand(s, i, i), len2 = expand(s, i, i+1);\n int len = Math.max(len1, len2);\n if (len > end - start) { start = i - (len-1)/2; end = i + len/2; }\n }\n return s.substring(start, end + 1);\n}\nprivate int expand(String s, int l, int r) {\n while (l >= 0 && r < s.length() && s.charAt(l) == s.charAt(r)) { l--; r++; }\n return r - l - 1;\n}", "solution_cpp": "string longestPalindrome(string s) {\n int start = 0, end = 0;\n for (int i = 0; i < s.size(); i++) {\n int len1 = expand(s, i, i), len2 = expand(s, i, i+1);\n if (max(len1, len2) > end - start) { start = i - (max(len1,len2)-1)/2; end = i + max(len1,len2)/2; }\n }\n return s.substr(start, end - start + 1);\n}", "test_cases": ["s=\"babad\" -> bab或aba", "s=\"cbbd\" -> bb"], "key_points": ["中心扩展法", "处理奇偶长度"], "tags": ["string", "medium", "Google", "Amazon"]} {"problem_id": "algo_01486", "original_id": "reverse-list", "title": "反转链表", "category": "linkedlist", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "给你单链表的头节点 head,请你反转链表,并返回反转后的链表。", "solution_python": "def reverseList(head):\n prev = None\n curr = head\n while curr:\n nxt = curr.next\n curr.next = prev\n prev = curr\n curr = nxt\n return prev", "solution_java": "public ListNode reverseList(ListNode head) {\n ListNode prev = null, curr = head;\n while (curr != null) {\n ListNode next = curr.next;\n curr.next = prev;\n prev = curr;\n curr = next;\n }\n return prev;\n}", "solution_cpp": "ListNode* reverseList(ListNode* head) {\n ListNode* prev = nullptr, *curr = head;\n while (curr) {\n ListNode* next = curr->next;\n curr->next = prev;\n prev = curr;\n curr = next;\n }\n return prev;\n}", "test_cases": ["head=[1,2,3,4,5] -> [5,4,3,2,1]", "head=[1,2] -> [2,1]"], "key_points": ["迭代法 O(1)空间", "递归法 O(n)空间"], "tags": ["linkedlist", "medium", "Google", "Microsoft"]} {"problem_id": "algo_01487", "original_id": "middle-node", "title": "链表的中间结点", "category": "linkedlist", "difficulty": "easy", "companies": ["Amazon", "Facebook"], "description": "给你单链表的头节点 head,请你找出并返回链表的中间结点。如果有两个中间结点,则返回第二个中间结点。", "solution_python": "def middleNode(head):\n slow = fast = head\n while fast and fast.next:\n slow = slow.next\n fast = fast.next.next\n return slow", "solution_java": "public ListNode middleNode(ListNode head) {\n ListNode slow = head, fast = head;\n while (fast != null && fast.next != null) {\n slow = slow.next;\n fast = fast.next.next;\n }\n return slow;\n}", "solution_cpp": "ListNode* middleNode(ListNode* head) {\n ListNode* slow = head, *fast = head;\n while (fast && fast->next) { slow = slow->next; fast = fast->next->next; }\n return slow;\n}", "test_cases": ["head=[1,2,3,4,5] -> 3", "head=[1,2,3,4,5,6] -> 4"], "key_points": ["快慢指针", "O(n)时间O(1)空间"], "tags": ["linkedlist", "easy", "Amazon", "Facebook"]} {"problem_id": "algo_01488", "original_id": "max-depth", "title": "二叉树的最大深度", "category": "tree", "difficulty": "easy", "companies": ["Microsoft", "Apple"], "description": "给定一个二叉树 root,返回其最大深度。", "solution_python": "def maxDepth(root):\n if not root: return 0\n return max(maxDepth(root.left), maxDepth(root.right)) + 1", "solution_java": "public int maxDepth(TreeNode root) {\n if (root == null) return 0;\n return Math.max(maxDepth(root.left), maxDepth(root.right)) + 1;\n}", "solution_cpp": "int maxDepth(TreeNode* root) {\n if (!root) return 0;\n return max(maxDepth(root->left), maxDepth(root->right)) + 1;\n}", "test_cases": ["root=[3,9,20,null,null,15,7] -> 3", "root=[1,null,2] -> 2"], "key_points": ["DFS递归", "层序遍历也可"], "tags": ["tree", "easy", "Microsoft", "Apple"]} {"problem_id": "algo_01489", "original_id": "inorder-traversal", "title": "二叉树的中序遍历", "category": "tree", "difficulty": "easy", "companies": ["Google", "Microsoft"], "description": "给定一个二叉树的根节点 root,返回它的中序遍历结果。", "solution_python": "def inorderTraversal(root):\n result = []\n def dfs(node):\n if node:\n dfs(node.left)\n result.append(node.val)\n dfs(node.right)\n dfs(root)\n return result", "solution_java": "public List inorderTraversal(TreeNode root) {\n List res = new ArrayList<>();\n dfs(root, res);\n return res;\n}\nprivate void dfs(TreeNode node, List res) {\n if (node == null) return;\n dfs(node.left, res); res.add(node.val); dfs(node.right, res);\n}", "solution_cpp": "vector inorderTraversal(TreeNode* root) {\n vector res;\n dfs(root, res);\n return res;\n}\nvoid dfs(TreeNode* node, vector& res) {\n if (!node) return;\n dfs(node->left, res); res.push_back(node->val); dfs(node->right, res);\n}", "test_cases": ["root=[1,null,2,3] -> [1,3,2]", "root=[] -> []"], "key_points": ["左-根-右顺序", "递归最简洁"], "tags": ["tree", "easy", "Google", "Microsoft"]} {"problem_id": "algo_01490", "original_id": "binary-search", "title": "二分查找", "category": "binarysearch", "difficulty": "easy", "companies": ["Google", "Amazon"], "description": "给定一个 n 个元素有序的(升序)整型数组 nums 和一个目标值 target,写一个函数搜索 nums 中的 target,如果目标值存在返回下标,否则返回 -1。", "solution_python": "def search(nums, target):\n left, right = 0, len(nums) - 1\n while left <= right:\n mid = (left + right) // 2\n if nums[mid] == target: return mid\n elif nums[mid] < target: left = mid + 1\n else: right = mid - 1\n return -1", "solution_java": "public int search(int[] nums, int target) {\n int left = 0, right = nums.length - 1;\n while (left <= right) {\n int mid = left + (right - left) / 2;\n if (nums[mid] == target) return mid;\n else if (nums[mid] < target) left = mid + 1;\n else right = mid - 1;\n }\n return -1;\n}", "solution_cpp": "int search(vector& nums, int target) {\n int left = 0, right = nums.size() - 1;\n while (left <= right) {\n int mid = left + (right - left) / 2;\n if (nums[mid] == target) return mid;\n else if (nums[mid] < target) left = mid + 1;\n else right = mid - 1;\n }\n return -1;\n}", "test_cases": ["nums=[-1,0,3,5,9,12], target=9 -> 4", "nums=[-1,0,3,5,9,12], target=2 -> -1"], "key_points": ["标准模板", "注意防溢出写法"], "tags": ["binarysearch", "easy", "Google", "Amazon"]} {"problem_id": "algo_01491", "original_id": "climbing-stairs", "title": "爬楼梯", "category": "dp", "difficulty": "easy", "companies": ["Amazon", "Google"], "description": "假设你正在爬楼梯。需要 n 阶你才能到达楼顶。每次你可以爬 1 或 2 个台阶。你有多少种不同的方法可以爬到楼顶?", "solution_python": "def climbStairs(n):\n if n <= 2: return n\n a, b = 1, 2\n for _ in range(3, n+1):\n a, b = b, a + b\n return b", "solution_java": "public int climbStairs(int n) {\n if (n <= 2) return n;\n int a = 1, b = 2;\n for (int i = 3; i <= n; i++) { int temp = a + b; a = b; b = temp; }\n return b;\n}", "solution_cpp": "int climbStairs(int n) {\n if (n <= 2) return n;\n int a = 1, b = 2;\n for (int i = 3; i <= n; i++) { int temp = a + b; a = b; b = temp; }\n return b;\n}", "test_cases": ["n=2 -> 2", "n=3 -> 3", "n=5 -> 8"], "key_points": ["斐波那契数列", "滚动数组优化空间"], "tags": ["dp", "easy", "Amazon", "Google"]} {"problem_id": "algo_01492", "original_id": "coin-change", "title": "零钱兑换", "category": "dp", "difficulty": "medium", "companies": ["Google", "Amazon"], "description": "给你一个整数数组 coins 表示不同面额的硬币,以及一个整数 amount 表示总金额。计算并返回可以凑成总金额所需的最少的硬币个数。如果没有任何一种硬币组合能组成总金额,返回 -1。", "solution_python": "def coinChange(coins, amount):\n dp = [float('inf')] * (amount + 1)\n dp[0] = 0\n for coin in coins:\n for x in range(coin, amount + 1):\n dp[x] = min(dp[x], dp[x - coin] + 1)\n return dp[amount] if dp[amount] != float('inf') else -1", "solution_java": "public int coinChange(int[] coins, int amount) {\n int[] dp = new int[amount + 1];\n Arrays.fill(dp, amount + 1);\n dp[0] = 0;\n for (int coin : coins) {\n for (int x = coin; x <= amount; x++) {\n dp[x] = Math.min(dp[x], dp[x - coin] + 1);\n }\n }\n return dp[amount] > amount ? -1 : dp[amount];\n}", "solution_cpp": "int coinChange(vector& coins, int amount) {\n vector dp(amount + 1, amount + 1);\n dp[0] = 0;\n for (int coin : coins) {\n for (int x = coin; x <= amount; x++) {\n dp[x] = min(dp[x], dp[x - coin] + 1);\n }\n }\n return dp[amount] > amount ? -1 : dp[amount];\n}", "test_cases": ["coins=[1,2,5], amount=11 -> 3", "coins=[2], amount=3 -> -1"], "key_points": ["完全背包问题", "dp[x] = min(dp[x-coin]+1)"], "tags": ["dp", "medium", "Google", "Amazon"]} {"problem_id": "algo_01493", "original_id": "subsets", "title": "子集", "category": "backtracking", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "给你一个整数数组 nums ,数组中的元素 互不相同 。返回该数组所有可能的子集(幂集)。", "solution_python": "def subsets(nums):\n result = []\n def backtrack(start, path):\n result.append(path[:])\n for i in range(start, len(nums)):\n path.append(nums[i])\n backtrack(i + 1, path)\n path.pop()\n backtrack(0, [])\n return result", "solution_java": "public List> subsets(int[] nums) {\n List> result = new ArrayList<>();\n backtrack(nums, 0, new ArrayList<>(), result);\n return result;\n}\nprivate void backtrack(int[] nums, int start, List path, List> result) {\n result.add(new ArrayList<>(path));\n for (int i = start; i < nums.length; i++) {\n path.add(nums[i]);\n backtrack(nums, i + 1, path, result);\n path.remove(path.size() - 1);\n }\n}", "solution_cpp": "vector> subsets(vector& nums) {\n vector> result;\n vector path;\n backtrack(nums, 0, path, result);\n return result;\n}\nvoid backtrack(vector& nums, int start, vector& path, vector>& result) {\n result.push_back(path);\n for (int i = start; i < nums.size(); i++) {\n path.push_back(nums[i]);\n backtrack(nums, i + 1, path, result);\n path.pop_back();\n }\n}", "test_cases": ["nums=[1,2,3] -> [[],[1],[2],[1,2],[3],[1,3],[2,3],[1,2,3]]"], "key_points": ["选或不选", "DFS遍历子集树"], "tags": ["backtracking", "medium", "Google", "Microsoft"]} {"problem_id": "algo_01494", "original_id": "permutations", "title": "全排列", "category": "backtracking", "difficulty": "medium", "companies": ["Google", "Facebook"], "description": "给定一个不含重复数字的数组 nums,返回其所有可能的全排列。", "solution_python": "def permute(nums):\n result = []\n def backtrack(path, used):\n if len(path) == len(nums):\n result.append(path[:])\n return\n for i in range(len(nums)):\n if used[i]: continue\n used[i] = True\n path.append(nums[i])\n backtrack(path, used)\n path.pop()\n used[i] = False\n backtrack([], [False]*len(nums))\n return result", "solution_java": "public List> permute(int[] nums) {\n List> result = new ArrayList<>();\n boolean[] used = new boolean[nums.length];\n backtrack(nums, used, new ArrayList<>(), result);\n return result;\n}\nprivate void backtrack(int[] nums, boolean[] used, List path, List> result) {\n if (path.size() == nums.length) { result.add(new ArrayList<>(path)); return; }\n for (int i = 0; i < nums.length; i++) {\n if (used[i]) continue;\n used[i] = true;\n path.add(nums[i]);\n backtrack(nums, used, path, result);\n path.remove(path.size() - 1);\n used[i] = false;\n }\n}", "solution_cpp": "vector> permute(vector& nums) {\n vector> result;\n vector used(nums.size(), false);\n vector path;\n backtrack(nums, used, path, result);\n return result;\n}\nvoid backtrack(vector& nums, vector& used, vector& path, vector>& result) {\n if (path.size() == nums.size()) { result.push_back(path); return; }\n for (int i = 0; i < nums.size(); i++) {\n if (used[i]) continue;\n used[i] = true;\n path.push_back(nums[i]);\n backtrack(nums, used, path, result);\n path.pop_back();\n used[i] = false;\n }\n}", "test_cases": ["nums=[1,2,3] -> [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]"], "key_points": ["标记已使用元素", "回溯经典模板"], "tags": ["backtracking", "medium", "Google", "Facebook"]} {"problem_id": "algo_01495", "original_id": "top-k-frequent", "title": "前K个高频元素", "category": "heap", "difficulty": "medium", "companies": ["Amazon", "Facebook"], "description": "给你一个整数数组 nums 和一个整数 k,请你返回其中出现频率前 k 高的元素。", "solution_python": "import heapq\nfrom collections import Counter\ndef topKFrequent(nums, k):\n count = Counter(nums)\n heap = []\n for num, freq in count.items():\n heapq.heappush(heap, (freq, num))\n if len(heap) > k: heapq.heappop(heap)\n return [num for freq, num in heap]", "solution_java": "public int[] topKFrequent(int[] nums, int k) {\n Map count = new HashMap<>();\n for (int n : nums) count.put(n, count.getOrDefault(n, 0) + 1);\n PriorityQueue> heap = \n new PriorityQueue<>((a, b) -> a.getValue() - b.getValue());\n for (Map.Entry e : count.entrySet()) {\n heap.offer(e);\n if (heap.size() > k) heap.poll();\n }\n int[] res = new int[k];\n for (int i = k - 1; i >= 0; i--) res[i] = heap.poll().getKey();\n return res;\n}", "solution_cpp": "vector topKFrequent(vector& nums, int k) {\n unordered_map count;\n for (int n : nums) count[n]++;\n priority_queue, vector>, greater>> heap;\n for (auto& [num, freq] : count) {\n heap.push({freq, num});\n if (heap.size() > k) heap.pop();\n }\n vector res;\n while (!heap.empty()) { res.push_back(heap.top().second); heap.pop(); }\n reverse(res.begin(), res.end());\n return res;\n}", "test_cases": ["nums=[1,1,1,2,2,3], k=2 -> [1,2]", "nums=[1], k=1 -> [1]"], "key_points": ["小顶堆保持大小k", "时间复杂度O(nlogk)"], "tags": ["heap", "medium", "Amazon", "Facebook"]} {"problem_id": "algo_01496", "original_id": "3sum", "title": "三数之和", "category": "two-pointers", "difficulty": "medium", "companies": ["Google", "Amazon"], "description": "给你一个整数数组 nums,判断是否存在三元组满足和为0,返回所有不重复的三元组。", "solution_python": "def threeSum(nums):\n nums.sort()\n result = []\n for i in range(len(nums) - 2):\n if i > 0 and nums[i] == nums[i-1]: continue\n left, right = i + 1, len(nums) - 1\n while left < right:\n total = nums[i] + nums[left] + nums[right]\n if total < 0: left += 1\n elif total > 0: right -= 1\n else:\n result.append([nums[i], nums[left], nums[right]])\n while left < right and nums[left] == nums[left+1]: left += 1\n while left < right and nums[right] == nums[right-1]: right -= 1\n left += 1; right -= 1\n return result", "solution_java": "public List> threeSum(int[] nums) {\n Arrays.sort(nums);\n List> result = new ArrayList<>();\n for (int i = 0; i < nums.length - 2; i++) {\n if (i > 0 && nums[i] == nums[i-1]) continue;\n int left = i + 1, right = nums.length - 1;\n while (left < right) {\n int total = nums[i] + nums[left] + nums[right];\n if (total < 0) left++;\n else if (total > 0) right--;\n else {\n result.add(Arrays.asList(nums[i], nums[left], nums[right]));\n while (left < right && nums[left] == nums[left+1]) left++;\n while (left < right && nums[right] == nums[right-1]) right--;\n left++; right--;\n }\n }\n }\n return result;\n}", "solution_cpp": "vector> threeSum(vector& nums) {\n sort(nums.begin(), nums.end());\n vector> result;\n for (int i = 0; i < nums.size() - 2; i++) {\n if (i > 0 && nums[i] == nums[i-1]) continue;\n int left = i + 1, right = nums.size() - 1;\n while (left < right) {\n int total = nums[i] + nums[left] + nums[right];\n if (total < 0) left++;\n else if (total > 0) right--;\n else {\n result.push_back({nums[i], nums[left], nums[right]});\n while (left < right && nums[left] == nums[left+1]) left++;\n while (left < right && nums[right] == nums[right-1]) right--;\n left++; right--;\n }\n }\n }\n return result;\n}", "test_cases": ["nums=[-1,0,1,2,-1,-4] -> [[-1,-1,2],[-1,0,1]]"], "key_points": ["排序+双指针", "去重是关键"], "tags": ["two-pointers", "medium", "Google", "Amazon"]} {"problem_id": "algo_01497", "original_id": "container-water", "title": "盛最多水的容器", "category": "two-pointers", "difficulty": "medium", "companies": ["Google", "Uber"], "description": "给定一个长度为 n 的整数数组 height,找出其中的两条线,使得它们与 x 轴共同构成的容器可以容纳最多的水。", "solution_python": "def maxArea(height):\n left, right = 0, len(height) - 1\n max_area = 0\n while left < right:\n h = min(height[left], height[right])\n max_area = max(max_area, h * (right - left))\n if height[left] < height[right]: left += 1\n else: right -= 1\n return max_area", "solution_java": "public int maxArea(int[] height) {\n int left = 0, right = height.length - 1, maxArea = 0;\n while (left < right) {\n int h = Math.min(height[left], height[right]);\n maxArea = Math.max(maxArea, h * (right - left));\n if (height[left] < height[right]) left++;\n else right--;\n }\n return maxArea;\n}", "solution_cpp": "int maxArea(vector& height) {\n int left = 0, right = height.size() - 1, maxArea = 0;\n while (left < right) {\n int h = min(height[left], height[right]);\n maxArea = max(maxArea, h * (right - left));\n if (height[left] < height[right]) left++;\n else right--;\n }\n return maxArea;\n}", "test_cases": ["height=[1,8,6,2,5,4,8,3,7] -> 49"], "key_points": ["移动短边指针", "面积=min(h1,h2)*width"], "tags": ["two-pointers", "medium", "Google", "Uber"]} {"problem_id": "algo_01498", "original_id": "min-stack", "title": "最小栈", "category": "stack", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "设计一个支持 push,pop,top 操作,并能在常数时间内检索到最小元素的栈。", "solution_python": "class MinStack:\n def __init__(self):\n self.stack = []\n self.min_stack = []\n def push(self, val):\n self.stack.append(val)\n self.min_stack.append(min(val, self.min_stack[-1] if self.min_stack else val))\n def pop(self):\n self.stack.pop(); self.min_stack.pop()\n def top(self): return self.stack[-1]\n def getMin(self): return self.min_stack[-1]", "solution_java": "class MinStack {\n Stack stack = new Stack<>();\n Stack minStack = new Stack<>();\n public void push(int val) { stack.push(val); minStack.push(Math.min(val, minStack.isEmpty() ? val : minStack.peek())); }\n public void pop() { stack.pop(); minStack.pop(); }\n public int top() { return stack.peek(); }\n public int getMin() { return minStack.peek(); }\n}", "solution_cpp": "class MinStack {\n stack st, minSt;\npublic:\n void push(int val) { st.push(val); minSt.push(min(val, minSt.empty() ? val : minSt.top())); }\n void pop() { st.pop(); minSt.pop(); }\n int top() { return st.top(); }\n int getMin() { return minSt.top(); }\n};", "test_cases": ["push(-2), push(0), push(-3) -> getMin() returns -3"], "key_points": ["辅助栈记录最小值", "O(1)时间获取最小值"], "tags": ["stack", "medium", "Google", "Microsoft"]} {"problem_id": "algo_01499", "original_id": "lru-cache", "title": "LRU缓存", "category": "design", "difficulty": "hard", "companies": ["Google", "Amazon"], "description": "设计和实现一个 LRU(最近最少使用)缓存机制。", "solution_python": "class LRUCache:\n def __init__(self, capacity):\n self.capacity = capacity\n self.cache = {}\n self.order = []\n def get(self, key):\n if key not in self.cache: return -1\n self.order.remove(key); self.order.append(key)\n return self.cache[key]\n def put(self, key, value):\n if key in self.cache:\n self.order.remove(key)\n elif len(self.cache) >= self.capacity:\n del self.cache[self.order.pop(0)]\n self.cache[key] = value; self.order.append(key)", "solution_java": "class LRUCache {\n int capacity;\n LinkedHashMap cache = new LinkedHashMap<>();\n public LRUCache(int cap) { capacity = cap; }\n public int get(int key) { return cache.containsKey(key) ? cache.remove(key) : -1; }\n public void put(int key, int val) {\n if (cache.containsKey(key)) cache.remove(key);\n else if (cache.size() >= capacity) cache.remove(cache.keySet().iterator().next());\n cache.put(key, val);\n }\n}", "solution_cpp": "class LRUCache {\n int cap;\n list> dll;\n unordered_map>::iterator> cache;\npublic:\n LRUCache(int capacity) : cap(capacity) {}\n int get(int key) {\n auto it = cache.find(key);\n if (it == cache.end()) return -1;\n dll.splice(dll.end(), dll, it->second);\n return it->second->second;\n }\n void put(int key, int value) {\n auto it = cache.find(key);\n if (it != cache.end()) dll.erase(it->second);\n else if (cache.size() >= cap) { cache.erase(dll.front().first); dll.pop_front(); }\n dll.push_back({key, value});\n cache[key] = --dll.end();\n }\n};", "test_cases": ["put(1,1), put(2,2), get(1) -> 1"], "key_points": ["HashMap + 双向链表", "O(1)时间操作"], "tags": ["design", "hard", "Google", "Amazon"]} {"problem_id": "algo_01500", "original_id": "num-islands", "title": "岛屿数量", "category": "graph", "difficulty": "medium", "companies": ["Google", "Facebook"], "description": "给你一个由 '1'(陆地)和 '0'(水)组成的二维网格,请你计算网格中岛屿的数量。岛屿总是被水包围,且只能由水平或垂直方向相邻的陆地连接形成。", "solution_python": "def numIslands(grid):\n if not grid: return 0\n rows, cols = len(grid), len(grid[0])\n count = 0\n def dfs(r, c):\n if r < 0 or r >= rows or c < 0 or c >= cols or grid[r][c] != '1': return\n grid[r][c] = '0'\n dfs(r+1, c); dfs(r-1, c); dfs(r, c+1); dfs(r, c-1)\n for r in range(rows):\n for c in range(cols):\n if grid[r][c] == '1': count += 1; dfs(r, c)\n return count", "solution_java": "public int numIslands(char[][] grid) {\n if (grid.length == 0) return 0;\n int count = 0;\n for (int i = 0; i < grid.length; i++)\n for (int j = 0; j < grid[0].length; j++)\n if (grid[i][j] == '1') { count++; dfs(grid, i, j); }\n return count;\n}\nprivate void dfs(char[][] grid, int r, int c) {\n if (r < 0 || r >= grid.length || c < 0 || c >= grid[0].length || grid[r][c] != '1') return;\n grid[r][c] = '0';\n dfs(grid, r+1, c); dfs(grid, r-1, c); dfs(grid, r, c+1); dfs(grid, r, c-1);\n}", "solution_cpp": "int numIslands(vector>& grid) {\n if (grid.empty()) return 0;\n int count = 0;\n for (int i = 0; i < grid.size(); i++)\n for (int j = 0; j < grid[0].size(); j++)\n if (grid[i][j] == '1') { count++; dfs(grid, i, j); }\n return count;\n}\nvoid dfs(vector>& grid, int r, int c) {\n if (r < 0 || r >= grid.size() || c < 0 || c >= grid[0].size() || grid[r][c] != '1') return;\n grid[r][c] = '0';\n dfs(grid, r+1, c); dfs(grid, r-1, c); dfs(grid, r, c+1); dfs(grid, r, c-1);\n}", "test_cases": ["grid=[[1,1,1,1,0],[1,1,0,1,0],[1,1,0,0,0],[0,0,0,0,0]] -> 1"], "key_points": ["DFS/BFS遍历", "访问后标记为0避免重复"], "tags": ["graph", "medium", "Google", "Facebook"]} {"problem_id": "algo_01501", "original_id": "two-sum", "title": "两数之和", "category": "array", "difficulty": "easy", "companies": ["Amazon", "Google"], "description": "给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那两个整数,并返回他们的数组下标。", "solution_python": "def twoSum(nums, target):\n hashmap = {}\n for i, num in enumerate(nums):\n complement = target - num\n if complement in hashmap:\n return [hashmap[complement], i]\n hashmap[num] = i\n return []", "solution_java": "public int[] twoSum(int[] nums, int target) {\n Map map = new HashMap<>();\n for (int i = 0; i < nums.length; i++) {\n int complement = target - nums[i];\n if (map.containsKey(complement)) return new int[]{map.get(complement), i};\n map.put(nums[i], i);\n }\n return new int[]{};\n}", "solution_cpp": "vector twoSum(vector& nums, int target) {\n unordered_map m;\n for (int i = 0; i < nums.size(); i++) {\n if (m.count(target - nums[i])) return {m[target - nums[i]], i};\n m[nums[i]] = i;\n }\n return {};\n}", "test_cases": ["nums=[2,7,11,15], target=9 -> [0,1]", "nums=[3,2,4], target=6 -> [1,2]"], "key_points": ["哈希表一次遍历", "空间换时间"], "tags": ["array", "easy", "Amazon", "Google"]} {"problem_id": "algo_01502", "original_id": "merge-sorted", "title": "合并两个有序数组", "category": "array", "difficulty": "easy", "companies": ["Microsoft", "Uber"], "description": "给你两个按非递减顺序排列的整数数组 nums1 和 nums2,另有两个整数 m 和 n,分别表示 nums1 和 nums2 中的元素数目。请你合并 nums2 到 nums1 中。", "solution_python": "def merge(nums1, m, nums2, n):\n p1, p2, p = m-1, n-1, m+n-1\n while p1 >= 0 and p2 >= 0:\n if nums1[p1] > nums2[p2]: nums1[p] = nums1[p1]; p1 -= 1\n else: nums1[p] = nums2[p2]; p2 -= 1\n p -= 1\n while p2 >= 0: nums1[p] = nums2[p2]; p2 -= 1; p -= 1", "solution_java": "public void merge(int[] nums1, int m, int[] nums2, int n) {\n int p1 = m-1, p2 = n-1, p = m+n-1;\n while (p1 >= 0 && p2 >= 0) {\n nums1[p--] = nums1[p1] > nums2[p2] ? nums1[p1--] : nums2[p2--];\n }\n while (p2 >= 0) nums1[p--] = nums2[p2--];\n}", "solution_cpp": "void merge(vector& nums1, int m, vector& nums2, int n) {\n int p1 = m-1, p2 = n-1, p = m+n-1;\n while (p1 >= 0 && p2 >= 0) nums1[p--] = nums1[p1] > nums2[p2] ? nums1[p1--] : nums2[p2--];\n while (p2 >= 0) nums1[p--] = nums2[p2--];\n}", "test_cases": ["nums1=[1,2,3], m=3, nums2=[2,5,6], n=3 -> [1,2,2,3,5,6]", "nums1=[], m=0, nums2=[1], n=1 -> [1]"], "key_points": ["从后往前合并", "三指针技巧"], "tags": ["array", "easy", "Microsoft", "Uber"]} {"problem_id": "algo_01503", "original_id": "max-subarray", "title": "最大子数组和", "category": "array", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "给你一个整数数组 nums ,请你找出一个具有最大和的连续子数组,返回其最大和。", "solution_python": "def maxSubArray(nums):\n max_sum = current = nums[0]\n for num in nums[1:]:\n current = max(num, current + num)\n max_sum = max(max_sum, current)\n return max_sum", "solution_java": "public int maxSubArray(int[] nums) {\n int maxSum = nums[0], curr = nums[0];\n for (int i = 1; i < nums.length; i++) {\n curr = Math.max(nums[i], curr + nums[i]);\n maxSum = Math.max(maxSum, curr);\n }\n return maxSum;\n}", "solution_cpp": "int maxSubArray(vector& nums) {\n int maxSum = nums[0], curr = nums[0];\n for (int i = 1; i < nums.size(); i++) {\n curr = max(nums[i], curr + nums[i]);\n maxSum = max(maxSum, curr);\n }\n return maxSum;\n}", "test_cases": ["nums=[-2,1,-3,4,-1,2,1,-5,4] -> 6", "nums=[1] -> 1"], "key_points": ["Kadane算法", "动态规划基础题"], "tags": ["array", "medium", "Google", "Microsoft"]} {"problem_id": "algo_01504", "original_id": "valid-parentheses", "title": "有效的括号", "category": "string", "difficulty": "easy", "companies": ["Google", "Uber"], "description": "给定一个只包括 '(',')','{','}','[',']' 的字符串 s,判断字符串是否有效。", "solution_python": "def isValid(s):\n stack = []\n mapping = {')': '(', ']': '[', '}': '{'}\n for c in s:\n if c in mapping:\n if not stack or stack[-1] != mapping[c]: return False\n stack.pop()\n else: stack.append(c)\n return not stack", "solution_java": "public boolean isValid(String s) {\n Stack stack = new Stack<>();\n Map map = Map.of(')', '(', ']', '[', '}', '{');\n for (char c : s.toCharArray()) {\n if (map.containsValue(c)) stack.push(c);\n else if (!stack.isEmpty() && stack.pop() != map.get(c)) return false;\n }\n return stack.isEmpty();\n}", "solution_cpp": "bool isValid(string s) {\n stack st;\n unordered_map m = {{')','('},{']','['},{'}','{'}};\n for (char c : s) {\n if (m.find(c) == m.end()) st.push(c);\n else if (st.empty() || st.top() != m[c]) return false;\n else st.pop();\n }\n return st.empty();\n}", "test_cases": ["s=\"()\" -> true", "s=\"()[]{}\" -> true", "s=\"(]\" -> false"], "key_points": ["栈匹配法", "注意空栈边界"], "tags": ["string", "easy", "Google", "Uber"]} {"problem_id": "algo_01505", "original_id": "longest-palindrome", "title": "最长回文子串", "category": "string", "difficulty": "medium", "companies": ["Google", "Amazon"], "description": "给你一个字符串 s,找到 s 中最长的回文子串。", "solution_python": "def longestPalindrome(s):\n def expand(l, r):\n while l >= 0 and r < len(s) and s[l] == s[r]: l -= 1; r += 1\n return l + 1, r - 1\n start = end = 0\n for i in range(len(s)):\n l1, r1 = expand(i, i)\n l2, r2 = expand(i, i + 1)\n if r1 - l1 > end - start: start, end = l1, r1\n if r2 - l2 > end - start: start, end = l2, r2\n return s[start:end+1]", "solution_java": "public String longestPalindrome(String s) {\n int start = 0, end = 0;\n for (int i = 0; i < s.length(); i++) {\n int len1 = expand(s, i, i), len2 = expand(s, i, i+1);\n int len = Math.max(len1, len2);\n if (len > end - start) { start = i - (len-1)/2; end = i + len/2; }\n }\n return s.substring(start, end + 1);\n}\nprivate int expand(String s, int l, int r) {\n while (l >= 0 && r < s.length() && s.charAt(l) == s.charAt(r)) { l--; r++; }\n return r - l - 1;\n}", "solution_cpp": "string longestPalindrome(string s) {\n int start = 0, end = 0;\n for (int i = 0; i < s.size(); i++) {\n int len1 = expand(s, i, i), len2 = expand(s, i, i+1);\n if (max(len1, len2) > end - start) { start = i - (max(len1,len2)-1)/2; end = i + max(len1,len2)/2; }\n }\n return s.substr(start, end - start + 1);\n}", "test_cases": ["s=\"babad\" -> bab或aba", "s=\"cbbd\" -> bb"], "key_points": ["中心扩展法", "处理奇偶长度"], "tags": ["string", "medium", "Google", "Amazon"]} {"problem_id": "algo_01506", "original_id": "reverse-list", "title": "反转链表", "category": "linkedlist", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "给你单链表的头节点 head,请你反转链表,并返回反转后的链表。", "solution_python": "def reverseList(head):\n prev = None\n curr = head\n while curr:\n nxt = curr.next\n curr.next = prev\n prev = curr\n curr = nxt\n return prev", "solution_java": "public ListNode reverseList(ListNode head) {\n ListNode prev = null, curr = head;\n while (curr != null) {\n ListNode next = curr.next;\n curr.next = prev;\n prev = curr;\n curr = next;\n }\n return prev;\n}", "solution_cpp": "ListNode* reverseList(ListNode* head) {\n ListNode* prev = nullptr, *curr = head;\n while (curr) {\n ListNode* next = curr->next;\n curr->next = prev;\n prev = curr;\n curr = next;\n }\n return prev;\n}", "test_cases": ["head=[1,2,3,4,5] -> [5,4,3,2,1]", "head=[1,2] -> [2,1]"], "key_points": ["迭代法 O(1)空间", "递归法 O(n)空间"], "tags": ["linkedlist", "medium", "Google", "Microsoft"]} {"problem_id": "algo_01507", "original_id": "middle-node", "title": "链表的中间结点", "category": "linkedlist", "difficulty": "easy", "companies": ["Amazon", "Facebook"], "description": "给你单链表的头节点 head,请你找出并返回链表的中间结点。如果有两个中间结点,则返回第二个中间结点。", "solution_python": "def middleNode(head):\n slow = fast = head\n while fast and fast.next:\n slow = slow.next\n fast = fast.next.next\n return slow", "solution_java": "public ListNode middleNode(ListNode head) {\n ListNode slow = head, fast = head;\n while (fast != null && fast.next != null) {\n slow = slow.next;\n fast = fast.next.next;\n }\n return slow;\n}", "solution_cpp": "ListNode* middleNode(ListNode* head) {\n ListNode* slow = head, *fast = head;\n while (fast && fast->next) { slow = slow->next; fast = fast->next->next; }\n return slow;\n}", "test_cases": ["head=[1,2,3,4,5] -> 3", "head=[1,2,3,4,5,6] -> 4"], "key_points": ["快慢指针", "O(n)时间O(1)空间"], "tags": ["linkedlist", "easy", "Amazon", "Facebook"]} {"problem_id": "algo_01508", "original_id": "max-depth", "title": "二叉树的最大深度", "category": "tree", "difficulty": "easy", "companies": ["Microsoft", "Apple"], "description": "给定一个二叉树 root,返回其最大深度。", "solution_python": "def maxDepth(root):\n if not root: return 0\n return max(maxDepth(root.left), maxDepth(root.right)) + 1", "solution_java": "public int maxDepth(TreeNode root) {\n if (root == null) return 0;\n return Math.max(maxDepth(root.left), maxDepth(root.right)) + 1;\n}", "solution_cpp": "int maxDepth(TreeNode* root) {\n if (!root) return 0;\n return max(maxDepth(root->left), maxDepth(root->right)) + 1;\n}", "test_cases": ["root=[3,9,20,null,null,15,7] -> 3", "root=[1,null,2] -> 2"], "key_points": ["DFS递归", "层序遍历也可"], "tags": ["tree", "easy", "Microsoft", "Apple"]} {"problem_id": "algo_01509", "original_id": "inorder-traversal", "title": "二叉树的中序遍历", "category": "tree", "difficulty": "easy", "companies": ["Google", "Microsoft"], "description": "给定一个二叉树的根节点 root,返回它的中序遍历结果。", "solution_python": "def inorderTraversal(root):\n result = []\n def dfs(node):\n if node:\n dfs(node.left)\n result.append(node.val)\n dfs(node.right)\n dfs(root)\n return result", "solution_java": "public List inorderTraversal(TreeNode root) {\n List res = new ArrayList<>();\n dfs(root, res);\n return res;\n}\nprivate void dfs(TreeNode node, List res) {\n if (node == null) return;\n dfs(node.left, res); res.add(node.val); dfs(node.right, res);\n}", "solution_cpp": "vector inorderTraversal(TreeNode* root) {\n vector res;\n dfs(root, res);\n return res;\n}\nvoid dfs(TreeNode* node, vector& res) {\n if (!node) return;\n dfs(node->left, res); res.push_back(node->val); dfs(node->right, res);\n}", "test_cases": ["root=[1,null,2,3] -> [1,3,2]", "root=[] -> []"], "key_points": ["左-根-右顺序", "递归最简洁"], "tags": ["tree", "easy", "Google", "Microsoft"]} {"problem_id": "algo_01510", "original_id": "binary-search", "title": "二分查找", "category": "binarysearch", "difficulty": "easy", "companies": ["Google", "Amazon"], "description": "给定一个 n 个元素有序的(升序)整型数组 nums 和一个目标值 target,写一个函数搜索 nums 中的 target,如果目标值存在返回下标,否则返回 -1。", "solution_python": "def search(nums, target):\n left, right = 0, len(nums) - 1\n while left <= right:\n mid = (left + right) // 2\n if nums[mid] == target: return mid\n elif nums[mid] < target: left = mid + 1\n else: right = mid - 1\n return -1", "solution_java": "public int search(int[] nums, int target) {\n int left = 0, right = nums.length - 1;\n while (left <= right) {\n int mid = left + (right - left) / 2;\n if (nums[mid] == target) return mid;\n else if (nums[mid] < target) left = mid + 1;\n else right = mid - 1;\n }\n return -1;\n}", "solution_cpp": "int search(vector& nums, int target) {\n int left = 0, right = nums.size() - 1;\n while (left <= right) {\n int mid = left + (right - left) / 2;\n if (nums[mid] == target) return mid;\n else if (nums[mid] < target) left = mid + 1;\n else right = mid - 1;\n }\n return -1;\n}", "test_cases": ["nums=[-1,0,3,5,9,12], target=9 -> 4", "nums=[-1,0,3,5,9,12], target=2 -> -1"], "key_points": ["标准模板", "注意防溢出写法"], "tags": ["binarysearch", "easy", "Google", "Amazon"]} {"problem_id": "algo_01511", "original_id": "climbing-stairs", "title": "爬楼梯", "category": "dp", "difficulty": "easy", "companies": ["Amazon", "Google"], "description": "假设你正在爬楼梯。需要 n 阶你才能到达楼顶。每次你可以爬 1 或 2 个台阶。你有多少种不同的方法可以爬到楼顶?", "solution_python": "def climbStairs(n):\n if n <= 2: return n\n a, b = 1, 2\n for _ in range(3, n+1):\n a, b = b, a + b\n return b", "solution_java": "public int climbStairs(int n) {\n if (n <= 2) return n;\n int a = 1, b = 2;\n for (int i = 3; i <= n; i++) { int temp = a + b; a = b; b = temp; }\n return b;\n}", "solution_cpp": "int climbStairs(int n) {\n if (n <= 2) return n;\n int a = 1, b = 2;\n for (int i = 3; i <= n; i++) { int temp = a + b; a = b; b = temp; }\n return b;\n}", "test_cases": ["n=2 -> 2", "n=3 -> 3", "n=5 -> 8"], "key_points": ["斐波那契数列", "滚动数组优化空间"], "tags": ["dp", "easy", "Amazon", "Google"]} {"problem_id": "algo_01512", "original_id": "coin-change", "title": "零钱兑换", "category": "dp", "difficulty": "medium", "companies": ["Google", "Amazon"], "description": "给你一个整数数组 coins 表示不同面额的硬币,以及一个整数 amount 表示总金额。计算并返回可以凑成总金额所需的最少的硬币个数。如果没有任何一种硬币组合能组成总金额,返回 -1。", "solution_python": "def coinChange(coins, amount):\n dp = [float('inf')] * (amount + 1)\n dp[0] = 0\n for coin in coins:\n for x in range(coin, amount + 1):\n dp[x] = min(dp[x], dp[x - coin] + 1)\n return dp[amount] if dp[amount] != float('inf') else -1", "solution_java": "public int coinChange(int[] coins, int amount) {\n int[] dp = new int[amount + 1];\n Arrays.fill(dp, amount + 1);\n dp[0] = 0;\n for (int coin : coins) {\n for (int x = coin; x <= amount; x++) {\n dp[x] = Math.min(dp[x], dp[x - coin] + 1);\n }\n }\n return dp[amount] > amount ? -1 : dp[amount];\n}", "solution_cpp": "int coinChange(vector& coins, int amount) {\n vector dp(amount + 1, amount + 1);\n dp[0] = 0;\n for (int coin : coins) {\n for (int x = coin; x <= amount; x++) {\n dp[x] = min(dp[x], dp[x - coin] + 1);\n }\n }\n return dp[amount] > amount ? -1 : dp[amount];\n}", "test_cases": ["coins=[1,2,5], amount=11 -> 3", "coins=[2], amount=3 -> -1"], "key_points": ["完全背包问题", "dp[x] = min(dp[x-coin]+1)"], "tags": ["dp", "medium", "Google", "Amazon"]} {"problem_id": "algo_01513", "original_id": "subsets", "title": "子集", "category": "backtracking", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "给你一个整数数组 nums ,数组中的元素 互不相同 。返回该数组所有可能的子集(幂集)。", "solution_python": "def subsets(nums):\n result = []\n def backtrack(start, path):\n result.append(path[:])\n for i in range(start, len(nums)):\n path.append(nums[i])\n backtrack(i + 1, path)\n path.pop()\n backtrack(0, [])\n return result", "solution_java": "public List> subsets(int[] nums) {\n List> result = new ArrayList<>();\n backtrack(nums, 0, new ArrayList<>(), result);\n return result;\n}\nprivate void backtrack(int[] nums, int start, List path, List> result) {\n result.add(new ArrayList<>(path));\n for (int i = start; i < nums.length; i++) {\n path.add(nums[i]);\n backtrack(nums, i + 1, path, result);\n path.remove(path.size() - 1);\n }\n}", "solution_cpp": "vector> subsets(vector& nums) {\n vector> result;\n vector path;\n backtrack(nums, 0, path, result);\n return result;\n}\nvoid backtrack(vector& nums, int start, vector& path, vector>& result) {\n result.push_back(path);\n for (int i = start; i < nums.size(); i++) {\n path.push_back(nums[i]);\n backtrack(nums, i + 1, path, result);\n path.pop_back();\n }\n}", "test_cases": ["nums=[1,2,3] -> [[],[1],[2],[1,2],[3],[1,3],[2,3],[1,2,3]]"], "key_points": ["选或不选", "DFS遍历子集树"], "tags": ["backtracking", "medium", "Google", "Microsoft"]} {"problem_id": "algo_01514", "original_id": "permutations", "title": "全排列", "category": "backtracking", "difficulty": "medium", "companies": ["Google", "Facebook"], "description": "给定一个不含重复数字的数组 nums,返回其所有可能的全排列。", "solution_python": "def permute(nums):\n result = []\n def backtrack(path, used):\n if len(path) == len(nums):\n result.append(path[:])\n return\n for i in range(len(nums)):\n if used[i]: continue\n used[i] = True\n path.append(nums[i])\n backtrack(path, used)\n path.pop()\n used[i] = False\n backtrack([], [False]*len(nums))\n return result", "solution_java": "public List> permute(int[] nums) {\n List> result = new ArrayList<>();\n boolean[] used = new boolean[nums.length];\n backtrack(nums, used, new ArrayList<>(), result);\n return result;\n}\nprivate void backtrack(int[] nums, boolean[] used, List path, List> result) {\n if (path.size() == nums.length) { result.add(new ArrayList<>(path)); return; }\n for (int i = 0; i < nums.length; i++) {\n if (used[i]) continue;\n used[i] = true;\n path.add(nums[i]);\n backtrack(nums, used, path, result);\n path.remove(path.size() - 1);\n used[i] = false;\n }\n}", "solution_cpp": "vector> permute(vector& nums) {\n vector> result;\n vector used(nums.size(), false);\n vector path;\n backtrack(nums, used, path, result);\n return result;\n}\nvoid backtrack(vector& nums, vector& used, vector& path, vector>& result) {\n if (path.size() == nums.size()) { result.push_back(path); return; }\n for (int i = 0; i < nums.size(); i++) {\n if (used[i]) continue;\n used[i] = true;\n path.push_back(nums[i]);\n backtrack(nums, used, path, result);\n path.pop_back();\n used[i] = false;\n }\n}", "test_cases": ["nums=[1,2,3] -> [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]"], "key_points": ["标记已使用元素", "回溯经典模板"], "tags": ["backtracking", "medium", "Google", "Facebook"]} {"problem_id": "algo_01515", "original_id": "top-k-frequent", "title": "前K个高频元素", "category": "heap", "difficulty": "medium", "companies": ["Amazon", "Facebook"], "description": "给你一个整数数组 nums 和一个整数 k,请你返回其中出现频率前 k 高的元素。", "solution_python": "import heapq\nfrom collections import Counter\ndef topKFrequent(nums, k):\n count = Counter(nums)\n heap = []\n for num, freq in count.items():\n heapq.heappush(heap, (freq, num))\n if len(heap) > k: heapq.heappop(heap)\n return [num for freq, num in heap]", "solution_java": "public int[] topKFrequent(int[] nums, int k) {\n Map count = new HashMap<>();\n for (int n : nums) count.put(n, count.getOrDefault(n, 0) + 1);\n PriorityQueue> heap = \n new PriorityQueue<>((a, b) -> a.getValue() - b.getValue());\n for (Map.Entry e : count.entrySet()) {\n heap.offer(e);\n if (heap.size() > k) heap.poll();\n }\n int[] res = new int[k];\n for (int i = k - 1; i >= 0; i--) res[i] = heap.poll().getKey();\n return res;\n}", "solution_cpp": "vector topKFrequent(vector& nums, int k) {\n unordered_map count;\n for (int n : nums) count[n]++;\n priority_queue, vector>, greater>> heap;\n for (auto& [num, freq] : count) {\n heap.push({freq, num});\n if (heap.size() > k) heap.pop();\n }\n vector res;\n while (!heap.empty()) { res.push_back(heap.top().second); heap.pop(); }\n reverse(res.begin(), res.end());\n return res;\n}", "test_cases": ["nums=[1,1,1,2,2,3], k=2 -> [1,2]", "nums=[1], k=1 -> [1]"], "key_points": ["小顶堆保持大小k", "时间复杂度O(nlogk)"], "tags": ["heap", "medium", "Amazon", "Facebook"]} {"problem_id": "algo_01516", "original_id": "3sum", "title": "三数之和", "category": "two-pointers", "difficulty": "medium", "companies": ["Google", "Amazon"], "description": "给你一个整数数组 nums,判断是否存在三元组满足和为0,返回所有不重复的三元组。", "solution_python": "def threeSum(nums):\n nums.sort()\n result = []\n for i in range(len(nums) - 2):\n if i > 0 and nums[i] == nums[i-1]: continue\n left, right = i + 1, len(nums) - 1\n while left < right:\n total = nums[i] + nums[left] + nums[right]\n if total < 0: left += 1\n elif total > 0: right -= 1\n else:\n result.append([nums[i], nums[left], nums[right]])\n while left < right and nums[left] == nums[left+1]: left += 1\n while left < right and nums[right] == nums[right-1]: right -= 1\n left += 1; right -= 1\n return result", "solution_java": "public List> threeSum(int[] nums) {\n Arrays.sort(nums);\n List> result = new ArrayList<>();\n for (int i = 0; i < nums.length - 2; i++) {\n if (i > 0 && nums[i] == nums[i-1]) continue;\n int left = i + 1, right = nums.length - 1;\n while (left < right) {\n int total = nums[i] + nums[left] + nums[right];\n if (total < 0) left++;\n else if (total > 0) right--;\n else {\n result.add(Arrays.asList(nums[i], nums[left], nums[right]));\n while (left < right && nums[left] == nums[left+1]) left++;\n while (left < right && nums[right] == nums[right-1]) right--;\n left++; right--;\n }\n }\n }\n return result;\n}", "solution_cpp": "vector> threeSum(vector& nums) {\n sort(nums.begin(), nums.end());\n vector> result;\n for (int i = 0; i < nums.size() - 2; i++) {\n if (i > 0 && nums[i] == nums[i-1]) continue;\n int left = i + 1, right = nums.size() - 1;\n while (left < right) {\n int total = nums[i] + nums[left] + nums[right];\n if (total < 0) left++;\n else if (total > 0) right--;\n else {\n result.push_back({nums[i], nums[left], nums[right]});\n while (left < right && nums[left] == nums[left+1]) left++;\n while (left < right && nums[right] == nums[right-1]) right--;\n left++; right--;\n }\n }\n }\n return result;\n}", "test_cases": ["nums=[-1,0,1,2,-1,-4] -> [[-1,-1,2],[-1,0,1]]"], "key_points": ["排序+双指针", "去重是关键"], "tags": ["two-pointers", "medium", "Google", "Amazon"]} {"problem_id": "algo_01517", "original_id": "container-water", "title": "盛最多水的容器", "category": "two-pointers", "difficulty": "medium", "companies": ["Google", "Uber"], "description": "给定一个长度为 n 的整数数组 height,找出其中的两条线,使得它们与 x 轴共同构成的容器可以容纳最多的水。", "solution_python": "def maxArea(height):\n left, right = 0, len(height) - 1\n max_area = 0\n while left < right:\n h = min(height[left], height[right])\n max_area = max(max_area, h * (right - left))\n if height[left] < height[right]: left += 1\n else: right -= 1\n return max_area", "solution_java": "public int maxArea(int[] height) {\n int left = 0, right = height.length - 1, maxArea = 0;\n while (left < right) {\n int h = Math.min(height[left], height[right]);\n maxArea = Math.max(maxArea, h * (right - left));\n if (height[left] < height[right]) left++;\n else right--;\n }\n return maxArea;\n}", "solution_cpp": "int maxArea(vector& height) {\n int left = 0, right = height.size() - 1, maxArea = 0;\n while (left < right) {\n int h = min(height[left], height[right]);\n maxArea = max(maxArea, h * (right - left));\n if (height[left] < height[right]) left++;\n else right--;\n }\n return maxArea;\n}", "test_cases": ["height=[1,8,6,2,5,4,8,3,7] -> 49"], "key_points": ["移动短边指针", "面积=min(h1,h2)*width"], "tags": ["two-pointers", "medium", "Google", "Uber"]} {"problem_id": "algo_01518", "original_id": "min-stack", "title": "最小栈", "category": "stack", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "设计一个支持 push,pop,top 操作,并能在常数时间内检索到最小元素的栈。", "solution_python": "class MinStack:\n def __init__(self):\n self.stack = []\n self.min_stack = []\n def push(self, val):\n self.stack.append(val)\n self.min_stack.append(min(val, self.min_stack[-1] if self.min_stack else val))\n def pop(self):\n self.stack.pop(); self.min_stack.pop()\n def top(self): return self.stack[-1]\n def getMin(self): return self.min_stack[-1]", "solution_java": "class MinStack {\n Stack stack = new Stack<>();\n Stack minStack = new Stack<>();\n public void push(int val) { stack.push(val); minStack.push(Math.min(val, minStack.isEmpty() ? val : minStack.peek())); }\n public void pop() { stack.pop(); minStack.pop(); }\n public int top() { return stack.peek(); }\n public int getMin() { return minStack.peek(); }\n}", "solution_cpp": "class MinStack {\n stack st, minSt;\npublic:\n void push(int val) { st.push(val); minSt.push(min(val, minSt.empty() ? val : minSt.top())); }\n void pop() { st.pop(); minSt.pop(); }\n int top() { return st.top(); }\n int getMin() { return minSt.top(); }\n};", "test_cases": ["push(-2), push(0), push(-3) -> getMin() returns -3"], "key_points": ["辅助栈记录最小值", "O(1)时间获取最小值"], "tags": ["stack", "medium", "Google", "Microsoft"]} {"problem_id": "algo_01519", "original_id": "lru-cache", "title": "LRU缓存", "category": "design", "difficulty": "hard", "companies": ["Google", "Amazon"], "description": "设计和实现一个 LRU(最近最少使用)缓存机制。", "solution_python": "class LRUCache:\n def __init__(self, capacity):\n self.capacity = capacity\n self.cache = {}\n self.order = []\n def get(self, key):\n if key not in self.cache: return -1\n self.order.remove(key); self.order.append(key)\n return self.cache[key]\n def put(self, key, value):\n if key in self.cache:\n self.order.remove(key)\n elif len(self.cache) >= self.capacity:\n del self.cache[self.order.pop(0)]\n self.cache[key] = value; self.order.append(key)", "solution_java": "class LRUCache {\n int capacity;\n LinkedHashMap cache = new LinkedHashMap<>();\n public LRUCache(int cap) { capacity = cap; }\n public int get(int key) { return cache.containsKey(key) ? cache.remove(key) : -1; }\n public void put(int key, int val) {\n if (cache.containsKey(key)) cache.remove(key);\n else if (cache.size() >= capacity) cache.remove(cache.keySet().iterator().next());\n cache.put(key, val);\n }\n}", "solution_cpp": "class LRUCache {\n int cap;\n list> dll;\n unordered_map>::iterator> cache;\npublic:\n LRUCache(int capacity) : cap(capacity) {}\n int get(int key) {\n auto it = cache.find(key);\n if (it == cache.end()) return -1;\n dll.splice(dll.end(), dll, it->second);\n return it->second->second;\n }\n void put(int key, int value) {\n auto it = cache.find(key);\n if (it != cache.end()) dll.erase(it->second);\n else if (cache.size() >= cap) { cache.erase(dll.front().first); dll.pop_front(); }\n dll.push_back({key, value});\n cache[key] = --dll.end();\n }\n};", "test_cases": ["put(1,1), put(2,2), get(1) -> 1"], "key_points": ["HashMap + 双向链表", "O(1)时间操作"], "tags": ["design", "hard", "Google", "Amazon"]} {"problem_id": "algo_01520", "original_id": "num-islands", "title": "岛屿数量", "category": "graph", "difficulty": "medium", "companies": ["Google", "Facebook"], "description": "给你一个由 '1'(陆地)和 '0'(水)组成的二维网格,请你计算网格中岛屿的数量。岛屿总是被水包围,且只能由水平或垂直方向相邻的陆地连接形成。", "solution_python": "def numIslands(grid):\n if not grid: return 0\n rows, cols = len(grid), len(grid[0])\n count = 0\n def dfs(r, c):\n if r < 0 or r >= rows or c < 0 or c >= cols or grid[r][c] != '1': return\n grid[r][c] = '0'\n dfs(r+1, c); dfs(r-1, c); dfs(r, c+1); dfs(r, c-1)\n for r in range(rows):\n for c in range(cols):\n if grid[r][c] == '1': count += 1; dfs(r, c)\n return count", "solution_java": "public int numIslands(char[][] grid) {\n if (grid.length == 0) return 0;\n int count = 0;\n for (int i = 0; i < grid.length; i++)\n for (int j = 0; j < grid[0].length; j++)\n if (grid[i][j] == '1') { count++; dfs(grid, i, j); }\n return count;\n}\nprivate void dfs(char[][] grid, int r, int c) {\n if (r < 0 || r >= grid.length || c < 0 || c >= grid[0].length || grid[r][c] != '1') return;\n grid[r][c] = '0';\n dfs(grid, r+1, c); dfs(grid, r-1, c); dfs(grid, r, c+1); dfs(grid, r, c-1);\n}", "solution_cpp": "int numIslands(vector>& grid) {\n if (grid.empty()) return 0;\n int count = 0;\n for (int i = 0; i < grid.size(); i++)\n for (int j = 0; j < grid[0].size(); j++)\n if (grid[i][j] == '1') { count++; dfs(grid, i, j); }\n return count;\n}\nvoid dfs(vector>& grid, int r, int c) {\n if (r < 0 || r >= grid.size() || c < 0 || c >= grid[0].size() || grid[r][c] != '1') return;\n grid[r][c] = '0';\n dfs(grid, r+1, c); dfs(grid, r-1, c); dfs(grid, r, c+1); dfs(grid, r, c-1);\n}", "test_cases": ["grid=[[1,1,1,1,0],[1,1,0,1,0],[1,1,0,0,0],[0,0,0,0,0]] -> 1"], "key_points": ["DFS/BFS遍历", "访问后标记为0避免重复"], "tags": ["graph", "medium", "Google", "Facebook"]} {"problem_id": "algo_01521", "original_id": "two-sum", "title": "两数之和", "category": "array", "difficulty": "easy", "companies": ["Amazon", "Google"], "description": "给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那两个整数,并返回他们的数组下标。", "solution_python": "def twoSum(nums, target):\n hashmap = {}\n for i, num in enumerate(nums):\n complement = target - num\n if complement in hashmap:\n return [hashmap[complement], i]\n hashmap[num] = i\n return []", "solution_java": "public int[] twoSum(int[] nums, int target) {\n Map map = new HashMap<>();\n for (int i = 0; i < nums.length; i++) {\n int complement = target - nums[i];\n if (map.containsKey(complement)) return new int[]{map.get(complement), i};\n map.put(nums[i], i);\n }\n return new int[]{};\n}", "solution_cpp": "vector twoSum(vector& nums, int target) {\n unordered_map m;\n for (int i = 0; i < nums.size(); i++) {\n if (m.count(target - nums[i])) return {m[target - nums[i]], i};\n m[nums[i]] = i;\n }\n return {};\n}", "test_cases": ["nums=[2,7,11,15], target=9 -> [0,1]", "nums=[3,2,4], target=6 -> [1,2]"], "key_points": ["哈希表一次遍历", "空间换时间"], "tags": ["array", "easy", "Amazon", "Google"]} {"problem_id": "algo_01522", "original_id": "merge-sorted", "title": "合并两个有序数组", "category": "array", "difficulty": "easy", "companies": ["Microsoft", "Uber"], "description": "给你两个按非递减顺序排列的整数数组 nums1 和 nums2,另有两个整数 m 和 n,分别表示 nums1 和 nums2 中的元素数目。请你合并 nums2 到 nums1 中。", "solution_python": "def merge(nums1, m, nums2, n):\n p1, p2, p = m-1, n-1, m+n-1\n while p1 >= 0 and p2 >= 0:\n if nums1[p1] > nums2[p2]: nums1[p] = nums1[p1]; p1 -= 1\n else: nums1[p] = nums2[p2]; p2 -= 1\n p -= 1\n while p2 >= 0: nums1[p] = nums2[p2]; p2 -= 1; p -= 1", "solution_java": "public void merge(int[] nums1, int m, int[] nums2, int n) {\n int p1 = m-1, p2 = n-1, p = m+n-1;\n while (p1 >= 0 && p2 >= 0) {\n nums1[p--] = nums1[p1] > nums2[p2] ? nums1[p1--] : nums2[p2--];\n }\n while (p2 >= 0) nums1[p--] = nums2[p2--];\n}", "solution_cpp": "void merge(vector& nums1, int m, vector& nums2, int n) {\n int p1 = m-1, p2 = n-1, p = m+n-1;\n while (p1 >= 0 && p2 >= 0) nums1[p--] = nums1[p1] > nums2[p2] ? nums1[p1--] : nums2[p2--];\n while (p2 >= 0) nums1[p--] = nums2[p2--];\n}", "test_cases": ["nums1=[1,2,3], m=3, nums2=[2,5,6], n=3 -> [1,2,2,3,5,6]", "nums1=[], m=0, nums2=[1], n=1 -> [1]"], "key_points": ["从后往前合并", "三指针技巧"], "tags": ["array", "easy", "Microsoft", "Uber"]} {"problem_id": "algo_01523", "original_id": "max-subarray", "title": "最大子数组和", "category": "array", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "给你一个整数数组 nums ,请你找出一个具有最大和的连续子数组,返回其最大和。", "solution_python": "def maxSubArray(nums):\n max_sum = current = nums[0]\n for num in nums[1:]:\n current = max(num, current + num)\n max_sum = max(max_sum, current)\n return max_sum", "solution_java": "public int maxSubArray(int[] nums) {\n int maxSum = nums[0], curr = nums[0];\n for (int i = 1; i < nums.length; i++) {\n curr = Math.max(nums[i], curr + nums[i]);\n maxSum = Math.max(maxSum, curr);\n }\n return maxSum;\n}", "solution_cpp": "int maxSubArray(vector& nums) {\n int maxSum = nums[0], curr = nums[0];\n for (int i = 1; i < nums.size(); i++) {\n curr = max(nums[i], curr + nums[i]);\n maxSum = max(maxSum, curr);\n }\n return maxSum;\n}", "test_cases": ["nums=[-2,1,-3,4,-1,2,1,-5,4] -> 6", "nums=[1] -> 1"], "key_points": ["Kadane算法", "动态规划基础题"], "tags": ["array", "medium", "Google", "Microsoft"]} {"problem_id": "algo_01524", "original_id": "valid-parentheses", "title": "有效的括号", "category": "string", "difficulty": "easy", "companies": ["Google", "Uber"], "description": "给定一个只包括 '(',')','{','}','[',']' 的字符串 s,判断字符串是否有效。", "solution_python": "def isValid(s):\n stack = []\n mapping = {')': '(', ']': '[', '}': '{'}\n for c in s:\n if c in mapping:\n if not stack or stack[-1] != mapping[c]: return False\n stack.pop()\n else: stack.append(c)\n return not stack", "solution_java": "public boolean isValid(String s) {\n Stack stack = new Stack<>();\n Map map = Map.of(')', '(', ']', '[', '}', '{');\n for (char c : s.toCharArray()) {\n if (map.containsValue(c)) stack.push(c);\n else if (!stack.isEmpty() && stack.pop() != map.get(c)) return false;\n }\n return stack.isEmpty();\n}", "solution_cpp": "bool isValid(string s) {\n stack st;\n unordered_map m = {{')','('},{']','['},{'}','{'}};\n for (char c : s) {\n if (m.find(c) == m.end()) st.push(c);\n else if (st.empty() || st.top() != m[c]) return false;\n else st.pop();\n }\n return st.empty();\n}", "test_cases": ["s=\"()\" -> true", "s=\"()[]{}\" -> true", "s=\"(]\" -> false"], "key_points": ["栈匹配法", "注意空栈边界"], "tags": ["string", "easy", "Google", "Uber"]} {"problem_id": "algo_01525", "original_id": "longest-palindrome", "title": "最长回文子串", "category": "string", "difficulty": "medium", "companies": ["Google", "Amazon"], "description": "给你一个字符串 s,找到 s 中最长的回文子串。", "solution_python": "def longestPalindrome(s):\n def expand(l, r):\n while l >= 0 and r < len(s) and s[l] == s[r]: l -= 1; r += 1\n return l + 1, r - 1\n start = end = 0\n for i in range(len(s)):\n l1, r1 = expand(i, i)\n l2, r2 = expand(i, i + 1)\n if r1 - l1 > end - start: start, end = l1, r1\n if r2 - l2 > end - start: start, end = l2, r2\n return s[start:end+1]", "solution_java": "public String longestPalindrome(String s) {\n int start = 0, end = 0;\n for (int i = 0; i < s.length(); i++) {\n int len1 = expand(s, i, i), len2 = expand(s, i, i+1);\n int len = Math.max(len1, len2);\n if (len > end - start) { start = i - (len-1)/2; end = i + len/2; }\n }\n return s.substring(start, end + 1);\n}\nprivate int expand(String s, int l, int r) {\n while (l >= 0 && r < s.length() && s.charAt(l) == s.charAt(r)) { l--; r++; }\n return r - l - 1;\n}", "solution_cpp": "string longestPalindrome(string s) {\n int start = 0, end = 0;\n for (int i = 0; i < s.size(); i++) {\n int len1 = expand(s, i, i), len2 = expand(s, i, i+1);\n if (max(len1, len2) > end - start) { start = i - (max(len1,len2)-1)/2; end = i + max(len1,len2)/2; }\n }\n return s.substr(start, end - start + 1);\n}", "test_cases": ["s=\"babad\" -> bab或aba", "s=\"cbbd\" -> bb"], "key_points": ["中心扩展法", "处理奇偶长度"], "tags": ["string", "medium", "Google", "Amazon"]} {"problem_id": "algo_01526", "original_id": "reverse-list", "title": "反转链表", "category": "linkedlist", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "给你单链表的头节点 head,请你反转链表,并返回反转后的链表。", "solution_python": "def reverseList(head):\n prev = None\n curr = head\n while curr:\n nxt = curr.next\n curr.next = prev\n prev = curr\n curr = nxt\n return prev", "solution_java": "public ListNode reverseList(ListNode head) {\n ListNode prev = null, curr = head;\n while (curr != null) {\n ListNode next = curr.next;\n curr.next = prev;\n prev = curr;\n curr = next;\n }\n return prev;\n}", "solution_cpp": "ListNode* reverseList(ListNode* head) {\n ListNode* prev = nullptr, *curr = head;\n while (curr) {\n ListNode* next = curr->next;\n curr->next = prev;\n prev = curr;\n curr = next;\n }\n return prev;\n}", "test_cases": ["head=[1,2,3,4,5] -> [5,4,3,2,1]", "head=[1,2] -> [2,1]"], "key_points": ["迭代法 O(1)空间", "递归法 O(n)空间"], "tags": ["linkedlist", "medium", "Google", "Microsoft"]} {"problem_id": "algo_01527", "original_id": "middle-node", "title": "链表的中间结点", "category": "linkedlist", "difficulty": "easy", "companies": ["Amazon", "Facebook"], "description": "给你单链表的头节点 head,请你找出并返回链表的中间结点。如果有两个中间结点,则返回第二个中间结点。", "solution_python": "def middleNode(head):\n slow = fast = head\n while fast and fast.next:\n slow = slow.next\n fast = fast.next.next\n return slow", "solution_java": "public ListNode middleNode(ListNode head) {\n ListNode slow = head, fast = head;\n while (fast != null && fast.next != null) {\n slow = slow.next;\n fast = fast.next.next;\n }\n return slow;\n}", "solution_cpp": "ListNode* middleNode(ListNode* head) {\n ListNode* slow = head, *fast = head;\n while (fast && fast->next) { slow = slow->next; fast = fast->next->next; }\n return slow;\n}", "test_cases": ["head=[1,2,3,4,5] -> 3", "head=[1,2,3,4,5,6] -> 4"], "key_points": ["快慢指针", "O(n)时间O(1)空间"], "tags": ["linkedlist", "easy", "Amazon", "Facebook"]} {"problem_id": "algo_01528", "original_id": "max-depth", "title": "二叉树的最大深度", "category": "tree", "difficulty": "easy", "companies": ["Microsoft", "Apple"], "description": "给定一个二叉树 root,返回其最大深度。", "solution_python": "def maxDepth(root):\n if not root: return 0\n return max(maxDepth(root.left), maxDepth(root.right)) + 1", "solution_java": "public int maxDepth(TreeNode root) {\n if (root == null) return 0;\n return Math.max(maxDepth(root.left), maxDepth(root.right)) + 1;\n}", "solution_cpp": "int maxDepth(TreeNode* root) {\n if (!root) return 0;\n return max(maxDepth(root->left), maxDepth(root->right)) + 1;\n}", "test_cases": ["root=[3,9,20,null,null,15,7] -> 3", "root=[1,null,2] -> 2"], "key_points": ["DFS递归", "层序遍历也可"], "tags": ["tree", "easy", "Microsoft", "Apple"]} {"problem_id": "algo_01529", "original_id": "inorder-traversal", "title": "二叉树的中序遍历", "category": "tree", "difficulty": "easy", "companies": ["Google", "Microsoft"], "description": "给定一个二叉树的根节点 root,返回它的中序遍历结果。", "solution_python": "def inorderTraversal(root):\n result = []\n def dfs(node):\n if node:\n dfs(node.left)\n result.append(node.val)\n dfs(node.right)\n dfs(root)\n return result", "solution_java": "public List inorderTraversal(TreeNode root) {\n List res = new ArrayList<>();\n dfs(root, res);\n return res;\n}\nprivate void dfs(TreeNode node, List res) {\n if (node == null) return;\n dfs(node.left, res); res.add(node.val); dfs(node.right, res);\n}", "solution_cpp": "vector inorderTraversal(TreeNode* root) {\n vector res;\n dfs(root, res);\n return res;\n}\nvoid dfs(TreeNode* node, vector& res) {\n if (!node) return;\n dfs(node->left, res); res.push_back(node->val); dfs(node->right, res);\n}", "test_cases": ["root=[1,null,2,3] -> [1,3,2]", "root=[] -> []"], "key_points": ["左-根-右顺序", "递归最简洁"], "tags": ["tree", "easy", "Google", "Microsoft"]} {"problem_id": "algo_01530", "original_id": "binary-search", "title": "二分查找", "category": "binarysearch", "difficulty": "easy", "companies": ["Google", "Amazon"], "description": "给定一个 n 个元素有序的(升序)整型数组 nums 和一个目标值 target,写一个函数搜索 nums 中的 target,如果目标值存在返回下标,否则返回 -1。", "solution_python": "def search(nums, target):\n left, right = 0, len(nums) - 1\n while left <= right:\n mid = (left + right) // 2\n if nums[mid] == target: return mid\n elif nums[mid] < target: left = mid + 1\n else: right = mid - 1\n return -1", "solution_java": "public int search(int[] nums, int target) {\n int left = 0, right = nums.length - 1;\n while (left <= right) {\n int mid = left + (right - left) / 2;\n if (nums[mid] == target) return mid;\n else if (nums[mid] < target) left = mid + 1;\n else right = mid - 1;\n }\n return -1;\n}", "solution_cpp": "int search(vector& nums, int target) {\n int left = 0, right = nums.size() - 1;\n while (left <= right) {\n int mid = left + (right - left) / 2;\n if (nums[mid] == target) return mid;\n else if (nums[mid] < target) left = mid + 1;\n else right = mid - 1;\n }\n return -1;\n}", "test_cases": ["nums=[-1,0,3,5,9,12], target=9 -> 4", "nums=[-1,0,3,5,9,12], target=2 -> -1"], "key_points": ["标准模板", "注意防溢出写法"], "tags": ["binarysearch", "easy", "Google", "Amazon"]} {"problem_id": "algo_01531", "original_id": "climbing-stairs", "title": "爬楼梯", "category": "dp", "difficulty": "easy", "companies": ["Amazon", "Google"], "description": "假设你正在爬楼梯。需要 n 阶你才能到达楼顶。每次你可以爬 1 或 2 个台阶。你有多少种不同的方法可以爬到楼顶?", "solution_python": "def climbStairs(n):\n if n <= 2: return n\n a, b = 1, 2\n for _ in range(3, n+1):\n a, b = b, a + b\n return b", "solution_java": "public int climbStairs(int n) {\n if (n <= 2) return n;\n int a = 1, b = 2;\n for (int i = 3; i <= n; i++) { int temp = a + b; a = b; b = temp; }\n return b;\n}", "solution_cpp": "int climbStairs(int n) {\n if (n <= 2) return n;\n int a = 1, b = 2;\n for (int i = 3; i <= n; i++) { int temp = a + b; a = b; b = temp; }\n return b;\n}", "test_cases": ["n=2 -> 2", "n=3 -> 3", "n=5 -> 8"], "key_points": ["斐波那契数列", "滚动数组优化空间"], "tags": ["dp", "easy", "Amazon", "Google"]} {"problem_id": "algo_01532", "original_id": "coin-change", "title": "零钱兑换", "category": "dp", "difficulty": "medium", "companies": ["Google", "Amazon"], "description": "给你一个整数数组 coins 表示不同面额的硬币,以及一个整数 amount 表示总金额。计算并返回可以凑成总金额所需的最少的硬币个数。如果没有任何一种硬币组合能组成总金额,返回 -1。", "solution_python": "def coinChange(coins, amount):\n dp = [float('inf')] * (amount + 1)\n dp[0] = 0\n for coin in coins:\n for x in range(coin, amount + 1):\n dp[x] = min(dp[x], dp[x - coin] + 1)\n return dp[amount] if dp[amount] != float('inf') else -1", "solution_java": "public int coinChange(int[] coins, int amount) {\n int[] dp = new int[amount + 1];\n Arrays.fill(dp, amount + 1);\n dp[0] = 0;\n for (int coin : coins) {\n for (int x = coin; x <= amount; x++) {\n dp[x] = Math.min(dp[x], dp[x - coin] + 1);\n }\n }\n return dp[amount] > amount ? -1 : dp[amount];\n}", "solution_cpp": "int coinChange(vector& coins, int amount) {\n vector dp(amount + 1, amount + 1);\n dp[0] = 0;\n for (int coin : coins) {\n for (int x = coin; x <= amount; x++) {\n dp[x] = min(dp[x], dp[x - coin] + 1);\n }\n }\n return dp[amount] > amount ? -1 : dp[amount];\n}", "test_cases": ["coins=[1,2,5], amount=11 -> 3", "coins=[2], amount=3 -> -1"], "key_points": ["完全背包问题", "dp[x] = min(dp[x-coin]+1)"], "tags": ["dp", "medium", "Google", "Amazon"]} {"problem_id": "algo_01533", "original_id": "subsets", "title": "子集", "category": "backtracking", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "给你一个整数数组 nums ,数组中的元素 互不相同 。返回该数组所有可能的子集(幂集)。", "solution_python": "def subsets(nums):\n result = []\n def backtrack(start, path):\n result.append(path[:])\n for i in range(start, len(nums)):\n path.append(nums[i])\n backtrack(i + 1, path)\n path.pop()\n backtrack(0, [])\n return result", "solution_java": "public List> subsets(int[] nums) {\n List> result = new ArrayList<>();\n backtrack(nums, 0, new ArrayList<>(), result);\n return result;\n}\nprivate void backtrack(int[] nums, int start, List path, List> result) {\n result.add(new ArrayList<>(path));\n for (int i = start; i < nums.length; i++) {\n path.add(nums[i]);\n backtrack(nums, i + 1, path, result);\n path.remove(path.size() - 1);\n }\n}", "solution_cpp": "vector> subsets(vector& nums) {\n vector> result;\n vector path;\n backtrack(nums, 0, path, result);\n return result;\n}\nvoid backtrack(vector& nums, int start, vector& path, vector>& result) {\n result.push_back(path);\n for (int i = start; i < nums.size(); i++) {\n path.push_back(nums[i]);\n backtrack(nums, i + 1, path, result);\n path.pop_back();\n }\n}", "test_cases": ["nums=[1,2,3] -> [[],[1],[2],[1,2],[3],[1,3],[2,3],[1,2,3]]"], "key_points": ["选或不选", "DFS遍历子集树"], "tags": ["backtracking", "medium", "Google", "Microsoft"]} {"problem_id": "algo_01534", "original_id": "permutations", "title": "全排列", "category": "backtracking", "difficulty": "medium", "companies": ["Google", "Facebook"], "description": "给定一个不含重复数字的数组 nums,返回其所有可能的全排列。", "solution_python": "def permute(nums):\n result = []\n def backtrack(path, used):\n if len(path) == len(nums):\n result.append(path[:])\n return\n for i in range(len(nums)):\n if used[i]: continue\n used[i] = True\n path.append(nums[i])\n backtrack(path, used)\n path.pop()\n used[i] = False\n backtrack([], [False]*len(nums))\n return result", "solution_java": "public List> permute(int[] nums) {\n List> result = new ArrayList<>();\n boolean[] used = new boolean[nums.length];\n backtrack(nums, used, new ArrayList<>(), result);\n return result;\n}\nprivate void backtrack(int[] nums, boolean[] used, List path, List> result) {\n if (path.size() == nums.length) { result.add(new ArrayList<>(path)); return; }\n for (int i = 0; i < nums.length; i++) {\n if (used[i]) continue;\n used[i] = true;\n path.add(nums[i]);\n backtrack(nums, used, path, result);\n path.remove(path.size() - 1);\n used[i] = false;\n }\n}", "solution_cpp": "vector> permute(vector& nums) {\n vector> result;\n vector used(nums.size(), false);\n vector path;\n backtrack(nums, used, path, result);\n return result;\n}\nvoid backtrack(vector& nums, vector& used, vector& path, vector>& result) {\n if (path.size() == nums.size()) { result.push_back(path); return; }\n for (int i = 0; i < nums.size(); i++) {\n if (used[i]) continue;\n used[i] = true;\n path.push_back(nums[i]);\n backtrack(nums, used, path, result);\n path.pop_back();\n used[i] = false;\n }\n}", "test_cases": ["nums=[1,2,3] -> [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]"], "key_points": ["标记已使用元素", "回溯经典模板"], "tags": ["backtracking", "medium", "Google", "Facebook"]} {"problem_id": "algo_01535", "original_id": "top-k-frequent", "title": "前K个高频元素", "category": "heap", "difficulty": "medium", "companies": ["Amazon", "Facebook"], "description": "给你一个整数数组 nums 和一个整数 k,请你返回其中出现频率前 k 高的元素。", "solution_python": "import heapq\nfrom collections import Counter\ndef topKFrequent(nums, k):\n count = Counter(nums)\n heap = []\n for num, freq in count.items():\n heapq.heappush(heap, (freq, num))\n if len(heap) > k: heapq.heappop(heap)\n return [num for freq, num in heap]", "solution_java": "public int[] topKFrequent(int[] nums, int k) {\n Map count = new HashMap<>();\n for (int n : nums) count.put(n, count.getOrDefault(n, 0) + 1);\n PriorityQueue> heap = \n new PriorityQueue<>((a, b) -> a.getValue() - b.getValue());\n for (Map.Entry e : count.entrySet()) {\n heap.offer(e);\n if (heap.size() > k) heap.poll();\n }\n int[] res = new int[k];\n for (int i = k - 1; i >= 0; i--) res[i] = heap.poll().getKey();\n return res;\n}", "solution_cpp": "vector topKFrequent(vector& nums, int k) {\n unordered_map count;\n for (int n : nums) count[n]++;\n priority_queue, vector>, greater>> heap;\n for (auto& [num, freq] : count) {\n heap.push({freq, num});\n if (heap.size() > k) heap.pop();\n }\n vector res;\n while (!heap.empty()) { res.push_back(heap.top().second); heap.pop(); }\n reverse(res.begin(), res.end());\n return res;\n}", "test_cases": ["nums=[1,1,1,2,2,3], k=2 -> [1,2]", "nums=[1], k=1 -> [1]"], "key_points": ["小顶堆保持大小k", "时间复杂度O(nlogk)"], "tags": ["heap", "medium", "Amazon", "Facebook"]} {"problem_id": "algo_01536", "original_id": "3sum", "title": "三数之和", "category": "two-pointers", "difficulty": "medium", "companies": ["Google", "Amazon"], "description": "给你一个整数数组 nums,判断是否存在三元组满足和为0,返回所有不重复的三元组。", "solution_python": "def threeSum(nums):\n nums.sort()\n result = []\n for i in range(len(nums) - 2):\n if i > 0 and nums[i] == nums[i-1]: continue\n left, right = i + 1, len(nums) - 1\n while left < right:\n total = nums[i] + nums[left] + nums[right]\n if total < 0: left += 1\n elif total > 0: right -= 1\n else:\n result.append([nums[i], nums[left], nums[right]])\n while left < right and nums[left] == nums[left+1]: left += 1\n while left < right and nums[right] == nums[right-1]: right -= 1\n left += 1; right -= 1\n return result", "solution_java": "public List> threeSum(int[] nums) {\n Arrays.sort(nums);\n List> result = new ArrayList<>();\n for (int i = 0; i < nums.length - 2; i++) {\n if (i > 0 && nums[i] == nums[i-1]) continue;\n int left = i + 1, right = nums.length - 1;\n while (left < right) {\n int total = nums[i] + nums[left] + nums[right];\n if (total < 0) left++;\n else if (total > 0) right--;\n else {\n result.add(Arrays.asList(nums[i], nums[left], nums[right]));\n while (left < right && nums[left] == nums[left+1]) left++;\n while (left < right && nums[right] == nums[right-1]) right--;\n left++; right--;\n }\n }\n }\n return result;\n}", "solution_cpp": "vector> threeSum(vector& nums) {\n sort(nums.begin(), nums.end());\n vector> result;\n for (int i = 0; i < nums.size() - 2; i++) {\n if (i > 0 && nums[i] == nums[i-1]) continue;\n int left = i + 1, right = nums.size() - 1;\n while (left < right) {\n int total = nums[i] + nums[left] + nums[right];\n if (total < 0) left++;\n else if (total > 0) right--;\n else {\n result.push_back({nums[i], nums[left], nums[right]});\n while (left < right && nums[left] == nums[left+1]) left++;\n while (left < right && nums[right] == nums[right-1]) right--;\n left++; right--;\n }\n }\n }\n return result;\n}", "test_cases": ["nums=[-1,0,1,2,-1,-4] -> [[-1,-1,2],[-1,0,1]]"], "key_points": ["排序+双指针", "去重是关键"], "tags": ["two-pointers", "medium", "Google", "Amazon"]} {"problem_id": "algo_01537", "original_id": "container-water", "title": "盛最多水的容器", "category": "two-pointers", "difficulty": "medium", "companies": ["Google", "Uber"], "description": "给定一个长度为 n 的整数数组 height,找出其中的两条线,使得它们与 x 轴共同构成的容器可以容纳最多的水。", "solution_python": "def maxArea(height):\n left, right = 0, len(height) - 1\n max_area = 0\n while left < right:\n h = min(height[left], height[right])\n max_area = max(max_area, h * (right - left))\n if height[left] < height[right]: left += 1\n else: right -= 1\n return max_area", "solution_java": "public int maxArea(int[] height) {\n int left = 0, right = height.length - 1, maxArea = 0;\n while (left < right) {\n int h = Math.min(height[left], height[right]);\n maxArea = Math.max(maxArea, h * (right - left));\n if (height[left] < height[right]) left++;\n else right--;\n }\n return maxArea;\n}", "solution_cpp": "int maxArea(vector& height) {\n int left = 0, right = height.size() - 1, maxArea = 0;\n while (left < right) {\n int h = min(height[left], height[right]);\n maxArea = max(maxArea, h * (right - left));\n if (height[left] < height[right]) left++;\n else right--;\n }\n return maxArea;\n}", "test_cases": ["height=[1,8,6,2,5,4,8,3,7] -> 49"], "key_points": ["移动短边指针", "面积=min(h1,h2)*width"], "tags": ["two-pointers", "medium", "Google", "Uber"]} {"problem_id": "algo_01538", "original_id": "min-stack", "title": "最小栈", "category": "stack", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "设计一个支持 push,pop,top 操作,并能在常数时间内检索到最小元素的栈。", "solution_python": "class MinStack:\n def __init__(self):\n self.stack = []\n self.min_stack = []\n def push(self, val):\n self.stack.append(val)\n self.min_stack.append(min(val, self.min_stack[-1] if self.min_stack else val))\n def pop(self):\n self.stack.pop(); self.min_stack.pop()\n def top(self): return self.stack[-1]\n def getMin(self): return self.min_stack[-1]", "solution_java": "class MinStack {\n Stack stack = new Stack<>();\n Stack minStack = new Stack<>();\n public void push(int val) { stack.push(val); minStack.push(Math.min(val, minStack.isEmpty() ? val : minStack.peek())); }\n public void pop() { stack.pop(); minStack.pop(); }\n public int top() { return stack.peek(); }\n public int getMin() { return minStack.peek(); }\n}", "solution_cpp": "class MinStack {\n stack st, minSt;\npublic:\n void push(int val) { st.push(val); minSt.push(min(val, minSt.empty() ? val : minSt.top())); }\n void pop() { st.pop(); minSt.pop(); }\n int top() { return st.top(); }\n int getMin() { return minSt.top(); }\n};", "test_cases": ["push(-2), push(0), push(-3) -> getMin() returns -3"], "key_points": ["辅助栈记录最小值", "O(1)时间获取最小值"], "tags": ["stack", "medium", "Google", "Microsoft"]} {"problem_id": "algo_01539", "original_id": "lru-cache", "title": "LRU缓存", "category": "design", "difficulty": "hard", "companies": ["Google", "Amazon"], "description": "设计和实现一个 LRU(最近最少使用)缓存机制。", "solution_python": "class LRUCache:\n def __init__(self, capacity):\n self.capacity = capacity\n self.cache = {}\n self.order = []\n def get(self, key):\n if key not in self.cache: return -1\n self.order.remove(key); self.order.append(key)\n return self.cache[key]\n def put(self, key, value):\n if key in self.cache:\n self.order.remove(key)\n elif len(self.cache) >= self.capacity:\n del self.cache[self.order.pop(0)]\n self.cache[key] = value; self.order.append(key)", "solution_java": "class LRUCache {\n int capacity;\n LinkedHashMap cache = new LinkedHashMap<>();\n public LRUCache(int cap) { capacity = cap; }\n public int get(int key) { return cache.containsKey(key) ? cache.remove(key) : -1; }\n public void put(int key, int val) {\n if (cache.containsKey(key)) cache.remove(key);\n else if (cache.size() >= capacity) cache.remove(cache.keySet().iterator().next());\n cache.put(key, val);\n }\n}", "solution_cpp": "class LRUCache {\n int cap;\n list> dll;\n unordered_map>::iterator> cache;\npublic:\n LRUCache(int capacity) : cap(capacity) {}\n int get(int key) {\n auto it = cache.find(key);\n if (it == cache.end()) return -1;\n dll.splice(dll.end(), dll, it->second);\n return it->second->second;\n }\n void put(int key, int value) {\n auto it = cache.find(key);\n if (it != cache.end()) dll.erase(it->second);\n else if (cache.size() >= cap) { cache.erase(dll.front().first); dll.pop_front(); }\n dll.push_back({key, value});\n cache[key] = --dll.end();\n }\n};", "test_cases": ["put(1,1), put(2,2), get(1) -> 1"], "key_points": ["HashMap + 双向链表", "O(1)时间操作"], "tags": ["design", "hard", "Google", "Amazon"]} {"problem_id": "algo_01540", "original_id": "num-islands", "title": "岛屿数量", "category": "graph", "difficulty": "medium", "companies": ["Google", "Facebook"], "description": "给你一个由 '1'(陆地)和 '0'(水)组成的二维网格,请你计算网格中岛屿的数量。岛屿总是被水包围,且只能由水平或垂直方向相邻的陆地连接形成。", "solution_python": "def numIslands(grid):\n if not grid: return 0\n rows, cols = len(grid), len(grid[0])\n count = 0\n def dfs(r, c):\n if r < 0 or r >= rows or c < 0 or c >= cols or grid[r][c] != '1': return\n grid[r][c] = '0'\n dfs(r+1, c); dfs(r-1, c); dfs(r, c+1); dfs(r, c-1)\n for r in range(rows):\n for c in range(cols):\n if grid[r][c] == '1': count += 1; dfs(r, c)\n return count", "solution_java": "public int numIslands(char[][] grid) {\n if (grid.length == 0) return 0;\n int count = 0;\n for (int i = 0; i < grid.length; i++)\n for (int j = 0; j < grid[0].length; j++)\n if (grid[i][j] == '1') { count++; dfs(grid, i, j); }\n return count;\n}\nprivate void dfs(char[][] grid, int r, int c) {\n if (r < 0 || r >= grid.length || c < 0 || c >= grid[0].length || grid[r][c] != '1') return;\n grid[r][c] = '0';\n dfs(grid, r+1, c); dfs(grid, r-1, c); dfs(grid, r, c+1); dfs(grid, r, c-1);\n}", "solution_cpp": "int numIslands(vector>& grid) {\n if (grid.empty()) return 0;\n int count = 0;\n for (int i = 0; i < grid.size(); i++)\n for (int j = 0; j < grid[0].size(); j++)\n if (grid[i][j] == '1') { count++; dfs(grid, i, j); }\n return count;\n}\nvoid dfs(vector>& grid, int r, int c) {\n if (r < 0 || r >= grid.size() || c < 0 || c >= grid[0].size() || grid[r][c] != '1') return;\n grid[r][c] = '0';\n dfs(grid, r+1, c); dfs(grid, r-1, c); dfs(grid, r, c+1); dfs(grid, r, c-1);\n}", "test_cases": ["grid=[[1,1,1,1,0],[1,1,0,1,0],[1,1,0,0,0],[0,0,0,0,0]] -> 1"], "key_points": ["DFS/BFS遍历", "访问后标记为0避免重复"], "tags": ["graph", "medium", "Google", "Facebook"]} {"problem_id": "algo_01541", "original_id": "two-sum", "title": "两数之和", "category": "array", "difficulty": "easy", "companies": ["Amazon", "Google"], "description": "给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那两个整数,并返回他们的数组下标。", "solution_python": "def twoSum(nums, target):\n hashmap = {}\n for i, num in enumerate(nums):\n complement = target - num\n if complement in hashmap:\n return [hashmap[complement], i]\n hashmap[num] = i\n return []", "solution_java": "public int[] twoSum(int[] nums, int target) {\n Map map = new HashMap<>();\n for (int i = 0; i < nums.length; i++) {\n int complement = target - nums[i];\n if (map.containsKey(complement)) return new int[]{map.get(complement), i};\n map.put(nums[i], i);\n }\n return new int[]{};\n}", "solution_cpp": "vector twoSum(vector& nums, int target) {\n unordered_map m;\n for (int i = 0; i < nums.size(); i++) {\n if (m.count(target - nums[i])) return {m[target - nums[i]], i};\n m[nums[i]] = i;\n }\n return {};\n}", "test_cases": ["nums=[2,7,11,15], target=9 -> [0,1]", "nums=[3,2,4], target=6 -> [1,2]"], "key_points": ["哈希表一次遍历", "空间换时间"], "tags": ["array", "easy", "Amazon", "Google"]} {"problem_id": "algo_01542", "original_id": "merge-sorted", "title": "合并两个有序数组", "category": "array", "difficulty": "easy", "companies": ["Microsoft", "Uber"], "description": "给你两个按非递减顺序排列的整数数组 nums1 和 nums2,另有两个整数 m 和 n,分别表示 nums1 和 nums2 中的元素数目。请你合并 nums2 到 nums1 中。", "solution_python": "def merge(nums1, m, nums2, n):\n p1, p2, p = m-1, n-1, m+n-1\n while p1 >= 0 and p2 >= 0:\n if nums1[p1] > nums2[p2]: nums1[p] = nums1[p1]; p1 -= 1\n else: nums1[p] = nums2[p2]; p2 -= 1\n p -= 1\n while p2 >= 0: nums1[p] = nums2[p2]; p2 -= 1; p -= 1", "solution_java": "public void merge(int[] nums1, int m, int[] nums2, int n) {\n int p1 = m-1, p2 = n-1, p = m+n-1;\n while (p1 >= 0 && p2 >= 0) {\n nums1[p--] = nums1[p1] > nums2[p2] ? nums1[p1--] : nums2[p2--];\n }\n while (p2 >= 0) nums1[p--] = nums2[p2--];\n}", "solution_cpp": "void merge(vector& nums1, int m, vector& nums2, int n) {\n int p1 = m-1, p2 = n-1, p = m+n-1;\n while (p1 >= 0 && p2 >= 0) nums1[p--] = nums1[p1] > nums2[p2] ? nums1[p1--] : nums2[p2--];\n while (p2 >= 0) nums1[p--] = nums2[p2--];\n}", "test_cases": ["nums1=[1,2,3], m=3, nums2=[2,5,6], n=3 -> [1,2,2,3,5,6]", "nums1=[], m=0, nums2=[1], n=1 -> [1]"], "key_points": ["从后往前合并", "三指针技巧"], "tags": ["array", "easy", "Microsoft", "Uber"]} {"problem_id": "algo_01543", "original_id": "max-subarray", "title": "最大子数组和", "category": "array", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "给你一个整数数组 nums ,请你找出一个具有最大和的连续子数组,返回其最大和。", "solution_python": "def maxSubArray(nums):\n max_sum = current = nums[0]\n for num in nums[1:]:\n current = max(num, current + num)\n max_sum = max(max_sum, current)\n return max_sum", "solution_java": "public int maxSubArray(int[] nums) {\n int maxSum = nums[0], curr = nums[0];\n for (int i = 1; i < nums.length; i++) {\n curr = Math.max(nums[i], curr + nums[i]);\n maxSum = Math.max(maxSum, curr);\n }\n return maxSum;\n}", "solution_cpp": "int maxSubArray(vector& nums) {\n int maxSum = nums[0], curr = nums[0];\n for (int i = 1; i < nums.size(); i++) {\n curr = max(nums[i], curr + nums[i]);\n maxSum = max(maxSum, curr);\n }\n return maxSum;\n}", "test_cases": ["nums=[-2,1,-3,4,-1,2,1,-5,4] -> 6", "nums=[1] -> 1"], "key_points": ["Kadane算法", "动态规划基础题"], "tags": ["array", "medium", "Google", "Microsoft"]} {"problem_id": "algo_01544", "original_id": "valid-parentheses", "title": "有效的括号", "category": "string", "difficulty": "easy", "companies": ["Google", "Uber"], "description": "给定一个只包括 '(',')','{','}','[',']' 的字符串 s,判断字符串是否有效。", "solution_python": "def isValid(s):\n stack = []\n mapping = {')': '(', ']': '[', '}': '{'}\n for c in s:\n if c in mapping:\n if not stack or stack[-1] != mapping[c]: return False\n stack.pop()\n else: stack.append(c)\n return not stack", "solution_java": "public boolean isValid(String s) {\n Stack stack = new Stack<>();\n Map map = Map.of(')', '(', ']', '[', '}', '{');\n for (char c : s.toCharArray()) {\n if (map.containsValue(c)) stack.push(c);\n else if (!stack.isEmpty() && stack.pop() != map.get(c)) return false;\n }\n return stack.isEmpty();\n}", "solution_cpp": "bool isValid(string s) {\n stack st;\n unordered_map m = {{')','('},{']','['},{'}','{'}};\n for (char c : s) {\n if (m.find(c) == m.end()) st.push(c);\n else if (st.empty() || st.top() != m[c]) return false;\n else st.pop();\n }\n return st.empty();\n}", "test_cases": ["s=\"()\" -> true", "s=\"()[]{}\" -> true", "s=\"(]\" -> false"], "key_points": ["栈匹配法", "注意空栈边界"], "tags": ["string", "easy", "Google", "Uber"]} {"problem_id": "algo_01545", "original_id": "longest-palindrome", "title": "最长回文子串", "category": "string", "difficulty": "medium", "companies": ["Google", "Amazon"], "description": "给你一个字符串 s,找到 s 中最长的回文子串。", "solution_python": "def longestPalindrome(s):\n def expand(l, r):\n while l >= 0 and r < len(s) and s[l] == s[r]: l -= 1; r += 1\n return l + 1, r - 1\n start = end = 0\n for i in range(len(s)):\n l1, r1 = expand(i, i)\n l2, r2 = expand(i, i + 1)\n if r1 - l1 > end - start: start, end = l1, r1\n if r2 - l2 > end - start: start, end = l2, r2\n return s[start:end+1]", "solution_java": "public String longestPalindrome(String s) {\n int start = 0, end = 0;\n for (int i = 0; i < s.length(); i++) {\n int len1 = expand(s, i, i), len2 = expand(s, i, i+1);\n int len = Math.max(len1, len2);\n if (len > end - start) { start = i - (len-1)/2; end = i + len/2; }\n }\n return s.substring(start, end + 1);\n}\nprivate int expand(String s, int l, int r) {\n while (l >= 0 && r < s.length() && s.charAt(l) == s.charAt(r)) { l--; r++; }\n return r - l - 1;\n}", "solution_cpp": "string longestPalindrome(string s) {\n int start = 0, end = 0;\n for (int i = 0; i < s.size(); i++) {\n int len1 = expand(s, i, i), len2 = expand(s, i, i+1);\n if (max(len1, len2) > end - start) { start = i - (max(len1,len2)-1)/2; end = i + max(len1,len2)/2; }\n }\n return s.substr(start, end - start + 1);\n}", "test_cases": ["s=\"babad\" -> bab或aba", "s=\"cbbd\" -> bb"], "key_points": ["中心扩展法", "处理奇偶长度"], "tags": ["string", "medium", "Google", "Amazon"]} {"problem_id": "algo_01546", "original_id": "reverse-list", "title": "反转链表", "category": "linkedlist", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "给你单链表的头节点 head,请你反转链表,并返回反转后的链表。", "solution_python": "def reverseList(head):\n prev = None\n curr = head\n while curr:\n nxt = curr.next\n curr.next = prev\n prev = curr\n curr = nxt\n return prev", "solution_java": "public ListNode reverseList(ListNode head) {\n ListNode prev = null, curr = head;\n while (curr != null) {\n ListNode next = curr.next;\n curr.next = prev;\n prev = curr;\n curr = next;\n }\n return prev;\n}", "solution_cpp": "ListNode* reverseList(ListNode* head) {\n ListNode* prev = nullptr, *curr = head;\n while (curr) {\n ListNode* next = curr->next;\n curr->next = prev;\n prev = curr;\n curr = next;\n }\n return prev;\n}", "test_cases": ["head=[1,2,3,4,5] -> [5,4,3,2,1]", "head=[1,2] -> [2,1]"], "key_points": ["迭代法 O(1)空间", "递归法 O(n)空间"], "tags": ["linkedlist", "medium", "Google", "Microsoft"]} {"problem_id": "algo_01547", "original_id": "middle-node", "title": "链表的中间结点", "category": "linkedlist", "difficulty": "easy", "companies": ["Amazon", "Facebook"], "description": "给你单链表的头节点 head,请你找出并返回链表的中间结点。如果有两个中间结点,则返回第二个中间结点。", "solution_python": "def middleNode(head):\n slow = fast = head\n while fast and fast.next:\n slow = slow.next\n fast = fast.next.next\n return slow", "solution_java": "public ListNode middleNode(ListNode head) {\n ListNode slow = head, fast = head;\n while (fast != null && fast.next != null) {\n slow = slow.next;\n fast = fast.next.next;\n }\n return slow;\n}", "solution_cpp": "ListNode* middleNode(ListNode* head) {\n ListNode* slow = head, *fast = head;\n while (fast && fast->next) { slow = slow->next; fast = fast->next->next; }\n return slow;\n}", "test_cases": ["head=[1,2,3,4,5] -> 3", "head=[1,2,3,4,5,6] -> 4"], "key_points": ["快慢指针", "O(n)时间O(1)空间"], "tags": ["linkedlist", "easy", "Amazon", "Facebook"]} {"problem_id": "algo_01548", "original_id": "max-depth", "title": "二叉树的最大深度", "category": "tree", "difficulty": "easy", "companies": ["Microsoft", "Apple"], "description": "给定一个二叉树 root,返回其最大深度。", "solution_python": "def maxDepth(root):\n if not root: return 0\n return max(maxDepth(root.left), maxDepth(root.right)) + 1", "solution_java": "public int maxDepth(TreeNode root) {\n if (root == null) return 0;\n return Math.max(maxDepth(root.left), maxDepth(root.right)) + 1;\n}", "solution_cpp": "int maxDepth(TreeNode* root) {\n if (!root) return 0;\n return max(maxDepth(root->left), maxDepth(root->right)) + 1;\n}", "test_cases": ["root=[3,9,20,null,null,15,7] -> 3", "root=[1,null,2] -> 2"], "key_points": ["DFS递归", "层序遍历也可"], "tags": ["tree", "easy", "Microsoft", "Apple"]} {"problem_id": "algo_01549", "original_id": "inorder-traversal", "title": "二叉树的中序遍历", "category": "tree", "difficulty": "easy", "companies": ["Google", "Microsoft"], "description": "给定一个二叉树的根节点 root,返回它的中序遍历结果。", "solution_python": "def inorderTraversal(root):\n result = []\n def dfs(node):\n if node:\n dfs(node.left)\n result.append(node.val)\n dfs(node.right)\n dfs(root)\n return result", "solution_java": "public List inorderTraversal(TreeNode root) {\n List res = new ArrayList<>();\n dfs(root, res);\n return res;\n}\nprivate void dfs(TreeNode node, List res) {\n if (node == null) return;\n dfs(node.left, res); res.add(node.val); dfs(node.right, res);\n}", "solution_cpp": "vector inorderTraversal(TreeNode* root) {\n vector res;\n dfs(root, res);\n return res;\n}\nvoid dfs(TreeNode* node, vector& res) {\n if (!node) return;\n dfs(node->left, res); res.push_back(node->val); dfs(node->right, res);\n}", "test_cases": ["root=[1,null,2,3] -> [1,3,2]", "root=[] -> []"], "key_points": ["左-根-右顺序", "递归最简洁"], "tags": ["tree", "easy", "Google", "Microsoft"]} {"problem_id": "algo_01550", "original_id": "binary-search", "title": "二分查找", "category": "binarysearch", "difficulty": "easy", "companies": ["Google", "Amazon"], "description": "给定一个 n 个元素有序的(升序)整型数组 nums 和一个目标值 target,写一个函数搜索 nums 中的 target,如果目标值存在返回下标,否则返回 -1。", "solution_python": "def search(nums, target):\n left, right = 0, len(nums) - 1\n while left <= right:\n mid = (left + right) // 2\n if nums[mid] == target: return mid\n elif nums[mid] < target: left = mid + 1\n else: right = mid - 1\n return -1", "solution_java": "public int search(int[] nums, int target) {\n int left = 0, right = nums.length - 1;\n while (left <= right) {\n int mid = left + (right - left) / 2;\n if (nums[mid] == target) return mid;\n else if (nums[mid] < target) left = mid + 1;\n else right = mid - 1;\n }\n return -1;\n}", "solution_cpp": "int search(vector& nums, int target) {\n int left = 0, right = nums.size() - 1;\n while (left <= right) {\n int mid = left + (right - left) / 2;\n if (nums[mid] == target) return mid;\n else if (nums[mid] < target) left = mid + 1;\n else right = mid - 1;\n }\n return -1;\n}", "test_cases": ["nums=[-1,0,3,5,9,12], target=9 -> 4", "nums=[-1,0,3,5,9,12], target=2 -> -1"], "key_points": ["标准模板", "注意防溢出写法"], "tags": ["binarysearch", "easy", "Google", "Amazon"]} {"problem_id": "algo_01551", "original_id": "climbing-stairs", "title": "爬楼梯", "category": "dp", "difficulty": "easy", "companies": ["Amazon", "Google"], "description": "假设你正在爬楼梯。需要 n 阶你才能到达楼顶。每次你可以爬 1 或 2 个台阶。你有多少种不同的方法可以爬到楼顶?", "solution_python": "def climbStairs(n):\n if n <= 2: return n\n a, b = 1, 2\n for _ in range(3, n+1):\n a, b = b, a + b\n return b", "solution_java": "public int climbStairs(int n) {\n if (n <= 2) return n;\n int a = 1, b = 2;\n for (int i = 3; i <= n; i++) { int temp = a + b; a = b; b = temp; }\n return b;\n}", "solution_cpp": "int climbStairs(int n) {\n if (n <= 2) return n;\n int a = 1, b = 2;\n for (int i = 3; i <= n; i++) { int temp = a + b; a = b; b = temp; }\n return b;\n}", "test_cases": ["n=2 -> 2", "n=3 -> 3", "n=5 -> 8"], "key_points": ["斐波那契数列", "滚动数组优化空间"], "tags": ["dp", "easy", "Amazon", "Google"]} {"problem_id": "algo_01552", "original_id": "coin-change", "title": "零钱兑换", "category": "dp", "difficulty": "medium", "companies": ["Google", "Amazon"], "description": "给你一个整数数组 coins 表示不同面额的硬币,以及一个整数 amount 表示总金额。计算并返回可以凑成总金额所需的最少的硬币个数。如果没有任何一种硬币组合能组成总金额,返回 -1。", "solution_python": "def coinChange(coins, amount):\n dp = [float('inf')] * (amount + 1)\n dp[0] = 0\n for coin in coins:\n for x in range(coin, amount + 1):\n dp[x] = min(dp[x], dp[x - coin] + 1)\n return dp[amount] if dp[amount] != float('inf') else -1", "solution_java": "public int coinChange(int[] coins, int amount) {\n int[] dp = new int[amount + 1];\n Arrays.fill(dp, amount + 1);\n dp[0] = 0;\n for (int coin : coins) {\n for (int x = coin; x <= amount; x++) {\n dp[x] = Math.min(dp[x], dp[x - coin] + 1);\n }\n }\n return dp[amount] > amount ? -1 : dp[amount];\n}", "solution_cpp": "int coinChange(vector& coins, int amount) {\n vector dp(amount + 1, amount + 1);\n dp[0] = 0;\n for (int coin : coins) {\n for (int x = coin; x <= amount; x++) {\n dp[x] = min(dp[x], dp[x - coin] + 1);\n }\n }\n return dp[amount] > amount ? -1 : dp[amount];\n}", "test_cases": ["coins=[1,2,5], amount=11 -> 3", "coins=[2], amount=3 -> -1"], "key_points": ["完全背包问题", "dp[x] = min(dp[x-coin]+1)"], "tags": ["dp", "medium", "Google", "Amazon"]} {"problem_id": "algo_01553", "original_id": "subsets", "title": "子集", "category": "backtracking", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "给你一个整数数组 nums ,数组中的元素 互不相同 。返回该数组所有可能的子集(幂集)。", "solution_python": "def subsets(nums):\n result = []\n def backtrack(start, path):\n result.append(path[:])\n for i in range(start, len(nums)):\n path.append(nums[i])\n backtrack(i + 1, path)\n path.pop()\n backtrack(0, [])\n return result", "solution_java": "public List> subsets(int[] nums) {\n List> result = new ArrayList<>();\n backtrack(nums, 0, new ArrayList<>(), result);\n return result;\n}\nprivate void backtrack(int[] nums, int start, List path, List> result) {\n result.add(new ArrayList<>(path));\n for (int i = start; i < nums.length; i++) {\n path.add(nums[i]);\n backtrack(nums, i + 1, path, result);\n path.remove(path.size() - 1);\n }\n}", "solution_cpp": "vector> subsets(vector& nums) {\n vector> result;\n vector path;\n backtrack(nums, 0, path, result);\n return result;\n}\nvoid backtrack(vector& nums, int start, vector& path, vector>& result) {\n result.push_back(path);\n for (int i = start; i < nums.size(); i++) {\n path.push_back(nums[i]);\n backtrack(nums, i + 1, path, result);\n path.pop_back();\n }\n}", "test_cases": ["nums=[1,2,3] -> [[],[1],[2],[1,2],[3],[1,3],[2,3],[1,2,3]]"], "key_points": ["选或不选", "DFS遍历子集树"], "tags": ["backtracking", "medium", "Google", "Microsoft"]} {"problem_id": "algo_01554", "original_id": "permutations", "title": "全排列", "category": "backtracking", "difficulty": "medium", "companies": ["Google", "Facebook"], "description": "给定一个不含重复数字的数组 nums,返回其所有可能的全排列。", "solution_python": "def permute(nums):\n result = []\n def backtrack(path, used):\n if len(path) == len(nums):\n result.append(path[:])\n return\n for i in range(len(nums)):\n if used[i]: continue\n used[i] = True\n path.append(nums[i])\n backtrack(path, used)\n path.pop()\n used[i] = False\n backtrack([], [False]*len(nums))\n return result", "solution_java": "public List> permute(int[] nums) {\n List> result = new ArrayList<>();\n boolean[] used = new boolean[nums.length];\n backtrack(nums, used, new ArrayList<>(), result);\n return result;\n}\nprivate void backtrack(int[] nums, boolean[] used, List path, List> result) {\n if (path.size() == nums.length) { result.add(new ArrayList<>(path)); return; }\n for (int i = 0; i < nums.length; i++) {\n if (used[i]) continue;\n used[i] = true;\n path.add(nums[i]);\n backtrack(nums, used, path, result);\n path.remove(path.size() - 1);\n used[i] = false;\n }\n}", "solution_cpp": "vector> permute(vector& nums) {\n vector> result;\n vector used(nums.size(), false);\n vector path;\n backtrack(nums, used, path, result);\n return result;\n}\nvoid backtrack(vector& nums, vector& used, vector& path, vector>& result) {\n if (path.size() == nums.size()) { result.push_back(path); return; }\n for (int i = 0; i < nums.size(); i++) {\n if (used[i]) continue;\n used[i] = true;\n path.push_back(nums[i]);\n backtrack(nums, used, path, result);\n path.pop_back();\n used[i] = false;\n }\n}", "test_cases": ["nums=[1,2,3] -> [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]"], "key_points": ["标记已使用元素", "回溯经典模板"], "tags": ["backtracking", "medium", "Google", "Facebook"]} {"problem_id": "algo_01555", "original_id": "top-k-frequent", "title": "前K个高频元素", "category": "heap", "difficulty": "medium", "companies": ["Amazon", "Facebook"], "description": "给你一个整数数组 nums 和一个整数 k,请你返回其中出现频率前 k 高的元素。", "solution_python": "import heapq\nfrom collections import Counter\ndef topKFrequent(nums, k):\n count = Counter(nums)\n heap = []\n for num, freq in count.items():\n heapq.heappush(heap, (freq, num))\n if len(heap) > k: heapq.heappop(heap)\n return [num for freq, num in heap]", "solution_java": "public int[] topKFrequent(int[] nums, int k) {\n Map count = new HashMap<>();\n for (int n : nums) count.put(n, count.getOrDefault(n, 0) + 1);\n PriorityQueue> heap = \n new PriorityQueue<>((a, b) -> a.getValue() - b.getValue());\n for (Map.Entry e : count.entrySet()) {\n heap.offer(e);\n if (heap.size() > k) heap.poll();\n }\n int[] res = new int[k];\n for (int i = k - 1; i >= 0; i--) res[i] = heap.poll().getKey();\n return res;\n}", "solution_cpp": "vector topKFrequent(vector& nums, int k) {\n unordered_map count;\n for (int n : nums) count[n]++;\n priority_queue, vector>, greater>> heap;\n for (auto& [num, freq] : count) {\n heap.push({freq, num});\n if (heap.size() > k) heap.pop();\n }\n vector res;\n while (!heap.empty()) { res.push_back(heap.top().second); heap.pop(); }\n reverse(res.begin(), res.end());\n return res;\n}", "test_cases": ["nums=[1,1,1,2,2,3], k=2 -> [1,2]", "nums=[1], k=1 -> [1]"], "key_points": ["小顶堆保持大小k", "时间复杂度O(nlogk)"], "tags": ["heap", "medium", "Amazon", "Facebook"]} {"problem_id": "algo_01556", "original_id": "3sum", "title": "三数之和", "category": "two-pointers", "difficulty": "medium", "companies": ["Google", "Amazon"], "description": "给你一个整数数组 nums,判断是否存在三元组满足和为0,返回所有不重复的三元组。", "solution_python": "def threeSum(nums):\n nums.sort()\n result = []\n for i in range(len(nums) - 2):\n if i > 0 and nums[i] == nums[i-1]: continue\n left, right = i + 1, len(nums) - 1\n while left < right:\n total = nums[i] + nums[left] + nums[right]\n if total < 0: left += 1\n elif total > 0: right -= 1\n else:\n result.append([nums[i], nums[left], nums[right]])\n while left < right and nums[left] == nums[left+1]: left += 1\n while left < right and nums[right] == nums[right-1]: right -= 1\n left += 1; right -= 1\n return result", "solution_java": "public List> threeSum(int[] nums) {\n Arrays.sort(nums);\n List> result = new ArrayList<>();\n for (int i = 0; i < nums.length - 2; i++) {\n if (i > 0 && nums[i] == nums[i-1]) continue;\n int left = i + 1, right = nums.length - 1;\n while (left < right) {\n int total = nums[i] + nums[left] + nums[right];\n if (total < 0) left++;\n else if (total > 0) right--;\n else {\n result.add(Arrays.asList(nums[i], nums[left], nums[right]));\n while (left < right && nums[left] == nums[left+1]) left++;\n while (left < right && nums[right] == nums[right-1]) right--;\n left++; right--;\n }\n }\n }\n return result;\n}", "solution_cpp": "vector> threeSum(vector& nums) {\n sort(nums.begin(), nums.end());\n vector> result;\n for (int i = 0; i < nums.size() - 2; i++) {\n if (i > 0 && nums[i] == nums[i-1]) continue;\n int left = i + 1, right = nums.size() - 1;\n while (left < right) {\n int total = nums[i] + nums[left] + nums[right];\n if (total < 0) left++;\n else if (total > 0) right--;\n else {\n result.push_back({nums[i], nums[left], nums[right]});\n while (left < right && nums[left] == nums[left+1]) left++;\n while (left < right && nums[right] == nums[right-1]) right--;\n left++; right--;\n }\n }\n }\n return result;\n}", "test_cases": ["nums=[-1,0,1,2,-1,-4] -> [[-1,-1,2],[-1,0,1]]"], "key_points": ["排序+双指针", "去重是关键"], "tags": ["two-pointers", "medium", "Google", "Amazon"]} {"problem_id": "algo_01557", "original_id": "container-water", "title": "盛最多水的容器", "category": "two-pointers", "difficulty": "medium", "companies": ["Google", "Uber"], "description": "给定一个长度为 n 的整数数组 height,找出其中的两条线,使得它们与 x 轴共同构成的容器可以容纳最多的水。", "solution_python": "def maxArea(height):\n left, right = 0, len(height) - 1\n max_area = 0\n while left < right:\n h = min(height[left], height[right])\n max_area = max(max_area, h * (right - left))\n if height[left] < height[right]: left += 1\n else: right -= 1\n return max_area", "solution_java": "public int maxArea(int[] height) {\n int left = 0, right = height.length - 1, maxArea = 0;\n while (left < right) {\n int h = Math.min(height[left], height[right]);\n maxArea = Math.max(maxArea, h * (right - left));\n if (height[left] < height[right]) left++;\n else right--;\n }\n return maxArea;\n}", "solution_cpp": "int maxArea(vector& height) {\n int left = 0, right = height.size() - 1, maxArea = 0;\n while (left < right) {\n int h = min(height[left], height[right]);\n maxArea = max(maxArea, h * (right - left));\n if (height[left] < height[right]) left++;\n else right--;\n }\n return maxArea;\n}", "test_cases": ["height=[1,8,6,2,5,4,8,3,7] -> 49"], "key_points": ["移动短边指针", "面积=min(h1,h2)*width"], "tags": ["two-pointers", "medium", "Google", "Uber"]} {"problem_id": "algo_01558", "original_id": "min-stack", "title": "最小栈", "category": "stack", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "设计一个支持 push,pop,top 操作,并能在常数时间内检索到最小元素的栈。", "solution_python": "class MinStack:\n def __init__(self):\n self.stack = []\n self.min_stack = []\n def push(self, val):\n self.stack.append(val)\n self.min_stack.append(min(val, self.min_stack[-1] if self.min_stack else val))\n def pop(self):\n self.stack.pop(); self.min_stack.pop()\n def top(self): return self.stack[-1]\n def getMin(self): return self.min_stack[-1]", "solution_java": "class MinStack {\n Stack stack = new Stack<>();\n Stack minStack = new Stack<>();\n public void push(int val) { stack.push(val); minStack.push(Math.min(val, minStack.isEmpty() ? val : minStack.peek())); }\n public void pop() { stack.pop(); minStack.pop(); }\n public int top() { return stack.peek(); }\n public int getMin() { return minStack.peek(); }\n}", "solution_cpp": "class MinStack {\n stack st, minSt;\npublic:\n void push(int val) { st.push(val); minSt.push(min(val, minSt.empty() ? val : minSt.top())); }\n void pop() { st.pop(); minSt.pop(); }\n int top() { return st.top(); }\n int getMin() { return minSt.top(); }\n};", "test_cases": ["push(-2), push(0), push(-3) -> getMin() returns -3"], "key_points": ["辅助栈记录最小值", "O(1)时间获取最小值"], "tags": ["stack", "medium", "Google", "Microsoft"]} {"problem_id": "algo_01559", "original_id": "lru-cache", "title": "LRU缓存", "category": "design", "difficulty": "hard", "companies": ["Google", "Amazon"], "description": "设计和实现一个 LRU(最近最少使用)缓存机制。", "solution_python": "class LRUCache:\n def __init__(self, capacity):\n self.capacity = capacity\n self.cache = {}\n self.order = []\n def get(self, key):\n if key not in self.cache: return -1\n self.order.remove(key); self.order.append(key)\n return self.cache[key]\n def put(self, key, value):\n if key in self.cache:\n self.order.remove(key)\n elif len(self.cache) >= self.capacity:\n del self.cache[self.order.pop(0)]\n self.cache[key] = value; self.order.append(key)", "solution_java": "class LRUCache {\n int capacity;\n LinkedHashMap cache = new LinkedHashMap<>();\n public LRUCache(int cap) { capacity = cap; }\n public int get(int key) { return cache.containsKey(key) ? cache.remove(key) : -1; }\n public void put(int key, int val) {\n if (cache.containsKey(key)) cache.remove(key);\n else if (cache.size() >= capacity) cache.remove(cache.keySet().iterator().next());\n cache.put(key, val);\n }\n}", "solution_cpp": "class LRUCache {\n int cap;\n list> dll;\n unordered_map>::iterator> cache;\npublic:\n LRUCache(int capacity) : cap(capacity) {}\n int get(int key) {\n auto it = cache.find(key);\n if (it == cache.end()) return -1;\n dll.splice(dll.end(), dll, it->second);\n return it->second->second;\n }\n void put(int key, int value) {\n auto it = cache.find(key);\n if (it != cache.end()) dll.erase(it->second);\n else if (cache.size() >= cap) { cache.erase(dll.front().first); dll.pop_front(); }\n dll.push_back({key, value});\n cache[key] = --dll.end();\n }\n};", "test_cases": ["put(1,1), put(2,2), get(1) -> 1"], "key_points": ["HashMap + 双向链表", "O(1)时间操作"], "tags": ["design", "hard", "Google", "Amazon"]} {"problem_id": "algo_01560", "original_id": "num-islands", "title": "岛屿数量", "category": "graph", "difficulty": "medium", "companies": ["Google", "Facebook"], "description": "给你一个由 '1'(陆地)和 '0'(水)组成的二维网格,请你计算网格中岛屿的数量。岛屿总是被水包围,且只能由水平或垂直方向相邻的陆地连接形成。", "solution_python": "def numIslands(grid):\n if not grid: return 0\n rows, cols = len(grid), len(grid[0])\n count = 0\n def dfs(r, c):\n if r < 0 or r >= rows or c < 0 or c >= cols or grid[r][c] != '1': return\n grid[r][c] = '0'\n dfs(r+1, c); dfs(r-1, c); dfs(r, c+1); dfs(r, c-1)\n for r in range(rows):\n for c in range(cols):\n if grid[r][c] == '1': count += 1; dfs(r, c)\n return count", "solution_java": "public int numIslands(char[][] grid) {\n if (grid.length == 0) return 0;\n int count = 0;\n for (int i = 0; i < grid.length; i++)\n for (int j = 0; j < grid[0].length; j++)\n if (grid[i][j] == '1') { count++; dfs(grid, i, j); }\n return count;\n}\nprivate void dfs(char[][] grid, int r, int c) {\n if (r < 0 || r >= grid.length || c < 0 || c >= grid[0].length || grid[r][c] != '1') return;\n grid[r][c] = '0';\n dfs(grid, r+1, c); dfs(grid, r-1, c); dfs(grid, r, c+1); dfs(grid, r, c-1);\n}", "solution_cpp": "int numIslands(vector>& grid) {\n if (grid.empty()) return 0;\n int count = 0;\n for (int i = 0; i < grid.size(); i++)\n for (int j = 0; j < grid[0].size(); j++)\n if (grid[i][j] == '1') { count++; dfs(grid, i, j); }\n return count;\n}\nvoid dfs(vector>& grid, int r, int c) {\n if (r < 0 || r >= grid.size() || c < 0 || c >= grid[0].size() || grid[r][c] != '1') return;\n grid[r][c] = '0';\n dfs(grid, r+1, c); dfs(grid, r-1, c); dfs(grid, r, c+1); dfs(grid, r, c-1);\n}", "test_cases": ["grid=[[1,1,1,1,0],[1,1,0,1,0],[1,1,0,0,0],[0,0,0,0,0]] -> 1"], "key_points": ["DFS/BFS遍历", "访问后标记为0避免重复"], "tags": ["graph", "medium", "Google", "Facebook"]} {"problem_id": "algo_01561", "original_id": "two-sum", "title": "两数之和", "category": "array", "difficulty": "easy", "companies": ["Amazon", "Google"], "description": "给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那两个整数,并返回他们的数组下标。", "solution_python": "def twoSum(nums, target):\n hashmap = {}\n for i, num in enumerate(nums):\n complement = target - num\n if complement in hashmap:\n return [hashmap[complement], i]\n hashmap[num] = i\n return []", "solution_java": "public int[] twoSum(int[] nums, int target) {\n Map map = new HashMap<>();\n for (int i = 0; i < nums.length; i++) {\n int complement = target - nums[i];\n if (map.containsKey(complement)) return new int[]{map.get(complement), i};\n map.put(nums[i], i);\n }\n return new int[]{};\n}", "solution_cpp": "vector twoSum(vector& nums, int target) {\n unordered_map m;\n for (int i = 0; i < nums.size(); i++) {\n if (m.count(target - nums[i])) return {m[target - nums[i]], i};\n m[nums[i]] = i;\n }\n return {};\n}", "test_cases": ["nums=[2,7,11,15], target=9 -> [0,1]", "nums=[3,2,4], target=6 -> [1,2]"], "key_points": ["哈希表一次遍历", "空间换时间"], "tags": ["array", "easy", "Amazon", "Google"]} {"problem_id": "algo_01562", "original_id": "merge-sorted", "title": "合并两个有序数组", "category": "array", "difficulty": "easy", "companies": ["Microsoft", "Uber"], "description": "给你两个按非递减顺序排列的整数数组 nums1 和 nums2,另有两个整数 m 和 n,分别表示 nums1 和 nums2 中的元素数目。请你合并 nums2 到 nums1 中。", "solution_python": "def merge(nums1, m, nums2, n):\n p1, p2, p = m-1, n-1, m+n-1\n while p1 >= 0 and p2 >= 0:\n if nums1[p1] > nums2[p2]: nums1[p] = nums1[p1]; p1 -= 1\n else: nums1[p] = nums2[p2]; p2 -= 1\n p -= 1\n while p2 >= 0: nums1[p] = nums2[p2]; p2 -= 1; p -= 1", "solution_java": "public void merge(int[] nums1, int m, int[] nums2, int n) {\n int p1 = m-1, p2 = n-1, p = m+n-1;\n while (p1 >= 0 && p2 >= 0) {\n nums1[p--] = nums1[p1] > nums2[p2] ? nums1[p1--] : nums2[p2--];\n }\n while (p2 >= 0) nums1[p--] = nums2[p2--];\n}", "solution_cpp": "void merge(vector& nums1, int m, vector& nums2, int n) {\n int p1 = m-1, p2 = n-1, p = m+n-1;\n while (p1 >= 0 && p2 >= 0) nums1[p--] = nums1[p1] > nums2[p2] ? nums1[p1--] : nums2[p2--];\n while (p2 >= 0) nums1[p--] = nums2[p2--];\n}", "test_cases": ["nums1=[1,2,3], m=3, nums2=[2,5,6], n=3 -> [1,2,2,3,5,6]", "nums1=[], m=0, nums2=[1], n=1 -> [1]"], "key_points": ["从后往前合并", "三指针技巧"], "tags": ["array", "easy", "Microsoft", "Uber"]} {"problem_id": "algo_01563", "original_id": "max-subarray", "title": "最大子数组和", "category": "array", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "给你一个整数数组 nums ,请你找出一个具有最大和的连续子数组,返回其最大和。", "solution_python": "def maxSubArray(nums):\n max_sum = current = nums[0]\n for num in nums[1:]:\n current = max(num, current + num)\n max_sum = max(max_sum, current)\n return max_sum", "solution_java": "public int maxSubArray(int[] nums) {\n int maxSum = nums[0], curr = nums[0];\n for (int i = 1; i < nums.length; i++) {\n curr = Math.max(nums[i], curr + nums[i]);\n maxSum = Math.max(maxSum, curr);\n }\n return maxSum;\n}", "solution_cpp": "int maxSubArray(vector& nums) {\n int maxSum = nums[0], curr = nums[0];\n for (int i = 1; i < nums.size(); i++) {\n curr = max(nums[i], curr + nums[i]);\n maxSum = max(maxSum, curr);\n }\n return maxSum;\n}", "test_cases": ["nums=[-2,1,-3,4,-1,2,1,-5,4] -> 6", "nums=[1] -> 1"], "key_points": ["Kadane算法", "动态规划基础题"], "tags": ["array", "medium", "Google", "Microsoft"]} {"problem_id": "algo_01564", "original_id": "valid-parentheses", "title": "有效的括号", "category": "string", "difficulty": "easy", "companies": ["Google", "Uber"], "description": "给定一个只包括 '(',')','{','}','[',']' 的字符串 s,判断字符串是否有效。", "solution_python": "def isValid(s):\n stack = []\n mapping = {')': '(', ']': '[', '}': '{'}\n for c in s:\n if c in mapping:\n if not stack or stack[-1] != mapping[c]: return False\n stack.pop()\n else: stack.append(c)\n return not stack", "solution_java": "public boolean isValid(String s) {\n Stack stack = new Stack<>();\n Map map = Map.of(')', '(', ']', '[', '}', '{');\n for (char c : s.toCharArray()) {\n if (map.containsValue(c)) stack.push(c);\n else if (!stack.isEmpty() && stack.pop() != map.get(c)) return false;\n }\n return stack.isEmpty();\n}", "solution_cpp": "bool isValid(string s) {\n stack st;\n unordered_map m = {{')','('},{']','['},{'}','{'}};\n for (char c : s) {\n if (m.find(c) == m.end()) st.push(c);\n else if (st.empty() || st.top() != m[c]) return false;\n else st.pop();\n }\n return st.empty();\n}", "test_cases": ["s=\"()\" -> true", "s=\"()[]{}\" -> true", "s=\"(]\" -> false"], "key_points": ["栈匹配法", "注意空栈边界"], "tags": ["string", "easy", "Google", "Uber"]} {"problem_id": "algo_01565", "original_id": "longest-palindrome", "title": "最长回文子串", "category": "string", "difficulty": "medium", "companies": ["Google", "Amazon"], "description": "给你一个字符串 s,找到 s 中最长的回文子串。", "solution_python": "def longestPalindrome(s):\n def expand(l, r):\n while l >= 0 and r < len(s) and s[l] == s[r]: l -= 1; r += 1\n return l + 1, r - 1\n start = end = 0\n for i in range(len(s)):\n l1, r1 = expand(i, i)\n l2, r2 = expand(i, i + 1)\n if r1 - l1 > end - start: start, end = l1, r1\n if r2 - l2 > end - start: start, end = l2, r2\n return s[start:end+1]", "solution_java": "public String longestPalindrome(String s) {\n int start = 0, end = 0;\n for (int i = 0; i < s.length(); i++) {\n int len1 = expand(s, i, i), len2 = expand(s, i, i+1);\n int len = Math.max(len1, len2);\n if (len > end - start) { start = i - (len-1)/2; end = i + len/2; }\n }\n return s.substring(start, end + 1);\n}\nprivate int expand(String s, int l, int r) {\n while (l >= 0 && r < s.length() && s.charAt(l) == s.charAt(r)) { l--; r++; }\n return r - l - 1;\n}", "solution_cpp": "string longestPalindrome(string s) {\n int start = 0, end = 0;\n for (int i = 0; i < s.size(); i++) {\n int len1 = expand(s, i, i), len2 = expand(s, i, i+1);\n if (max(len1, len2) > end - start) { start = i - (max(len1,len2)-1)/2; end = i + max(len1,len2)/2; }\n }\n return s.substr(start, end - start + 1);\n}", "test_cases": ["s=\"babad\" -> bab或aba", "s=\"cbbd\" -> bb"], "key_points": ["中心扩展法", "处理奇偶长度"], "tags": ["string", "medium", "Google", "Amazon"]} {"problem_id": "algo_01566", "original_id": "reverse-list", "title": "反转链表", "category": "linkedlist", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "给你单链表的头节点 head,请你反转链表,并返回反转后的链表。", "solution_python": "def reverseList(head):\n prev = None\n curr = head\n while curr:\n nxt = curr.next\n curr.next = prev\n prev = curr\n curr = nxt\n return prev", "solution_java": "public ListNode reverseList(ListNode head) {\n ListNode prev = null, curr = head;\n while (curr != null) {\n ListNode next = curr.next;\n curr.next = prev;\n prev = curr;\n curr = next;\n }\n return prev;\n}", "solution_cpp": "ListNode* reverseList(ListNode* head) {\n ListNode* prev = nullptr, *curr = head;\n while (curr) {\n ListNode* next = curr->next;\n curr->next = prev;\n prev = curr;\n curr = next;\n }\n return prev;\n}", "test_cases": ["head=[1,2,3,4,5] -> [5,4,3,2,1]", "head=[1,2] -> [2,1]"], "key_points": ["迭代法 O(1)空间", "递归法 O(n)空间"], "tags": ["linkedlist", "medium", "Google", "Microsoft"]} {"problem_id": "algo_01567", "original_id": "middle-node", "title": "链表的中间结点", "category": "linkedlist", "difficulty": "easy", "companies": ["Amazon", "Facebook"], "description": "给你单链表的头节点 head,请你找出并返回链表的中间结点。如果有两个中间结点,则返回第二个中间结点。", "solution_python": "def middleNode(head):\n slow = fast = head\n while fast and fast.next:\n slow = slow.next\n fast = fast.next.next\n return slow", "solution_java": "public ListNode middleNode(ListNode head) {\n ListNode slow = head, fast = head;\n while (fast != null && fast.next != null) {\n slow = slow.next;\n fast = fast.next.next;\n }\n return slow;\n}", "solution_cpp": "ListNode* middleNode(ListNode* head) {\n ListNode* slow = head, *fast = head;\n while (fast && fast->next) { slow = slow->next; fast = fast->next->next; }\n return slow;\n}", "test_cases": ["head=[1,2,3,4,5] -> 3", "head=[1,2,3,4,5,6] -> 4"], "key_points": ["快慢指针", "O(n)时间O(1)空间"], "tags": ["linkedlist", "easy", "Amazon", "Facebook"]} {"problem_id": "algo_01568", "original_id": "max-depth", "title": "二叉树的最大深度", "category": "tree", "difficulty": "easy", "companies": ["Microsoft", "Apple"], "description": "给定一个二叉树 root,返回其最大深度。", "solution_python": "def maxDepth(root):\n if not root: return 0\n return max(maxDepth(root.left), maxDepth(root.right)) + 1", "solution_java": "public int maxDepth(TreeNode root) {\n if (root == null) return 0;\n return Math.max(maxDepth(root.left), maxDepth(root.right)) + 1;\n}", "solution_cpp": "int maxDepth(TreeNode* root) {\n if (!root) return 0;\n return max(maxDepth(root->left), maxDepth(root->right)) + 1;\n}", "test_cases": ["root=[3,9,20,null,null,15,7] -> 3", "root=[1,null,2] -> 2"], "key_points": ["DFS递归", "层序遍历也可"], "tags": ["tree", "easy", "Microsoft", "Apple"]} {"problem_id": "algo_01569", "original_id": "inorder-traversal", "title": "二叉树的中序遍历", "category": "tree", "difficulty": "easy", "companies": ["Google", "Microsoft"], "description": "给定一个二叉树的根节点 root,返回它的中序遍历结果。", "solution_python": "def inorderTraversal(root):\n result = []\n def dfs(node):\n if node:\n dfs(node.left)\n result.append(node.val)\n dfs(node.right)\n dfs(root)\n return result", "solution_java": "public List inorderTraversal(TreeNode root) {\n List res = new ArrayList<>();\n dfs(root, res);\n return res;\n}\nprivate void dfs(TreeNode node, List res) {\n if (node == null) return;\n dfs(node.left, res); res.add(node.val); dfs(node.right, res);\n}", "solution_cpp": "vector inorderTraversal(TreeNode* root) {\n vector res;\n dfs(root, res);\n return res;\n}\nvoid dfs(TreeNode* node, vector& res) {\n if (!node) return;\n dfs(node->left, res); res.push_back(node->val); dfs(node->right, res);\n}", "test_cases": ["root=[1,null,2,3] -> [1,3,2]", "root=[] -> []"], "key_points": ["左-根-右顺序", "递归最简洁"], "tags": ["tree", "easy", "Google", "Microsoft"]} {"problem_id": "algo_01570", "original_id": "binary-search", "title": "二分查找", "category": "binarysearch", "difficulty": "easy", "companies": ["Google", "Amazon"], "description": "给定一个 n 个元素有序的(升序)整型数组 nums 和一个目标值 target,写一个函数搜索 nums 中的 target,如果目标值存在返回下标,否则返回 -1。", "solution_python": "def search(nums, target):\n left, right = 0, len(nums) - 1\n while left <= right:\n mid = (left + right) // 2\n if nums[mid] == target: return mid\n elif nums[mid] < target: left = mid + 1\n else: right = mid - 1\n return -1", "solution_java": "public int search(int[] nums, int target) {\n int left = 0, right = nums.length - 1;\n while (left <= right) {\n int mid = left + (right - left) / 2;\n if (nums[mid] == target) return mid;\n else if (nums[mid] < target) left = mid + 1;\n else right = mid - 1;\n }\n return -1;\n}", "solution_cpp": "int search(vector& nums, int target) {\n int left = 0, right = nums.size() - 1;\n while (left <= right) {\n int mid = left + (right - left) / 2;\n if (nums[mid] == target) return mid;\n else if (nums[mid] < target) left = mid + 1;\n else right = mid - 1;\n }\n return -1;\n}", "test_cases": ["nums=[-1,0,3,5,9,12], target=9 -> 4", "nums=[-1,0,3,5,9,12], target=2 -> -1"], "key_points": ["标准模板", "注意防溢出写法"], "tags": ["binarysearch", "easy", "Google", "Amazon"]} {"problem_id": "algo_01571", "original_id": "climbing-stairs", "title": "爬楼梯", "category": "dp", "difficulty": "easy", "companies": ["Amazon", "Google"], "description": "假设你正在爬楼梯。需要 n 阶你才能到达楼顶。每次你可以爬 1 或 2 个台阶。你有多少种不同的方法可以爬到楼顶?", "solution_python": "def climbStairs(n):\n if n <= 2: return n\n a, b = 1, 2\n for _ in range(3, n+1):\n a, b = b, a + b\n return b", "solution_java": "public int climbStairs(int n) {\n if (n <= 2) return n;\n int a = 1, b = 2;\n for (int i = 3; i <= n; i++) { int temp = a + b; a = b; b = temp; }\n return b;\n}", "solution_cpp": "int climbStairs(int n) {\n if (n <= 2) return n;\n int a = 1, b = 2;\n for (int i = 3; i <= n; i++) { int temp = a + b; a = b; b = temp; }\n return b;\n}", "test_cases": ["n=2 -> 2", "n=3 -> 3", "n=5 -> 8"], "key_points": ["斐波那契数列", "滚动数组优化空间"], "tags": ["dp", "easy", "Amazon", "Google"]} {"problem_id": "algo_01572", "original_id": "coin-change", "title": "零钱兑换", "category": "dp", "difficulty": "medium", "companies": ["Google", "Amazon"], "description": "给你一个整数数组 coins 表示不同面额的硬币,以及一个整数 amount 表示总金额。计算并返回可以凑成总金额所需的最少的硬币个数。如果没有任何一种硬币组合能组成总金额,返回 -1。", "solution_python": "def coinChange(coins, amount):\n dp = [float('inf')] * (amount + 1)\n dp[0] = 0\n for coin in coins:\n for x in range(coin, amount + 1):\n dp[x] = min(dp[x], dp[x - coin] + 1)\n return dp[amount] if dp[amount] != float('inf') else -1", "solution_java": "public int coinChange(int[] coins, int amount) {\n int[] dp = new int[amount + 1];\n Arrays.fill(dp, amount + 1);\n dp[0] = 0;\n for (int coin : coins) {\n for (int x = coin; x <= amount; x++) {\n dp[x] = Math.min(dp[x], dp[x - coin] + 1);\n }\n }\n return dp[amount] > amount ? -1 : dp[amount];\n}", "solution_cpp": "int coinChange(vector& coins, int amount) {\n vector dp(amount + 1, amount + 1);\n dp[0] = 0;\n for (int coin : coins) {\n for (int x = coin; x <= amount; x++) {\n dp[x] = min(dp[x], dp[x - coin] + 1);\n }\n }\n return dp[amount] > amount ? -1 : dp[amount];\n}", "test_cases": ["coins=[1,2,5], amount=11 -> 3", "coins=[2], amount=3 -> -1"], "key_points": ["完全背包问题", "dp[x] = min(dp[x-coin]+1)"], "tags": ["dp", "medium", "Google", "Amazon"]} {"problem_id": "algo_01573", "original_id": "subsets", "title": "子集", "category": "backtracking", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "给你一个整数数组 nums ,数组中的元素 互不相同 。返回该数组所有可能的子集(幂集)。", "solution_python": "def subsets(nums):\n result = []\n def backtrack(start, path):\n result.append(path[:])\n for i in range(start, len(nums)):\n path.append(nums[i])\n backtrack(i + 1, path)\n path.pop()\n backtrack(0, [])\n return result", "solution_java": "public List> subsets(int[] nums) {\n List> result = new ArrayList<>();\n backtrack(nums, 0, new ArrayList<>(), result);\n return result;\n}\nprivate void backtrack(int[] nums, int start, List path, List> result) {\n result.add(new ArrayList<>(path));\n for (int i = start; i < nums.length; i++) {\n path.add(nums[i]);\n backtrack(nums, i + 1, path, result);\n path.remove(path.size() - 1);\n }\n}", "solution_cpp": "vector> subsets(vector& nums) {\n vector> result;\n vector path;\n backtrack(nums, 0, path, result);\n return result;\n}\nvoid backtrack(vector& nums, int start, vector& path, vector>& result) {\n result.push_back(path);\n for (int i = start; i < nums.size(); i++) {\n path.push_back(nums[i]);\n backtrack(nums, i + 1, path, result);\n path.pop_back();\n }\n}", "test_cases": ["nums=[1,2,3] -> [[],[1],[2],[1,2],[3],[1,3],[2,3],[1,2,3]]"], "key_points": ["选或不选", "DFS遍历子集树"], "tags": ["backtracking", "medium", "Google", "Microsoft"]} {"problem_id": "algo_01574", "original_id": "permutations", "title": "全排列", "category": "backtracking", "difficulty": "medium", "companies": ["Google", "Facebook"], "description": "给定一个不含重复数字的数组 nums,返回其所有可能的全排列。", "solution_python": "def permute(nums):\n result = []\n def backtrack(path, used):\n if len(path) == len(nums):\n result.append(path[:])\n return\n for i in range(len(nums)):\n if used[i]: continue\n used[i] = True\n path.append(nums[i])\n backtrack(path, used)\n path.pop()\n used[i] = False\n backtrack([], [False]*len(nums))\n return result", "solution_java": "public List> permute(int[] nums) {\n List> result = new ArrayList<>();\n boolean[] used = new boolean[nums.length];\n backtrack(nums, used, new ArrayList<>(), result);\n return result;\n}\nprivate void backtrack(int[] nums, boolean[] used, List path, List> result) {\n if (path.size() == nums.length) { result.add(new ArrayList<>(path)); return; }\n for (int i = 0; i < nums.length; i++) {\n if (used[i]) continue;\n used[i] = true;\n path.add(nums[i]);\n backtrack(nums, used, path, result);\n path.remove(path.size() - 1);\n used[i] = false;\n }\n}", "solution_cpp": "vector> permute(vector& nums) {\n vector> result;\n vector used(nums.size(), false);\n vector path;\n backtrack(nums, used, path, result);\n return result;\n}\nvoid backtrack(vector& nums, vector& used, vector& path, vector>& result) {\n if (path.size() == nums.size()) { result.push_back(path); return; }\n for (int i = 0; i < nums.size(); i++) {\n if (used[i]) continue;\n used[i] = true;\n path.push_back(nums[i]);\n backtrack(nums, used, path, result);\n path.pop_back();\n used[i] = false;\n }\n}", "test_cases": ["nums=[1,2,3] -> [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]"], "key_points": ["标记已使用元素", "回溯经典模板"], "tags": ["backtracking", "medium", "Google", "Facebook"]} {"problem_id": "algo_01575", "original_id": "top-k-frequent", "title": "前K个高频元素", "category": "heap", "difficulty": "medium", "companies": ["Amazon", "Facebook"], "description": "给你一个整数数组 nums 和一个整数 k,请你返回其中出现频率前 k 高的元素。", "solution_python": "import heapq\nfrom collections import Counter\ndef topKFrequent(nums, k):\n count = Counter(nums)\n heap = []\n for num, freq in count.items():\n heapq.heappush(heap, (freq, num))\n if len(heap) > k: heapq.heappop(heap)\n return [num for freq, num in heap]", "solution_java": "public int[] topKFrequent(int[] nums, int k) {\n Map count = new HashMap<>();\n for (int n : nums) count.put(n, count.getOrDefault(n, 0) + 1);\n PriorityQueue> heap = \n new PriorityQueue<>((a, b) -> a.getValue() - b.getValue());\n for (Map.Entry e : count.entrySet()) {\n heap.offer(e);\n if (heap.size() > k) heap.poll();\n }\n int[] res = new int[k];\n for (int i = k - 1; i >= 0; i--) res[i] = heap.poll().getKey();\n return res;\n}", "solution_cpp": "vector topKFrequent(vector& nums, int k) {\n unordered_map count;\n for (int n : nums) count[n]++;\n priority_queue, vector>, greater>> heap;\n for (auto& [num, freq] : count) {\n heap.push({freq, num});\n if (heap.size() > k) heap.pop();\n }\n vector res;\n while (!heap.empty()) { res.push_back(heap.top().second); heap.pop(); }\n reverse(res.begin(), res.end());\n return res;\n}", "test_cases": ["nums=[1,1,1,2,2,3], k=2 -> [1,2]", "nums=[1], k=1 -> [1]"], "key_points": ["小顶堆保持大小k", "时间复杂度O(nlogk)"], "tags": ["heap", "medium", "Amazon", "Facebook"]} {"problem_id": "algo_01576", "original_id": "3sum", "title": "三数之和", "category": "two-pointers", "difficulty": "medium", "companies": ["Google", "Amazon"], "description": "给你一个整数数组 nums,判断是否存在三元组满足和为0,返回所有不重复的三元组。", "solution_python": "def threeSum(nums):\n nums.sort()\n result = []\n for i in range(len(nums) - 2):\n if i > 0 and nums[i] == nums[i-1]: continue\n left, right = i + 1, len(nums) - 1\n while left < right:\n total = nums[i] + nums[left] + nums[right]\n if total < 0: left += 1\n elif total > 0: right -= 1\n else:\n result.append([nums[i], nums[left], nums[right]])\n while left < right and nums[left] == nums[left+1]: left += 1\n while left < right and nums[right] == nums[right-1]: right -= 1\n left += 1; right -= 1\n return result", "solution_java": "public List> threeSum(int[] nums) {\n Arrays.sort(nums);\n List> result = new ArrayList<>();\n for (int i = 0; i < nums.length - 2; i++) {\n if (i > 0 && nums[i] == nums[i-1]) continue;\n int left = i + 1, right = nums.length - 1;\n while (left < right) {\n int total = nums[i] + nums[left] + nums[right];\n if (total < 0) left++;\n else if (total > 0) right--;\n else {\n result.add(Arrays.asList(nums[i], nums[left], nums[right]));\n while (left < right && nums[left] == nums[left+1]) left++;\n while (left < right && nums[right] == nums[right-1]) right--;\n left++; right--;\n }\n }\n }\n return result;\n}", "solution_cpp": "vector> threeSum(vector& nums) {\n sort(nums.begin(), nums.end());\n vector> result;\n for (int i = 0; i < nums.size() - 2; i++) {\n if (i > 0 && nums[i] == nums[i-1]) continue;\n int left = i + 1, right = nums.size() - 1;\n while (left < right) {\n int total = nums[i] + nums[left] + nums[right];\n if (total < 0) left++;\n else if (total > 0) right--;\n else {\n result.push_back({nums[i], nums[left], nums[right]});\n while (left < right && nums[left] == nums[left+1]) left++;\n while (left < right && nums[right] == nums[right-1]) right--;\n left++; right--;\n }\n }\n }\n return result;\n}", "test_cases": ["nums=[-1,0,1,2,-1,-4] -> [[-1,-1,2],[-1,0,1]]"], "key_points": ["排序+双指针", "去重是关键"], "tags": ["two-pointers", "medium", "Google", "Amazon"]} {"problem_id": "algo_01577", "original_id": "container-water", "title": "盛最多水的容器", "category": "two-pointers", "difficulty": "medium", "companies": ["Google", "Uber"], "description": "给定一个长度为 n 的整数数组 height,找出其中的两条线,使得它们与 x 轴共同构成的容器可以容纳最多的水。", "solution_python": "def maxArea(height):\n left, right = 0, len(height) - 1\n max_area = 0\n while left < right:\n h = min(height[left], height[right])\n max_area = max(max_area, h * (right - left))\n if height[left] < height[right]: left += 1\n else: right -= 1\n return max_area", "solution_java": "public int maxArea(int[] height) {\n int left = 0, right = height.length - 1, maxArea = 0;\n while (left < right) {\n int h = Math.min(height[left], height[right]);\n maxArea = Math.max(maxArea, h * (right - left));\n if (height[left] < height[right]) left++;\n else right--;\n }\n return maxArea;\n}", "solution_cpp": "int maxArea(vector& height) {\n int left = 0, right = height.size() - 1, maxArea = 0;\n while (left < right) {\n int h = min(height[left], height[right]);\n maxArea = max(maxArea, h * (right - left));\n if (height[left] < height[right]) left++;\n else right--;\n }\n return maxArea;\n}", "test_cases": ["height=[1,8,6,2,5,4,8,3,7] -> 49"], "key_points": ["移动短边指针", "面积=min(h1,h2)*width"], "tags": ["two-pointers", "medium", "Google", "Uber"]} {"problem_id": "algo_01578", "original_id": "min-stack", "title": "最小栈", "category": "stack", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "设计一个支持 push,pop,top 操作,并能在常数时间内检索到最小元素的栈。", "solution_python": "class MinStack:\n def __init__(self):\n self.stack = []\n self.min_stack = []\n def push(self, val):\n self.stack.append(val)\n self.min_stack.append(min(val, self.min_stack[-1] if self.min_stack else val))\n def pop(self):\n self.stack.pop(); self.min_stack.pop()\n def top(self): return self.stack[-1]\n def getMin(self): return self.min_stack[-1]", "solution_java": "class MinStack {\n Stack stack = new Stack<>();\n Stack minStack = new Stack<>();\n public void push(int val) { stack.push(val); minStack.push(Math.min(val, minStack.isEmpty() ? val : minStack.peek())); }\n public void pop() { stack.pop(); minStack.pop(); }\n public int top() { return stack.peek(); }\n public int getMin() { return minStack.peek(); }\n}", "solution_cpp": "class MinStack {\n stack st, minSt;\npublic:\n void push(int val) { st.push(val); minSt.push(min(val, minSt.empty() ? val : minSt.top())); }\n void pop() { st.pop(); minSt.pop(); }\n int top() { return st.top(); }\n int getMin() { return minSt.top(); }\n};", "test_cases": ["push(-2), push(0), push(-3) -> getMin() returns -3"], "key_points": ["辅助栈记录最小值", "O(1)时间获取最小值"], "tags": ["stack", "medium", "Google", "Microsoft"]} {"problem_id": "algo_01579", "original_id": "lru-cache", "title": "LRU缓存", "category": "design", "difficulty": "hard", "companies": ["Google", "Amazon"], "description": "设计和实现一个 LRU(最近最少使用)缓存机制。", "solution_python": "class LRUCache:\n def __init__(self, capacity):\n self.capacity = capacity\n self.cache = {}\n self.order = []\n def get(self, key):\n if key not in self.cache: return -1\n self.order.remove(key); self.order.append(key)\n return self.cache[key]\n def put(self, key, value):\n if key in self.cache:\n self.order.remove(key)\n elif len(self.cache) >= self.capacity:\n del self.cache[self.order.pop(0)]\n self.cache[key] = value; self.order.append(key)", "solution_java": "class LRUCache {\n int capacity;\n LinkedHashMap cache = new LinkedHashMap<>();\n public LRUCache(int cap) { capacity = cap; }\n public int get(int key) { return cache.containsKey(key) ? cache.remove(key) : -1; }\n public void put(int key, int val) {\n if (cache.containsKey(key)) cache.remove(key);\n else if (cache.size() >= capacity) cache.remove(cache.keySet().iterator().next());\n cache.put(key, val);\n }\n}", "solution_cpp": "class LRUCache {\n int cap;\n list> dll;\n unordered_map>::iterator> cache;\npublic:\n LRUCache(int capacity) : cap(capacity) {}\n int get(int key) {\n auto it = cache.find(key);\n if (it == cache.end()) return -1;\n dll.splice(dll.end(), dll, it->second);\n return it->second->second;\n }\n void put(int key, int value) {\n auto it = cache.find(key);\n if (it != cache.end()) dll.erase(it->second);\n else if (cache.size() >= cap) { cache.erase(dll.front().first); dll.pop_front(); }\n dll.push_back({key, value});\n cache[key] = --dll.end();\n }\n};", "test_cases": ["put(1,1), put(2,2), get(1) -> 1"], "key_points": ["HashMap + 双向链表", "O(1)时间操作"], "tags": ["design", "hard", "Google", "Amazon"]} {"problem_id": "algo_01580", "original_id": "num-islands", "title": "岛屿数量", "category": "graph", "difficulty": "medium", "companies": ["Google", "Facebook"], "description": "给你一个由 '1'(陆地)和 '0'(水)组成的二维网格,请你计算网格中岛屿的数量。岛屿总是被水包围,且只能由水平或垂直方向相邻的陆地连接形成。", "solution_python": "def numIslands(grid):\n if not grid: return 0\n rows, cols = len(grid), len(grid[0])\n count = 0\n def dfs(r, c):\n if r < 0 or r >= rows or c < 0 or c >= cols or grid[r][c] != '1': return\n grid[r][c] = '0'\n dfs(r+1, c); dfs(r-1, c); dfs(r, c+1); dfs(r, c-1)\n for r in range(rows):\n for c in range(cols):\n if grid[r][c] == '1': count += 1; dfs(r, c)\n return count", "solution_java": "public int numIslands(char[][] grid) {\n if (grid.length == 0) return 0;\n int count = 0;\n for (int i = 0; i < grid.length; i++)\n for (int j = 0; j < grid[0].length; j++)\n if (grid[i][j] == '1') { count++; dfs(grid, i, j); }\n return count;\n}\nprivate void dfs(char[][] grid, int r, int c) {\n if (r < 0 || r >= grid.length || c < 0 || c >= grid[0].length || grid[r][c] != '1') return;\n grid[r][c] = '0';\n dfs(grid, r+1, c); dfs(grid, r-1, c); dfs(grid, r, c+1); dfs(grid, r, c-1);\n}", "solution_cpp": "int numIslands(vector>& grid) {\n if (grid.empty()) return 0;\n int count = 0;\n for (int i = 0; i < grid.size(); i++)\n for (int j = 0; j < grid[0].size(); j++)\n if (grid[i][j] == '1') { count++; dfs(grid, i, j); }\n return count;\n}\nvoid dfs(vector>& grid, int r, int c) {\n if (r < 0 || r >= grid.size() || c < 0 || c >= grid[0].size() || grid[r][c] != '1') return;\n grid[r][c] = '0';\n dfs(grid, r+1, c); dfs(grid, r-1, c); dfs(grid, r, c+1); dfs(grid, r, c-1);\n}", "test_cases": ["grid=[[1,1,1,1,0],[1,1,0,1,0],[1,1,0,0,0],[0,0,0,0,0]] -> 1"], "key_points": ["DFS/BFS遍历", "访问后标记为0避免重复"], "tags": ["graph", "medium", "Google", "Facebook"]} {"problem_id": "algo_01581", "original_id": "two-sum", "title": "两数之和", "category": "array", "difficulty": "easy", "companies": ["Amazon", "Google"], "description": "给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那两个整数,并返回他们的数组下标。", "solution_python": "def twoSum(nums, target):\n hashmap = {}\n for i, num in enumerate(nums):\n complement = target - num\n if complement in hashmap:\n return [hashmap[complement], i]\n hashmap[num] = i\n return []", "solution_java": "public int[] twoSum(int[] nums, int target) {\n Map map = new HashMap<>();\n for (int i = 0; i < nums.length; i++) {\n int complement = target - nums[i];\n if (map.containsKey(complement)) return new int[]{map.get(complement), i};\n map.put(nums[i], i);\n }\n return new int[]{};\n}", "solution_cpp": "vector twoSum(vector& nums, int target) {\n unordered_map m;\n for (int i = 0; i < nums.size(); i++) {\n if (m.count(target - nums[i])) return {m[target - nums[i]], i};\n m[nums[i]] = i;\n }\n return {};\n}", "test_cases": ["nums=[2,7,11,15], target=9 -> [0,1]", "nums=[3,2,4], target=6 -> [1,2]"], "key_points": ["哈希表一次遍历", "空间换时间"], "tags": ["array", "easy", "Amazon", "Google"]} {"problem_id": "algo_01582", "original_id": "merge-sorted", "title": "合并两个有序数组", "category": "array", "difficulty": "easy", "companies": ["Microsoft", "Uber"], "description": "给你两个按非递减顺序排列的整数数组 nums1 和 nums2,另有两个整数 m 和 n,分别表示 nums1 和 nums2 中的元素数目。请你合并 nums2 到 nums1 中。", "solution_python": "def merge(nums1, m, nums2, n):\n p1, p2, p = m-1, n-1, m+n-1\n while p1 >= 0 and p2 >= 0:\n if nums1[p1] > nums2[p2]: nums1[p] = nums1[p1]; p1 -= 1\n else: nums1[p] = nums2[p2]; p2 -= 1\n p -= 1\n while p2 >= 0: nums1[p] = nums2[p2]; p2 -= 1; p -= 1", "solution_java": "public void merge(int[] nums1, int m, int[] nums2, int n) {\n int p1 = m-1, p2 = n-1, p = m+n-1;\n while (p1 >= 0 && p2 >= 0) {\n nums1[p--] = nums1[p1] > nums2[p2] ? nums1[p1--] : nums2[p2--];\n }\n while (p2 >= 0) nums1[p--] = nums2[p2--];\n}", "solution_cpp": "void merge(vector& nums1, int m, vector& nums2, int n) {\n int p1 = m-1, p2 = n-1, p = m+n-1;\n while (p1 >= 0 && p2 >= 0) nums1[p--] = nums1[p1] > nums2[p2] ? nums1[p1--] : nums2[p2--];\n while (p2 >= 0) nums1[p--] = nums2[p2--];\n}", "test_cases": ["nums1=[1,2,3], m=3, nums2=[2,5,6], n=3 -> [1,2,2,3,5,6]", "nums1=[], m=0, nums2=[1], n=1 -> [1]"], "key_points": ["从后往前合并", "三指针技巧"], "tags": ["array", "easy", "Microsoft", "Uber"]} {"problem_id": "algo_01583", "original_id": "max-subarray", "title": "最大子数组和", "category": "array", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "给你一个整数数组 nums ,请你找出一个具有最大和的连续子数组,返回其最大和。", "solution_python": "def maxSubArray(nums):\n max_sum = current = nums[0]\n for num in nums[1:]:\n current = max(num, current + num)\n max_sum = max(max_sum, current)\n return max_sum", "solution_java": "public int maxSubArray(int[] nums) {\n int maxSum = nums[0], curr = nums[0];\n for (int i = 1; i < nums.length; i++) {\n curr = Math.max(nums[i], curr + nums[i]);\n maxSum = Math.max(maxSum, curr);\n }\n return maxSum;\n}", "solution_cpp": "int maxSubArray(vector& nums) {\n int maxSum = nums[0], curr = nums[0];\n for (int i = 1; i < nums.size(); i++) {\n curr = max(nums[i], curr + nums[i]);\n maxSum = max(maxSum, curr);\n }\n return maxSum;\n}", "test_cases": ["nums=[-2,1,-3,4,-1,2,1,-5,4] -> 6", "nums=[1] -> 1"], "key_points": ["Kadane算法", "动态规划基础题"], "tags": ["array", "medium", "Google", "Microsoft"]} {"problem_id": "algo_01584", "original_id": "valid-parentheses", "title": "有效的括号", "category": "string", "difficulty": "easy", "companies": ["Google", "Uber"], "description": "给定一个只包括 '(',')','{','}','[',']' 的字符串 s,判断字符串是否有效。", "solution_python": "def isValid(s):\n stack = []\n mapping = {')': '(', ']': '[', '}': '{'}\n for c in s:\n if c in mapping:\n if not stack or stack[-1] != mapping[c]: return False\n stack.pop()\n else: stack.append(c)\n return not stack", "solution_java": "public boolean isValid(String s) {\n Stack stack = new Stack<>();\n Map map = Map.of(')', '(', ']', '[', '}', '{');\n for (char c : s.toCharArray()) {\n if (map.containsValue(c)) stack.push(c);\n else if (!stack.isEmpty() && stack.pop() != map.get(c)) return false;\n }\n return stack.isEmpty();\n}", "solution_cpp": "bool isValid(string s) {\n stack st;\n unordered_map m = {{')','('},{']','['},{'}','{'}};\n for (char c : s) {\n if (m.find(c) == m.end()) st.push(c);\n else if (st.empty() || st.top() != m[c]) return false;\n else st.pop();\n }\n return st.empty();\n}", "test_cases": ["s=\"()\" -> true", "s=\"()[]{}\" -> true", "s=\"(]\" -> false"], "key_points": ["栈匹配法", "注意空栈边界"], "tags": ["string", "easy", "Google", "Uber"]} {"problem_id": "algo_01585", "original_id": "longest-palindrome", "title": "最长回文子串", "category": "string", "difficulty": "medium", "companies": ["Google", "Amazon"], "description": "给你一个字符串 s,找到 s 中最长的回文子串。", "solution_python": "def longestPalindrome(s):\n def expand(l, r):\n while l >= 0 and r < len(s) and s[l] == s[r]: l -= 1; r += 1\n return l + 1, r - 1\n start = end = 0\n for i in range(len(s)):\n l1, r1 = expand(i, i)\n l2, r2 = expand(i, i + 1)\n if r1 - l1 > end - start: start, end = l1, r1\n if r2 - l2 > end - start: start, end = l2, r2\n return s[start:end+1]", "solution_java": "public String longestPalindrome(String s) {\n int start = 0, end = 0;\n for (int i = 0; i < s.length(); i++) {\n int len1 = expand(s, i, i), len2 = expand(s, i, i+1);\n int len = Math.max(len1, len2);\n if (len > end - start) { start = i - (len-1)/2; end = i + len/2; }\n }\n return s.substring(start, end + 1);\n}\nprivate int expand(String s, int l, int r) {\n while (l >= 0 && r < s.length() && s.charAt(l) == s.charAt(r)) { l--; r++; }\n return r - l - 1;\n}", "solution_cpp": "string longestPalindrome(string s) {\n int start = 0, end = 0;\n for (int i = 0; i < s.size(); i++) {\n int len1 = expand(s, i, i), len2 = expand(s, i, i+1);\n if (max(len1, len2) > end - start) { start = i - (max(len1,len2)-1)/2; end = i + max(len1,len2)/2; }\n }\n return s.substr(start, end - start + 1);\n}", "test_cases": ["s=\"babad\" -> bab或aba", "s=\"cbbd\" -> bb"], "key_points": ["中心扩展法", "处理奇偶长度"], "tags": ["string", "medium", "Google", "Amazon"]} {"problem_id": "algo_01586", "original_id": "reverse-list", "title": "反转链表", "category": "linkedlist", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "给你单链表的头节点 head,请你反转链表,并返回反转后的链表。", "solution_python": "def reverseList(head):\n prev = None\n curr = head\n while curr:\n nxt = curr.next\n curr.next = prev\n prev = curr\n curr = nxt\n return prev", "solution_java": "public ListNode reverseList(ListNode head) {\n ListNode prev = null, curr = head;\n while (curr != null) {\n ListNode next = curr.next;\n curr.next = prev;\n prev = curr;\n curr = next;\n }\n return prev;\n}", "solution_cpp": "ListNode* reverseList(ListNode* head) {\n ListNode* prev = nullptr, *curr = head;\n while (curr) {\n ListNode* next = curr->next;\n curr->next = prev;\n prev = curr;\n curr = next;\n }\n return prev;\n}", "test_cases": ["head=[1,2,3,4,5] -> [5,4,3,2,1]", "head=[1,2] -> [2,1]"], "key_points": ["迭代法 O(1)空间", "递归法 O(n)空间"], "tags": ["linkedlist", "medium", "Google", "Microsoft"]} {"problem_id": "algo_01587", "original_id": "middle-node", "title": "链表的中间结点", "category": "linkedlist", "difficulty": "easy", "companies": ["Amazon", "Facebook"], "description": "给你单链表的头节点 head,请你找出并返回链表的中间结点。如果有两个中间结点,则返回第二个中间结点。", "solution_python": "def middleNode(head):\n slow = fast = head\n while fast and fast.next:\n slow = slow.next\n fast = fast.next.next\n return slow", "solution_java": "public ListNode middleNode(ListNode head) {\n ListNode slow = head, fast = head;\n while (fast != null && fast.next != null) {\n slow = slow.next;\n fast = fast.next.next;\n }\n return slow;\n}", "solution_cpp": "ListNode* middleNode(ListNode* head) {\n ListNode* slow = head, *fast = head;\n while (fast && fast->next) { slow = slow->next; fast = fast->next->next; }\n return slow;\n}", "test_cases": ["head=[1,2,3,4,5] -> 3", "head=[1,2,3,4,5,6] -> 4"], "key_points": ["快慢指针", "O(n)时间O(1)空间"], "tags": ["linkedlist", "easy", "Amazon", "Facebook"]} {"problem_id": "algo_01588", "original_id": "max-depth", "title": "二叉树的最大深度", "category": "tree", "difficulty": "easy", "companies": ["Microsoft", "Apple"], "description": "给定一个二叉树 root,返回其最大深度。", "solution_python": "def maxDepth(root):\n if not root: return 0\n return max(maxDepth(root.left), maxDepth(root.right)) + 1", "solution_java": "public int maxDepth(TreeNode root) {\n if (root == null) return 0;\n return Math.max(maxDepth(root.left), maxDepth(root.right)) + 1;\n}", "solution_cpp": "int maxDepth(TreeNode* root) {\n if (!root) return 0;\n return max(maxDepth(root->left), maxDepth(root->right)) + 1;\n}", "test_cases": ["root=[3,9,20,null,null,15,7] -> 3", "root=[1,null,2] -> 2"], "key_points": ["DFS递归", "层序遍历也可"], "tags": ["tree", "easy", "Microsoft", "Apple"]} {"problem_id": "algo_01589", "original_id": "inorder-traversal", "title": "二叉树的中序遍历", "category": "tree", "difficulty": "easy", "companies": ["Google", "Microsoft"], "description": "给定一个二叉树的根节点 root,返回它的中序遍历结果。", "solution_python": "def inorderTraversal(root):\n result = []\n def dfs(node):\n if node:\n dfs(node.left)\n result.append(node.val)\n dfs(node.right)\n dfs(root)\n return result", "solution_java": "public List inorderTraversal(TreeNode root) {\n List res = new ArrayList<>();\n dfs(root, res);\n return res;\n}\nprivate void dfs(TreeNode node, List res) {\n if (node == null) return;\n dfs(node.left, res); res.add(node.val); dfs(node.right, res);\n}", "solution_cpp": "vector inorderTraversal(TreeNode* root) {\n vector res;\n dfs(root, res);\n return res;\n}\nvoid dfs(TreeNode* node, vector& res) {\n if (!node) return;\n dfs(node->left, res); res.push_back(node->val); dfs(node->right, res);\n}", "test_cases": ["root=[1,null,2,3] -> [1,3,2]", "root=[] -> []"], "key_points": ["左-根-右顺序", "递归最简洁"], "tags": ["tree", "easy", "Google", "Microsoft"]} {"problem_id": "algo_01590", "original_id": "binary-search", "title": "二分查找", "category": "binarysearch", "difficulty": "easy", "companies": ["Google", "Amazon"], "description": "给定一个 n 个元素有序的(升序)整型数组 nums 和一个目标值 target,写一个函数搜索 nums 中的 target,如果目标值存在返回下标,否则返回 -1。", "solution_python": "def search(nums, target):\n left, right = 0, len(nums) - 1\n while left <= right:\n mid = (left + right) // 2\n if nums[mid] == target: return mid\n elif nums[mid] < target: left = mid + 1\n else: right = mid - 1\n return -1", "solution_java": "public int search(int[] nums, int target) {\n int left = 0, right = nums.length - 1;\n while (left <= right) {\n int mid = left + (right - left) / 2;\n if (nums[mid] == target) return mid;\n else if (nums[mid] < target) left = mid + 1;\n else right = mid - 1;\n }\n return -1;\n}", "solution_cpp": "int search(vector& nums, int target) {\n int left = 0, right = nums.size() - 1;\n while (left <= right) {\n int mid = left + (right - left) / 2;\n if (nums[mid] == target) return mid;\n else if (nums[mid] < target) left = mid + 1;\n else right = mid - 1;\n }\n return -1;\n}", "test_cases": ["nums=[-1,0,3,5,9,12], target=9 -> 4", "nums=[-1,0,3,5,9,12], target=2 -> -1"], "key_points": ["标准模板", "注意防溢出写法"], "tags": ["binarysearch", "easy", "Google", "Amazon"]} {"problem_id": "algo_01591", "original_id": "climbing-stairs", "title": "爬楼梯", "category": "dp", "difficulty": "easy", "companies": ["Amazon", "Google"], "description": "假设你正在爬楼梯。需要 n 阶你才能到达楼顶。每次你可以爬 1 或 2 个台阶。你有多少种不同的方法可以爬到楼顶?", "solution_python": "def climbStairs(n):\n if n <= 2: return n\n a, b = 1, 2\n for _ in range(3, n+1):\n a, b = b, a + b\n return b", "solution_java": "public int climbStairs(int n) {\n if (n <= 2) return n;\n int a = 1, b = 2;\n for (int i = 3; i <= n; i++) { int temp = a + b; a = b; b = temp; }\n return b;\n}", "solution_cpp": "int climbStairs(int n) {\n if (n <= 2) return n;\n int a = 1, b = 2;\n for (int i = 3; i <= n; i++) { int temp = a + b; a = b; b = temp; }\n return b;\n}", "test_cases": ["n=2 -> 2", "n=3 -> 3", "n=5 -> 8"], "key_points": ["斐波那契数列", "滚动数组优化空间"], "tags": ["dp", "easy", "Amazon", "Google"]} {"problem_id": "algo_01592", "original_id": "coin-change", "title": "零钱兑换", "category": "dp", "difficulty": "medium", "companies": ["Google", "Amazon"], "description": "给你一个整数数组 coins 表示不同面额的硬币,以及一个整数 amount 表示总金额。计算并返回可以凑成总金额所需的最少的硬币个数。如果没有任何一种硬币组合能组成总金额,返回 -1。", "solution_python": "def coinChange(coins, amount):\n dp = [float('inf')] * (amount + 1)\n dp[0] = 0\n for coin in coins:\n for x in range(coin, amount + 1):\n dp[x] = min(dp[x], dp[x - coin] + 1)\n return dp[amount] if dp[amount] != float('inf') else -1", "solution_java": "public int coinChange(int[] coins, int amount) {\n int[] dp = new int[amount + 1];\n Arrays.fill(dp, amount + 1);\n dp[0] = 0;\n for (int coin : coins) {\n for (int x = coin; x <= amount; x++) {\n dp[x] = Math.min(dp[x], dp[x - coin] + 1);\n }\n }\n return dp[amount] > amount ? -1 : dp[amount];\n}", "solution_cpp": "int coinChange(vector& coins, int amount) {\n vector dp(amount + 1, amount + 1);\n dp[0] = 0;\n for (int coin : coins) {\n for (int x = coin; x <= amount; x++) {\n dp[x] = min(dp[x], dp[x - coin] + 1);\n }\n }\n return dp[amount] > amount ? -1 : dp[amount];\n}", "test_cases": ["coins=[1,2,5], amount=11 -> 3", "coins=[2], amount=3 -> -1"], "key_points": ["完全背包问题", "dp[x] = min(dp[x-coin]+1)"], "tags": ["dp", "medium", "Google", "Amazon"]} {"problem_id": "algo_01593", "original_id": "subsets", "title": "子集", "category": "backtracking", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "给你一个整数数组 nums ,数组中的元素 互不相同 。返回该数组所有可能的子集(幂集)。", "solution_python": "def subsets(nums):\n result = []\n def backtrack(start, path):\n result.append(path[:])\n for i in range(start, len(nums)):\n path.append(nums[i])\n backtrack(i + 1, path)\n path.pop()\n backtrack(0, [])\n return result", "solution_java": "public List> subsets(int[] nums) {\n List> result = new ArrayList<>();\n backtrack(nums, 0, new ArrayList<>(), result);\n return result;\n}\nprivate void backtrack(int[] nums, int start, List path, List> result) {\n result.add(new ArrayList<>(path));\n for (int i = start; i < nums.length; i++) {\n path.add(nums[i]);\n backtrack(nums, i + 1, path, result);\n path.remove(path.size() - 1);\n }\n}", "solution_cpp": "vector> subsets(vector& nums) {\n vector> result;\n vector path;\n backtrack(nums, 0, path, result);\n return result;\n}\nvoid backtrack(vector& nums, int start, vector& path, vector>& result) {\n result.push_back(path);\n for (int i = start; i < nums.size(); i++) {\n path.push_back(nums[i]);\n backtrack(nums, i + 1, path, result);\n path.pop_back();\n }\n}", "test_cases": ["nums=[1,2,3] -> [[],[1],[2],[1,2],[3],[1,3],[2,3],[1,2,3]]"], "key_points": ["选或不选", "DFS遍历子集树"], "tags": ["backtracking", "medium", "Google", "Microsoft"]} {"problem_id": "algo_01594", "original_id": "permutations", "title": "全排列", "category": "backtracking", "difficulty": "medium", "companies": ["Google", "Facebook"], "description": "给定一个不含重复数字的数组 nums,返回其所有可能的全排列。", "solution_python": "def permute(nums):\n result = []\n def backtrack(path, used):\n if len(path) == len(nums):\n result.append(path[:])\n return\n for i in range(len(nums)):\n if used[i]: continue\n used[i] = True\n path.append(nums[i])\n backtrack(path, used)\n path.pop()\n used[i] = False\n backtrack([], [False]*len(nums))\n return result", "solution_java": "public List> permute(int[] nums) {\n List> result = new ArrayList<>();\n boolean[] used = new boolean[nums.length];\n backtrack(nums, used, new ArrayList<>(), result);\n return result;\n}\nprivate void backtrack(int[] nums, boolean[] used, List path, List> result) {\n if (path.size() == nums.length) { result.add(new ArrayList<>(path)); return; }\n for (int i = 0; i < nums.length; i++) {\n if (used[i]) continue;\n used[i] = true;\n path.add(nums[i]);\n backtrack(nums, used, path, result);\n path.remove(path.size() - 1);\n used[i] = false;\n }\n}", "solution_cpp": "vector> permute(vector& nums) {\n vector> result;\n vector used(nums.size(), false);\n vector path;\n backtrack(nums, used, path, result);\n return result;\n}\nvoid backtrack(vector& nums, vector& used, vector& path, vector>& result) {\n if (path.size() == nums.size()) { result.push_back(path); return; }\n for (int i = 0; i < nums.size(); i++) {\n if (used[i]) continue;\n used[i] = true;\n path.push_back(nums[i]);\n backtrack(nums, used, path, result);\n path.pop_back();\n used[i] = false;\n }\n}", "test_cases": ["nums=[1,2,3] -> [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]"], "key_points": ["标记已使用元素", "回溯经典模板"], "tags": ["backtracking", "medium", "Google", "Facebook"]} {"problem_id": "algo_01595", "original_id": "top-k-frequent", "title": "前K个高频元素", "category": "heap", "difficulty": "medium", "companies": ["Amazon", "Facebook"], "description": "给你一个整数数组 nums 和一个整数 k,请你返回其中出现频率前 k 高的元素。", "solution_python": "import heapq\nfrom collections import Counter\ndef topKFrequent(nums, k):\n count = Counter(nums)\n heap = []\n for num, freq in count.items():\n heapq.heappush(heap, (freq, num))\n if len(heap) > k: heapq.heappop(heap)\n return [num for freq, num in heap]", "solution_java": "public int[] topKFrequent(int[] nums, int k) {\n Map count = new HashMap<>();\n for (int n : nums) count.put(n, count.getOrDefault(n, 0) + 1);\n PriorityQueue> heap = \n new PriorityQueue<>((a, b) -> a.getValue() - b.getValue());\n for (Map.Entry e : count.entrySet()) {\n heap.offer(e);\n if (heap.size() > k) heap.poll();\n }\n int[] res = new int[k];\n for (int i = k - 1; i >= 0; i--) res[i] = heap.poll().getKey();\n return res;\n}", "solution_cpp": "vector topKFrequent(vector& nums, int k) {\n unordered_map count;\n for (int n : nums) count[n]++;\n priority_queue, vector>, greater>> heap;\n for (auto& [num, freq] : count) {\n heap.push({freq, num});\n if (heap.size() > k) heap.pop();\n }\n vector res;\n while (!heap.empty()) { res.push_back(heap.top().second); heap.pop(); }\n reverse(res.begin(), res.end());\n return res;\n}", "test_cases": ["nums=[1,1,1,2,2,3], k=2 -> [1,2]", "nums=[1], k=1 -> [1]"], "key_points": ["小顶堆保持大小k", "时间复杂度O(nlogk)"], "tags": ["heap", "medium", "Amazon", "Facebook"]} {"problem_id": "algo_01596", "original_id": "3sum", "title": "三数之和", "category": "two-pointers", "difficulty": "medium", "companies": ["Google", "Amazon"], "description": "给你一个整数数组 nums,判断是否存在三元组满足和为0,返回所有不重复的三元组。", "solution_python": "def threeSum(nums):\n nums.sort()\n result = []\n for i in range(len(nums) - 2):\n if i > 0 and nums[i] == nums[i-1]: continue\n left, right = i + 1, len(nums) - 1\n while left < right:\n total = nums[i] + nums[left] + nums[right]\n if total < 0: left += 1\n elif total > 0: right -= 1\n else:\n result.append([nums[i], nums[left], nums[right]])\n while left < right and nums[left] == nums[left+1]: left += 1\n while left < right and nums[right] == nums[right-1]: right -= 1\n left += 1; right -= 1\n return result", "solution_java": "public List> threeSum(int[] nums) {\n Arrays.sort(nums);\n List> result = new ArrayList<>();\n for (int i = 0; i < nums.length - 2; i++) {\n if (i > 0 && nums[i] == nums[i-1]) continue;\n int left = i + 1, right = nums.length - 1;\n while (left < right) {\n int total = nums[i] + nums[left] + nums[right];\n if (total < 0) left++;\n else if (total > 0) right--;\n else {\n result.add(Arrays.asList(nums[i], nums[left], nums[right]));\n while (left < right && nums[left] == nums[left+1]) left++;\n while (left < right && nums[right] == nums[right-1]) right--;\n left++; right--;\n }\n }\n }\n return result;\n}", "solution_cpp": "vector> threeSum(vector& nums) {\n sort(nums.begin(), nums.end());\n vector> result;\n for (int i = 0; i < nums.size() - 2; i++) {\n if (i > 0 && nums[i] == nums[i-1]) continue;\n int left = i + 1, right = nums.size() - 1;\n while (left < right) {\n int total = nums[i] + nums[left] + nums[right];\n if (total < 0) left++;\n else if (total > 0) right--;\n else {\n result.push_back({nums[i], nums[left], nums[right]});\n while (left < right && nums[left] == nums[left+1]) left++;\n while (left < right && nums[right] == nums[right-1]) right--;\n left++; right--;\n }\n }\n }\n return result;\n}", "test_cases": ["nums=[-1,0,1,2,-1,-4] -> [[-1,-1,2],[-1,0,1]]"], "key_points": ["排序+双指针", "去重是关键"], "tags": ["two-pointers", "medium", "Google", "Amazon"]} {"problem_id": "algo_01597", "original_id": "container-water", "title": "盛最多水的容器", "category": "two-pointers", "difficulty": "medium", "companies": ["Google", "Uber"], "description": "给定一个长度为 n 的整数数组 height,找出其中的两条线,使得它们与 x 轴共同构成的容器可以容纳最多的水。", "solution_python": "def maxArea(height):\n left, right = 0, len(height) - 1\n max_area = 0\n while left < right:\n h = min(height[left], height[right])\n max_area = max(max_area, h * (right - left))\n if height[left] < height[right]: left += 1\n else: right -= 1\n return max_area", "solution_java": "public int maxArea(int[] height) {\n int left = 0, right = height.length - 1, maxArea = 0;\n while (left < right) {\n int h = Math.min(height[left], height[right]);\n maxArea = Math.max(maxArea, h * (right - left));\n if (height[left] < height[right]) left++;\n else right--;\n }\n return maxArea;\n}", "solution_cpp": "int maxArea(vector& height) {\n int left = 0, right = height.size() - 1, maxArea = 0;\n while (left < right) {\n int h = min(height[left], height[right]);\n maxArea = max(maxArea, h * (right - left));\n if (height[left] < height[right]) left++;\n else right--;\n }\n return maxArea;\n}", "test_cases": ["height=[1,8,6,2,5,4,8,3,7] -> 49"], "key_points": ["移动短边指针", "面积=min(h1,h2)*width"], "tags": ["two-pointers", "medium", "Google", "Uber"]} {"problem_id": "algo_01598", "original_id": "min-stack", "title": "最小栈", "category": "stack", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "设计一个支持 push,pop,top 操作,并能在常数时间内检索到最小元素的栈。", "solution_python": "class MinStack:\n def __init__(self):\n self.stack = []\n self.min_stack = []\n def push(self, val):\n self.stack.append(val)\n self.min_stack.append(min(val, self.min_stack[-1] if self.min_stack else val))\n def pop(self):\n self.stack.pop(); self.min_stack.pop()\n def top(self): return self.stack[-1]\n def getMin(self): return self.min_stack[-1]", "solution_java": "class MinStack {\n Stack stack = new Stack<>();\n Stack minStack = new Stack<>();\n public void push(int val) { stack.push(val); minStack.push(Math.min(val, minStack.isEmpty() ? val : minStack.peek())); }\n public void pop() { stack.pop(); minStack.pop(); }\n public int top() { return stack.peek(); }\n public int getMin() { return minStack.peek(); }\n}", "solution_cpp": "class MinStack {\n stack st, minSt;\npublic:\n void push(int val) { st.push(val); minSt.push(min(val, minSt.empty() ? val : minSt.top())); }\n void pop() { st.pop(); minSt.pop(); }\n int top() { return st.top(); }\n int getMin() { return minSt.top(); }\n};", "test_cases": ["push(-2), push(0), push(-3) -> getMin() returns -3"], "key_points": ["辅助栈记录最小值", "O(1)时间获取最小值"], "tags": ["stack", "medium", "Google", "Microsoft"]} {"problem_id": "algo_01599", "original_id": "lru-cache", "title": "LRU缓存", "category": "design", "difficulty": "hard", "companies": ["Google", "Amazon"], "description": "设计和实现一个 LRU(最近最少使用)缓存机制。", "solution_python": "class LRUCache:\n def __init__(self, capacity):\n self.capacity = capacity\n self.cache = {}\n self.order = []\n def get(self, key):\n if key not in self.cache: return -1\n self.order.remove(key); self.order.append(key)\n return self.cache[key]\n def put(self, key, value):\n if key in self.cache:\n self.order.remove(key)\n elif len(self.cache) >= self.capacity:\n del self.cache[self.order.pop(0)]\n self.cache[key] = value; self.order.append(key)", "solution_java": "class LRUCache {\n int capacity;\n LinkedHashMap cache = new LinkedHashMap<>();\n public LRUCache(int cap) { capacity = cap; }\n public int get(int key) { return cache.containsKey(key) ? cache.remove(key) : -1; }\n public void put(int key, int val) {\n if (cache.containsKey(key)) cache.remove(key);\n else if (cache.size() >= capacity) cache.remove(cache.keySet().iterator().next());\n cache.put(key, val);\n }\n}", "solution_cpp": "class LRUCache {\n int cap;\n list> dll;\n unordered_map>::iterator> cache;\npublic:\n LRUCache(int capacity) : cap(capacity) {}\n int get(int key) {\n auto it = cache.find(key);\n if (it == cache.end()) return -1;\n dll.splice(dll.end(), dll, it->second);\n return it->second->second;\n }\n void put(int key, int value) {\n auto it = cache.find(key);\n if (it != cache.end()) dll.erase(it->second);\n else if (cache.size() >= cap) { cache.erase(dll.front().first); dll.pop_front(); }\n dll.push_back({key, value});\n cache[key] = --dll.end();\n }\n};", "test_cases": ["put(1,1), put(2,2), get(1) -> 1"], "key_points": ["HashMap + 双向链表", "O(1)时间操作"], "tags": ["design", "hard", "Google", "Amazon"]} {"problem_id": "algo_01600", "original_id": "num-islands", "title": "岛屿数量", "category": "graph", "difficulty": "medium", "companies": ["Google", "Facebook"], "description": "给你一个由 '1'(陆地)和 '0'(水)组成的二维网格,请你计算网格中岛屿的数量。岛屿总是被水包围,且只能由水平或垂直方向相邻的陆地连接形成。", "solution_python": "def numIslands(grid):\n if not grid: return 0\n rows, cols = len(grid), len(grid[0])\n count = 0\n def dfs(r, c):\n if r < 0 or r >= rows or c < 0 or c >= cols or grid[r][c] != '1': return\n grid[r][c] = '0'\n dfs(r+1, c); dfs(r-1, c); dfs(r, c+1); dfs(r, c-1)\n for r in range(rows):\n for c in range(cols):\n if grid[r][c] == '1': count += 1; dfs(r, c)\n return count", "solution_java": "public int numIslands(char[][] grid) {\n if (grid.length == 0) return 0;\n int count = 0;\n for (int i = 0; i < grid.length; i++)\n for (int j = 0; j < grid[0].length; j++)\n if (grid[i][j] == '1') { count++; dfs(grid, i, j); }\n return count;\n}\nprivate void dfs(char[][] grid, int r, int c) {\n if (r < 0 || r >= grid.length || c < 0 || c >= grid[0].length || grid[r][c] != '1') return;\n grid[r][c] = '0';\n dfs(grid, r+1, c); dfs(grid, r-1, c); dfs(grid, r, c+1); dfs(grid, r, c-1);\n}", "solution_cpp": "int numIslands(vector>& grid) {\n if (grid.empty()) return 0;\n int count = 0;\n for (int i = 0; i < grid.size(); i++)\n for (int j = 0; j < grid[0].size(); j++)\n if (grid[i][j] == '1') { count++; dfs(grid, i, j); }\n return count;\n}\nvoid dfs(vector>& grid, int r, int c) {\n if (r < 0 || r >= grid.size() || c < 0 || c >= grid[0].size() || grid[r][c] != '1') return;\n grid[r][c] = '0';\n dfs(grid, r+1, c); dfs(grid, r-1, c); dfs(grid, r, c+1); dfs(grid, r, c-1);\n}", "test_cases": ["grid=[[1,1,1,1,0],[1,1,0,1,0],[1,1,0,0,0],[0,0,0,0,0]] -> 1"], "key_points": ["DFS/BFS遍历", "访问后标记为0避免重复"], "tags": ["graph", "medium", "Google", "Facebook"]} {"problem_id": "algo_01601", "original_id": "two-sum", "title": "两数之和", "category": "array", "difficulty": "easy", "companies": ["Amazon", "Google"], "description": "给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那两个整数,并返回他们的数组下标。", "solution_python": "def twoSum(nums, target):\n hashmap = {}\n for i, num in enumerate(nums):\n complement = target - num\n if complement in hashmap:\n return [hashmap[complement], i]\n hashmap[num] = i\n return []", "solution_java": "public int[] twoSum(int[] nums, int target) {\n Map map = new HashMap<>();\n for (int i = 0; i < nums.length; i++) {\n int complement = target - nums[i];\n if (map.containsKey(complement)) return new int[]{map.get(complement), i};\n map.put(nums[i], i);\n }\n return new int[]{};\n}", "solution_cpp": "vector twoSum(vector& nums, int target) {\n unordered_map m;\n for (int i = 0; i < nums.size(); i++) {\n if (m.count(target - nums[i])) return {m[target - nums[i]], i};\n m[nums[i]] = i;\n }\n return {};\n}", "test_cases": ["nums=[2,7,11,15], target=9 -> [0,1]", "nums=[3,2,4], target=6 -> [1,2]"], "key_points": ["哈希表一次遍历", "空间换时间"], "tags": ["array", "easy", "Amazon", "Google"]} {"problem_id": "algo_01602", "original_id": "merge-sorted", "title": "合并两个有序数组", "category": "array", "difficulty": "easy", "companies": ["Microsoft", "Uber"], "description": "给你两个按非递减顺序排列的整数数组 nums1 和 nums2,另有两个整数 m 和 n,分别表示 nums1 和 nums2 中的元素数目。请你合并 nums2 到 nums1 中。", "solution_python": "def merge(nums1, m, nums2, n):\n p1, p2, p = m-1, n-1, m+n-1\n while p1 >= 0 and p2 >= 0:\n if nums1[p1] > nums2[p2]: nums1[p] = nums1[p1]; p1 -= 1\n else: nums1[p] = nums2[p2]; p2 -= 1\n p -= 1\n while p2 >= 0: nums1[p] = nums2[p2]; p2 -= 1; p -= 1", "solution_java": "public void merge(int[] nums1, int m, int[] nums2, int n) {\n int p1 = m-1, p2 = n-1, p = m+n-1;\n while (p1 >= 0 && p2 >= 0) {\n nums1[p--] = nums1[p1] > nums2[p2] ? nums1[p1--] : nums2[p2--];\n }\n while (p2 >= 0) nums1[p--] = nums2[p2--];\n}", "solution_cpp": "void merge(vector& nums1, int m, vector& nums2, int n) {\n int p1 = m-1, p2 = n-1, p = m+n-1;\n while (p1 >= 0 && p2 >= 0) nums1[p--] = nums1[p1] > nums2[p2] ? nums1[p1--] : nums2[p2--];\n while (p2 >= 0) nums1[p--] = nums2[p2--];\n}", "test_cases": ["nums1=[1,2,3], m=3, nums2=[2,5,6], n=3 -> [1,2,2,3,5,6]", "nums1=[], m=0, nums2=[1], n=1 -> [1]"], "key_points": ["从后往前合并", "三指针技巧"], "tags": ["array", "easy", "Microsoft", "Uber"]} {"problem_id": "algo_01603", "original_id": "max-subarray", "title": "最大子数组和", "category": "array", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "给你一个整数数组 nums ,请你找出一个具有最大和的连续子数组,返回其最大和。", "solution_python": "def maxSubArray(nums):\n max_sum = current = nums[0]\n for num in nums[1:]:\n current = max(num, current + num)\n max_sum = max(max_sum, current)\n return max_sum", "solution_java": "public int maxSubArray(int[] nums) {\n int maxSum = nums[0], curr = nums[0];\n for (int i = 1; i < nums.length; i++) {\n curr = Math.max(nums[i], curr + nums[i]);\n maxSum = Math.max(maxSum, curr);\n }\n return maxSum;\n}", "solution_cpp": "int maxSubArray(vector& nums) {\n int maxSum = nums[0], curr = nums[0];\n for (int i = 1; i < nums.size(); i++) {\n curr = max(nums[i], curr + nums[i]);\n maxSum = max(maxSum, curr);\n }\n return maxSum;\n}", "test_cases": ["nums=[-2,1,-3,4,-1,2,1,-5,4] -> 6", "nums=[1] -> 1"], "key_points": ["Kadane算法", "动态规划基础题"], "tags": ["array", "medium", "Google", "Microsoft"]} {"problem_id": "algo_01604", "original_id": "valid-parentheses", "title": "有效的括号", "category": "string", "difficulty": "easy", "companies": ["Google", "Uber"], "description": "给定一个只包括 '(',')','{','}','[',']' 的字符串 s,判断字符串是否有效。", "solution_python": "def isValid(s):\n stack = []\n mapping = {')': '(', ']': '[', '}': '{'}\n for c in s:\n if c in mapping:\n if not stack or stack[-1] != mapping[c]: return False\n stack.pop()\n else: stack.append(c)\n return not stack", "solution_java": "public boolean isValid(String s) {\n Stack stack = new Stack<>();\n Map map = Map.of(')', '(', ']', '[', '}', '{');\n for (char c : s.toCharArray()) {\n if (map.containsValue(c)) stack.push(c);\n else if (!stack.isEmpty() && stack.pop() != map.get(c)) return false;\n }\n return stack.isEmpty();\n}", "solution_cpp": "bool isValid(string s) {\n stack st;\n unordered_map m = {{')','('},{']','['},{'}','{'}};\n for (char c : s) {\n if (m.find(c) == m.end()) st.push(c);\n else if (st.empty() || st.top() != m[c]) return false;\n else st.pop();\n }\n return st.empty();\n}", "test_cases": ["s=\"()\" -> true", "s=\"()[]{}\" -> true", "s=\"(]\" -> false"], "key_points": ["栈匹配法", "注意空栈边界"], "tags": ["string", "easy", "Google", "Uber"]} {"problem_id": "algo_01605", "original_id": "longest-palindrome", "title": "最长回文子串", "category": "string", "difficulty": "medium", "companies": ["Google", "Amazon"], "description": "给你一个字符串 s,找到 s 中最长的回文子串。", "solution_python": "def longestPalindrome(s):\n def expand(l, r):\n while l >= 0 and r < len(s) and s[l] == s[r]: l -= 1; r += 1\n return l + 1, r - 1\n start = end = 0\n for i in range(len(s)):\n l1, r1 = expand(i, i)\n l2, r2 = expand(i, i + 1)\n if r1 - l1 > end - start: start, end = l1, r1\n if r2 - l2 > end - start: start, end = l2, r2\n return s[start:end+1]", "solution_java": "public String longestPalindrome(String s) {\n int start = 0, end = 0;\n for (int i = 0; i < s.length(); i++) {\n int len1 = expand(s, i, i), len2 = expand(s, i, i+1);\n int len = Math.max(len1, len2);\n if (len > end - start) { start = i - (len-1)/2; end = i + len/2; }\n }\n return s.substring(start, end + 1);\n}\nprivate int expand(String s, int l, int r) {\n while (l >= 0 && r < s.length() && s.charAt(l) == s.charAt(r)) { l--; r++; }\n return r - l - 1;\n}", "solution_cpp": "string longestPalindrome(string s) {\n int start = 0, end = 0;\n for (int i = 0; i < s.size(); i++) {\n int len1 = expand(s, i, i), len2 = expand(s, i, i+1);\n if (max(len1, len2) > end - start) { start = i - (max(len1,len2)-1)/2; end = i + max(len1,len2)/2; }\n }\n return s.substr(start, end - start + 1);\n}", "test_cases": ["s=\"babad\" -> bab或aba", "s=\"cbbd\" -> bb"], "key_points": ["中心扩展法", "处理奇偶长度"], "tags": ["string", "medium", "Google", "Amazon"]} {"problem_id": "algo_01606", "original_id": "reverse-list", "title": "反转链表", "category": "linkedlist", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "给你单链表的头节点 head,请你反转链表,并返回反转后的链表。", "solution_python": "def reverseList(head):\n prev = None\n curr = head\n while curr:\n nxt = curr.next\n curr.next = prev\n prev = curr\n curr = nxt\n return prev", "solution_java": "public ListNode reverseList(ListNode head) {\n ListNode prev = null, curr = head;\n while (curr != null) {\n ListNode next = curr.next;\n curr.next = prev;\n prev = curr;\n curr = next;\n }\n return prev;\n}", "solution_cpp": "ListNode* reverseList(ListNode* head) {\n ListNode* prev = nullptr, *curr = head;\n while (curr) {\n ListNode* next = curr->next;\n curr->next = prev;\n prev = curr;\n curr = next;\n }\n return prev;\n}", "test_cases": ["head=[1,2,3,4,5] -> [5,4,3,2,1]", "head=[1,2] -> [2,1]"], "key_points": ["迭代法 O(1)空间", "递归法 O(n)空间"], "tags": ["linkedlist", "medium", "Google", "Microsoft"]} {"problem_id": "algo_01607", "original_id": "middle-node", "title": "链表的中间结点", "category": "linkedlist", "difficulty": "easy", "companies": ["Amazon", "Facebook"], "description": "给你单链表的头节点 head,请你找出并返回链表的中间结点。如果有两个中间结点,则返回第二个中间结点。", "solution_python": "def middleNode(head):\n slow = fast = head\n while fast and fast.next:\n slow = slow.next\n fast = fast.next.next\n return slow", "solution_java": "public ListNode middleNode(ListNode head) {\n ListNode slow = head, fast = head;\n while (fast != null && fast.next != null) {\n slow = slow.next;\n fast = fast.next.next;\n }\n return slow;\n}", "solution_cpp": "ListNode* middleNode(ListNode* head) {\n ListNode* slow = head, *fast = head;\n while (fast && fast->next) { slow = slow->next; fast = fast->next->next; }\n return slow;\n}", "test_cases": ["head=[1,2,3,4,5] -> 3", "head=[1,2,3,4,5,6] -> 4"], "key_points": ["快慢指针", "O(n)时间O(1)空间"], "tags": ["linkedlist", "easy", "Amazon", "Facebook"]} {"problem_id": "algo_01608", "original_id": "max-depth", "title": "二叉树的最大深度", "category": "tree", "difficulty": "easy", "companies": ["Microsoft", "Apple"], "description": "给定一个二叉树 root,返回其最大深度。", "solution_python": "def maxDepth(root):\n if not root: return 0\n return max(maxDepth(root.left), maxDepth(root.right)) + 1", "solution_java": "public int maxDepth(TreeNode root) {\n if (root == null) return 0;\n return Math.max(maxDepth(root.left), maxDepth(root.right)) + 1;\n}", "solution_cpp": "int maxDepth(TreeNode* root) {\n if (!root) return 0;\n return max(maxDepth(root->left), maxDepth(root->right)) + 1;\n}", "test_cases": ["root=[3,9,20,null,null,15,7] -> 3", "root=[1,null,2] -> 2"], "key_points": ["DFS递归", "层序遍历也可"], "tags": ["tree", "easy", "Microsoft", "Apple"]} {"problem_id": "algo_01609", "original_id": "inorder-traversal", "title": "二叉树的中序遍历", "category": "tree", "difficulty": "easy", "companies": ["Google", "Microsoft"], "description": "给定一个二叉树的根节点 root,返回它的中序遍历结果。", "solution_python": "def inorderTraversal(root):\n result = []\n def dfs(node):\n if node:\n dfs(node.left)\n result.append(node.val)\n dfs(node.right)\n dfs(root)\n return result", "solution_java": "public List inorderTraversal(TreeNode root) {\n List res = new ArrayList<>();\n dfs(root, res);\n return res;\n}\nprivate void dfs(TreeNode node, List res) {\n if (node == null) return;\n dfs(node.left, res); res.add(node.val); dfs(node.right, res);\n}", "solution_cpp": "vector inorderTraversal(TreeNode* root) {\n vector res;\n dfs(root, res);\n return res;\n}\nvoid dfs(TreeNode* node, vector& res) {\n if (!node) return;\n dfs(node->left, res); res.push_back(node->val); dfs(node->right, res);\n}", "test_cases": ["root=[1,null,2,3] -> [1,3,2]", "root=[] -> []"], "key_points": ["左-根-右顺序", "递归最简洁"], "tags": ["tree", "easy", "Google", "Microsoft"]} {"problem_id": "algo_01610", "original_id": "binary-search", "title": "二分查找", "category": "binarysearch", "difficulty": "easy", "companies": ["Google", "Amazon"], "description": "给定一个 n 个元素有序的(升序)整型数组 nums 和一个目标值 target,写一个函数搜索 nums 中的 target,如果目标值存在返回下标,否则返回 -1。", "solution_python": "def search(nums, target):\n left, right = 0, len(nums) - 1\n while left <= right:\n mid = (left + right) // 2\n if nums[mid] == target: return mid\n elif nums[mid] < target: left = mid + 1\n else: right = mid - 1\n return -1", "solution_java": "public int search(int[] nums, int target) {\n int left = 0, right = nums.length - 1;\n while (left <= right) {\n int mid = left + (right - left) / 2;\n if (nums[mid] == target) return mid;\n else if (nums[mid] < target) left = mid + 1;\n else right = mid - 1;\n }\n return -1;\n}", "solution_cpp": "int search(vector& nums, int target) {\n int left = 0, right = nums.size() - 1;\n while (left <= right) {\n int mid = left + (right - left) / 2;\n if (nums[mid] == target) return mid;\n else if (nums[mid] < target) left = mid + 1;\n else right = mid - 1;\n }\n return -1;\n}", "test_cases": ["nums=[-1,0,3,5,9,12], target=9 -> 4", "nums=[-1,0,3,5,9,12], target=2 -> -1"], "key_points": ["标准模板", "注意防溢出写法"], "tags": ["binarysearch", "easy", "Google", "Amazon"]} {"problem_id": "algo_01611", "original_id": "climbing-stairs", "title": "爬楼梯", "category": "dp", "difficulty": "easy", "companies": ["Amazon", "Google"], "description": "假设你正在爬楼梯。需要 n 阶你才能到达楼顶。每次你可以爬 1 或 2 个台阶。你有多少种不同的方法可以爬到楼顶?", "solution_python": "def climbStairs(n):\n if n <= 2: return n\n a, b = 1, 2\n for _ in range(3, n+1):\n a, b = b, a + b\n return b", "solution_java": "public int climbStairs(int n) {\n if (n <= 2) return n;\n int a = 1, b = 2;\n for (int i = 3; i <= n; i++) { int temp = a + b; a = b; b = temp; }\n return b;\n}", "solution_cpp": "int climbStairs(int n) {\n if (n <= 2) return n;\n int a = 1, b = 2;\n for (int i = 3; i <= n; i++) { int temp = a + b; a = b; b = temp; }\n return b;\n}", "test_cases": ["n=2 -> 2", "n=3 -> 3", "n=5 -> 8"], "key_points": ["斐波那契数列", "滚动数组优化空间"], "tags": ["dp", "easy", "Amazon", "Google"]} {"problem_id": "algo_01612", "original_id": "coin-change", "title": "零钱兑换", "category": "dp", "difficulty": "medium", "companies": ["Google", "Amazon"], "description": "给你一个整数数组 coins 表示不同面额的硬币,以及一个整数 amount 表示总金额。计算并返回可以凑成总金额所需的最少的硬币个数。如果没有任何一种硬币组合能组成总金额,返回 -1。", "solution_python": "def coinChange(coins, amount):\n dp = [float('inf')] * (amount + 1)\n dp[0] = 0\n for coin in coins:\n for x in range(coin, amount + 1):\n dp[x] = min(dp[x], dp[x - coin] + 1)\n return dp[amount] if dp[amount] != float('inf') else -1", "solution_java": "public int coinChange(int[] coins, int amount) {\n int[] dp = new int[amount + 1];\n Arrays.fill(dp, amount + 1);\n dp[0] = 0;\n for (int coin : coins) {\n for (int x = coin; x <= amount; x++) {\n dp[x] = Math.min(dp[x], dp[x - coin] + 1);\n }\n }\n return dp[amount] > amount ? -1 : dp[amount];\n}", "solution_cpp": "int coinChange(vector& coins, int amount) {\n vector dp(amount + 1, amount + 1);\n dp[0] = 0;\n for (int coin : coins) {\n for (int x = coin; x <= amount; x++) {\n dp[x] = min(dp[x], dp[x - coin] + 1);\n }\n }\n return dp[amount] > amount ? -1 : dp[amount];\n}", "test_cases": ["coins=[1,2,5], amount=11 -> 3", "coins=[2], amount=3 -> -1"], "key_points": ["完全背包问题", "dp[x] = min(dp[x-coin]+1)"], "tags": ["dp", "medium", "Google", "Amazon"]} {"problem_id": "algo_01613", "original_id": "subsets", "title": "子集", "category": "backtracking", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "给你一个整数数组 nums ,数组中的元素 互不相同 。返回该数组所有可能的子集(幂集)。", "solution_python": "def subsets(nums):\n result = []\n def backtrack(start, path):\n result.append(path[:])\n for i in range(start, len(nums)):\n path.append(nums[i])\n backtrack(i + 1, path)\n path.pop()\n backtrack(0, [])\n return result", "solution_java": "public List> subsets(int[] nums) {\n List> result = new ArrayList<>();\n backtrack(nums, 0, new ArrayList<>(), result);\n return result;\n}\nprivate void backtrack(int[] nums, int start, List path, List> result) {\n result.add(new ArrayList<>(path));\n for (int i = start; i < nums.length; i++) {\n path.add(nums[i]);\n backtrack(nums, i + 1, path, result);\n path.remove(path.size() - 1);\n }\n}", "solution_cpp": "vector> subsets(vector& nums) {\n vector> result;\n vector path;\n backtrack(nums, 0, path, result);\n return result;\n}\nvoid backtrack(vector& nums, int start, vector& path, vector>& result) {\n result.push_back(path);\n for (int i = start; i < nums.size(); i++) {\n path.push_back(nums[i]);\n backtrack(nums, i + 1, path, result);\n path.pop_back();\n }\n}", "test_cases": ["nums=[1,2,3] -> [[],[1],[2],[1,2],[3],[1,3],[2,3],[1,2,3]]"], "key_points": ["选或不选", "DFS遍历子集树"], "tags": ["backtracking", "medium", "Google", "Microsoft"]} {"problem_id": "algo_01614", "original_id": "permutations", "title": "全排列", "category": "backtracking", "difficulty": "medium", "companies": ["Google", "Facebook"], "description": "给定一个不含重复数字的数组 nums,返回其所有可能的全排列。", "solution_python": "def permute(nums):\n result = []\n def backtrack(path, used):\n if len(path) == len(nums):\n result.append(path[:])\n return\n for i in range(len(nums)):\n if used[i]: continue\n used[i] = True\n path.append(nums[i])\n backtrack(path, used)\n path.pop()\n used[i] = False\n backtrack([], [False]*len(nums))\n return result", "solution_java": "public List> permute(int[] nums) {\n List> result = new ArrayList<>();\n boolean[] used = new boolean[nums.length];\n backtrack(nums, used, new ArrayList<>(), result);\n return result;\n}\nprivate void backtrack(int[] nums, boolean[] used, List path, List> result) {\n if (path.size() == nums.length) { result.add(new ArrayList<>(path)); return; }\n for (int i = 0; i < nums.length; i++) {\n if (used[i]) continue;\n used[i] = true;\n path.add(nums[i]);\n backtrack(nums, used, path, result);\n path.remove(path.size() - 1);\n used[i] = false;\n }\n}", "solution_cpp": "vector> permute(vector& nums) {\n vector> result;\n vector used(nums.size(), false);\n vector path;\n backtrack(nums, used, path, result);\n return result;\n}\nvoid backtrack(vector& nums, vector& used, vector& path, vector>& result) {\n if (path.size() == nums.size()) { result.push_back(path); return; }\n for (int i = 0; i < nums.size(); i++) {\n if (used[i]) continue;\n used[i] = true;\n path.push_back(nums[i]);\n backtrack(nums, used, path, result);\n path.pop_back();\n used[i] = false;\n }\n}", "test_cases": ["nums=[1,2,3] -> [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]"], "key_points": ["标记已使用元素", "回溯经典模板"], "tags": ["backtracking", "medium", "Google", "Facebook"]} {"problem_id": "algo_01615", "original_id": "top-k-frequent", "title": "前K个高频元素", "category": "heap", "difficulty": "medium", "companies": ["Amazon", "Facebook"], "description": "给你一个整数数组 nums 和一个整数 k,请你返回其中出现频率前 k 高的元素。", "solution_python": "import heapq\nfrom collections import Counter\ndef topKFrequent(nums, k):\n count = Counter(nums)\n heap = []\n for num, freq in count.items():\n heapq.heappush(heap, (freq, num))\n if len(heap) > k: heapq.heappop(heap)\n return [num for freq, num in heap]", "solution_java": "public int[] topKFrequent(int[] nums, int k) {\n Map count = new HashMap<>();\n for (int n : nums) count.put(n, count.getOrDefault(n, 0) + 1);\n PriorityQueue> heap = \n new PriorityQueue<>((a, b) -> a.getValue() - b.getValue());\n for (Map.Entry e : count.entrySet()) {\n heap.offer(e);\n if (heap.size() > k) heap.poll();\n }\n int[] res = new int[k];\n for (int i = k - 1; i >= 0; i--) res[i] = heap.poll().getKey();\n return res;\n}", "solution_cpp": "vector topKFrequent(vector& nums, int k) {\n unordered_map count;\n for (int n : nums) count[n]++;\n priority_queue, vector>, greater>> heap;\n for (auto& [num, freq] : count) {\n heap.push({freq, num});\n if (heap.size() > k) heap.pop();\n }\n vector res;\n while (!heap.empty()) { res.push_back(heap.top().second); heap.pop(); }\n reverse(res.begin(), res.end());\n return res;\n}", "test_cases": ["nums=[1,1,1,2,2,3], k=2 -> [1,2]", "nums=[1], k=1 -> [1]"], "key_points": ["小顶堆保持大小k", "时间复杂度O(nlogk)"], "tags": ["heap", "medium", "Amazon", "Facebook"]} {"problem_id": "algo_01616", "original_id": "3sum", "title": "三数之和", "category": "two-pointers", "difficulty": "medium", "companies": ["Google", "Amazon"], "description": "给你一个整数数组 nums,判断是否存在三元组满足和为0,返回所有不重复的三元组。", "solution_python": "def threeSum(nums):\n nums.sort()\n result = []\n for i in range(len(nums) - 2):\n if i > 0 and nums[i] == nums[i-1]: continue\n left, right = i + 1, len(nums) - 1\n while left < right:\n total = nums[i] + nums[left] + nums[right]\n if total < 0: left += 1\n elif total > 0: right -= 1\n else:\n result.append([nums[i], nums[left], nums[right]])\n while left < right and nums[left] == nums[left+1]: left += 1\n while left < right and nums[right] == nums[right-1]: right -= 1\n left += 1; right -= 1\n return result", "solution_java": "public List> threeSum(int[] nums) {\n Arrays.sort(nums);\n List> result = new ArrayList<>();\n for (int i = 0; i < nums.length - 2; i++) {\n if (i > 0 && nums[i] == nums[i-1]) continue;\n int left = i + 1, right = nums.length - 1;\n while (left < right) {\n int total = nums[i] + nums[left] + nums[right];\n if (total < 0) left++;\n else if (total > 0) right--;\n else {\n result.add(Arrays.asList(nums[i], nums[left], nums[right]));\n while (left < right && nums[left] == nums[left+1]) left++;\n while (left < right && nums[right] == nums[right-1]) right--;\n left++; right--;\n }\n }\n }\n return result;\n}", "solution_cpp": "vector> threeSum(vector& nums) {\n sort(nums.begin(), nums.end());\n vector> result;\n for (int i = 0; i < nums.size() - 2; i++) {\n if (i > 0 && nums[i] == nums[i-1]) continue;\n int left = i + 1, right = nums.size() - 1;\n while (left < right) {\n int total = nums[i] + nums[left] + nums[right];\n if (total < 0) left++;\n else if (total > 0) right--;\n else {\n result.push_back({nums[i], nums[left], nums[right]});\n while (left < right && nums[left] == nums[left+1]) left++;\n while (left < right && nums[right] == nums[right-1]) right--;\n left++; right--;\n }\n }\n }\n return result;\n}", "test_cases": ["nums=[-1,0,1,2,-1,-4] -> [[-1,-1,2],[-1,0,1]]"], "key_points": ["排序+双指针", "去重是关键"], "tags": ["two-pointers", "medium", "Google", "Amazon"]} {"problem_id": "algo_01617", "original_id": "container-water", "title": "盛最多水的容器", "category": "two-pointers", "difficulty": "medium", "companies": ["Google", "Uber"], "description": "给定一个长度为 n 的整数数组 height,找出其中的两条线,使得它们与 x 轴共同构成的容器可以容纳最多的水。", "solution_python": "def maxArea(height):\n left, right = 0, len(height) - 1\n max_area = 0\n while left < right:\n h = min(height[left], height[right])\n max_area = max(max_area, h * (right - left))\n if height[left] < height[right]: left += 1\n else: right -= 1\n return max_area", "solution_java": "public int maxArea(int[] height) {\n int left = 0, right = height.length - 1, maxArea = 0;\n while (left < right) {\n int h = Math.min(height[left], height[right]);\n maxArea = Math.max(maxArea, h * (right - left));\n if (height[left] < height[right]) left++;\n else right--;\n }\n return maxArea;\n}", "solution_cpp": "int maxArea(vector& height) {\n int left = 0, right = height.size() - 1, maxArea = 0;\n while (left < right) {\n int h = min(height[left], height[right]);\n maxArea = max(maxArea, h * (right - left));\n if (height[left] < height[right]) left++;\n else right--;\n }\n return maxArea;\n}", "test_cases": ["height=[1,8,6,2,5,4,8,3,7] -> 49"], "key_points": ["移动短边指针", "面积=min(h1,h2)*width"], "tags": ["two-pointers", "medium", "Google", "Uber"]} {"problem_id": "algo_01618", "original_id": "min-stack", "title": "最小栈", "category": "stack", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "设计一个支持 push,pop,top 操作,并能在常数时间内检索到最小元素的栈。", "solution_python": "class MinStack:\n def __init__(self):\n self.stack = []\n self.min_stack = []\n def push(self, val):\n self.stack.append(val)\n self.min_stack.append(min(val, self.min_stack[-1] if self.min_stack else val))\n def pop(self):\n self.stack.pop(); self.min_stack.pop()\n def top(self): return self.stack[-1]\n def getMin(self): return self.min_stack[-1]", "solution_java": "class MinStack {\n Stack stack = new Stack<>();\n Stack minStack = new Stack<>();\n public void push(int val) { stack.push(val); minStack.push(Math.min(val, minStack.isEmpty() ? val : minStack.peek())); }\n public void pop() { stack.pop(); minStack.pop(); }\n public int top() { return stack.peek(); }\n public int getMin() { return minStack.peek(); }\n}", "solution_cpp": "class MinStack {\n stack st, minSt;\npublic:\n void push(int val) { st.push(val); minSt.push(min(val, minSt.empty() ? val : minSt.top())); }\n void pop() { st.pop(); minSt.pop(); }\n int top() { return st.top(); }\n int getMin() { return minSt.top(); }\n};", "test_cases": ["push(-2), push(0), push(-3) -> getMin() returns -3"], "key_points": ["辅助栈记录最小值", "O(1)时间获取最小值"], "tags": ["stack", "medium", "Google", "Microsoft"]} {"problem_id": "algo_01619", "original_id": "lru-cache", "title": "LRU缓存", "category": "design", "difficulty": "hard", "companies": ["Google", "Amazon"], "description": "设计和实现一个 LRU(最近最少使用)缓存机制。", "solution_python": "class LRUCache:\n def __init__(self, capacity):\n self.capacity = capacity\n self.cache = {}\n self.order = []\n def get(self, key):\n if key not in self.cache: return -1\n self.order.remove(key); self.order.append(key)\n return self.cache[key]\n def put(self, key, value):\n if key in self.cache:\n self.order.remove(key)\n elif len(self.cache) >= self.capacity:\n del self.cache[self.order.pop(0)]\n self.cache[key] = value; self.order.append(key)", "solution_java": "class LRUCache {\n int capacity;\n LinkedHashMap cache = new LinkedHashMap<>();\n public LRUCache(int cap) { capacity = cap; }\n public int get(int key) { return cache.containsKey(key) ? cache.remove(key) : -1; }\n public void put(int key, int val) {\n if (cache.containsKey(key)) cache.remove(key);\n else if (cache.size() >= capacity) cache.remove(cache.keySet().iterator().next());\n cache.put(key, val);\n }\n}", "solution_cpp": "class LRUCache {\n int cap;\n list> dll;\n unordered_map>::iterator> cache;\npublic:\n LRUCache(int capacity) : cap(capacity) {}\n int get(int key) {\n auto it = cache.find(key);\n if (it == cache.end()) return -1;\n dll.splice(dll.end(), dll, it->second);\n return it->second->second;\n }\n void put(int key, int value) {\n auto it = cache.find(key);\n if (it != cache.end()) dll.erase(it->second);\n else if (cache.size() >= cap) { cache.erase(dll.front().first); dll.pop_front(); }\n dll.push_back({key, value});\n cache[key] = --dll.end();\n }\n};", "test_cases": ["put(1,1), put(2,2), get(1) -> 1"], "key_points": ["HashMap + 双向链表", "O(1)时间操作"], "tags": ["design", "hard", "Google", "Amazon"]} {"problem_id": "algo_01620", "original_id": "num-islands", "title": "岛屿数量", "category": "graph", "difficulty": "medium", "companies": ["Google", "Facebook"], "description": "给你一个由 '1'(陆地)和 '0'(水)组成的二维网格,请你计算网格中岛屿的数量。岛屿总是被水包围,且只能由水平或垂直方向相邻的陆地连接形成。", "solution_python": "def numIslands(grid):\n if not grid: return 0\n rows, cols = len(grid), len(grid[0])\n count = 0\n def dfs(r, c):\n if r < 0 or r >= rows or c < 0 or c >= cols or grid[r][c] != '1': return\n grid[r][c] = '0'\n dfs(r+1, c); dfs(r-1, c); dfs(r, c+1); dfs(r, c-1)\n for r in range(rows):\n for c in range(cols):\n if grid[r][c] == '1': count += 1; dfs(r, c)\n return count", "solution_java": "public int numIslands(char[][] grid) {\n if (grid.length == 0) return 0;\n int count = 0;\n for (int i = 0; i < grid.length; i++)\n for (int j = 0; j < grid[0].length; j++)\n if (grid[i][j] == '1') { count++; dfs(grid, i, j); }\n return count;\n}\nprivate void dfs(char[][] grid, int r, int c) {\n if (r < 0 || r >= grid.length || c < 0 || c >= grid[0].length || grid[r][c] != '1') return;\n grid[r][c] = '0';\n dfs(grid, r+1, c); dfs(grid, r-1, c); dfs(grid, r, c+1); dfs(grid, r, c-1);\n}", "solution_cpp": "int numIslands(vector>& grid) {\n if (grid.empty()) return 0;\n int count = 0;\n for (int i = 0; i < grid.size(); i++)\n for (int j = 0; j < grid[0].size(); j++)\n if (grid[i][j] == '1') { count++; dfs(grid, i, j); }\n return count;\n}\nvoid dfs(vector>& grid, int r, int c) {\n if (r < 0 || r >= grid.size() || c < 0 || c >= grid[0].size() || grid[r][c] != '1') return;\n grid[r][c] = '0';\n dfs(grid, r+1, c); dfs(grid, r-1, c); dfs(grid, r, c+1); dfs(grid, r, c-1);\n}", "test_cases": ["grid=[[1,1,1,1,0],[1,1,0,1,0],[1,1,0,0,0],[0,0,0,0,0]] -> 1"], "key_points": ["DFS/BFS遍历", "访问后标记为0避免重复"], "tags": ["graph", "medium", "Google", "Facebook"]} {"problem_id": "algo_01621", "original_id": "two-sum", "title": "两数之和", "category": "array", "difficulty": "easy", "companies": ["Amazon", "Google"], "description": "给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那两个整数,并返回他们的数组下标。", "solution_python": "def twoSum(nums, target):\n hashmap = {}\n for i, num in enumerate(nums):\n complement = target - num\n if complement in hashmap:\n return [hashmap[complement], i]\n hashmap[num] = i\n return []", "solution_java": "public int[] twoSum(int[] nums, int target) {\n Map map = new HashMap<>();\n for (int i = 0; i < nums.length; i++) {\n int complement = target - nums[i];\n if (map.containsKey(complement)) return new int[]{map.get(complement), i};\n map.put(nums[i], i);\n }\n return new int[]{};\n}", "solution_cpp": "vector twoSum(vector& nums, int target) {\n unordered_map m;\n for (int i = 0; i < nums.size(); i++) {\n if (m.count(target - nums[i])) return {m[target - nums[i]], i};\n m[nums[i]] = i;\n }\n return {};\n}", "test_cases": ["nums=[2,7,11,15], target=9 -> [0,1]", "nums=[3,2,4], target=6 -> [1,2]"], "key_points": ["哈希表一次遍历", "空间换时间"], "tags": ["array", "easy", "Amazon", "Google"]} {"problem_id": "algo_01622", "original_id": "merge-sorted", "title": "合并两个有序数组", "category": "array", "difficulty": "easy", "companies": ["Microsoft", "Uber"], "description": "给你两个按非递减顺序排列的整数数组 nums1 和 nums2,另有两个整数 m 和 n,分别表示 nums1 和 nums2 中的元素数目。请你合并 nums2 到 nums1 中。", "solution_python": "def merge(nums1, m, nums2, n):\n p1, p2, p = m-1, n-1, m+n-1\n while p1 >= 0 and p2 >= 0:\n if nums1[p1] > nums2[p2]: nums1[p] = nums1[p1]; p1 -= 1\n else: nums1[p] = nums2[p2]; p2 -= 1\n p -= 1\n while p2 >= 0: nums1[p] = nums2[p2]; p2 -= 1; p -= 1", "solution_java": "public void merge(int[] nums1, int m, int[] nums2, int n) {\n int p1 = m-1, p2 = n-1, p = m+n-1;\n while (p1 >= 0 && p2 >= 0) {\n nums1[p--] = nums1[p1] > nums2[p2] ? nums1[p1--] : nums2[p2--];\n }\n while (p2 >= 0) nums1[p--] = nums2[p2--];\n}", "solution_cpp": "void merge(vector& nums1, int m, vector& nums2, int n) {\n int p1 = m-1, p2 = n-1, p = m+n-1;\n while (p1 >= 0 && p2 >= 0) nums1[p--] = nums1[p1] > nums2[p2] ? nums1[p1--] : nums2[p2--];\n while (p2 >= 0) nums1[p--] = nums2[p2--];\n}", "test_cases": ["nums1=[1,2,3], m=3, nums2=[2,5,6], n=3 -> [1,2,2,3,5,6]", "nums1=[], m=0, nums2=[1], n=1 -> [1]"], "key_points": ["从后往前合并", "三指针技巧"], "tags": ["array", "easy", "Microsoft", "Uber"]} {"problem_id": "algo_01623", "original_id": "max-subarray", "title": "最大子数组和", "category": "array", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "给你一个整数数组 nums ,请你找出一个具有最大和的连续子数组,返回其最大和。", "solution_python": "def maxSubArray(nums):\n max_sum = current = nums[0]\n for num in nums[1:]:\n current = max(num, current + num)\n max_sum = max(max_sum, current)\n return max_sum", "solution_java": "public int maxSubArray(int[] nums) {\n int maxSum = nums[0], curr = nums[0];\n for (int i = 1; i < nums.length; i++) {\n curr = Math.max(nums[i], curr + nums[i]);\n maxSum = Math.max(maxSum, curr);\n }\n return maxSum;\n}", "solution_cpp": "int maxSubArray(vector& nums) {\n int maxSum = nums[0], curr = nums[0];\n for (int i = 1; i < nums.size(); i++) {\n curr = max(nums[i], curr + nums[i]);\n maxSum = max(maxSum, curr);\n }\n return maxSum;\n}", "test_cases": ["nums=[-2,1,-3,4,-1,2,1,-5,4] -> 6", "nums=[1] -> 1"], "key_points": ["Kadane算法", "动态规划基础题"], "tags": ["array", "medium", "Google", "Microsoft"]} {"problem_id": "algo_01624", "original_id": "valid-parentheses", "title": "有效的括号", "category": "string", "difficulty": "easy", "companies": ["Google", "Uber"], "description": "给定一个只包括 '(',')','{','}','[',']' 的字符串 s,判断字符串是否有效。", "solution_python": "def isValid(s):\n stack = []\n mapping = {')': '(', ']': '[', '}': '{'}\n for c in s:\n if c in mapping:\n if not stack or stack[-1] != mapping[c]: return False\n stack.pop()\n else: stack.append(c)\n return not stack", "solution_java": "public boolean isValid(String s) {\n Stack stack = new Stack<>();\n Map map = Map.of(')', '(', ']', '[', '}', '{');\n for (char c : s.toCharArray()) {\n if (map.containsValue(c)) stack.push(c);\n else if (!stack.isEmpty() && stack.pop() != map.get(c)) return false;\n }\n return stack.isEmpty();\n}", "solution_cpp": "bool isValid(string s) {\n stack st;\n unordered_map m = {{')','('},{']','['},{'}','{'}};\n for (char c : s) {\n if (m.find(c) == m.end()) st.push(c);\n else if (st.empty() || st.top() != m[c]) return false;\n else st.pop();\n }\n return st.empty();\n}", "test_cases": ["s=\"()\" -> true", "s=\"()[]{}\" -> true", "s=\"(]\" -> false"], "key_points": ["栈匹配法", "注意空栈边界"], "tags": ["string", "easy", "Google", "Uber"]} {"problem_id": "algo_01625", "original_id": "longest-palindrome", "title": "最长回文子串", "category": "string", "difficulty": "medium", "companies": ["Google", "Amazon"], "description": "给你一个字符串 s,找到 s 中最长的回文子串。", "solution_python": "def longestPalindrome(s):\n def expand(l, r):\n while l >= 0 and r < len(s) and s[l] == s[r]: l -= 1; r += 1\n return l + 1, r - 1\n start = end = 0\n for i in range(len(s)):\n l1, r1 = expand(i, i)\n l2, r2 = expand(i, i + 1)\n if r1 - l1 > end - start: start, end = l1, r1\n if r2 - l2 > end - start: start, end = l2, r2\n return s[start:end+1]", "solution_java": "public String longestPalindrome(String s) {\n int start = 0, end = 0;\n for (int i = 0; i < s.length(); i++) {\n int len1 = expand(s, i, i), len2 = expand(s, i, i+1);\n int len = Math.max(len1, len2);\n if (len > end - start) { start = i - (len-1)/2; end = i + len/2; }\n }\n return s.substring(start, end + 1);\n}\nprivate int expand(String s, int l, int r) {\n while (l >= 0 && r < s.length() && s.charAt(l) == s.charAt(r)) { l--; r++; }\n return r - l - 1;\n}", "solution_cpp": "string longestPalindrome(string s) {\n int start = 0, end = 0;\n for (int i = 0; i < s.size(); i++) {\n int len1 = expand(s, i, i), len2 = expand(s, i, i+1);\n if (max(len1, len2) > end - start) { start = i - (max(len1,len2)-1)/2; end = i + max(len1,len2)/2; }\n }\n return s.substr(start, end - start + 1);\n}", "test_cases": ["s=\"babad\" -> bab或aba", "s=\"cbbd\" -> bb"], "key_points": ["中心扩展法", "处理奇偶长度"], "tags": ["string", "medium", "Google", "Amazon"]} {"problem_id": "algo_01626", "original_id": "reverse-list", "title": "反转链表", "category": "linkedlist", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "给你单链表的头节点 head,请你反转链表,并返回反转后的链表。", "solution_python": "def reverseList(head):\n prev = None\n curr = head\n while curr:\n nxt = curr.next\n curr.next = prev\n prev = curr\n curr = nxt\n return prev", "solution_java": "public ListNode reverseList(ListNode head) {\n ListNode prev = null, curr = head;\n while (curr != null) {\n ListNode next = curr.next;\n curr.next = prev;\n prev = curr;\n curr = next;\n }\n return prev;\n}", "solution_cpp": "ListNode* reverseList(ListNode* head) {\n ListNode* prev = nullptr, *curr = head;\n while (curr) {\n ListNode* next = curr->next;\n curr->next = prev;\n prev = curr;\n curr = next;\n }\n return prev;\n}", "test_cases": ["head=[1,2,3,4,5] -> [5,4,3,2,1]", "head=[1,2] -> [2,1]"], "key_points": ["迭代法 O(1)空间", "递归法 O(n)空间"], "tags": ["linkedlist", "medium", "Google", "Microsoft"]} {"problem_id": "algo_01627", "original_id": "middle-node", "title": "链表的中间结点", "category": "linkedlist", "difficulty": "easy", "companies": ["Amazon", "Facebook"], "description": "给你单链表的头节点 head,请你找出并返回链表的中间结点。如果有两个中间结点,则返回第二个中间结点。", "solution_python": "def middleNode(head):\n slow = fast = head\n while fast and fast.next:\n slow = slow.next\n fast = fast.next.next\n return slow", "solution_java": "public ListNode middleNode(ListNode head) {\n ListNode slow = head, fast = head;\n while (fast != null && fast.next != null) {\n slow = slow.next;\n fast = fast.next.next;\n }\n return slow;\n}", "solution_cpp": "ListNode* middleNode(ListNode* head) {\n ListNode* slow = head, *fast = head;\n while (fast && fast->next) { slow = slow->next; fast = fast->next->next; }\n return slow;\n}", "test_cases": ["head=[1,2,3,4,5] -> 3", "head=[1,2,3,4,5,6] -> 4"], "key_points": ["快慢指针", "O(n)时间O(1)空间"], "tags": ["linkedlist", "easy", "Amazon", "Facebook"]} {"problem_id": "algo_01628", "original_id": "max-depth", "title": "二叉树的最大深度", "category": "tree", "difficulty": "easy", "companies": ["Microsoft", "Apple"], "description": "给定一个二叉树 root,返回其最大深度。", "solution_python": "def maxDepth(root):\n if not root: return 0\n return max(maxDepth(root.left), maxDepth(root.right)) + 1", "solution_java": "public int maxDepth(TreeNode root) {\n if (root == null) return 0;\n return Math.max(maxDepth(root.left), maxDepth(root.right)) + 1;\n}", "solution_cpp": "int maxDepth(TreeNode* root) {\n if (!root) return 0;\n return max(maxDepth(root->left), maxDepth(root->right)) + 1;\n}", "test_cases": ["root=[3,9,20,null,null,15,7] -> 3", "root=[1,null,2] -> 2"], "key_points": ["DFS递归", "层序遍历也可"], "tags": ["tree", "easy", "Microsoft", "Apple"]} {"problem_id": "algo_01629", "original_id": "inorder-traversal", "title": "二叉树的中序遍历", "category": "tree", "difficulty": "easy", "companies": ["Google", "Microsoft"], "description": "给定一个二叉树的根节点 root,返回它的中序遍历结果。", "solution_python": "def inorderTraversal(root):\n result = []\n def dfs(node):\n if node:\n dfs(node.left)\n result.append(node.val)\n dfs(node.right)\n dfs(root)\n return result", "solution_java": "public List inorderTraversal(TreeNode root) {\n List res = new ArrayList<>();\n dfs(root, res);\n return res;\n}\nprivate void dfs(TreeNode node, List res) {\n if (node == null) return;\n dfs(node.left, res); res.add(node.val); dfs(node.right, res);\n}", "solution_cpp": "vector inorderTraversal(TreeNode* root) {\n vector res;\n dfs(root, res);\n return res;\n}\nvoid dfs(TreeNode* node, vector& res) {\n if (!node) return;\n dfs(node->left, res); res.push_back(node->val); dfs(node->right, res);\n}", "test_cases": ["root=[1,null,2,3] -> [1,3,2]", "root=[] -> []"], "key_points": ["左-根-右顺序", "递归最简洁"], "tags": ["tree", "easy", "Google", "Microsoft"]} {"problem_id": "algo_01630", "original_id": "binary-search", "title": "二分查找", "category": "binarysearch", "difficulty": "easy", "companies": ["Google", "Amazon"], "description": "给定一个 n 个元素有序的(升序)整型数组 nums 和一个目标值 target,写一个函数搜索 nums 中的 target,如果目标值存在返回下标,否则返回 -1。", "solution_python": "def search(nums, target):\n left, right = 0, len(nums) - 1\n while left <= right:\n mid = (left + right) // 2\n if nums[mid] == target: return mid\n elif nums[mid] < target: left = mid + 1\n else: right = mid - 1\n return -1", "solution_java": "public int search(int[] nums, int target) {\n int left = 0, right = nums.length - 1;\n while (left <= right) {\n int mid = left + (right - left) / 2;\n if (nums[mid] == target) return mid;\n else if (nums[mid] < target) left = mid + 1;\n else right = mid - 1;\n }\n return -1;\n}", "solution_cpp": "int search(vector& nums, int target) {\n int left = 0, right = nums.size() - 1;\n while (left <= right) {\n int mid = left + (right - left) / 2;\n if (nums[mid] == target) return mid;\n else if (nums[mid] < target) left = mid + 1;\n else right = mid - 1;\n }\n return -1;\n}", "test_cases": ["nums=[-1,0,3,5,9,12], target=9 -> 4", "nums=[-1,0,3,5,9,12], target=2 -> -1"], "key_points": ["标准模板", "注意防溢出写法"], "tags": ["binarysearch", "easy", "Google", "Amazon"]} {"problem_id": "algo_01631", "original_id": "climbing-stairs", "title": "爬楼梯", "category": "dp", "difficulty": "easy", "companies": ["Amazon", "Google"], "description": "假设你正在爬楼梯。需要 n 阶你才能到达楼顶。每次你可以爬 1 或 2 个台阶。你有多少种不同的方法可以爬到楼顶?", "solution_python": "def climbStairs(n):\n if n <= 2: return n\n a, b = 1, 2\n for _ in range(3, n+1):\n a, b = b, a + b\n return b", "solution_java": "public int climbStairs(int n) {\n if (n <= 2) return n;\n int a = 1, b = 2;\n for (int i = 3; i <= n; i++) { int temp = a + b; a = b; b = temp; }\n return b;\n}", "solution_cpp": "int climbStairs(int n) {\n if (n <= 2) return n;\n int a = 1, b = 2;\n for (int i = 3; i <= n; i++) { int temp = a + b; a = b; b = temp; }\n return b;\n}", "test_cases": ["n=2 -> 2", "n=3 -> 3", "n=5 -> 8"], "key_points": ["斐波那契数列", "滚动数组优化空间"], "tags": ["dp", "easy", "Amazon", "Google"]} {"problem_id": "algo_01632", "original_id": "coin-change", "title": "零钱兑换", "category": "dp", "difficulty": "medium", "companies": ["Google", "Amazon"], "description": "给你一个整数数组 coins 表示不同面额的硬币,以及一个整数 amount 表示总金额。计算并返回可以凑成总金额所需的最少的硬币个数。如果没有任何一种硬币组合能组成总金额,返回 -1。", "solution_python": "def coinChange(coins, amount):\n dp = [float('inf')] * (amount + 1)\n dp[0] = 0\n for coin in coins:\n for x in range(coin, amount + 1):\n dp[x] = min(dp[x], dp[x - coin] + 1)\n return dp[amount] if dp[amount] != float('inf') else -1", "solution_java": "public int coinChange(int[] coins, int amount) {\n int[] dp = new int[amount + 1];\n Arrays.fill(dp, amount + 1);\n dp[0] = 0;\n for (int coin : coins) {\n for (int x = coin; x <= amount; x++) {\n dp[x] = Math.min(dp[x], dp[x - coin] + 1);\n }\n }\n return dp[amount] > amount ? -1 : dp[amount];\n}", "solution_cpp": "int coinChange(vector& coins, int amount) {\n vector dp(amount + 1, amount + 1);\n dp[0] = 0;\n for (int coin : coins) {\n for (int x = coin; x <= amount; x++) {\n dp[x] = min(dp[x], dp[x - coin] + 1);\n }\n }\n return dp[amount] > amount ? -1 : dp[amount];\n}", "test_cases": ["coins=[1,2,5], amount=11 -> 3", "coins=[2], amount=3 -> -1"], "key_points": ["完全背包问题", "dp[x] = min(dp[x-coin]+1)"], "tags": ["dp", "medium", "Google", "Amazon"]} {"problem_id": "algo_01633", "original_id": "subsets", "title": "子集", "category": "backtracking", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "给你一个整数数组 nums ,数组中的元素 互不相同 。返回该数组所有可能的子集(幂集)。", "solution_python": "def subsets(nums):\n result = []\n def backtrack(start, path):\n result.append(path[:])\n for i in range(start, len(nums)):\n path.append(nums[i])\n backtrack(i + 1, path)\n path.pop()\n backtrack(0, [])\n return result", "solution_java": "public List> subsets(int[] nums) {\n List> result = new ArrayList<>();\n backtrack(nums, 0, new ArrayList<>(), result);\n return result;\n}\nprivate void backtrack(int[] nums, int start, List path, List> result) {\n result.add(new ArrayList<>(path));\n for (int i = start; i < nums.length; i++) {\n path.add(nums[i]);\n backtrack(nums, i + 1, path, result);\n path.remove(path.size() - 1);\n }\n}", "solution_cpp": "vector> subsets(vector& nums) {\n vector> result;\n vector path;\n backtrack(nums, 0, path, result);\n return result;\n}\nvoid backtrack(vector& nums, int start, vector& path, vector>& result) {\n result.push_back(path);\n for (int i = start; i < nums.size(); i++) {\n path.push_back(nums[i]);\n backtrack(nums, i + 1, path, result);\n path.pop_back();\n }\n}", "test_cases": ["nums=[1,2,3] -> [[],[1],[2],[1,2],[3],[1,3],[2,3],[1,2,3]]"], "key_points": ["选或不选", "DFS遍历子集树"], "tags": ["backtracking", "medium", "Google", "Microsoft"]} {"problem_id": "algo_01634", "original_id": "permutations", "title": "全排列", "category": "backtracking", "difficulty": "medium", "companies": ["Google", "Facebook"], "description": "给定一个不含重复数字的数组 nums,返回其所有可能的全排列。", "solution_python": "def permute(nums):\n result = []\n def backtrack(path, used):\n if len(path) == len(nums):\n result.append(path[:])\n return\n for i in range(len(nums)):\n if used[i]: continue\n used[i] = True\n path.append(nums[i])\n backtrack(path, used)\n path.pop()\n used[i] = False\n backtrack([], [False]*len(nums))\n return result", "solution_java": "public List> permute(int[] nums) {\n List> result = new ArrayList<>();\n boolean[] used = new boolean[nums.length];\n backtrack(nums, used, new ArrayList<>(), result);\n return result;\n}\nprivate void backtrack(int[] nums, boolean[] used, List path, List> result) {\n if (path.size() == nums.length) { result.add(new ArrayList<>(path)); return; }\n for (int i = 0; i < nums.length; i++) {\n if (used[i]) continue;\n used[i] = true;\n path.add(nums[i]);\n backtrack(nums, used, path, result);\n path.remove(path.size() - 1);\n used[i] = false;\n }\n}", "solution_cpp": "vector> permute(vector& nums) {\n vector> result;\n vector used(nums.size(), false);\n vector path;\n backtrack(nums, used, path, result);\n return result;\n}\nvoid backtrack(vector& nums, vector& used, vector& path, vector>& result) {\n if (path.size() == nums.size()) { result.push_back(path); return; }\n for (int i = 0; i < nums.size(); i++) {\n if (used[i]) continue;\n used[i] = true;\n path.push_back(nums[i]);\n backtrack(nums, used, path, result);\n path.pop_back();\n used[i] = false;\n }\n}", "test_cases": ["nums=[1,2,3] -> [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]"], "key_points": ["标记已使用元素", "回溯经典模板"], "tags": ["backtracking", "medium", "Google", "Facebook"]} {"problem_id": "algo_01635", "original_id": "top-k-frequent", "title": "前K个高频元素", "category": "heap", "difficulty": "medium", "companies": ["Amazon", "Facebook"], "description": "给你一个整数数组 nums 和一个整数 k,请你返回其中出现频率前 k 高的元素。", "solution_python": "import heapq\nfrom collections import Counter\ndef topKFrequent(nums, k):\n count = Counter(nums)\n heap = []\n for num, freq in count.items():\n heapq.heappush(heap, (freq, num))\n if len(heap) > k: heapq.heappop(heap)\n return [num for freq, num in heap]", "solution_java": "public int[] topKFrequent(int[] nums, int k) {\n Map count = new HashMap<>();\n for (int n : nums) count.put(n, count.getOrDefault(n, 0) + 1);\n PriorityQueue> heap = \n new PriorityQueue<>((a, b) -> a.getValue() - b.getValue());\n for (Map.Entry e : count.entrySet()) {\n heap.offer(e);\n if (heap.size() > k) heap.poll();\n }\n int[] res = new int[k];\n for (int i = k - 1; i >= 0; i--) res[i] = heap.poll().getKey();\n return res;\n}", "solution_cpp": "vector topKFrequent(vector& nums, int k) {\n unordered_map count;\n for (int n : nums) count[n]++;\n priority_queue, vector>, greater>> heap;\n for (auto& [num, freq] : count) {\n heap.push({freq, num});\n if (heap.size() > k) heap.pop();\n }\n vector res;\n while (!heap.empty()) { res.push_back(heap.top().second); heap.pop(); }\n reverse(res.begin(), res.end());\n return res;\n}", "test_cases": ["nums=[1,1,1,2,2,3], k=2 -> [1,2]", "nums=[1], k=1 -> [1]"], "key_points": ["小顶堆保持大小k", "时间复杂度O(nlogk)"], "tags": ["heap", "medium", "Amazon", "Facebook"]} {"problem_id": "algo_01636", "original_id": "3sum", "title": "三数之和", "category": "two-pointers", "difficulty": "medium", "companies": ["Google", "Amazon"], "description": "给你一个整数数组 nums,判断是否存在三元组满足和为0,返回所有不重复的三元组。", "solution_python": "def threeSum(nums):\n nums.sort()\n result = []\n for i in range(len(nums) - 2):\n if i > 0 and nums[i] == nums[i-1]: continue\n left, right = i + 1, len(nums) - 1\n while left < right:\n total = nums[i] + nums[left] + nums[right]\n if total < 0: left += 1\n elif total > 0: right -= 1\n else:\n result.append([nums[i], nums[left], nums[right]])\n while left < right and nums[left] == nums[left+1]: left += 1\n while left < right and nums[right] == nums[right-1]: right -= 1\n left += 1; right -= 1\n return result", "solution_java": "public List> threeSum(int[] nums) {\n Arrays.sort(nums);\n List> result = new ArrayList<>();\n for (int i = 0; i < nums.length - 2; i++) {\n if (i > 0 && nums[i] == nums[i-1]) continue;\n int left = i + 1, right = nums.length - 1;\n while (left < right) {\n int total = nums[i] + nums[left] + nums[right];\n if (total < 0) left++;\n else if (total > 0) right--;\n else {\n result.add(Arrays.asList(nums[i], nums[left], nums[right]));\n while (left < right && nums[left] == nums[left+1]) left++;\n while (left < right && nums[right] == nums[right-1]) right--;\n left++; right--;\n }\n }\n }\n return result;\n}", "solution_cpp": "vector> threeSum(vector& nums) {\n sort(nums.begin(), nums.end());\n vector> result;\n for (int i = 0; i < nums.size() - 2; i++) {\n if (i > 0 && nums[i] == nums[i-1]) continue;\n int left = i + 1, right = nums.size() - 1;\n while (left < right) {\n int total = nums[i] + nums[left] + nums[right];\n if (total < 0) left++;\n else if (total > 0) right--;\n else {\n result.push_back({nums[i], nums[left], nums[right]});\n while (left < right && nums[left] == nums[left+1]) left++;\n while (left < right && nums[right] == nums[right-1]) right--;\n left++; right--;\n }\n }\n }\n return result;\n}", "test_cases": ["nums=[-1,0,1,2,-1,-4] -> [[-1,-1,2],[-1,0,1]]"], "key_points": ["排序+双指针", "去重是关键"], "tags": ["two-pointers", "medium", "Google", "Amazon"]} {"problem_id": "algo_01637", "original_id": "container-water", "title": "盛最多水的容器", "category": "two-pointers", "difficulty": "medium", "companies": ["Google", "Uber"], "description": "给定一个长度为 n 的整数数组 height,找出其中的两条线,使得它们与 x 轴共同构成的容器可以容纳最多的水。", "solution_python": "def maxArea(height):\n left, right = 0, len(height) - 1\n max_area = 0\n while left < right:\n h = min(height[left], height[right])\n max_area = max(max_area, h * (right - left))\n if height[left] < height[right]: left += 1\n else: right -= 1\n return max_area", "solution_java": "public int maxArea(int[] height) {\n int left = 0, right = height.length - 1, maxArea = 0;\n while (left < right) {\n int h = Math.min(height[left], height[right]);\n maxArea = Math.max(maxArea, h * (right - left));\n if (height[left] < height[right]) left++;\n else right--;\n }\n return maxArea;\n}", "solution_cpp": "int maxArea(vector& height) {\n int left = 0, right = height.size() - 1, maxArea = 0;\n while (left < right) {\n int h = min(height[left], height[right]);\n maxArea = max(maxArea, h * (right - left));\n if (height[left] < height[right]) left++;\n else right--;\n }\n return maxArea;\n}", "test_cases": ["height=[1,8,6,2,5,4,8,3,7] -> 49"], "key_points": ["移动短边指针", "面积=min(h1,h2)*width"], "tags": ["two-pointers", "medium", "Google", "Uber"]} {"problem_id": "algo_01638", "original_id": "min-stack", "title": "最小栈", "category": "stack", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "设计一个支持 push,pop,top 操作,并能在常数时间内检索到最小元素的栈。", "solution_python": "class MinStack:\n def __init__(self):\n self.stack = []\n self.min_stack = []\n def push(self, val):\n self.stack.append(val)\n self.min_stack.append(min(val, self.min_stack[-1] if self.min_stack else val))\n def pop(self):\n self.stack.pop(); self.min_stack.pop()\n def top(self): return self.stack[-1]\n def getMin(self): return self.min_stack[-1]", "solution_java": "class MinStack {\n Stack stack = new Stack<>();\n Stack minStack = new Stack<>();\n public void push(int val) { stack.push(val); minStack.push(Math.min(val, minStack.isEmpty() ? val : minStack.peek())); }\n public void pop() { stack.pop(); minStack.pop(); }\n public int top() { return stack.peek(); }\n public int getMin() { return minStack.peek(); }\n}", "solution_cpp": "class MinStack {\n stack st, minSt;\npublic:\n void push(int val) { st.push(val); minSt.push(min(val, minSt.empty() ? val : minSt.top())); }\n void pop() { st.pop(); minSt.pop(); }\n int top() { return st.top(); }\n int getMin() { return minSt.top(); }\n};", "test_cases": ["push(-2), push(0), push(-3) -> getMin() returns -3"], "key_points": ["辅助栈记录最小值", "O(1)时间获取最小值"], "tags": ["stack", "medium", "Google", "Microsoft"]} {"problem_id": "algo_01639", "original_id": "lru-cache", "title": "LRU缓存", "category": "design", "difficulty": "hard", "companies": ["Google", "Amazon"], "description": "设计和实现一个 LRU(最近最少使用)缓存机制。", "solution_python": "class LRUCache:\n def __init__(self, capacity):\n self.capacity = capacity\n self.cache = {}\n self.order = []\n def get(self, key):\n if key not in self.cache: return -1\n self.order.remove(key); self.order.append(key)\n return self.cache[key]\n def put(self, key, value):\n if key in self.cache:\n self.order.remove(key)\n elif len(self.cache) >= self.capacity:\n del self.cache[self.order.pop(0)]\n self.cache[key] = value; self.order.append(key)", "solution_java": "class LRUCache {\n int capacity;\n LinkedHashMap cache = new LinkedHashMap<>();\n public LRUCache(int cap) { capacity = cap; }\n public int get(int key) { return cache.containsKey(key) ? cache.remove(key) : -1; }\n public void put(int key, int val) {\n if (cache.containsKey(key)) cache.remove(key);\n else if (cache.size() >= capacity) cache.remove(cache.keySet().iterator().next());\n cache.put(key, val);\n }\n}", "solution_cpp": "class LRUCache {\n int cap;\n list> dll;\n unordered_map>::iterator> cache;\npublic:\n LRUCache(int capacity) : cap(capacity) {}\n int get(int key) {\n auto it = cache.find(key);\n if (it == cache.end()) return -1;\n dll.splice(dll.end(), dll, it->second);\n return it->second->second;\n }\n void put(int key, int value) {\n auto it = cache.find(key);\n if (it != cache.end()) dll.erase(it->second);\n else if (cache.size() >= cap) { cache.erase(dll.front().first); dll.pop_front(); }\n dll.push_back({key, value});\n cache[key] = --dll.end();\n }\n};", "test_cases": ["put(1,1), put(2,2), get(1) -> 1"], "key_points": ["HashMap + 双向链表", "O(1)时间操作"], "tags": ["design", "hard", "Google", "Amazon"]} {"problem_id": "algo_01640", "original_id": "num-islands", "title": "岛屿数量", "category": "graph", "difficulty": "medium", "companies": ["Google", "Facebook"], "description": "给你一个由 '1'(陆地)和 '0'(水)组成的二维网格,请你计算网格中岛屿的数量。岛屿总是被水包围,且只能由水平或垂直方向相邻的陆地连接形成。", "solution_python": "def numIslands(grid):\n if not grid: return 0\n rows, cols = len(grid), len(grid[0])\n count = 0\n def dfs(r, c):\n if r < 0 or r >= rows or c < 0 or c >= cols or grid[r][c] != '1': return\n grid[r][c] = '0'\n dfs(r+1, c); dfs(r-1, c); dfs(r, c+1); dfs(r, c-1)\n for r in range(rows):\n for c in range(cols):\n if grid[r][c] == '1': count += 1; dfs(r, c)\n return count", "solution_java": "public int numIslands(char[][] grid) {\n if (grid.length == 0) return 0;\n int count = 0;\n for (int i = 0; i < grid.length; i++)\n for (int j = 0; j < grid[0].length; j++)\n if (grid[i][j] == '1') { count++; dfs(grid, i, j); }\n return count;\n}\nprivate void dfs(char[][] grid, int r, int c) {\n if (r < 0 || r >= grid.length || c < 0 || c >= grid[0].length || grid[r][c] != '1') return;\n grid[r][c] = '0';\n dfs(grid, r+1, c); dfs(grid, r-1, c); dfs(grid, r, c+1); dfs(grid, r, c-1);\n}", "solution_cpp": "int numIslands(vector>& grid) {\n if (grid.empty()) return 0;\n int count = 0;\n for (int i = 0; i < grid.size(); i++)\n for (int j = 0; j < grid[0].size(); j++)\n if (grid[i][j] == '1') { count++; dfs(grid, i, j); }\n return count;\n}\nvoid dfs(vector>& grid, int r, int c) {\n if (r < 0 || r >= grid.size() || c < 0 || c >= grid[0].size() || grid[r][c] != '1') return;\n grid[r][c] = '0';\n dfs(grid, r+1, c); dfs(grid, r-1, c); dfs(grid, r, c+1); dfs(grid, r, c-1);\n}", "test_cases": ["grid=[[1,1,1,1,0],[1,1,0,1,0],[1,1,0,0,0],[0,0,0,0,0]] -> 1"], "key_points": ["DFS/BFS遍历", "访问后标记为0避免重复"], "tags": ["graph", "medium", "Google", "Facebook"]} {"problem_id": "algo_01641", "original_id": "two-sum", "title": "两数之和", "category": "array", "difficulty": "easy", "companies": ["Amazon", "Google"], "description": "给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那两个整数,并返回他们的数组下标。", "solution_python": "def twoSum(nums, target):\n hashmap = {}\n for i, num in enumerate(nums):\n complement = target - num\n if complement in hashmap:\n return [hashmap[complement], i]\n hashmap[num] = i\n return []", "solution_java": "public int[] twoSum(int[] nums, int target) {\n Map map = new HashMap<>();\n for (int i = 0; i < nums.length; i++) {\n int complement = target - nums[i];\n if (map.containsKey(complement)) return new int[]{map.get(complement), i};\n map.put(nums[i], i);\n }\n return new int[]{};\n}", "solution_cpp": "vector twoSum(vector& nums, int target) {\n unordered_map m;\n for (int i = 0; i < nums.size(); i++) {\n if (m.count(target - nums[i])) return {m[target - nums[i]], i};\n m[nums[i]] = i;\n }\n return {};\n}", "test_cases": ["nums=[2,7,11,15], target=9 -> [0,1]", "nums=[3,2,4], target=6 -> [1,2]"], "key_points": ["哈希表一次遍历", "空间换时间"], "tags": ["array", "easy", "Amazon", "Google"]} {"problem_id": "algo_01642", "original_id": "merge-sorted", "title": "合并两个有序数组", "category": "array", "difficulty": "easy", "companies": ["Microsoft", "Uber"], "description": "给你两个按非递减顺序排列的整数数组 nums1 和 nums2,另有两个整数 m 和 n,分别表示 nums1 和 nums2 中的元素数目。请你合并 nums2 到 nums1 中。", "solution_python": "def merge(nums1, m, nums2, n):\n p1, p2, p = m-1, n-1, m+n-1\n while p1 >= 0 and p2 >= 0:\n if nums1[p1] > nums2[p2]: nums1[p] = nums1[p1]; p1 -= 1\n else: nums1[p] = nums2[p2]; p2 -= 1\n p -= 1\n while p2 >= 0: nums1[p] = nums2[p2]; p2 -= 1; p -= 1", "solution_java": "public void merge(int[] nums1, int m, int[] nums2, int n) {\n int p1 = m-1, p2 = n-1, p = m+n-1;\n while (p1 >= 0 && p2 >= 0) {\n nums1[p--] = nums1[p1] > nums2[p2] ? nums1[p1--] : nums2[p2--];\n }\n while (p2 >= 0) nums1[p--] = nums2[p2--];\n}", "solution_cpp": "void merge(vector& nums1, int m, vector& nums2, int n) {\n int p1 = m-1, p2 = n-1, p = m+n-1;\n while (p1 >= 0 && p2 >= 0) nums1[p--] = nums1[p1] > nums2[p2] ? nums1[p1--] : nums2[p2--];\n while (p2 >= 0) nums1[p--] = nums2[p2--];\n}", "test_cases": ["nums1=[1,2,3], m=3, nums2=[2,5,6], n=3 -> [1,2,2,3,5,6]", "nums1=[], m=0, nums2=[1], n=1 -> [1]"], "key_points": ["从后往前合并", "三指针技巧"], "tags": ["array", "easy", "Microsoft", "Uber"]} {"problem_id": "algo_01643", "original_id": "max-subarray", "title": "最大子数组和", "category": "array", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "给你一个整数数组 nums ,请你找出一个具有最大和的连续子数组,返回其最大和。", "solution_python": "def maxSubArray(nums):\n max_sum = current = nums[0]\n for num in nums[1:]:\n current = max(num, current + num)\n max_sum = max(max_sum, current)\n return max_sum", "solution_java": "public int maxSubArray(int[] nums) {\n int maxSum = nums[0], curr = nums[0];\n for (int i = 1; i < nums.length; i++) {\n curr = Math.max(nums[i], curr + nums[i]);\n maxSum = Math.max(maxSum, curr);\n }\n return maxSum;\n}", "solution_cpp": "int maxSubArray(vector& nums) {\n int maxSum = nums[0], curr = nums[0];\n for (int i = 1; i < nums.size(); i++) {\n curr = max(nums[i], curr + nums[i]);\n maxSum = max(maxSum, curr);\n }\n return maxSum;\n}", "test_cases": ["nums=[-2,1,-3,4,-1,2,1,-5,4] -> 6", "nums=[1] -> 1"], "key_points": ["Kadane算法", "动态规划基础题"], "tags": ["array", "medium", "Google", "Microsoft"]} {"problem_id": "algo_01644", "original_id": "valid-parentheses", "title": "有效的括号", "category": "string", "difficulty": "easy", "companies": ["Google", "Uber"], "description": "给定一个只包括 '(',')','{','}','[',']' 的字符串 s,判断字符串是否有效。", "solution_python": "def isValid(s):\n stack = []\n mapping = {')': '(', ']': '[', '}': '{'}\n for c in s:\n if c in mapping:\n if not stack or stack[-1] != mapping[c]: return False\n stack.pop()\n else: stack.append(c)\n return not stack", "solution_java": "public boolean isValid(String s) {\n Stack stack = new Stack<>();\n Map map = Map.of(')', '(', ']', '[', '}', '{');\n for (char c : s.toCharArray()) {\n if (map.containsValue(c)) stack.push(c);\n else if (!stack.isEmpty() && stack.pop() != map.get(c)) return false;\n }\n return stack.isEmpty();\n}", "solution_cpp": "bool isValid(string s) {\n stack st;\n unordered_map m = {{')','('},{']','['},{'}','{'}};\n for (char c : s) {\n if (m.find(c) == m.end()) st.push(c);\n else if (st.empty() || st.top() != m[c]) return false;\n else st.pop();\n }\n return st.empty();\n}", "test_cases": ["s=\"()\" -> true", "s=\"()[]{}\" -> true", "s=\"(]\" -> false"], "key_points": ["栈匹配法", "注意空栈边界"], "tags": ["string", "easy", "Google", "Uber"]} {"problem_id": "algo_01645", "original_id": "longest-palindrome", "title": "最长回文子串", "category": "string", "difficulty": "medium", "companies": ["Google", "Amazon"], "description": "给你一个字符串 s,找到 s 中最长的回文子串。", "solution_python": "def longestPalindrome(s):\n def expand(l, r):\n while l >= 0 and r < len(s) and s[l] == s[r]: l -= 1; r += 1\n return l + 1, r - 1\n start = end = 0\n for i in range(len(s)):\n l1, r1 = expand(i, i)\n l2, r2 = expand(i, i + 1)\n if r1 - l1 > end - start: start, end = l1, r1\n if r2 - l2 > end - start: start, end = l2, r2\n return s[start:end+1]", "solution_java": "public String longestPalindrome(String s) {\n int start = 0, end = 0;\n for (int i = 0; i < s.length(); i++) {\n int len1 = expand(s, i, i), len2 = expand(s, i, i+1);\n int len = Math.max(len1, len2);\n if (len > end - start) { start = i - (len-1)/2; end = i + len/2; }\n }\n return s.substring(start, end + 1);\n}\nprivate int expand(String s, int l, int r) {\n while (l >= 0 && r < s.length() && s.charAt(l) == s.charAt(r)) { l--; r++; }\n return r - l - 1;\n}", "solution_cpp": "string longestPalindrome(string s) {\n int start = 0, end = 0;\n for (int i = 0; i < s.size(); i++) {\n int len1 = expand(s, i, i), len2 = expand(s, i, i+1);\n if (max(len1, len2) > end - start) { start = i - (max(len1,len2)-1)/2; end = i + max(len1,len2)/2; }\n }\n return s.substr(start, end - start + 1);\n}", "test_cases": ["s=\"babad\" -> bab或aba", "s=\"cbbd\" -> bb"], "key_points": ["中心扩展法", "处理奇偶长度"], "tags": ["string", "medium", "Google", "Amazon"]} {"problem_id": "algo_01646", "original_id": "reverse-list", "title": "反转链表", "category": "linkedlist", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "给你单链表的头节点 head,请你反转链表,并返回反转后的链表。", "solution_python": "def reverseList(head):\n prev = None\n curr = head\n while curr:\n nxt = curr.next\n curr.next = prev\n prev = curr\n curr = nxt\n return prev", "solution_java": "public ListNode reverseList(ListNode head) {\n ListNode prev = null, curr = head;\n while (curr != null) {\n ListNode next = curr.next;\n curr.next = prev;\n prev = curr;\n curr = next;\n }\n return prev;\n}", "solution_cpp": "ListNode* reverseList(ListNode* head) {\n ListNode* prev = nullptr, *curr = head;\n while (curr) {\n ListNode* next = curr->next;\n curr->next = prev;\n prev = curr;\n curr = next;\n }\n return prev;\n}", "test_cases": ["head=[1,2,3,4,5] -> [5,4,3,2,1]", "head=[1,2] -> [2,1]"], "key_points": ["迭代法 O(1)空间", "递归法 O(n)空间"], "tags": ["linkedlist", "medium", "Google", "Microsoft"]} {"problem_id": "algo_01647", "original_id": "middle-node", "title": "链表的中间结点", "category": "linkedlist", "difficulty": "easy", "companies": ["Amazon", "Facebook"], "description": "给你单链表的头节点 head,请你找出并返回链表的中间结点。如果有两个中间结点,则返回第二个中间结点。", "solution_python": "def middleNode(head):\n slow = fast = head\n while fast and fast.next:\n slow = slow.next\n fast = fast.next.next\n return slow", "solution_java": "public ListNode middleNode(ListNode head) {\n ListNode slow = head, fast = head;\n while (fast != null && fast.next != null) {\n slow = slow.next;\n fast = fast.next.next;\n }\n return slow;\n}", "solution_cpp": "ListNode* middleNode(ListNode* head) {\n ListNode* slow = head, *fast = head;\n while (fast && fast->next) { slow = slow->next; fast = fast->next->next; }\n return slow;\n}", "test_cases": ["head=[1,2,3,4,5] -> 3", "head=[1,2,3,4,5,6] -> 4"], "key_points": ["快慢指针", "O(n)时间O(1)空间"], "tags": ["linkedlist", "easy", "Amazon", "Facebook"]} {"problem_id": "algo_01648", "original_id": "max-depth", "title": "二叉树的最大深度", "category": "tree", "difficulty": "easy", "companies": ["Microsoft", "Apple"], "description": "给定一个二叉树 root,返回其最大深度。", "solution_python": "def maxDepth(root):\n if not root: return 0\n return max(maxDepth(root.left), maxDepth(root.right)) + 1", "solution_java": "public int maxDepth(TreeNode root) {\n if (root == null) return 0;\n return Math.max(maxDepth(root.left), maxDepth(root.right)) + 1;\n}", "solution_cpp": "int maxDepth(TreeNode* root) {\n if (!root) return 0;\n return max(maxDepth(root->left), maxDepth(root->right)) + 1;\n}", "test_cases": ["root=[3,9,20,null,null,15,7] -> 3", "root=[1,null,2] -> 2"], "key_points": ["DFS递归", "层序遍历也可"], "tags": ["tree", "easy", "Microsoft", "Apple"]} {"problem_id": "algo_01649", "original_id": "inorder-traversal", "title": "二叉树的中序遍历", "category": "tree", "difficulty": "easy", "companies": ["Google", "Microsoft"], "description": "给定一个二叉树的根节点 root,返回它的中序遍历结果。", "solution_python": "def inorderTraversal(root):\n result = []\n def dfs(node):\n if node:\n dfs(node.left)\n result.append(node.val)\n dfs(node.right)\n dfs(root)\n return result", "solution_java": "public List inorderTraversal(TreeNode root) {\n List res = new ArrayList<>();\n dfs(root, res);\n return res;\n}\nprivate void dfs(TreeNode node, List res) {\n if (node == null) return;\n dfs(node.left, res); res.add(node.val); dfs(node.right, res);\n}", "solution_cpp": "vector inorderTraversal(TreeNode* root) {\n vector res;\n dfs(root, res);\n return res;\n}\nvoid dfs(TreeNode* node, vector& res) {\n if (!node) return;\n dfs(node->left, res); res.push_back(node->val); dfs(node->right, res);\n}", "test_cases": ["root=[1,null,2,3] -> [1,3,2]", "root=[] -> []"], "key_points": ["左-根-右顺序", "递归最简洁"], "tags": ["tree", "easy", "Google", "Microsoft"]} {"problem_id": "algo_01650", "original_id": "binary-search", "title": "二分查找", "category": "binarysearch", "difficulty": "easy", "companies": ["Google", "Amazon"], "description": "给定一个 n 个元素有序的(升序)整型数组 nums 和一个目标值 target,写一个函数搜索 nums 中的 target,如果目标值存在返回下标,否则返回 -1。", "solution_python": "def search(nums, target):\n left, right = 0, len(nums) - 1\n while left <= right:\n mid = (left + right) // 2\n if nums[mid] == target: return mid\n elif nums[mid] < target: left = mid + 1\n else: right = mid - 1\n return -1", "solution_java": "public int search(int[] nums, int target) {\n int left = 0, right = nums.length - 1;\n while (left <= right) {\n int mid = left + (right - left) / 2;\n if (nums[mid] == target) return mid;\n else if (nums[mid] < target) left = mid + 1;\n else right = mid - 1;\n }\n return -1;\n}", "solution_cpp": "int search(vector& nums, int target) {\n int left = 0, right = nums.size() - 1;\n while (left <= right) {\n int mid = left + (right - left) / 2;\n if (nums[mid] == target) return mid;\n else if (nums[mid] < target) left = mid + 1;\n else right = mid - 1;\n }\n return -1;\n}", "test_cases": ["nums=[-1,0,3,5,9,12], target=9 -> 4", "nums=[-1,0,3,5,9,12], target=2 -> -1"], "key_points": ["标准模板", "注意防溢出写法"], "tags": ["binarysearch", "easy", "Google", "Amazon"]} {"problem_id": "algo_01651", "original_id": "climbing-stairs", "title": "爬楼梯", "category": "dp", "difficulty": "easy", "companies": ["Amazon", "Google"], "description": "假设你正在爬楼梯。需要 n 阶你才能到达楼顶。每次你可以爬 1 或 2 个台阶。你有多少种不同的方法可以爬到楼顶?", "solution_python": "def climbStairs(n):\n if n <= 2: return n\n a, b = 1, 2\n for _ in range(3, n+1):\n a, b = b, a + b\n return b", "solution_java": "public int climbStairs(int n) {\n if (n <= 2) return n;\n int a = 1, b = 2;\n for (int i = 3; i <= n; i++) { int temp = a + b; a = b; b = temp; }\n return b;\n}", "solution_cpp": "int climbStairs(int n) {\n if (n <= 2) return n;\n int a = 1, b = 2;\n for (int i = 3; i <= n; i++) { int temp = a + b; a = b; b = temp; }\n return b;\n}", "test_cases": ["n=2 -> 2", "n=3 -> 3", "n=5 -> 8"], "key_points": ["斐波那契数列", "滚动数组优化空间"], "tags": ["dp", "easy", "Amazon", "Google"]} {"problem_id": "algo_01652", "original_id": "coin-change", "title": "零钱兑换", "category": "dp", "difficulty": "medium", "companies": ["Google", "Amazon"], "description": "给你一个整数数组 coins 表示不同面额的硬币,以及一个整数 amount 表示总金额。计算并返回可以凑成总金额所需的最少的硬币个数。如果没有任何一种硬币组合能组成总金额,返回 -1。", "solution_python": "def coinChange(coins, amount):\n dp = [float('inf')] * (amount + 1)\n dp[0] = 0\n for coin in coins:\n for x in range(coin, amount + 1):\n dp[x] = min(dp[x], dp[x - coin] + 1)\n return dp[amount] if dp[amount] != float('inf') else -1", "solution_java": "public int coinChange(int[] coins, int amount) {\n int[] dp = new int[amount + 1];\n Arrays.fill(dp, amount + 1);\n dp[0] = 0;\n for (int coin : coins) {\n for (int x = coin; x <= amount; x++) {\n dp[x] = Math.min(dp[x], dp[x - coin] + 1);\n }\n }\n return dp[amount] > amount ? -1 : dp[amount];\n}", "solution_cpp": "int coinChange(vector& coins, int amount) {\n vector dp(amount + 1, amount + 1);\n dp[0] = 0;\n for (int coin : coins) {\n for (int x = coin; x <= amount; x++) {\n dp[x] = min(dp[x], dp[x - coin] + 1);\n }\n }\n return dp[amount] > amount ? -1 : dp[amount];\n}", "test_cases": ["coins=[1,2,5], amount=11 -> 3", "coins=[2], amount=3 -> -1"], "key_points": ["完全背包问题", "dp[x] = min(dp[x-coin]+1)"], "tags": ["dp", "medium", "Google", "Amazon"]} {"problem_id": "algo_01653", "original_id": "subsets", "title": "子集", "category": "backtracking", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "给你一个整数数组 nums ,数组中的元素 互不相同 。返回该数组所有可能的子集(幂集)。", "solution_python": "def subsets(nums):\n result = []\n def backtrack(start, path):\n result.append(path[:])\n for i in range(start, len(nums)):\n path.append(nums[i])\n backtrack(i + 1, path)\n path.pop()\n backtrack(0, [])\n return result", "solution_java": "public List> subsets(int[] nums) {\n List> result = new ArrayList<>();\n backtrack(nums, 0, new ArrayList<>(), result);\n return result;\n}\nprivate void backtrack(int[] nums, int start, List path, List> result) {\n result.add(new ArrayList<>(path));\n for (int i = start; i < nums.length; i++) {\n path.add(nums[i]);\n backtrack(nums, i + 1, path, result);\n path.remove(path.size() - 1);\n }\n}", "solution_cpp": "vector> subsets(vector& nums) {\n vector> result;\n vector path;\n backtrack(nums, 0, path, result);\n return result;\n}\nvoid backtrack(vector& nums, int start, vector& path, vector>& result) {\n result.push_back(path);\n for (int i = start; i < nums.size(); i++) {\n path.push_back(nums[i]);\n backtrack(nums, i + 1, path, result);\n path.pop_back();\n }\n}", "test_cases": ["nums=[1,2,3] -> [[],[1],[2],[1,2],[3],[1,3],[2,3],[1,2,3]]"], "key_points": ["选或不选", "DFS遍历子集树"], "tags": ["backtracking", "medium", "Google", "Microsoft"]} {"problem_id": "algo_01654", "original_id": "permutations", "title": "全排列", "category": "backtracking", "difficulty": "medium", "companies": ["Google", "Facebook"], "description": "给定一个不含重复数字的数组 nums,返回其所有可能的全排列。", "solution_python": "def permute(nums):\n result = []\n def backtrack(path, used):\n if len(path) == len(nums):\n result.append(path[:])\n return\n for i in range(len(nums)):\n if used[i]: continue\n used[i] = True\n path.append(nums[i])\n backtrack(path, used)\n path.pop()\n used[i] = False\n backtrack([], [False]*len(nums))\n return result", "solution_java": "public List> permute(int[] nums) {\n List> result = new ArrayList<>();\n boolean[] used = new boolean[nums.length];\n backtrack(nums, used, new ArrayList<>(), result);\n return result;\n}\nprivate void backtrack(int[] nums, boolean[] used, List path, List> result) {\n if (path.size() == nums.length) { result.add(new ArrayList<>(path)); return; }\n for (int i = 0; i < nums.length; i++) {\n if (used[i]) continue;\n used[i] = true;\n path.add(nums[i]);\n backtrack(nums, used, path, result);\n path.remove(path.size() - 1);\n used[i] = false;\n }\n}", "solution_cpp": "vector> permute(vector& nums) {\n vector> result;\n vector used(nums.size(), false);\n vector path;\n backtrack(nums, used, path, result);\n return result;\n}\nvoid backtrack(vector& nums, vector& used, vector& path, vector>& result) {\n if (path.size() == nums.size()) { result.push_back(path); return; }\n for (int i = 0; i < nums.size(); i++) {\n if (used[i]) continue;\n used[i] = true;\n path.push_back(nums[i]);\n backtrack(nums, used, path, result);\n path.pop_back();\n used[i] = false;\n }\n}", "test_cases": ["nums=[1,2,3] -> [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]"], "key_points": ["标记已使用元素", "回溯经典模板"], "tags": ["backtracking", "medium", "Google", "Facebook"]} {"problem_id": "algo_01655", "original_id": "top-k-frequent", "title": "前K个高频元素", "category": "heap", "difficulty": "medium", "companies": ["Amazon", "Facebook"], "description": "给你一个整数数组 nums 和一个整数 k,请你返回其中出现频率前 k 高的元素。", "solution_python": "import heapq\nfrom collections import Counter\ndef topKFrequent(nums, k):\n count = Counter(nums)\n heap = []\n for num, freq in count.items():\n heapq.heappush(heap, (freq, num))\n if len(heap) > k: heapq.heappop(heap)\n return [num for freq, num in heap]", "solution_java": "public int[] topKFrequent(int[] nums, int k) {\n Map count = new HashMap<>();\n for (int n : nums) count.put(n, count.getOrDefault(n, 0) + 1);\n PriorityQueue> heap = \n new PriorityQueue<>((a, b) -> a.getValue() - b.getValue());\n for (Map.Entry e : count.entrySet()) {\n heap.offer(e);\n if (heap.size() > k) heap.poll();\n }\n int[] res = new int[k];\n for (int i = k - 1; i >= 0; i--) res[i] = heap.poll().getKey();\n return res;\n}", "solution_cpp": "vector topKFrequent(vector& nums, int k) {\n unordered_map count;\n for (int n : nums) count[n]++;\n priority_queue, vector>, greater>> heap;\n for (auto& [num, freq] : count) {\n heap.push({freq, num});\n if (heap.size() > k) heap.pop();\n }\n vector res;\n while (!heap.empty()) { res.push_back(heap.top().second); heap.pop(); }\n reverse(res.begin(), res.end());\n return res;\n}", "test_cases": ["nums=[1,1,1,2,2,3], k=2 -> [1,2]", "nums=[1], k=1 -> [1]"], "key_points": ["小顶堆保持大小k", "时间复杂度O(nlogk)"], "tags": ["heap", "medium", "Amazon", "Facebook"]} {"problem_id": "algo_01656", "original_id": "3sum", "title": "三数之和", "category": "two-pointers", "difficulty": "medium", "companies": ["Google", "Amazon"], "description": "给你一个整数数组 nums,判断是否存在三元组满足和为0,返回所有不重复的三元组。", "solution_python": "def threeSum(nums):\n nums.sort()\n result = []\n for i in range(len(nums) - 2):\n if i > 0 and nums[i] == nums[i-1]: continue\n left, right = i + 1, len(nums) - 1\n while left < right:\n total = nums[i] + nums[left] + nums[right]\n if total < 0: left += 1\n elif total > 0: right -= 1\n else:\n result.append([nums[i], nums[left], nums[right]])\n while left < right and nums[left] == nums[left+1]: left += 1\n while left < right and nums[right] == nums[right-1]: right -= 1\n left += 1; right -= 1\n return result", "solution_java": "public List> threeSum(int[] nums) {\n Arrays.sort(nums);\n List> result = new ArrayList<>();\n for (int i = 0; i < nums.length - 2; i++) {\n if (i > 0 && nums[i] == nums[i-1]) continue;\n int left = i + 1, right = nums.length - 1;\n while (left < right) {\n int total = nums[i] + nums[left] + nums[right];\n if (total < 0) left++;\n else if (total > 0) right--;\n else {\n result.add(Arrays.asList(nums[i], nums[left], nums[right]));\n while (left < right && nums[left] == nums[left+1]) left++;\n while (left < right && nums[right] == nums[right-1]) right--;\n left++; right--;\n }\n }\n }\n return result;\n}", "solution_cpp": "vector> threeSum(vector& nums) {\n sort(nums.begin(), nums.end());\n vector> result;\n for (int i = 0; i < nums.size() - 2; i++) {\n if (i > 0 && nums[i] == nums[i-1]) continue;\n int left = i + 1, right = nums.size() - 1;\n while (left < right) {\n int total = nums[i] + nums[left] + nums[right];\n if (total < 0) left++;\n else if (total > 0) right--;\n else {\n result.push_back({nums[i], nums[left], nums[right]});\n while (left < right && nums[left] == nums[left+1]) left++;\n while (left < right && nums[right] == nums[right-1]) right--;\n left++; right--;\n }\n }\n }\n return result;\n}", "test_cases": ["nums=[-1,0,1,2,-1,-4] -> [[-1,-1,2],[-1,0,1]]"], "key_points": ["排序+双指针", "去重是关键"], "tags": ["two-pointers", "medium", "Google", "Amazon"]} {"problem_id": "algo_01657", "original_id": "container-water", "title": "盛最多水的容器", "category": "two-pointers", "difficulty": "medium", "companies": ["Google", "Uber"], "description": "给定一个长度为 n 的整数数组 height,找出其中的两条线,使得它们与 x 轴共同构成的容器可以容纳最多的水。", "solution_python": "def maxArea(height):\n left, right = 0, len(height) - 1\n max_area = 0\n while left < right:\n h = min(height[left], height[right])\n max_area = max(max_area, h * (right - left))\n if height[left] < height[right]: left += 1\n else: right -= 1\n return max_area", "solution_java": "public int maxArea(int[] height) {\n int left = 0, right = height.length - 1, maxArea = 0;\n while (left < right) {\n int h = Math.min(height[left], height[right]);\n maxArea = Math.max(maxArea, h * (right - left));\n if (height[left] < height[right]) left++;\n else right--;\n }\n return maxArea;\n}", "solution_cpp": "int maxArea(vector& height) {\n int left = 0, right = height.size() - 1, maxArea = 0;\n while (left < right) {\n int h = min(height[left], height[right]);\n maxArea = max(maxArea, h * (right - left));\n if (height[left] < height[right]) left++;\n else right--;\n }\n return maxArea;\n}", "test_cases": ["height=[1,8,6,2,5,4,8,3,7] -> 49"], "key_points": ["移动短边指针", "面积=min(h1,h2)*width"], "tags": ["two-pointers", "medium", "Google", "Uber"]} {"problem_id": "algo_01658", "original_id": "min-stack", "title": "最小栈", "category": "stack", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "设计一个支持 push,pop,top 操作,并能在常数时间内检索到最小元素的栈。", "solution_python": "class MinStack:\n def __init__(self):\n self.stack = []\n self.min_stack = []\n def push(self, val):\n self.stack.append(val)\n self.min_stack.append(min(val, self.min_stack[-1] if self.min_stack else val))\n def pop(self):\n self.stack.pop(); self.min_stack.pop()\n def top(self): return self.stack[-1]\n def getMin(self): return self.min_stack[-1]", "solution_java": "class MinStack {\n Stack stack = new Stack<>();\n Stack minStack = new Stack<>();\n public void push(int val) { stack.push(val); minStack.push(Math.min(val, minStack.isEmpty() ? val : minStack.peek())); }\n public void pop() { stack.pop(); minStack.pop(); }\n public int top() { return stack.peek(); }\n public int getMin() { return minStack.peek(); }\n}", "solution_cpp": "class MinStack {\n stack st, minSt;\npublic:\n void push(int val) { st.push(val); minSt.push(min(val, minSt.empty() ? val : minSt.top())); }\n void pop() { st.pop(); minSt.pop(); }\n int top() { return st.top(); }\n int getMin() { return minSt.top(); }\n};", "test_cases": ["push(-2), push(0), push(-3) -> getMin() returns -3"], "key_points": ["辅助栈记录最小值", "O(1)时间获取最小值"], "tags": ["stack", "medium", "Google", "Microsoft"]} {"problem_id": "algo_01659", "original_id": "lru-cache", "title": "LRU缓存", "category": "design", "difficulty": "hard", "companies": ["Google", "Amazon"], "description": "设计和实现一个 LRU(最近最少使用)缓存机制。", "solution_python": "class LRUCache:\n def __init__(self, capacity):\n self.capacity = capacity\n self.cache = {}\n self.order = []\n def get(self, key):\n if key not in self.cache: return -1\n self.order.remove(key); self.order.append(key)\n return self.cache[key]\n def put(self, key, value):\n if key in self.cache:\n self.order.remove(key)\n elif len(self.cache) >= self.capacity:\n del self.cache[self.order.pop(0)]\n self.cache[key] = value; self.order.append(key)", "solution_java": "class LRUCache {\n int capacity;\n LinkedHashMap cache = new LinkedHashMap<>();\n public LRUCache(int cap) { capacity = cap; }\n public int get(int key) { return cache.containsKey(key) ? cache.remove(key) : -1; }\n public void put(int key, int val) {\n if (cache.containsKey(key)) cache.remove(key);\n else if (cache.size() >= capacity) cache.remove(cache.keySet().iterator().next());\n cache.put(key, val);\n }\n}", "solution_cpp": "class LRUCache {\n int cap;\n list> dll;\n unordered_map>::iterator> cache;\npublic:\n LRUCache(int capacity) : cap(capacity) {}\n int get(int key) {\n auto it = cache.find(key);\n if (it == cache.end()) return -1;\n dll.splice(dll.end(), dll, it->second);\n return it->second->second;\n }\n void put(int key, int value) {\n auto it = cache.find(key);\n if (it != cache.end()) dll.erase(it->second);\n else if (cache.size() >= cap) { cache.erase(dll.front().first); dll.pop_front(); }\n dll.push_back({key, value});\n cache[key] = --dll.end();\n }\n};", "test_cases": ["put(1,1), put(2,2), get(1) -> 1"], "key_points": ["HashMap + 双向链表", "O(1)时间操作"], "tags": ["design", "hard", "Google", "Amazon"]} {"problem_id": "algo_01660", "original_id": "num-islands", "title": "岛屿数量", "category": "graph", "difficulty": "medium", "companies": ["Google", "Facebook"], "description": "给你一个由 '1'(陆地)和 '0'(水)组成的二维网格,请你计算网格中岛屿的数量。岛屿总是被水包围,且只能由水平或垂直方向相邻的陆地连接形成。", "solution_python": "def numIslands(grid):\n if not grid: return 0\n rows, cols = len(grid), len(grid[0])\n count = 0\n def dfs(r, c):\n if r < 0 or r >= rows or c < 0 or c >= cols or grid[r][c] != '1': return\n grid[r][c] = '0'\n dfs(r+1, c); dfs(r-1, c); dfs(r, c+1); dfs(r, c-1)\n for r in range(rows):\n for c in range(cols):\n if grid[r][c] == '1': count += 1; dfs(r, c)\n return count", "solution_java": "public int numIslands(char[][] grid) {\n if (grid.length == 0) return 0;\n int count = 0;\n for (int i = 0; i < grid.length; i++)\n for (int j = 0; j < grid[0].length; j++)\n if (grid[i][j] == '1') { count++; dfs(grid, i, j); }\n return count;\n}\nprivate void dfs(char[][] grid, int r, int c) {\n if (r < 0 || r >= grid.length || c < 0 || c >= grid[0].length || grid[r][c] != '1') return;\n grid[r][c] = '0';\n dfs(grid, r+1, c); dfs(grid, r-1, c); dfs(grid, r, c+1); dfs(grid, r, c-1);\n}", "solution_cpp": "int numIslands(vector>& grid) {\n if (grid.empty()) return 0;\n int count = 0;\n for (int i = 0; i < grid.size(); i++)\n for (int j = 0; j < grid[0].size(); j++)\n if (grid[i][j] == '1') { count++; dfs(grid, i, j); }\n return count;\n}\nvoid dfs(vector>& grid, int r, int c) {\n if (r < 0 || r >= grid.size() || c < 0 || c >= grid[0].size() || grid[r][c] != '1') return;\n grid[r][c] = '0';\n dfs(grid, r+1, c); dfs(grid, r-1, c); dfs(grid, r, c+1); dfs(grid, r, c-1);\n}", "test_cases": ["grid=[[1,1,1,1,0],[1,1,0,1,0],[1,1,0,0,0],[0,0,0,0,0]] -> 1"], "key_points": ["DFS/BFS遍历", "访问后标记为0避免重复"], "tags": ["graph", "medium", "Google", "Facebook"]} {"problem_id": "algo_01661", "original_id": "two-sum", "title": "两数之和", "category": "array", "difficulty": "easy", "companies": ["Amazon", "Google"], "description": "给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那两个整数,并返回他们的数组下标。", "solution_python": "def twoSum(nums, target):\n hashmap = {}\n for i, num in enumerate(nums):\n complement = target - num\n if complement in hashmap:\n return [hashmap[complement], i]\n hashmap[num] = i\n return []", "solution_java": "public int[] twoSum(int[] nums, int target) {\n Map map = new HashMap<>();\n for (int i = 0; i < nums.length; i++) {\n int complement = target - nums[i];\n if (map.containsKey(complement)) return new int[]{map.get(complement), i};\n map.put(nums[i], i);\n }\n return new int[]{};\n}", "solution_cpp": "vector twoSum(vector& nums, int target) {\n unordered_map m;\n for (int i = 0; i < nums.size(); i++) {\n if (m.count(target - nums[i])) return {m[target - nums[i]], i};\n m[nums[i]] = i;\n }\n return {};\n}", "test_cases": ["nums=[2,7,11,15], target=9 -> [0,1]", "nums=[3,2,4], target=6 -> [1,2]"], "key_points": ["哈希表一次遍历", "空间换时间"], "tags": ["array", "easy", "Amazon", "Google"]} {"problem_id": "algo_01662", "original_id": "merge-sorted", "title": "合并两个有序数组", "category": "array", "difficulty": "easy", "companies": ["Microsoft", "Uber"], "description": "给你两个按非递减顺序排列的整数数组 nums1 和 nums2,另有两个整数 m 和 n,分别表示 nums1 和 nums2 中的元素数目。请你合并 nums2 到 nums1 中。", "solution_python": "def merge(nums1, m, nums2, n):\n p1, p2, p = m-1, n-1, m+n-1\n while p1 >= 0 and p2 >= 0:\n if nums1[p1] > nums2[p2]: nums1[p] = nums1[p1]; p1 -= 1\n else: nums1[p] = nums2[p2]; p2 -= 1\n p -= 1\n while p2 >= 0: nums1[p] = nums2[p2]; p2 -= 1; p -= 1", "solution_java": "public void merge(int[] nums1, int m, int[] nums2, int n) {\n int p1 = m-1, p2 = n-1, p = m+n-1;\n while (p1 >= 0 && p2 >= 0) {\n nums1[p--] = nums1[p1] > nums2[p2] ? nums1[p1--] : nums2[p2--];\n }\n while (p2 >= 0) nums1[p--] = nums2[p2--];\n}", "solution_cpp": "void merge(vector& nums1, int m, vector& nums2, int n) {\n int p1 = m-1, p2 = n-1, p = m+n-1;\n while (p1 >= 0 && p2 >= 0) nums1[p--] = nums1[p1] > nums2[p2] ? nums1[p1--] : nums2[p2--];\n while (p2 >= 0) nums1[p--] = nums2[p2--];\n}", "test_cases": ["nums1=[1,2,3], m=3, nums2=[2,5,6], n=3 -> [1,2,2,3,5,6]", "nums1=[], m=0, nums2=[1], n=1 -> [1]"], "key_points": ["从后往前合并", "三指针技巧"], "tags": ["array", "easy", "Microsoft", "Uber"]} {"problem_id": "algo_01663", "original_id": "max-subarray", "title": "最大子数组和", "category": "array", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "给你一个整数数组 nums ,请你找出一个具有最大和的连续子数组,返回其最大和。", "solution_python": "def maxSubArray(nums):\n max_sum = current = nums[0]\n for num in nums[1:]:\n current = max(num, current + num)\n max_sum = max(max_sum, current)\n return max_sum", "solution_java": "public int maxSubArray(int[] nums) {\n int maxSum = nums[0], curr = nums[0];\n for (int i = 1; i < nums.length; i++) {\n curr = Math.max(nums[i], curr + nums[i]);\n maxSum = Math.max(maxSum, curr);\n }\n return maxSum;\n}", "solution_cpp": "int maxSubArray(vector& nums) {\n int maxSum = nums[0], curr = nums[0];\n for (int i = 1; i < nums.size(); i++) {\n curr = max(nums[i], curr + nums[i]);\n maxSum = max(maxSum, curr);\n }\n return maxSum;\n}", "test_cases": ["nums=[-2,1,-3,4,-1,2,1,-5,4] -> 6", "nums=[1] -> 1"], "key_points": ["Kadane算法", "动态规划基础题"], "tags": ["array", "medium", "Google", "Microsoft"]} {"problem_id": "algo_01664", "original_id": "valid-parentheses", "title": "有效的括号", "category": "string", "difficulty": "easy", "companies": ["Google", "Uber"], "description": "给定一个只包括 '(',')','{','}','[',']' 的字符串 s,判断字符串是否有效。", "solution_python": "def isValid(s):\n stack = []\n mapping = {')': '(', ']': '[', '}': '{'}\n for c in s:\n if c in mapping:\n if not stack or stack[-1] != mapping[c]: return False\n stack.pop()\n else: stack.append(c)\n return not stack", "solution_java": "public boolean isValid(String s) {\n Stack stack = new Stack<>();\n Map map = Map.of(')', '(', ']', '[', '}', '{');\n for (char c : s.toCharArray()) {\n if (map.containsValue(c)) stack.push(c);\n else if (!stack.isEmpty() && stack.pop() != map.get(c)) return false;\n }\n return stack.isEmpty();\n}", "solution_cpp": "bool isValid(string s) {\n stack st;\n unordered_map m = {{')','('},{']','['},{'}','{'}};\n for (char c : s) {\n if (m.find(c) == m.end()) st.push(c);\n else if (st.empty() || st.top() != m[c]) return false;\n else st.pop();\n }\n return st.empty();\n}", "test_cases": ["s=\"()\" -> true", "s=\"()[]{}\" -> true", "s=\"(]\" -> false"], "key_points": ["栈匹配法", "注意空栈边界"], "tags": ["string", "easy", "Google", "Uber"]} {"problem_id": "algo_01665", "original_id": "longest-palindrome", "title": "最长回文子串", "category": "string", "difficulty": "medium", "companies": ["Google", "Amazon"], "description": "给你一个字符串 s,找到 s 中最长的回文子串。", "solution_python": "def longestPalindrome(s):\n def expand(l, r):\n while l >= 0 and r < len(s) and s[l] == s[r]: l -= 1; r += 1\n return l + 1, r - 1\n start = end = 0\n for i in range(len(s)):\n l1, r1 = expand(i, i)\n l2, r2 = expand(i, i + 1)\n if r1 - l1 > end - start: start, end = l1, r1\n if r2 - l2 > end - start: start, end = l2, r2\n return s[start:end+1]", "solution_java": "public String longestPalindrome(String s) {\n int start = 0, end = 0;\n for (int i = 0; i < s.length(); i++) {\n int len1 = expand(s, i, i), len2 = expand(s, i, i+1);\n int len = Math.max(len1, len2);\n if (len > end - start) { start = i - (len-1)/2; end = i + len/2; }\n }\n return s.substring(start, end + 1);\n}\nprivate int expand(String s, int l, int r) {\n while (l >= 0 && r < s.length() && s.charAt(l) == s.charAt(r)) { l--; r++; }\n return r - l - 1;\n}", "solution_cpp": "string longestPalindrome(string s) {\n int start = 0, end = 0;\n for (int i = 0; i < s.size(); i++) {\n int len1 = expand(s, i, i), len2 = expand(s, i, i+1);\n if (max(len1, len2) > end - start) { start = i - (max(len1,len2)-1)/2; end = i + max(len1,len2)/2; }\n }\n return s.substr(start, end - start + 1);\n}", "test_cases": ["s=\"babad\" -> bab或aba", "s=\"cbbd\" -> bb"], "key_points": ["中心扩展法", "处理奇偶长度"], "tags": ["string", "medium", "Google", "Amazon"]} {"problem_id": "algo_01666", "original_id": "reverse-list", "title": "反转链表", "category": "linkedlist", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "给你单链表的头节点 head,请你反转链表,并返回反转后的链表。", "solution_python": "def reverseList(head):\n prev = None\n curr = head\n while curr:\n nxt = curr.next\n curr.next = prev\n prev = curr\n curr = nxt\n return prev", "solution_java": "public ListNode reverseList(ListNode head) {\n ListNode prev = null, curr = head;\n while (curr != null) {\n ListNode next = curr.next;\n curr.next = prev;\n prev = curr;\n curr = next;\n }\n return prev;\n}", "solution_cpp": "ListNode* reverseList(ListNode* head) {\n ListNode* prev = nullptr, *curr = head;\n while (curr) {\n ListNode* next = curr->next;\n curr->next = prev;\n prev = curr;\n curr = next;\n }\n return prev;\n}", "test_cases": ["head=[1,2,3,4,5] -> [5,4,3,2,1]", "head=[1,2] -> [2,1]"], "key_points": ["迭代法 O(1)空间", "递归法 O(n)空间"], "tags": ["linkedlist", "medium", "Google", "Microsoft"]} {"problem_id": "algo_01667", "original_id": "middle-node", "title": "链表的中间结点", "category": "linkedlist", "difficulty": "easy", "companies": ["Amazon", "Facebook"], "description": "给你单链表的头节点 head,请你找出并返回链表的中间结点。如果有两个中间结点,则返回第二个中间结点。", "solution_python": "def middleNode(head):\n slow = fast = head\n while fast and fast.next:\n slow = slow.next\n fast = fast.next.next\n return slow", "solution_java": "public ListNode middleNode(ListNode head) {\n ListNode slow = head, fast = head;\n while (fast != null && fast.next != null) {\n slow = slow.next;\n fast = fast.next.next;\n }\n return slow;\n}", "solution_cpp": "ListNode* middleNode(ListNode* head) {\n ListNode* slow = head, *fast = head;\n while (fast && fast->next) { slow = slow->next; fast = fast->next->next; }\n return slow;\n}", "test_cases": ["head=[1,2,3,4,5] -> 3", "head=[1,2,3,4,5,6] -> 4"], "key_points": ["快慢指针", "O(n)时间O(1)空间"], "tags": ["linkedlist", "easy", "Amazon", "Facebook"]} {"problem_id": "algo_01668", "original_id": "max-depth", "title": "二叉树的最大深度", "category": "tree", "difficulty": "easy", "companies": ["Microsoft", "Apple"], "description": "给定一个二叉树 root,返回其最大深度。", "solution_python": "def maxDepth(root):\n if not root: return 0\n return max(maxDepth(root.left), maxDepth(root.right)) + 1", "solution_java": "public int maxDepth(TreeNode root) {\n if (root == null) return 0;\n return Math.max(maxDepth(root.left), maxDepth(root.right)) + 1;\n}", "solution_cpp": "int maxDepth(TreeNode* root) {\n if (!root) return 0;\n return max(maxDepth(root->left), maxDepth(root->right)) + 1;\n}", "test_cases": ["root=[3,9,20,null,null,15,7] -> 3", "root=[1,null,2] -> 2"], "key_points": ["DFS递归", "层序遍历也可"], "tags": ["tree", "easy", "Microsoft", "Apple"]} {"problem_id": "algo_01669", "original_id": "inorder-traversal", "title": "二叉树的中序遍历", "category": "tree", "difficulty": "easy", "companies": ["Google", "Microsoft"], "description": "给定一个二叉树的根节点 root,返回它的中序遍历结果。", "solution_python": "def inorderTraversal(root):\n result = []\n def dfs(node):\n if node:\n dfs(node.left)\n result.append(node.val)\n dfs(node.right)\n dfs(root)\n return result", "solution_java": "public List inorderTraversal(TreeNode root) {\n List res = new ArrayList<>();\n dfs(root, res);\n return res;\n}\nprivate void dfs(TreeNode node, List res) {\n if (node == null) return;\n dfs(node.left, res); res.add(node.val); dfs(node.right, res);\n}", "solution_cpp": "vector inorderTraversal(TreeNode* root) {\n vector res;\n dfs(root, res);\n return res;\n}\nvoid dfs(TreeNode* node, vector& res) {\n if (!node) return;\n dfs(node->left, res); res.push_back(node->val); dfs(node->right, res);\n}", "test_cases": ["root=[1,null,2,3] -> [1,3,2]", "root=[] -> []"], "key_points": ["左-根-右顺序", "递归最简洁"], "tags": ["tree", "easy", "Google", "Microsoft"]} {"problem_id": "algo_01670", "original_id": "binary-search", "title": "二分查找", "category": "binarysearch", "difficulty": "easy", "companies": ["Google", "Amazon"], "description": "给定一个 n 个元素有序的(升序)整型数组 nums 和一个目标值 target,写一个函数搜索 nums 中的 target,如果目标值存在返回下标,否则返回 -1。", "solution_python": "def search(nums, target):\n left, right = 0, len(nums) - 1\n while left <= right:\n mid = (left + right) // 2\n if nums[mid] == target: return mid\n elif nums[mid] < target: left = mid + 1\n else: right = mid - 1\n return -1", "solution_java": "public int search(int[] nums, int target) {\n int left = 0, right = nums.length - 1;\n while (left <= right) {\n int mid = left + (right - left) / 2;\n if (nums[mid] == target) return mid;\n else if (nums[mid] < target) left = mid + 1;\n else right = mid - 1;\n }\n return -1;\n}", "solution_cpp": "int search(vector& nums, int target) {\n int left = 0, right = nums.size() - 1;\n while (left <= right) {\n int mid = left + (right - left) / 2;\n if (nums[mid] == target) return mid;\n else if (nums[mid] < target) left = mid + 1;\n else right = mid - 1;\n }\n return -1;\n}", "test_cases": ["nums=[-1,0,3,5,9,12], target=9 -> 4", "nums=[-1,0,3,5,9,12], target=2 -> -1"], "key_points": ["标准模板", "注意防溢出写法"], "tags": ["binarysearch", "easy", "Google", "Amazon"]} {"problem_id": "algo_01671", "original_id": "climbing-stairs", "title": "爬楼梯", "category": "dp", "difficulty": "easy", "companies": ["Amazon", "Google"], "description": "假设你正在爬楼梯。需要 n 阶你才能到达楼顶。每次你可以爬 1 或 2 个台阶。你有多少种不同的方法可以爬到楼顶?", "solution_python": "def climbStairs(n):\n if n <= 2: return n\n a, b = 1, 2\n for _ in range(3, n+1):\n a, b = b, a + b\n return b", "solution_java": "public int climbStairs(int n) {\n if (n <= 2) return n;\n int a = 1, b = 2;\n for (int i = 3; i <= n; i++) { int temp = a + b; a = b; b = temp; }\n return b;\n}", "solution_cpp": "int climbStairs(int n) {\n if (n <= 2) return n;\n int a = 1, b = 2;\n for (int i = 3; i <= n; i++) { int temp = a + b; a = b; b = temp; }\n return b;\n}", "test_cases": ["n=2 -> 2", "n=3 -> 3", "n=5 -> 8"], "key_points": ["斐波那契数列", "滚动数组优化空间"], "tags": ["dp", "easy", "Amazon", "Google"]} {"problem_id": "algo_01672", "original_id": "coin-change", "title": "零钱兑换", "category": "dp", "difficulty": "medium", "companies": ["Google", "Amazon"], "description": "给你一个整数数组 coins 表示不同面额的硬币,以及一个整数 amount 表示总金额。计算并返回可以凑成总金额所需的最少的硬币个数。如果没有任何一种硬币组合能组成总金额,返回 -1。", "solution_python": "def coinChange(coins, amount):\n dp = [float('inf')] * (amount + 1)\n dp[0] = 0\n for coin in coins:\n for x in range(coin, amount + 1):\n dp[x] = min(dp[x], dp[x - coin] + 1)\n return dp[amount] if dp[amount] != float('inf') else -1", "solution_java": "public int coinChange(int[] coins, int amount) {\n int[] dp = new int[amount + 1];\n Arrays.fill(dp, amount + 1);\n dp[0] = 0;\n for (int coin : coins) {\n for (int x = coin; x <= amount; x++) {\n dp[x] = Math.min(dp[x], dp[x - coin] + 1);\n }\n }\n return dp[amount] > amount ? -1 : dp[amount];\n}", "solution_cpp": "int coinChange(vector& coins, int amount) {\n vector dp(amount + 1, amount + 1);\n dp[0] = 0;\n for (int coin : coins) {\n for (int x = coin; x <= amount; x++) {\n dp[x] = min(dp[x], dp[x - coin] + 1);\n }\n }\n return dp[amount] > amount ? -1 : dp[amount];\n}", "test_cases": ["coins=[1,2,5], amount=11 -> 3", "coins=[2], amount=3 -> -1"], "key_points": ["完全背包问题", "dp[x] = min(dp[x-coin]+1)"], "tags": ["dp", "medium", "Google", "Amazon"]} {"problem_id": "algo_01673", "original_id": "subsets", "title": "子集", "category": "backtracking", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "给你一个整数数组 nums ,数组中的元素 互不相同 。返回该数组所有可能的子集(幂集)。", "solution_python": "def subsets(nums):\n result = []\n def backtrack(start, path):\n result.append(path[:])\n for i in range(start, len(nums)):\n path.append(nums[i])\n backtrack(i + 1, path)\n path.pop()\n backtrack(0, [])\n return result", "solution_java": "public List> subsets(int[] nums) {\n List> result = new ArrayList<>();\n backtrack(nums, 0, new ArrayList<>(), result);\n return result;\n}\nprivate void backtrack(int[] nums, int start, List path, List> result) {\n result.add(new ArrayList<>(path));\n for (int i = start; i < nums.length; i++) {\n path.add(nums[i]);\n backtrack(nums, i + 1, path, result);\n path.remove(path.size() - 1);\n }\n}", "solution_cpp": "vector> subsets(vector& nums) {\n vector> result;\n vector path;\n backtrack(nums, 0, path, result);\n return result;\n}\nvoid backtrack(vector& nums, int start, vector& path, vector>& result) {\n result.push_back(path);\n for (int i = start; i < nums.size(); i++) {\n path.push_back(nums[i]);\n backtrack(nums, i + 1, path, result);\n path.pop_back();\n }\n}", "test_cases": ["nums=[1,2,3] -> [[],[1],[2],[1,2],[3],[1,3],[2,3],[1,2,3]]"], "key_points": ["选或不选", "DFS遍历子集树"], "tags": ["backtracking", "medium", "Google", "Microsoft"]} {"problem_id": "algo_01674", "original_id": "permutations", "title": "全排列", "category": "backtracking", "difficulty": "medium", "companies": ["Google", "Facebook"], "description": "给定一个不含重复数字的数组 nums,返回其所有可能的全排列。", "solution_python": "def permute(nums):\n result = []\n def backtrack(path, used):\n if len(path) == len(nums):\n result.append(path[:])\n return\n for i in range(len(nums)):\n if used[i]: continue\n used[i] = True\n path.append(nums[i])\n backtrack(path, used)\n path.pop()\n used[i] = False\n backtrack([], [False]*len(nums))\n return result", "solution_java": "public List> permute(int[] nums) {\n List> result = new ArrayList<>();\n boolean[] used = new boolean[nums.length];\n backtrack(nums, used, new ArrayList<>(), result);\n return result;\n}\nprivate void backtrack(int[] nums, boolean[] used, List path, List> result) {\n if (path.size() == nums.length) { result.add(new ArrayList<>(path)); return; }\n for (int i = 0; i < nums.length; i++) {\n if (used[i]) continue;\n used[i] = true;\n path.add(nums[i]);\n backtrack(nums, used, path, result);\n path.remove(path.size() - 1);\n used[i] = false;\n }\n}", "solution_cpp": "vector> permute(vector& nums) {\n vector> result;\n vector used(nums.size(), false);\n vector path;\n backtrack(nums, used, path, result);\n return result;\n}\nvoid backtrack(vector& nums, vector& used, vector& path, vector>& result) {\n if (path.size() == nums.size()) { result.push_back(path); return; }\n for (int i = 0; i < nums.size(); i++) {\n if (used[i]) continue;\n used[i] = true;\n path.push_back(nums[i]);\n backtrack(nums, used, path, result);\n path.pop_back();\n used[i] = false;\n }\n}", "test_cases": ["nums=[1,2,3] -> [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]"], "key_points": ["标记已使用元素", "回溯经典模板"], "tags": ["backtracking", "medium", "Google", "Facebook"]} {"problem_id": "algo_01675", "original_id": "top-k-frequent", "title": "前K个高频元素", "category": "heap", "difficulty": "medium", "companies": ["Amazon", "Facebook"], "description": "给你一个整数数组 nums 和一个整数 k,请你返回其中出现频率前 k 高的元素。", "solution_python": "import heapq\nfrom collections import Counter\ndef topKFrequent(nums, k):\n count = Counter(nums)\n heap = []\n for num, freq in count.items():\n heapq.heappush(heap, (freq, num))\n if len(heap) > k: heapq.heappop(heap)\n return [num for freq, num in heap]", "solution_java": "public int[] topKFrequent(int[] nums, int k) {\n Map count = new HashMap<>();\n for (int n : nums) count.put(n, count.getOrDefault(n, 0) + 1);\n PriorityQueue> heap = \n new PriorityQueue<>((a, b) -> a.getValue() - b.getValue());\n for (Map.Entry e : count.entrySet()) {\n heap.offer(e);\n if (heap.size() > k) heap.poll();\n }\n int[] res = new int[k];\n for (int i = k - 1; i >= 0; i--) res[i] = heap.poll().getKey();\n return res;\n}", "solution_cpp": "vector topKFrequent(vector& nums, int k) {\n unordered_map count;\n for (int n : nums) count[n]++;\n priority_queue, vector>, greater>> heap;\n for (auto& [num, freq] : count) {\n heap.push({freq, num});\n if (heap.size() > k) heap.pop();\n }\n vector res;\n while (!heap.empty()) { res.push_back(heap.top().second); heap.pop(); }\n reverse(res.begin(), res.end());\n return res;\n}", "test_cases": ["nums=[1,1,1,2,2,3], k=2 -> [1,2]", "nums=[1], k=1 -> [1]"], "key_points": ["小顶堆保持大小k", "时间复杂度O(nlogk)"], "tags": ["heap", "medium", "Amazon", "Facebook"]} {"problem_id": "algo_01676", "original_id": "3sum", "title": "三数之和", "category": "two-pointers", "difficulty": "medium", "companies": ["Google", "Amazon"], "description": "给你一个整数数组 nums,判断是否存在三元组满足和为0,返回所有不重复的三元组。", "solution_python": "def threeSum(nums):\n nums.sort()\n result = []\n for i in range(len(nums) - 2):\n if i > 0 and nums[i] == nums[i-1]: continue\n left, right = i + 1, len(nums) - 1\n while left < right:\n total = nums[i] + nums[left] + nums[right]\n if total < 0: left += 1\n elif total > 0: right -= 1\n else:\n result.append([nums[i], nums[left], nums[right]])\n while left < right and nums[left] == nums[left+1]: left += 1\n while left < right and nums[right] == nums[right-1]: right -= 1\n left += 1; right -= 1\n return result", "solution_java": "public List> threeSum(int[] nums) {\n Arrays.sort(nums);\n List> result = new ArrayList<>();\n for (int i = 0; i < nums.length - 2; i++) {\n if (i > 0 && nums[i] == nums[i-1]) continue;\n int left = i + 1, right = nums.length - 1;\n while (left < right) {\n int total = nums[i] + nums[left] + nums[right];\n if (total < 0) left++;\n else if (total > 0) right--;\n else {\n result.add(Arrays.asList(nums[i], nums[left], nums[right]));\n while (left < right && nums[left] == nums[left+1]) left++;\n while (left < right && nums[right] == nums[right-1]) right--;\n left++; right--;\n }\n }\n }\n return result;\n}", "solution_cpp": "vector> threeSum(vector& nums) {\n sort(nums.begin(), nums.end());\n vector> result;\n for (int i = 0; i < nums.size() - 2; i++) {\n if (i > 0 && nums[i] == nums[i-1]) continue;\n int left = i + 1, right = nums.size() - 1;\n while (left < right) {\n int total = nums[i] + nums[left] + nums[right];\n if (total < 0) left++;\n else if (total > 0) right--;\n else {\n result.push_back({nums[i], nums[left], nums[right]});\n while (left < right && nums[left] == nums[left+1]) left++;\n while (left < right && nums[right] == nums[right-1]) right--;\n left++; right--;\n }\n }\n }\n return result;\n}", "test_cases": ["nums=[-1,0,1,2,-1,-4] -> [[-1,-1,2],[-1,0,1]]"], "key_points": ["排序+双指针", "去重是关键"], "tags": ["two-pointers", "medium", "Google", "Amazon"]} {"problem_id": "algo_01677", "original_id": "container-water", "title": "盛最多水的容器", "category": "two-pointers", "difficulty": "medium", "companies": ["Google", "Uber"], "description": "给定一个长度为 n 的整数数组 height,找出其中的两条线,使得它们与 x 轴共同构成的容器可以容纳最多的水。", "solution_python": "def maxArea(height):\n left, right = 0, len(height) - 1\n max_area = 0\n while left < right:\n h = min(height[left], height[right])\n max_area = max(max_area, h * (right - left))\n if height[left] < height[right]: left += 1\n else: right -= 1\n return max_area", "solution_java": "public int maxArea(int[] height) {\n int left = 0, right = height.length - 1, maxArea = 0;\n while (left < right) {\n int h = Math.min(height[left], height[right]);\n maxArea = Math.max(maxArea, h * (right - left));\n if (height[left] < height[right]) left++;\n else right--;\n }\n return maxArea;\n}", "solution_cpp": "int maxArea(vector& height) {\n int left = 0, right = height.size() - 1, maxArea = 0;\n while (left < right) {\n int h = min(height[left], height[right]);\n maxArea = max(maxArea, h * (right - left));\n if (height[left] < height[right]) left++;\n else right--;\n }\n return maxArea;\n}", "test_cases": ["height=[1,8,6,2,5,4,8,3,7] -> 49"], "key_points": ["移动短边指针", "面积=min(h1,h2)*width"], "tags": ["two-pointers", "medium", "Google", "Uber"]} {"problem_id": "algo_01678", "original_id": "min-stack", "title": "最小栈", "category": "stack", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "设计一个支持 push,pop,top 操作,并能在常数时间内检索到最小元素的栈。", "solution_python": "class MinStack:\n def __init__(self):\n self.stack = []\n self.min_stack = []\n def push(self, val):\n self.stack.append(val)\n self.min_stack.append(min(val, self.min_stack[-1] if self.min_stack else val))\n def pop(self):\n self.stack.pop(); self.min_stack.pop()\n def top(self): return self.stack[-1]\n def getMin(self): return self.min_stack[-1]", "solution_java": "class MinStack {\n Stack stack = new Stack<>();\n Stack minStack = new Stack<>();\n public void push(int val) { stack.push(val); minStack.push(Math.min(val, minStack.isEmpty() ? val : minStack.peek())); }\n public void pop() { stack.pop(); minStack.pop(); }\n public int top() { return stack.peek(); }\n public int getMin() { return minStack.peek(); }\n}", "solution_cpp": "class MinStack {\n stack st, minSt;\npublic:\n void push(int val) { st.push(val); minSt.push(min(val, minSt.empty() ? val : minSt.top())); }\n void pop() { st.pop(); minSt.pop(); }\n int top() { return st.top(); }\n int getMin() { return minSt.top(); }\n};", "test_cases": ["push(-2), push(0), push(-3) -> getMin() returns -3"], "key_points": ["辅助栈记录最小值", "O(1)时间获取最小值"], "tags": ["stack", "medium", "Google", "Microsoft"]} {"problem_id": "algo_01679", "original_id": "lru-cache", "title": "LRU缓存", "category": "design", "difficulty": "hard", "companies": ["Google", "Amazon"], "description": "设计和实现一个 LRU(最近最少使用)缓存机制。", "solution_python": "class LRUCache:\n def __init__(self, capacity):\n self.capacity = capacity\n self.cache = {}\n self.order = []\n def get(self, key):\n if key not in self.cache: return -1\n self.order.remove(key); self.order.append(key)\n return self.cache[key]\n def put(self, key, value):\n if key in self.cache:\n self.order.remove(key)\n elif len(self.cache) >= self.capacity:\n del self.cache[self.order.pop(0)]\n self.cache[key] = value; self.order.append(key)", "solution_java": "class LRUCache {\n int capacity;\n LinkedHashMap cache = new LinkedHashMap<>();\n public LRUCache(int cap) { capacity = cap; }\n public int get(int key) { return cache.containsKey(key) ? cache.remove(key) : -1; }\n public void put(int key, int val) {\n if (cache.containsKey(key)) cache.remove(key);\n else if (cache.size() >= capacity) cache.remove(cache.keySet().iterator().next());\n cache.put(key, val);\n }\n}", "solution_cpp": "class LRUCache {\n int cap;\n list> dll;\n unordered_map>::iterator> cache;\npublic:\n LRUCache(int capacity) : cap(capacity) {}\n int get(int key) {\n auto it = cache.find(key);\n if (it == cache.end()) return -1;\n dll.splice(dll.end(), dll, it->second);\n return it->second->second;\n }\n void put(int key, int value) {\n auto it = cache.find(key);\n if (it != cache.end()) dll.erase(it->second);\n else if (cache.size() >= cap) { cache.erase(dll.front().first); dll.pop_front(); }\n dll.push_back({key, value});\n cache[key] = --dll.end();\n }\n};", "test_cases": ["put(1,1), put(2,2), get(1) -> 1"], "key_points": ["HashMap + 双向链表", "O(1)时间操作"], "tags": ["design", "hard", "Google", "Amazon"]} {"problem_id": "algo_01680", "original_id": "num-islands", "title": "岛屿数量", "category": "graph", "difficulty": "medium", "companies": ["Google", "Facebook"], "description": "给你一个由 '1'(陆地)和 '0'(水)组成的二维网格,请你计算网格中岛屿的数量。岛屿总是被水包围,且只能由水平或垂直方向相邻的陆地连接形成。", "solution_python": "def numIslands(grid):\n if not grid: return 0\n rows, cols = len(grid), len(grid[0])\n count = 0\n def dfs(r, c):\n if r < 0 or r >= rows or c < 0 or c >= cols or grid[r][c] != '1': return\n grid[r][c] = '0'\n dfs(r+1, c); dfs(r-1, c); dfs(r, c+1); dfs(r, c-1)\n for r in range(rows):\n for c in range(cols):\n if grid[r][c] == '1': count += 1; dfs(r, c)\n return count", "solution_java": "public int numIslands(char[][] grid) {\n if (grid.length == 0) return 0;\n int count = 0;\n for (int i = 0; i < grid.length; i++)\n for (int j = 0; j < grid[0].length; j++)\n if (grid[i][j] == '1') { count++; dfs(grid, i, j); }\n return count;\n}\nprivate void dfs(char[][] grid, int r, int c) {\n if (r < 0 || r >= grid.length || c < 0 || c >= grid[0].length || grid[r][c] != '1') return;\n grid[r][c] = '0';\n dfs(grid, r+1, c); dfs(grid, r-1, c); dfs(grid, r, c+1); dfs(grid, r, c-1);\n}", "solution_cpp": "int numIslands(vector>& grid) {\n if (grid.empty()) return 0;\n int count = 0;\n for (int i = 0; i < grid.size(); i++)\n for (int j = 0; j < grid[0].size(); j++)\n if (grid[i][j] == '1') { count++; dfs(grid, i, j); }\n return count;\n}\nvoid dfs(vector>& grid, int r, int c) {\n if (r < 0 || r >= grid.size() || c < 0 || c >= grid[0].size() || grid[r][c] != '1') return;\n grid[r][c] = '0';\n dfs(grid, r+1, c); dfs(grid, r-1, c); dfs(grid, r, c+1); dfs(grid, r, c-1);\n}", "test_cases": ["grid=[[1,1,1,1,0],[1,1,0,1,0],[1,1,0,0,0],[0,0,0,0,0]] -> 1"], "key_points": ["DFS/BFS遍历", "访问后标记为0避免重复"], "tags": ["graph", "medium", "Google", "Facebook"]} {"problem_id": "algo_01681", "original_id": "two-sum", "title": "两数之和", "category": "array", "difficulty": "easy", "companies": ["Amazon", "Google"], "description": "给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那两个整数,并返回他们的数组下标。", "solution_python": "def twoSum(nums, target):\n hashmap = {}\n for i, num in enumerate(nums):\n complement = target - num\n if complement in hashmap:\n return [hashmap[complement], i]\n hashmap[num] = i\n return []", "solution_java": "public int[] twoSum(int[] nums, int target) {\n Map map = new HashMap<>();\n for (int i = 0; i < nums.length; i++) {\n int complement = target - nums[i];\n if (map.containsKey(complement)) return new int[]{map.get(complement), i};\n map.put(nums[i], i);\n }\n return new int[]{};\n}", "solution_cpp": "vector twoSum(vector& nums, int target) {\n unordered_map m;\n for (int i = 0; i < nums.size(); i++) {\n if (m.count(target - nums[i])) return {m[target - nums[i]], i};\n m[nums[i]] = i;\n }\n return {};\n}", "test_cases": ["nums=[2,7,11,15], target=9 -> [0,1]", "nums=[3,2,4], target=6 -> [1,2]"], "key_points": ["哈希表一次遍历", "空间换时间"], "tags": ["array", "easy", "Amazon", "Google"]} {"problem_id": "algo_01682", "original_id": "merge-sorted", "title": "合并两个有序数组", "category": "array", "difficulty": "easy", "companies": ["Microsoft", "Uber"], "description": "给你两个按非递减顺序排列的整数数组 nums1 和 nums2,另有两个整数 m 和 n,分别表示 nums1 和 nums2 中的元素数目。请你合并 nums2 到 nums1 中。", "solution_python": "def merge(nums1, m, nums2, n):\n p1, p2, p = m-1, n-1, m+n-1\n while p1 >= 0 and p2 >= 0:\n if nums1[p1] > nums2[p2]: nums1[p] = nums1[p1]; p1 -= 1\n else: nums1[p] = nums2[p2]; p2 -= 1\n p -= 1\n while p2 >= 0: nums1[p] = nums2[p2]; p2 -= 1; p -= 1", "solution_java": "public void merge(int[] nums1, int m, int[] nums2, int n) {\n int p1 = m-1, p2 = n-1, p = m+n-1;\n while (p1 >= 0 && p2 >= 0) {\n nums1[p--] = nums1[p1] > nums2[p2] ? nums1[p1--] : nums2[p2--];\n }\n while (p2 >= 0) nums1[p--] = nums2[p2--];\n}", "solution_cpp": "void merge(vector& nums1, int m, vector& nums2, int n) {\n int p1 = m-1, p2 = n-1, p = m+n-1;\n while (p1 >= 0 && p2 >= 0) nums1[p--] = nums1[p1] > nums2[p2] ? nums1[p1--] : nums2[p2--];\n while (p2 >= 0) nums1[p--] = nums2[p2--];\n}", "test_cases": ["nums1=[1,2,3], m=3, nums2=[2,5,6], n=3 -> [1,2,2,3,5,6]", "nums1=[], m=0, nums2=[1], n=1 -> [1]"], "key_points": ["从后往前合并", "三指针技巧"], "tags": ["array", "easy", "Microsoft", "Uber"]} {"problem_id": "algo_01683", "original_id": "max-subarray", "title": "最大子数组和", "category": "array", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "给你一个整数数组 nums ,请你找出一个具有最大和的连续子数组,返回其最大和。", "solution_python": "def maxSubArray(nums):\n max_sum = current = nums[0]\n for num in nums[1:]:\n current = max(num, current + num)\n max_sum = max(max_sum, current)\n return max_sum", "solution_java": "public int maxSubArray(int[] nums) {\n int maxSum = nums[0], curr = nums[0];\n for (int i = 1; i < nums.length; i++) {\n curr = Math.max(nums[i], curr + nums[i]);\n maxSum = Math.max(maxSum, curr);\n }\n return maxSum;\n}", "solution_cpp": "int maxSubArray(vector& nums) {\n int maxSum = nums[0], curr = nums[0];\n for (int i = 1; i < nums.size(); i++) {\n curr = max(nums[i], curr + nums[i]);\n maxSum = max(maxSum, curr);\n }\n return maxSum;\n}", "test_cases": ["nums=[-2,1,-3,4,-1,2,1,-5,4] -> 6", "nums=[1] -> 1"], "key_points": ["Kadane算法", "动态规划基础题"], "tags": ["array", "medium", "Google", "Microsoft"]} {"problem_id": "algo_01684", "original_id": "valid-parentheses", "title": "有效的括号", "category": "string", "difficulty": "easy", "companies": ["Google", "Uber"], "description": "给定一个只包括 '(',')','{','}','[',']' 的字符串 s,判断字符串是否有效。", "solution_python": "def isValid(s):\n stack = []\n mapping = {')': '(', ']': '[', '}': '{'}\n for c in s:\n if c in mapping:\n if not stack or stack[-1] != mapping[c]: return False\n stack.pop()\n else: stack.append(c)\n return not stack", "solution_java": "public boolean isValid(String s) {\n Stack stack = new Stack<>();\n Map map = Map.of(')', '(', ']', '[', '}', '{');\n for (char c : s.toCharArray()) {\n if (map.containsValue(c)) stack.push(c);\n else if (!stack.isEmpty() && stack.pop() != map.get(c)) return false;\n }\n return stack.isEmpty();\n}", "solution_cpp": "bool isValid(string s) {\n stack st;\n unordered_map m = {{')','('},{']','['},{'}','{'}};\n for (char c : s) {\n if (m.find(c) == m.end()) st.push(c);\n else if (st.empty() || st.top() != m[c]) return false;\n else st.pop();\n }\n return st.empty();\n}", "test_cases": ["s=\"()\" -> true", "s=\"()[]{}\" -> true", "s=\"(]\" -> false"], "key_points": ["栈匹配法", "注意空栈边界"], "tags": ["string", "easy", "Google", "Uber"]} {"problem_id": "algo_01685", "original_id": "longest-palindrome", "title": "最长回文子串", "category": "string", "difficulty": "medium", "companies": ["Google", "Amazon"], "description": "给你一个字符串 s,找到 s 中最长的回文子串。", "solution_python": "def longestPalindrome(s):\n def expand(l, r):\n while l >= 0 and r < len(s) and s[l] == s[r]: l -= 1; r += 1\n return l + 1, r - 1\n start = end = 0\n for i in range(len(s)):\n l1, r1 = expand(i, i)\n l2, r2 = expand(i, i + 1)\n if r1 - l1 > end - start: start, end = l1, r1\n if r2 - l2 > end - start: start, end = l2, r2\n return s[start:end+1]", "solution_java": "public String longestPalindrome(String s) {\n int start = 0, end = 0;\n for (int i = 0; i < s.length(); i++) {\n int len1 = expand(s, i, i), len2 = expand(s, i, i+1);\n int len = Math.max(len1, len2);\n if (len > end - start) { start = i - (len-1)/2; end = i + len/2; }\n }\n return s.substring(start, end + 1);\n}\nprivate int expand(String s, int l, int r) {\n while (l >= 0 && r < s.length() && s.charAt(l) == s.charAt(r)) { l--; r++; }\n return r - l - 1;\n}", "solution_cpp": "string longestPalindrome(string s) {\n int start = 0, end = 0;\n for (int i = 0; i < s.size(); i++) {\n int len1 = expand(s, i, i), len2 = expand(s, i, i+1);\n if (max(len1, len2) > end - start) { start = i - (max(len1,len2)-1)/2; end = i + max(len1,len2)/2; }\n }\n return s.substr(start, end - start + 1);\n}", "test_cases": ["s=\"babad\" -> bab或aba", "s=\"cbbd\" -> bb"], "key_points": ["中心扩展法", "处理奇偶长度"], "tags": ["string", "medium", "Google", "Amazon"]} {"problem_id": "algo_01686", "original_id": "reverse-list", "title": "反转链表", "category": "linkedlist", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "给你单链表的头节点 head,请你反转链表,并返回反转后的链表。", "solution_python": "def reverseList(head):\n prev = None\n curr = head\n while curr:\n nxt = curr.next\n curr.next = prev\n prev = curr\n curr = nxt\n return prev", "solution_java": "public ListNode reverseList(ListNode head) {\n ListNode prev = null, curr = head;\n while (curr != null) {\n ListNode next = curr.next;\n curr.next = prev;\n prev = curr;\n curr = next;\n }\n return prev;\n}", "solution_cpp": "ListNode* reverseList(ListNode* head) {\n ListNode* prev = nullptr, *curr = head;\n while (curr) {\n ListNode* next = curr->next;\n curr->next = prev;\n prev = curr;\n curr = next;\n }\n return prev;\n}", "test_cases": ["head=[1,2,3,4,5] -> [5,4,3,2,1]", "head=[1,2] -> [2,1]"], "key_points": ["迭代法 O(1)空间", "递归法 O(n)空间"], "tags": ["linkedlist", "medium", "Google", "Microsoft"]} {"problem_id": "algo_01687", "original_id": "middle-node", "title": "链表的中间结点", "category": "linkedlist", "difficulty": "easy", "companies": ["Amazon", "Facebook"], "description": "给你单链表的头节点 head,请你找出并返回链表的中间结点。如果有两个中间结点,则返回第二个中间结点。", "solution_python": "def middleNode(head):\n slow = fast = head\n while fast and fast.next:\n slow = slow.next\n fast = fast.next.next\n return slow", "solution_java": "public ListNode middleNode(ListNode head) {\n ListNode slow = head, fast = head;\n while (fast != null && fast.next != null) {\n slow = slow.next;\n fast = fast.next.next;\n }\n return slow;\n}", "solution_cpp": "ListNode* middleNode(ListNode* head) {\n ListNode* slow = head, *fast = head;\n while (fast && fast->next) { slow = slow->next; fast = fast->next->next; }\n return slow;\n}", "test_cases": ["head=[1,2,3,4,5] -> 3", "head=[1,2,3,4,5,6] -> 4"], "key_points": ["快慢指针", "O(n)时间O(1)空间"], "tags": ["linkedlist", "easy", "Amazon", "Facebook"]} {"problem_id": "algo_01688", "original_id": "max-depth", "title": "二叉树的最大深度", "category": "tree", "difficulty": "easy", "companies": ["Microsoft", "Apple"], "description": "给定一个二叉树 root,返回其最大深度。", "solution_python": "def maxDepth(root):\n if not root: return 0\n return max(maxDepth(root.left), maxDepth(root.right)) + 1", "solution_java": "public int maxDepth(TreeNode root) {\n if (root == null) return 0;\n return Math.max(maxDepth(root.left), maxDepth(root.right)) + 1;\n}", "solution_cpp": "int maxDepth(TreeNode* root) {\n if (!root) return 0;\n return max(maxDepth(root->left), maxDepth(root->right)) + 1;\n}", "test_cases": ["root=[3,9,20,null,null,15,7] -> 3", "root=[1,null,2] -> 2"], "key_points": ["DFS递归", "层序遍历也可"], "tags": ["tree", "easy", "Microsoft", "Apple"]} {"problem_id": "algo_01689", "original_id": "inorder-traversal", "title": "二叉树的中序遍历", "category": "tree", "difficulty": "easy", "companies": ["Google", "Microsoft"], "description": "给定一个二叉树的根节点 root,返回它的中序遍历结果。", "solution_python": "def inorderTraversal(root):\n result = []\n def dfs(node):\n if node:\n dfs(node.left)\n result.append(node.val)\n dfs(node.right)\n dfs(root)\n return result", "solution_java": "public List inorderTraversal(TreeNode root) {\n List res = new ArrayList<>();\n dfs(root, res);\n return res;\n}\nprivate void dfs(TreeNode node, List res) {\n if (node == null) return;\n dfs(node.left, res); res.add(node.val); dfs(node.right, res);\n}", "solution_cpp": "vector inorderTraversal(TreeNode* root) {\n vector res;\n dfs(root, res);\n return res;\n}\nvoid dfs(TreeNode* node, vector& res) {\n if (!node) return;\n dfs(node->left, res); res.push_back(node->val); dfs(node->right, res);\n}", "test_cases": ["root=[1,null,2,3] -> [1,3,2]", "root=[] -> []"], "key_points": ["左-根-右顺序", "递归最简洁"], "tags": ["tree", "easy", "Google", "Microsoft"]} {"problem_id": "algo_01690", "original_id": "binary-search", "title": "二分查找", "category": "binarysearch", "difficulty": "easy", "companies": ["Google", "Amazon"], "description": "给定一个 n 个元素有序的(升序)整型数组 nums 和一个目标值 target,写一个函数搜索 nums 中的 target,如果目标值存在返回下标,否则返回 -1。", "solution_python": "def search(nums, target):\n left, right = 0, len(nums) - 1\n while left <= right:\n mid = (left + right) // 2\n if nums[mid] == target: return mid\n elif nums[mid] < target: left = mid + 1\n else: right = mid - 1\n return -1", "solution_java": "public int search(int[] nums, int target) {\n int left = 0, right = nums.length - 1;\n while (left <= right) {\n int mid = left + (right - left) / 2;\n if (nums[mid] == target) return mid;\n else if (nums[mid] < target) left = mid + 1;\n else right = mid - 1;\n }\n return -1;\n}", "solution_cpp": "int search(vector& nums, int target) {\n int left = 0, right = nums.size() - 1;\n while (left <= right) {\n int mid = left + (right - left) / 2;\n if (nums[mid] == target) return mid;\n else if (nums[mid] < target) left = mid + 1;\n else right = mid - 1;\n }\n return -1;\n}", "test_cases": ["nums=[-1,0,3,5,9,12], target=9 -> 4", "nums=[-1,0,3,5,9,12], target=2 -> -1"], "key_points": ["标准模板", "注意防溢出写法"], "tags": ["binarysearch", "easy", "Google", "Amazon"]} {"problem_id": "algo_01691", "original_id": "climbing-stairs", "title": "爬楼梯", "category": "dp", "difficulty": "easy", "companies": ["Amazon", "Google"], "description": "假设你正在爬楼梯。需要 n 阶你才能到达楼顶。每次你可以爬 1 或 2 个台阶。你有多少种不同的方法可以爬到楼顶?", "solution_python": "def climbStairs(n):\n if n <= 2: return n\n a, b = 1, 2\n for _ in range(3, n+1):\n a, b = b, a + b\n return b", "solution_java": "public int climbStairs(int n) {\n if (n <= 2) return n;\n int a = 1, b = 2;\n for (int i = 3; i <= n; i++) { int temp = a + b; a = b; b = temp; }\n return b;\n}", "solution_cpp": "int climbStairs(int n) {\n if (n <= 2) return n;\n int a = 1, b = 2;\n for (int i = 3; i <= n; i++) { int temp = a + b; a = b; b = temp; }\n return b;\n}", "test_cases": ["n=2 -> 2", "n=3 -> 3", "n=5 -> 8"], "key_points": ["斐波那契数列", "滚动数组优化空间"], "tags": ["dp", "easy", "Amazon", "Google"]} {"problem_id": "algo_01692", "original_id": "coin-change", "title": "零钱兑换", "category": "dp", "difficulty": "medium", "companies": ["Google", "Amazon"], "description": "给你一个整数数组 coins 表示不同面额的硬币,以及一个整数 amount 表示总金额。计算并返回可以凑成总金额所需的最少的硬币个数。如果没有任何一种硬币组合能组成总金额,返回 -1。", "solution_python": "def coinChange(coins, amount):\n dp = [float('inf')] * (amount + 1)\n dp[0] = 0\n for coin in coins:\n for x in range(coin, amount + 1):\n dp[x] = min(dp[x], dp[x - coin] + 1)\n return dp[amount] if dp[amount] != float('inf') else -1", "solution_java": "public int coinChange(int[] coins, int amount) {\n int[] dp = new int[amount + 1];\n Arrays.fill(dp, amount + 1);\n dp[0] = 0;\n for (int coin : coins) {\n for (int x = coin; x <= amount; x++) {\n dp[x] = Math.min(dp[x], dp[x - coin] + 1);\n }\n }\n return dp[amount] > amount ? -1 : dp[amount];\n}", "solution_cpp": "int coinChange(vector& coins, int amount) {\n vector dp(amount + 1, amount + 1);\n dp[0] = 0;\n for (int coin : coins) {\n for (int x = coin; x <= amount; x++) {\n dp[x] = min(dp[x], dp[x - coin] + 1);\n }\n }\n return dp[amount] > amount ? -1 : dp[amount];\n}", "test_cases": ["coins=[1,2,5], amount=11 -> 3", "coins=[2], amount=3 -> -1"], "key_points": ["完全背包问题", "dp[x] = min(dp[x-coin]+1)"], "tags": ["dp", "medium", "Google", "Amazon"]} {"problem_id": "algo_01693", "original_id": "subsets", "title": "子集", "category": "backtracking", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "给你一个整数数组 nums ,数组中的元素 互不相同 。返回该数组所有可能的子集(幂集)。", "solution_python": "def subsets(nums):\n result = []\n def backtrack(start, path):\n result.append(path[:])\n for i in range(start, len(nums)):\n path.append(nums[i])\n backtrack(i + 1, path)\n path.pop()\n backtrack(0, [])\n return result", "solution_java": "public List> subsets(int[] nums) {\n List> result = new ArrayList<>();\n backtrack(nums, 0, new ArrayList<>(), result);\n return result;\n}\nprivate void backtrack(int[] nums, int start, List path, List> result) {\n result.add(new ArrayList<>(path));\n for (int i = start; i < nums.length; i++) {\n path.add(nums[i]);\n backtrack(nums, i + 1, path, result);\n path.remove(path.size() - 1);\n }\n}", "solution_cpp": "vector> subsets(vector& nums) {\n vector> result;\n vector path;\n backtrack(nums, 0, path, result);\n return result;\n}\nvoid backtrack(vector& nums, int start, vector& path, vector>& result) {\n result.push_back(path);\n for (int i = start; i < nums.size(); i++) {\n path.push_back(nums[i]);\n backtrack(nums, i + 1, path, result);\n path.pop_back();\n }\n}", "test_cases": ["nums=[1,2,3] -> [[],[1],[2],[1,2],[3],[1,3],[2,3],[1,2,3]]"], "key_points": ["选或不选", "DFS遍历子集树"], "tags": ["backtracking", "medium", "Google", "Microsoft"]} {"problem_id": "algo_01694", "original_id": "permutations", "title": "全排列", "category": "backtracking", "difficulty": "medium", "companies": ["Google", "Facebook"], "description": "给定一个不含重复数字的数组 nums,返回其所有可能的全排列。", "solution_python": "def permute(nums):\n result = []\n def backtrack(path, used):\n if len(path) == len(nums):\n result.append(path[:])\n return\n for i in range(len(nums)):\n if used[i]: continue\n used[i] = True\n path.append(nums[i])\n backtrack(path, used)\n path.pop()\n used[i] = False\n backtrack([], [False]*len(nums))\n return result", "solution_java": "public List> permute(int[] nums) {\n List> result = new ArrayList<>();\n boolean[] used = new boolean[nums.length];\n backtrack(nums, used, new ArrayList<>(), result);\n return result;\n}\nprivate void backtrack(int[] nums, boolean[] used, List path, List> result) {\n if (path.size() == nums.length) { result.add(new ArrayList<>(path)); return; }\n for (int i = 0; i < nums.length; i++) {\n if (used[i]) continue;\n used[i] = true;\n path.add(nums[i]);\n backtrack(nums, used, path, result);\n path.remove(path.size() - 1);\n used[i] = false;\n }\n}", "solution_cpp": "vector> permute(vector& nums) {\n vector> result;\n vector used(nums.size(), false);\n vector path;\n backtrack(nums, used, path, result);\n return result;\n}\nvoid backtrack(vector& nums, vector& used, vector& path, vector>& result) {\n if (path.size() == nums.size()) { result.push_back(path); return; }\n for (int i = 0; i < nums.size(); i++) {\n if (used[i]) continue;\n used[i] = true;\n path.push_back(nums[i]);\n backtrack(nums, used, path, result);\n path.pop_back();\n used[i] = false;\n }\n}", "test_cases": ["nums=[1,2,3] -> [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]"], "key_points": ["标记已使用元素", "回溯经典模板"], "tags": ["backtracking", "medium", "Google", "Facebook"]} {"problem_id": "algo_01695", "original_id": "top-k-frequent", "title": "前K个高频元素", "category": "heap", "difficulty": "medium", "companies": ["Amazon", "Facebook"], "description": "给你一个整数数组 nums 和一个整数 k,请你返回其中出现频率前 k 高的元素。", "solution_python": "import heapq\nfrom collections import Counter\ndef topKFrequent(nums, k):\n count = Counter(nums)\n heap = []\n for num, freq in count.items():\n heapq.heappush(heap, (freq, num))\n if len(heap) > k: heapq.heappop(heap)\n return [num for freq, num in heap]", "solution_java": "public int[] topKFrequent(int[] nums, int k) {\n Map count = new HashMap<>();\n for (int n : nums) count.put(n, count.getOrDefault(n, 0) + 1);\n PriorityQueue> heap = \n new PriorityQueue<>((a, b) -> a.getValue() - b.getValue());\n for (Map.Entry e : count.entrySet()) {\n heap.offer(e);\n if (heap.size() > k) heap.poll();\n }\n int[] res = new int[k];\n for (int i = k - 1; i >= 0; i--) res[i] = heap.poll().getKey();\n return res;\n}", "solution_cpp": "vector topKFrequent(vector& nums, int k) {\n unordered_map count;\n for (int n : nums) count[n]++;\n priority_queue, vector>, greater>> heap;\n for (auto& [num, freq] : count) {\n heap.push({freq, num});\n if (heap.size() > k) heap.pop();\n }\n vector res;\n while (!heap.empty()) { res.push_back(heap.top().second); heap.pop(); }\n reverse(res.begin(), res.end());\n return res;\n}", "test_cases": ["nums=[1,1,1,2,2,3], k=2 -> [1,2]", "nums=[1], k=1 -> [1]"], "key_points": ["小顶堆保持大小k", "时间复杂度O(nlogk)"], "tags": ["heap", "medium", "Amazon", "Facebook"]} {"problem_id": "algo_01696", "original_id": "3sum", "title": "三数之和", "category": "two-pointers", "difficulty": "medium", "companies": ["Google", "Amazon"], "description": "给你一个整数数组 nums,判断是否存在三元组满足和为0,返回所有不重复的三元组。", "solution_python": "def threeSum(nums):\n nums.sort()\n result = []\n for i in range(len(nums) - 2):\n if i > 0 and nums[i] == nums[i-1]: continue\n left, right = i + 1, len(nums) - 1\n while left < right:\n total = nums[i] + nums[left] + nums[right]\n if total < 0: left += 1\n elif total > 0: right -= 1\n else:\n result.append([nums[i], nums[left], nums[right]])\n while left < right and nums[left] == nums[left+1]: left += 1\n while left < right and nums[right] == nums[right-1]: right -= 1\n left += 1; right -= 1\n return result", "solution_java": "public List> threeSum(int[] nums) {\n Arrays.sort(nums);\n List> result = new ArrayList<>();\n for (int i = 0; i < nums.length - 2; i++) {\n if (i > 0 && nums[i] == nums[i-1]) continue;\n int left = i + 1, right = nums.length - 1;\n while (left < right) {\n int total = nums[i] + nums[left] + nums[right];\n if (total < 0) left++;\n else if (total > 0) right--;\n else {\n result.add(Arrays.asList(nums[i], nums[left], nums[right]));\n while (left < right && nums[left] == nums[left+1]) left++;\n while (left < right && nums[right] == nums[right-1]) right--;\n left++; right--;\n }\n }\n }\n return result;\n}", "solution_cpp": "vector> threeSum(vector& nums) {\n sort(nums.begin(), nums.end());\n vector> result;\n for (int i = 0; i < nums.size() - 2; i++) {\n if (i > 0 && nums[i] == nums[i-1]) continue;\n int left = i + 1, right = nums.size() - 1;\n while (left < right) {\n int total = nums[i] + nums[left] + nums[right];\n if (total < 0) left++;\n else if (total > 0) right--;\n else {\n result.push_back({nums[i], nums[left], nums[right]});\n while (left < right && nums[left] == nums[left+1]) left++;\n while (left < right && nums[right] == nums[right-1]) right--;\n left++; right--;\n }\n }\n }\n return result;\n}", "test_cases": ["nums=[-1,0,1,2,-1,-4] -> [[-1,-1,2],[-1,0,1]]"], "key_points": ["排序+双指针", "去重是关键"], "tags": ["two-pointers", "medium", "Google", "Amazon"]} {"problem_id": "algo_01697", "original_id": "container-water", "title": "盛最多水的容器", "category": "two-pointers", "difficulty": "medium", "companies": ["Google", "Uber"], "description": "给定一个长度为 n 的整数数组 height,找出其中的两条线,使得它们与 x 轴共同构成的容器可以容纳最多的水。", "solution_python": "def maxArea(height):\n left, right = 0, len(height) - 1\n max_area = 0\n while left < right:\n h = min(height[left], height[right])\n max_area = max(max_area, h * (right - left))\n if height[left] < height[right]: left += 1\n else: right -= 1\n return max_area", "solution_java": "public int maxArea(int[] height) {\n int left = 0, right = height.length - 1, maxArea = 0;\n while (left < right) {\n int h = Math.min(height[left], height[right]);\n maxArea = Math.max(maxArea, h * (right - left));\n if (height[left] < height[right]) left++;\n else right--;\n }\n return maxArea;\n}", "solution_cpp": "int maxArea(vector& height) {\n int left = 0, right = height.size() - 1, maxArea = 0;\n while (left < right) {\n int h = min(height[left], height[right]);\n maxArea = max(maxArea, h * (right - left));\n if (height[left] < height[right]) left++;\n else right--;\n }\n return maxArea;\n}", "test_cases": ["height=[1,8,6,2,5,4,8,3,7] -> 49"], "key_points": ["移动短边指针", "面积=min(h1,h2)*width"], "tags": ["two-pointers", "medium", "Google", "Uber"]} {"problem_id": "algo_01698", "original_id": "min-stack", "title": "最小栈", "category": "stack", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "设计一个支持 push,pop,top 操作,并能在常数时间内检索到最小元素的栈。", "solution_python": "class MinStack:\n def __init__(self):\n self.stack = []\n self.min_stack = []\n def push(self, val):\n self.stack.append(val)\n self.min_stack.append(min(val, self.min_stack[-1] if self.min_stack else val))\n def pop(self):\n self.stack.pop(); self.min_stack.pop()\n def top(self): return self.stack[-1]\n def getMin(self): return self.min_stack[-1]", "solution_java": "class MinStack {\n Stack stack = new Stack<>();\n Stack minStack = new Stack<>();\n public void push(int val) { stack.push(val); minStack.push(Math.min(val, minStack.isEmpty() ? val : minStack.peek())); }\n public void pop() { stack.pop(); minStack.pop(); }\n public int top() { return stack.peek(); }\n public int getMin() { return minStack.peek(); }\n}", "solution_cpp": "class MinStack {\n stack st, minSt;\npublic:\n void push(int val) { st.push(val); minSt.push(min(val, minSt.empty() ? val : minSt.top())); }\n void pop() { st.pop(); minSt.pop(); }\n int top() { return st.top(); }\n int getMin() { return minSt.top(); }\n};", "test_cases": ["push(-2), push(0), push(-3) -> getMin() returns -3"], "key_points": ["辅助栈记录最小值", "O(1)时间获取最小值"], "tags": ["stack", "medium", "Google", "Microsoft"]} {"problem_id": "algo_01699", "original_id": "lru-cache", "title": "LRU缓存", "category": "design", "difficulty": "hard", "companies": ["Google", "Amazon"], "description": "设计和实现一个 LRU(最近最少使用)缓存机制。", "solution_python": "class LRUCache:\n def __init__(self, capacity):\n self.capacity = capacity\n self.cache = {}\n self.order = []\n def get(self, key):\n if key not in self.cache: return -1\n self.order.remove(key); self.order.append(key)\n return self.cache[key]\n def put(self, key, value):\n if key in self.cache:\n self.order.remove(key)\n elif len(self.cache) >= self.capacity:\n del self.cache[self.order.pop(0)]\n self.cache[key] = value; self.order.append(key)", "solution_java": "class LRUCache {\n int capacity;\n LinkedHashMap cache = new LinkedHashMap<>();\n public LRUCache(int cap) { capacity = cap; }\n public int get(int key) { return cache.containsKey(key) ? cache.remove(key) : -1; }\n public void put(int key, int val) {\n if (cache.containsKey(key)) cache.remove(key);\n else if (cache.size() >= capacity) cache.remove(cache.keySet().iterator().next());\n cache.put(key, val);\n }\n}", "solution_cpp": "class LRUCache {\n int cap;\n list> dll;\n unordered_map>::iterator> cache;\npublic:\n LRUCache(int capacity) : cap(capacity) {}\n int get(int key) {\n auto it = cache.find(key);\n if (it == cache.end()) return -1;\n dll.splice(dll.end(), dll, it->second);\n return it->second->second;\n }\n void put(int key, int value) {\n auto it = cache.find(key);\n if (it != cache.end()) dll.erase(it->second);\n else if (cache.size() >= cap) { cache.erase(dll.front().first); dll.pop_front(); }\n dll.push_back({key, value});\n cache[key] = --dll.end();\n }\n};", "test_cases": ["put(1,1), put(2,2), get(1) -> 1"], "key_points": ["HashMap + 双向链表", "O(1)时间操作"], "tags": ["design", "hard", "Google", "Amazon"]} {"problem_id": "algo_01700", "original_id": "num-islands", "title": "岛屿数量", "category": "graph", "difficulty": "medium", "companies": ["Google", "Facebook"], "description": "给你一个由 '1'(陆地)和 '0'(水)组成的二维网格,请你计算网格中岛屿的数量。岛屿总是被水包围,且只能由水平或垂直方向相邻的陆地连接形成。", "solution_python": "def numIslands(grid):\n if not grid: return 0\n rows, cols = len(grid), len(grid[0])\n count = 0\n def dfs(r, c):\n if r < 0 or r >= rows or c < 0 or c >= cols or grid[r][c] != '1': return\n grid[r][c] = '0'\n dfs(r+1, c); dfs(r-1, c); dfs(r, c+1); dfs(r, c-1)\n for r in range(rows):\n for c in range(cols):\n if grid[r][c] == '1': count += 1; dfs(r, c)\n return count", "solution_java": "public int numIslands(char[][] grid) {\n if (grid.length == 0) return 0;\n int count = 0;\n for (int i = 0; i < grid.length; i++)\n for (int j = 0; j < grid[0].length; j++)\n if (grid[i][j] == '1') { count++; dfs(grid, i, j); }\n return count;\n}\nprivate void dfs(char[][] grid, int r, int c) {\n if (r < 0 || r >= grid.length || c < 0 || c >= grid[0].length || grid[r][c] != '1') return;\n grid[r][c] = '0';\n dfs(grid, r+1, c); dfs(grid, r-1, c); dfs(grid, r, c+1); dfs(grid, r, c-1);\n}", "solution_cpp": "int numIslands(vector>& grid) {\n if (grid.empty()) return 0;\n int count = 0;\n for (int i = 0; i < grid.size(); i++)\n for (int j = 0; j < grid[0].size(); j++)\n if (grid[i][j] == '1') { count++; dfs(grid, i, j); }\n return count;\n}\nvoid dfs(vector>& grid, int r, int c) {\n if (r < 0 || r >= grid.size() || c < 0 || c >= grid[0].size() || grid[r][c] != '1') return;\n grid[r][c] = '0';\n dfs(grid, r+1, c); dfs(grid, r-1, c); dfs(grid, r, c+1); dfs(grid, r, c-1);\n}", "test_cases": ["grid=[[1,1,1,1,0],[1,1,0,1,0],[1,1,0,0,0],[0,0,0,0,0]] -> 1"], "key_points": ["DFS/BFS遍历", "访问后标记为0避免重复"], "tags": ["graph", "medium", "Google", "Facebook"]} {"problem_id": "algo_01701", "original_id": "two-sum", "title": "两数之和", "category": "array", "difficulty": "easy", "companies": ["Amazon", "Google"], "description": "给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那两个整数,并返回他们的数组下标。", "solution_python": "def twoSum(nums, target):\n hashmap = {}\n for i, num in enumerate(nums):\n complement = target - num\n if complement in hashmap:\n return [hashmap[complement], i]\n hashmap[num] = i\n return []", "solution_java": "public int[] twoSum(int[] nums, int target) {\n Map map = new HashMap<>();\n for (int i = 0; i < nums.length; i++) {\n int complement = target - nums[i];\n if (map.containsKey(complement)) return new int[]{map.get(complement), i};\n map.put(nums[i], i);\n }\n return new int[]{};\n}", "solution_cpp": "vector twoSum(vector& nums, int target) {\n unordered_map m;\n for (int i = 0; i < nums.size(); i++) {\n if (m.count(target - nums[i])) return {m[target - nums[i]], i};\n m[nums[i]] = i;\n }\n return {};\n}", "test_cases": ["nums=[2,7,11,15], target=9 -> [0,1]", "nums=[3,2,4], target=6 -> [1,2]"], "key_points": ["哈希表一次遍历", "空间换时间"], "tags": ["array", "easy", "Amazon", "Google"]} {"problem_id": "algo_01702", "original_id": "merge-sorted", "title": "合并两个有序数组", "category": "array", "difficulty": "easy", "companies": ["Microsoft", "Uber"], "description": "给你两个按非递减顺序排列的整数数组 nums1 和 nums2,另有两个整数 m 和 n,分别表示 nums1 和 nums2 中的元素数目。请你合并 nums2 到 nums1 中。", "solution_python": "def merge(nums1, m, nums2, n):\n p1, p2, p = m-1, n-1, m+n-1\n while p1 >= 0 and p2 >= 0:\n if nums1[p1] > nums2[p2]: nums1[p] = nums1[p1]; p1 -= 1\n else: nums1[p] = nums2[p2]; p2 -= 1\n p -= 1\n while p2 >= 0: nums1[p] = nums2[p2]; p2 -= 1; p -= 1", "solution_java": "public void merge(int[] nums1, int m, int[] nums2, int n) {\n int p1 = m-1, p2 = n-1, p = m+n-1;\n while (p1 >= 0 && p2 >= 0) {\n nums1[p--] = nums1[p1] > nums2[p2] ? nums1[p1--] : nums2[p2--];\n }\n while (p2 >= 0) nums1[p--] = nums2[p2--];\n}", "solution_cpp": "void merge(vector& nums1, int m, vector& nums2, int n) {\n int p1 = m-1, p2 = n-1, p = m+n-1;\n while (p1 >= 0 && p2 >= 0) nums1[p--] = nums1[p1] > nums2[p2] ? nums1[p1--] : nums2[p2--];\n while (p2 >= 0) nums1[p--] = nums2[p2--];\n}", "test_cases": ["nums1=[1,2,3], m=3, nums2=[2,5,6], n=3 -> [1,2,2,3,5,6]", "nums1=[], m=0, nums2=[1], n=1 -> [1]"], "key_points": ["从后往前合并", "三指针技巧"], "tags": ["array", "easy", "Microsoft", "Uber"]} {"problem_id": "algo_01703", "original_id": "max-subarray", "title": "最大子数组和", "category": "array", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "给你一个整数数组 nums ,请你找出一个具有最大和的连续子数组,返回其最大和。", "solution_python": "def maxSubArray(nums):\n max_sum = current = nums[0]\n for num in nums[1:]:\n current = max(num, current + num)\n max_sum = max(max_sum, current)\n return max_sum", "solution_java": "public int maxSubArray(int[] nums) {\n int maxSum = nums[0], curr = nums[0];\n for (int i = 1; i < nums.length; i++) {\n curr = Math.max(nums[i], curr + nums[i]);\n maxSum = Math.max(maxSum, curr);\n }\n return maxSum;\n}", "solution_cpp": "int maxSubArray(vector& nums) {\n int maxSum = nums[0], curr = nums[0];\n for (int i = 1; i < nums.size(); i++) {\n curr = max(nums[i], curr + nums[i]);\n maxSum = max(maxSum, curr);\n }\n return maxSum;\n}", "test_cases": ["nums=[-2,1,-3,4,-1,2,1,-5,4] -> 6", "nums=[1] -> 1"], "key_points": ["Kadane算法", "动态规划基础题"], "tags": ["array", "medium", "Google", "Microsoft"]} {"problem_id": "algo_01704", "original_id": "valid-parentheses", "title": "有效的括号", "category": "string", "difficulty": "easy", "companies": ["Google", "Uber"], "description": "给定一个只包括 '(',')','{','}','[',']' 的字符串 s,判断字符串是否有效。", "solution_python": "def isValid(s):\n stack = []\n mapping = {')': '(', ']': '[', '}': '{'}\n for c in s:\n if c in mapping:\n if not stack or stack[-1] != mapping[c]: return False\n stack.pop()\n else: stack.append(c)\n return not stack", "solution_java": "public boolean isValid(String s) {\n Stack stack = new Stack<>();\n Map map = Map.of(')', '(', ']', '[', '}', '{');\n for (char c : s.toCharArray()) {\n if (map.containsValue(c)) stack.push(c);\n else if (!stack.isEmpty() && stack.pop() != map.get(c)) return false;\n }\n return stack.isEmpty();\n}", "solution_cpp": "bool isValid(string s) {\n stack st;\n unordered_map m = {{')','('},{']','['},{'}','{'}};\n for (char c : s) {\n if (m.find(c) == m.end()) st.push(c);\n else if (st.empty() || st.top() != m[c]) return false;\n else st.pop();\n }\n return st.empty();\n}", "test_cases": ["s=\"()\" -> true", "s=\"()[]{}\" -> true", "s=\"(]\" -> false"], "key_points": ["栈匹配法", "注意空栈边界"], "tags": ["string", "easy", "Google", "Uber"]} {"problem_id": "algo_01705", "original_id": "longest-palindrome", "title": "最长回文子串", "category": "string", "difficulty": "medium", "companies": ["Google", "Amazon"], "description": "给你一个字符串 s,找到 s 中最长的回文子串。", "solution_python": "def longestPalindrome(s):\n def expand(l, r):\n while l >= 0 and r < len(s) and s[l] == s[r]: l -= 1; r += 1\n return l + 1, r - 1\n start = end = 0\n for i in range(len(s)):\n l1, r1 = expand(i, i)\n l2, r2 = expand(i, i + 1)\n if r1 - l1 > end - start: start, end = l1, r1\n if r2 - l2 > end - start: start, end = l2, r2\n return s[start:end+1]", "solution_java": "public String longestPalindrome(String s) {\n int start = 0, end = 0;\n for (int i = 0; i < s.length(); i++) {\n int len1 = expand(s, i, i), len2 = expand(s, i, i+1);\n int len = Math.max(len1, len2);\n if (len > end - start) { start = i - (len-1)/2; end = i + len/2; }\n }\n return s.substring(start, end + 1);\n}\nprivate int expand(String s, int l, int r) {\n while (l >= 0 && r < s.length() && s.charAt(l) == s.charAt(r)) { l--; r++; }\n return r - l - 1;\n}", "solution_cpp": "string longestPalindrome(string s) {\n int start = 0, end = 0;\n for (int i = 0; i < s.size(); i++) {\n int len1 = expand(s, i, i), len2 = expand(s, i, i+1);\n if (max(len1, len2) > end - start) { start = i - (max(len1,len2)-1)/2; end = i + max(len1,len2)/2; }\n }\n return s.substr(start, end - start + 1);\n}", "test_cases": ["s=\"babad\" -> bab或aba", "s=\"cbbd\" -> bb"], "key_points": ["中心扩展法", "处理奇偶长度"], "tags": ["string", "medium", "Google", "Amazon"]} {"problem_id": "algo_01706", "original_id": "reverse-list", "title": "反转链表", "category": "linkedlist", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "给你单链表的头节点 head,请你反转链表,并返回反转后的链表。", "solution_python": "def reverseList(head):\n prev = None\n curr = head\n while curr:\n nxt = curr.next\n curr.next = prev\n prev = curr\n curr = nxt\n return prev", "solution_java": "public ListNode reverseList(ListNode head) {\n ListNode prev = null, curr = head;\n while (curr != null) {\n ListNode next = curr.next;\n curr.next = prev;\n prev = curr;\n curr = next;\n }\n return prev;\n}", "solution_cpp": "ListNode* reverseList(ListNode* head) {\n ListNode* prev = nullptr, *curr = head;\n while (curr) {\n ListNode* next = curr->next;\n curr->next = prev;\n prev = curr;\n curr = next;\n }\n return prev;\n}", "test_cases": ["head=[1,2,3,4,5] -> [5,4,3,2,1]", "head=[1,2] -> [2,1]"], "key_points": ["迭代法 O(1)空间", "递归法 O(n)空间"], "tags": ["linkedlist", "medium", "Google", "Microsoft"]} {"problem_id": "algo_01707", "original_id": "middle-node", "title": "链表的中间结点", "category": "linkedlist", "difficulty": "easy", "companies": ["Amazon", "Facebook"], "description": "给你单链表的头节点 head,请你找出并返回链表的中间结点。如果有两个中间结点,则返回第二个中间结点。", "solution_python": "def middleNode(head):\n slow = fast = head\n while fast and fast.next:\n slow = slow.next\n fast = fast.next.next\n return slow", "solution_java": "public ListNode middleNode(ListNode head) {\n ListNode slow = head, fast = head;\n while (fast != null && fast.next != null) {\n slow = slow.next;\n fast = fast.next.next;\n }\n return slow;\n}", "solution_cpp": "ListNode* middleNode(ListNode* head) {\n ListNode* slow = head, *fast = head;\n while (fast && fast->next) { slow = slow->next; fast = fast->next->next; }\n return slow;\n}", "test_cases": ["head=[1,2,3,4,5] -> 3", "head=[1,2,3,4,5,6] -> 4"], "key_points": ["快慢指针", "O(n)时间O(1)空间"], "tags": ["linkedlist", "easy", "Amazon", "Facebook"]} {"problem_id": "algo_01708", "original_id": "max-depth", "title": "二叉树的最大深度", "category": "tree", "difficulty": "easy", "companies": ["Microsoft", "Apple"], "description": "给定一个二叉树 root,返回其最大深度。", "solution_python": "def maxDepth(root):\n if not root: return 0\n return max(maxDepth(root.left), maxDepth(root.right)) + 1", "solution_java": "public int maxDepth(TreeNode root) {\n if (root == null) return 0;\n return Math.max(maxDepth(root.left), maxDepth(root.right)) + 1;\n}", "solution_cpp": "int maxDepth(TreeNode* root) {\n if (!root) return 0;\n return max(maxDepth(root->left), maxDepth(root->right)) + 1;\n}", "test_cases": ["root=[3,9,20,null,null,15,7] -> 3", "root=[1,null,2] -> 2"], "key_points": ["DFS递归", "层序遍历也可"], "tags": ["tree", "easy", "Microsoft", "Apple"]} {"problem_id": "algo_01709", "original_id": "inorder-traversal", "title": "二叉树的中序遍历", "category": "tree", "difficulty": "easy", "companies": ["Google", "Microsoft"], "description": "给定一个二叉树的根节点 root,返回它的中序遍历结果。", "solution_python": "def inorderTraversal(root):\n result = []\n def dfs(node):\n if node:\n dfs(node.left)\n result.append(node.val)\n dfs(node.right)\n dfs(root)\n return result", "solution_java": "public List inorderTraversal(TreeNode root) {\n List res = new ArrayList<>();\n dfs(root, res);\n return res;\n}\nprivate void dfs(TreeNode node, List res) {\n if (node == null) return;\n dfs(node.left, res); res.add(node.val); dfs(node.right, res);\n}", "solution_cpp": "vector inorderTraversal(TreeNode* root) {\n vector res;\n dfs(root, res);\n return res;\n}\nvoid dfs(TreeNode* node, vector& res) {\n if (!node) return;\n dfs(node->left, res); res.push_back(node->val); dfs(node->right, res);\n}", "test_cases": ["root=[1,null,2,3] -> [1,3,2]", "root=[] -> []"], "key_points": ["左-根-右顺序", "递归最简洁"], "tags": ["tree", "easy", "Google", "Microsoft"]} {"problem_id": "algo_01710", "original_id": "binary-search", "title": "二分查找", "category": "binarysearch", "difficulty": "easy", "companies": ["Google", "Amazon"], "description": "给定一个 n 个元素有序的(升序)整型数组 nums 和一个目标值 target,写一个函数搜索 nums 中的 target,如果目标值存在返回下标,否则返回 -1。", "solution_python": "def search(nums, target):\n left, right = 0, len(nums) - 1\n while left <= right:\n mid = (left + right) // 2\n if nums[mid] == target: return mid\n elif nums[mid] < target: left = mid + 1\n else: right = mid - 1\n return -1", "solution_java": "public int search(int[] nums, int target) {\n int left = 0, right = nums.length - 1;\n while (left <= right) {\n int mid = left + (right - left) / 2;\n if (nums[mid] == target) return mid;\n else if (nums[mid] < target) left = mid + 1;\n else right = mid - 1;\n }\n return -1;\n}", "solution_cpp": "int search(vector& nums, int target) {\n int left = 0, right = nums.size() - 1;\n while (left <= right) {\n int mid = left + (right - left) / 2;\n if (nums[mid] == target) return mid;\n else if (nums[mid] < target) left = mid + 1;\n else right = mid - 1;\n }\n return -1;\n}", "test_cases": ["nums=[-1,0,3,5,9,12], target=9 -> 4", "nums=[-1,0,3,5,9,12], target=2 -> -1"], "key_points": ["标准模板", "注意防溢出写法"], "tags": ["binarysearch", "easy", "Google", "Amazon"]} {"problem_id": "algo_01711", "original_id": "climbing-stairs", "title": "爬楼梯", "category": "dp", "difficulty": "easy", "companies": ["Amazon", "Google"], "description": "假设你正在爬楼梯。需要 n 阶你才能到达楼顶。每次你可以爬 1 或 2 个台阶。你有多少种不同的方法可以爬到楼顶?", "solution_python": "def climbStairs(n):\n if n <= 2: return n\n a, b = 1, 2\n for _ in range(3, n+1):\n a, b = b, a + b\n return b", "solution_java": "public int climbStairs(int n) {\n if (n <= 2) return n;\n int a = 1, b = 2;\n for (int i = 3; i <= n; i++) { int temp = a + b; a = b; b = temp; }\n return b;\n}", "solution_cpp": "int climbStairs(int n) {\n if (n <= 2) return n;\n int a = 1, b = 2;\n for (int i = 3; i <= n; i++) { int temp = a + b; a = b; b = temp; }\n return b;\n}", "test_cases": ["n=2 -> 2", "n=3 -> 3", "n=5 -> 8"], "key_points": ["斐波那契数列", "滚动数组优化空间"], "tags": ["dp", "easy", "Amazon", "Google"]} {"problem_id": "algo_01712", "original_id": "coin-change", "title": "零钱兑换", "category": "dp", "difficulty": "medium", "companies": ["Google", "Amazon"], "description": "给你一个整数数组 coins 表示不同面额的硬币,以及一个整数 amount 表示总金额。计算并返回可以凑成总金额所需的最少的硬币个数。如果没有任何一种硬币组合能组成总金额,返回 -1。", "solution_python": "def coinChange(coins, amount):\n dp = [float('inf')] * (amount + 1)\n dp[0] = 0\n for coin in coins:\n for x in range(coin, amount + 1):\n dp[x] = min(dp[x], dp[x - coin] + 1)\n return dp[amount] if dp[amount] != float('inf') else -1", "solution_java": "public int coinChange(int[] coins, int amount) {\n int[] dp = new int[amount + 1];\n Arrays.fill(dp, amount + 1);\n dp[0] = 0;\n for (int coin : coins) {\n for (int x = coin; x <= amount; x++) {\n dp[x] = Math.min(dp[x], dp[x - coin] + 1);\n }\n }\n return dp[amount] > amount ? -1 : dp[amount];\n}", "solution_cpp": "int coinChange(vector& coins, int amount) {\n vector dp(amount + 1, amount + 1);\n dp[0] = 0;\n for (int coin : coins) {\n for (int x = coin; x <= amount; x++) {\n dp[x] = min(dp[x], dp[x - coin] + 1);\n }\n }\n return dp[amount] > amount ? -1 : dp[amount];\n}", "test_cases": ["coins=[1,2,5], amount=11 -> 3", "coins=[2], amount=3 -> -1"], "key_points": ["完全背包问题", "dp[x] = min(dp[x-coin]+1)"], "tags": ["dp", "medium", "Google", "Amazon"]} {"problem_id": "algo_01713", "original_id": "subsets", "title": "子集", "category": "backtracking", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "给你一个整数数组 nums ,数组中的元素 互不相同 。返回该数组所有可能的子集(幂集)。", "solution_python": "def subsets(nums):\n result = []\n def backtrack(start, path):\n result.append(path[:])\n for i in range(start, len(nums)):\n path.append(nums[i])\n backtrack(i + 1, path)\n path.pop()\n backtrack(0, [])\n return result", "solution_java": "public List> subsets(int[] nums) {\n List> result = new ArrayList<>();\n backtrack(nums, 0, new ArrayList<>(), result);\n return result;\n}\nprivate void backtrack(int[] nums, int start, List path, List> result) {\n result.add(new ArrayList<>(path));\n for (int i = start; i < nums.length; i++) {\n path.add(nums[i]);\n backtrack(nums, i + 1, path, result);\n path.remove(path.size() - 1);\n }\n}", "solution_cpp": "vector> subsets(vector& nums) {\n vector> result;\n vector path;\n backtrack(nums, 0, path, result);\n return result;\n}\nvoid backtrack(vector& nums, int start, vector& path, vector>& result) {\n result.push_back(path);\n for (int i = start; i < nums.size(); i++) {\n path.push_back(nums[i]);\n backtrack(nums, i + 1, path, result);\n path.pop_back();\n }\n}", "test_cases": ["nums=[1,2,3] -> [[],[1],[2],[1,2],[3],[1,3],[2,3],[1,2,3]]"], "key_points": ["选或不选", "DFS遍历子集树"], "tags": ["backtracking", "medium", "Google", "Microsoft"]} {"problem_id": "algo_01714", "original_id": "permutations", "title": "全排列", "category": "backtracking", "difficulty": "medium", "companies": ["Google", "Facebook"], "description": "给定一个不含重复数字的数组 nums,返回其所有可能的全排列。", "solution_python": "def permute(nums):\n result = []\n def backtrack(path, used):\n if len(path) == len(nums):\n result.append(path[:])\n return\n for i in range(len(nums)):\n if used[i]: continue\n used[i] = True\n path.append(nums[i])\n backtrack(path, used)\n path.pop()\n used[i] = False\n backtrack([], [False]*len(nums))\n return result", "solution_java": "public List> permute(int[] nums) {\n List> result = new ArrayList<>();\n boolean[] used = new boolean[nums.length];\n backtrack(nums, used, new ArrayList<>(), result);\n return result;\n}\nprivate void backtrack(int[] nums, boolean[] used, List path, List> result) {\n if (path.size() == nums.length) { result.add(new ArrayList<>(path)); return; }\n for (int i = 0; i < nums.length; i++) {\n if (used[i]) continue;\n used[i] = true;\n path.add(nums[i]);\n backtrack(nums, used, path, result);\n path.remove(path.size() - 1);\n used[i] = false;\n }\n}", "solution_cpp": "vector> permute(vector& nums) {\n vector> result;\n vector used(nums.size(), false);\n vector path;\n backtrack(nums, used, path, result);\n return result;\n}\nvoid backtrack(vector& nums, vector& used, vector& path, vector>& result) {\n if (path.size() == nums.size()) { result.push_back(path); return; }\n for (int i = 0; i < nums.size(); i++) {\n if (used[i]) continue;\n used[i] = true;\n path.push_back(nums[i]);\n backtrack(nums, used, path, result);\n path.pop_back();\n used[i] = false;\n }\n}", "test_cases": ["nums=[1,2,3] -> [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]"], "key_points": ["标记已使用元素", "回溯经典模板"], "tags": ["backtracking", "medium", "Google", "Facebook"]} {"problem_id": "algo_01715", "original_id": "top-k-frequent", "title": "前K个高频元素", "category": "heap", "difficulty": "medium", "companies": ["Amazon", "Facebook"], "description": "给你一个整数数组 nums 和一个整数 k,请你返回其中出现频率前 k 高的元素。", "solution_python": "import heapq\nfrom collections import Counter\ndef topKFrequent(nums, k):\n count = Counter(nums)\n heap = []\n for num, freq in count.items():\n heapq.heappush(heap, (freq, num))\n if len(heap) > k: heapq.heappop(heap)\n return [num for freq, num in heap]", "solution_java": "public int[] topKFrequent(int[] nums, int k) {\n Map count = new HashMap<>();\n for (int n : nums) count.put(n, count.getOrDefault(n, 0) + 1);\n PriorityQueue> heap = \n new PriorityQueue<>((a, b) -> a.getValue() - b.getValue());\n for (Map.Entry e : count.entrySet()) {\n heap.offer(e);\n if (heap.size() > k) heap.poll();\n }\n int[] res = new int[k];\n for (int i = k - 1; i >= 0; i--) res[i] = heap.poll().getKey();\n return res;\n}", "solution_cpp": "vector topKFrequent(vector& nums, int k) {\n unordered_map count;\n for (int n : nums) count[n]++;\n priority_queue, vector>, greater>> heap;\n for (auto& [num, freq] : count) {\n heap.push({freq, num});\n if (heap.size() > k) heap.pop();\n }\n vector res;\n while (!heap.empty()) { res.push_back(heap.top().second); heap.pop(); }\n reverse(res.begin(), res.end());\n return res;\n}", "test_cases": ["nums=[1,1,1,2,2,3], k=2 -> [1,2]", "nums=[1], k=1 -> [1]"], "key_points": ["小顶堆保持大小k", "时间复杂度O(nlogk)"], "tags": ["heap", "medium", "Amazon", "Facebook"]} {"problem_id": "algo_01716", "original_id": "3sum", "title": "三数之和", "category": "two-pointers", "difficulty": "medium", "companies": ["Google", "Amazon"], "description": "给你一个整数数组 nums,判断是否存在三元组满足和为0,返回所有不重复的三元组。", "solution_python": "def threeSum(nums):\n nums.sort()\n result = []\n for i in range(len(nums) - 2):\n if i > 0 and nums[i] == nums[i-1]: continue\n left, right = i + 1, len(nums) - 1\n while left < right:\n total = nums[i] + nums[left] + nums[right]\n if total < 0: left += 1\n elif total > 0: right -= 1\n else:\n result.append([nums[i], nums[left], nums[right]])\n while left < right and nums[left] == nums[left+1]: left += 1\n while left < right and nums[right] == nums[right-1]: right -= 1\n left += 1; right -= 1\n return result", "solution_java": "public List> threeSum(int[] nums) {\n Arrays.sort(nums);\n List> result = new ArrayList<>();\n for (int i = 0; i < nums.length - 2; i++) {\n if (i > 0 && nums[i] == nums[i-1]) continue;\n int left = i + 1, right = nums.length - 1;\n while (left < right) {\n int total = nums[i] + nums[left] + nums[right];\n if (total < 0) left++;\n else if (total > 0) right--;\n else {\n result.add(Arrays.asList(nums[i], nums[left], nums[right]));\n while (left < right && nums[left] == nums[left+1]) left++;\n while (left < right && nums[right] == nums[right-1]) right--;\n left++; right--;\n }\n }\n }\n return result;\n}", "solution_cpp": "vector> threeSum(vector& nums) {\n sort(nums.begin(), nums.end());\n vector> result;\n for (int i = 0; i < nums.size() - 2; i++) {\n if (i > 0 && nums[i] == nums[i-1]) continue;\n int left = i + 1, right = nums.size() - 1;\n while (left < right) {\n int total = nums[i] + nums[left] + nums[right];\n if (total < 0) left++;\n else if (total > 0) right--;\n else {\n result.push_back({nums[i], nums[left], nums[right]});\n while (left < right && nums[left] == nums[left+1]) left++;\n while (left < right && nums[right] == nums[right-1]) right--;\n left++; right--;\n }\n }\n }\n return result;\n}", "test_cases": ["nums=[-1,0,1,2,-1,-4] -> [[-1,-1,2],[-1,0,1]]"], "key_points": ["排序+双指针", "去重是关键"], "tags": ["two-pointers", "medium", "Google", "Amazon"]} {"problem_id": "algo_01717", "original_id": "container-water", "title": "盛最多水的容器", "category": "two-pointers", "difficulty": "medium", "companies": ["Google", "Uber"], "description": "给定一个长度为 n 的整数数组 height,找出其中的两条线,使得它们与 x 轴共同构成的容器可以容纳最多的水。", "solution_python": "def maxArea(height):\n left, right = 0, len(height) - 1\n max_area = 0\n while left < right:\n h = min(height[left], height[right])\n max_area = max(max_area, h * (right - left))\n if height[left] < height[right]: left += 1\n else: right -= 1\n return max_area", "solution_java": "public int maxArea(int[] height) {\n int left = 0, right = height.length - 1, maxArea = 0;\n while (left < right) {\n int h = Math.min(height[left], height[right]);\n maxArea = Math.max(maxArea, h * (right - left));\n if (height[left] < height[right]) left++;\n else right--;\n }\n return maxArea;\n}", "solution_cpp": "int maxArea(vector& height) {\n int left = 0, right = height.size() - 1, maxArea = 0;\n while (left < right) {\n int h = min(height[left], height[right]);\n maxArea = max(maxArea, h * (right - left));\n if (height[left] < height[right]) left++;\n else right--;\n }\n return maxArea;\n}", "test_cases": ["height=[1,8,6,2,5,4,8,3,7] -> 49"], "key_points": ["移动短边指针", "面积=min(h1,h2)*width"], "tags": ["two-pointers", "medium", "Google", "Uber"]} {"problem_id": "algo_01718", "original_id": "min-stack", "title": "最小栈", "category": "stack", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "设计一个支持 push,pop,top 操作,并能在常数时间内检索到最小元素的栈。", "solution_python": "class MinStack:\n def __init__(self):\n self.stack = []\n self.min_stack = []\n def push(self, val):\n self.stack.append(val)\n self.min_stack.append(min(val, self.min_stack[-1] if self.min_stack else val))\n def pop(self):\n self.stack.pop(); self.min_stack.pop()\n def top(self): return self.stack[-1]\n def getMin(self): return self.min_stack[-1]", "solution_java": "class MinStack {\n Stack stack = new Stack<>();\n Stack minStack = new Stack<>();\n public void push(int val) { stack.push(val); minStack.push(Math.min(val, minStack.isEmpty() ? val : minStack.peek())); }\n public void pop() { stack.pop(); minStack.pop(); }\n public int top() { return stack.peek(); }\n public int getMin() { return minStack.peek(); }\n}", "solution_cpp": "class MinStack {\n stack st, minSt;\npublic:\n void push(int val) { st.push(val); minSt.push(min(val, minSt.empty() ? val : minSt.top())); }\n void pop() { st.pop(); minSt.pop(); }\n int top() { return st.top(); }\n int getMin() { return minSt.top(); }\n};", "test_cases": ["push(-2), push(0), push(-3) -> getMin() returns -3"], "key_points": ["辅助栈记录最小值", "O(1)时间获取最小值"], "tags": ["stack", "medium", "Google", "Microsoft"]} {"problem_id": "algo_01719", "original_id": "lru-cache", "title": "LRU缓存", "category": "design", "difficulty": "hard", "companies": ["Google", "Amazon"], "description": "设计和实现一个 LRU(最近最少使用)缓存机制。", "solution_python": "class LRUCache:\n def __init__(self, capacity):\n self.capacity = capacity\n self.cache = {}\n self.order = []\n def get(self, key):\n if key not in self.cache: return -1\n self.order.remove(key); self.order.append(key)\n return self.cache[key]\n def put(self, key, value):\n if key in self.cache:\n self.order.remove(key)\n elif len(self.cache) >= self.capacity:\n del self.cache[self.order.pop(0)]\n self.cache[key] = value; self.order.append(key)", "solution_java": "class LRUCache {\n int capacity;\n LinkedHashMap cache = new LinkedHashMap<>();\n public LRUCache(int cap) { capacity = cap; }\n public int get(int key) { return cache.containsKey(key) ? cache.remove(key) : -1; }\n public void put(int key, int val) {\n if (cache.containsKey(key)) cache.remove(key);\n else if (cache.size() >= capacity) cache.remove(cache.keySet().iterator().next());\n cache.put(key, val);\n }\n}", "solution_cpp": "class LRUCache {\n int cap;\n list> dll;\n unordered_map>::iterator> cache;\npublic:\n LRUCache(int capacity) : cap(capacity) {}\n int get(int key) {\n auto it = cache.find(key);\n if (it == cache.end()) return -1;\n dll.splice(dll.end(), dll, it->second);\n return it->second->second;\n }\n void put(int key, int value) {\n auto it = cache.find(key);\n if (it != cache.end()) dll.erase(it->second);\n else if (cache.size() >= cap) { cache.erase(dll.front().first); dll.pop_front(); }\n dll.push_back({key, value});\n cache[key] = --dll.end();\n }\n};", "test_cases": ["put(1,1), put(2,2), get(1) -> 1"], "key_points": ["HashMap + 双向链表", "O(1)时间操作"], "tags": ["design", "hard", "Google", "Amazon"]} {"problem_id": "algo_01720", "original_id": "num-islands", "title": "岛屿数量", "category": "graph", "difficulty": "medium", "companies": ["Google", "Facebook"], "description": "给你一个由 '1'(陆地)和 '0'(水)组成的二维网格,请你计算网格中岛屿的数量。岛屿总是被水包围,且只能由水平或垂直方向相邻的陆地连接形成。", "solution_python": "def numIslands(grid):\n if not grid: return 0\n rows, cols = len(grid), len(grid[0])\n count = 0\n def dfs(r, c):\n if r < 0 or r >= rows or c < 0 or c >= cols or grid[r][c] != '1': return\n grid[r][c] = '0'\n dfs(r+1, c); dfs(r-1, c); dfs(r, c+1); dfs(r, c-1)\n for r in range(rows):\n for c in range(cols):\n if grid[r][c] == '1': count += 1; dfs(r, c)\n return count", "solution_java": "public int numIslands(char[][] grid) {\n if (grid.length == 0) return 0;\n int count = 0;\n for (int i = 0; i < grid.length; i++)\n for (int j = 0; j < grid[0].length; j++)\n if (grid[i][j] == '1') { count++; dfs(grid, i, j); }\n return count;\n}\nprivate void dfs(char[][] grid, int r, int c) {\n if (r < 0 || r >= grid.length || c < 0 || c >= grid[0].length || grid[r][c] != '1') return;\n grid[r][c] = '0';\n dfs(grid, r+1, c); dfs(grid, r-1, c); dfs(grid, r, c+1); dfs(grid, r, c-1);\n}", "solution_cpp": "int numIslands(vector>& grid) {\n if (grid.empty()) return 0;\n int count = 0;\n for (int i = 0; i < grid.size(); i++)\n for (int j = 0; j < grid[0].size(); j++)\n if (grid[i][j] == '1') { count++; dfs(grid, i, j); }\n return count;\n}\nvoid dfs(vector>& grid, int r, int c) {\n if (r < 0 || r >= grid.size() || c < 0 || c >= grid[0].size() || grid[r][c] != '1') return;\n grid[r][c] = '0';\n dfs(grid, r+1, c); dfs(grid, r-1, c); dfs(grid, r, c+1); dfs(grid, r, c-1);\n}", "test_cases": ["grid=[[1,1,1,1,0],[1,1,0,1,0],[1,1,0,0,0],[0,0,0,0,0]] -> 1"], "key_points": ["DFS/BFS遍历", "访问后标记为0避免重复"], "tags": ["graph", "medium", "Google", "Facebook"]} {"problem_id": "algo_01721", "original_id": "two-sum", "title": "两数之和", "category": "array", "difficulty": "easy", "companies": ["Amazon", "Google"], "description": "给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那两个整数,并返回他们的数组下标。", "solution_python": "def twoSum(nums, target):\n hashmap = {}\n for i, num in enumerate(nums):\n complement = target - num\n if complement in hashmap:\n return [hashmap[complement], i]\n hashmap[num] = i\n return []", "solution_java": "public int[] twoSum(int[] nums, int target) {\n Map map = new HashMap<>();\n for (int i = 0; i < nums.length; i++) {\n int complement = target - nums[i];\n if (map.containsKey(complement)) return new int[]{map.get(complement), i};\n map.put(nums[i], i);\n }\n return new int[]{};\n}", "solution_cpp": "vector twoSum(vector& nums, int target) {\n unordered_map m;\n for (int i = 0; i < nums.size(); i++) {\n if (m.count(target - nums[i])) return {m[target - nums[i]], i};\n m[nums[i]] = i;\n }\n return {};\n}", "test_cases": ["nums=[2,7,11,15], target=9 -> [0,1]", "nums=[3,2,4], target=6 -> [1,2]"], "key_points": ["哈希表一次遍历", "空间换时间"], "tags": ["array", "easy", "Amazon", "Google"]} {"problem_id": "algo_01722", "original_id": "merge-sorted", "title": "合并两个有序数组", "category": "array", "difficulty": "easy", "companies": ["Microsoft", "Uber"], "description": "给你两个按非递减顺序排列的整数数组 nums1 和 nums2,另有两个整数 m 和 n,分别表示 nums1 和 nums2 中的元素数目。请你合并 nums2 到 nums1 中。", "solution_python": "def merge(nums1, m, nums2, n):\n p1, p2, p = m-1, n-1, m+n-1\n while p1 >= 0 and p2 >= 0:\n if nums1[p1] > nums2[p2]: nums1[p] = nums1[p1]; p1 -= 1\n else: nums1[p] = nums2[p2]; p2 -= 1\n p -= 1\n while p2 >= 0: nums1[p] = nums2[p2]; p2 -= 1; p -= 1", "solution_java": "public void merge(int[] nums1, int m, int[] nums2, int n) {\n int p1 = m-1, p2 = n-1, p = m+n-1;\n while (p1 >= 0 && p2 >= 0) {\n nums1[p--] = nums1[p1] > nums2[p2] ? nums1[p1--] : nums2[p2--];\n }\n while (p2 >= 0) nums1[p--] = nums2[p2--];\n}", "solution_cpp": "void merge(vector& nums1, int m, vector& nums2, int n) {\n int p1 = m-1, p2 = n-1, p = m+n-1;\n while (p1 >= 0 && p2 >= 0) nums1[p--] = nums1[p1] > nums2[p2] ? nums1[p1--] : nums2[p2--];\n while (p2 >= 0) nums1[p--] = nums2[p2--];\n}", "test_cases": ["nums1=[1,2,3], m=3, nums2=[2,5,6], n=3 -> [1,2,2,3,5,6]", "nums1=[], m=0, nums2=[1], n=1 -> [1]"], "key_points": ["从后往前合并", "三指针技巧"], "tags": ["array", "easy", "Microsoft", "Uber"]} {"problem_id": "algo_01723", "original_id": "max-subarray", "title": "最大子数组和", "category": "array", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "给你一个整数数组 nums ,请你找出一个具有最大和的连续子数组,返回其最大和。", "solution_python": "def maxSubArray(nums):\n max_sum = current = nums[0]\n for num in nums[1:]:\n current = max(num, current + num)\n max_sum = max(max_sum, current)\n return max_sum", "solution_java": "public int maxSubArray(int[] nums) {\n int maxSum = nums[0], curr = nums[0];\n for (int i = 1; i < nums.length; i++) {\n curr = Math.max(nums[i], curr + nums[i]);\n maxSum = Math.max(maxSum, curr);\n }\n return maxSum;\n}", "solution_cpp": "int maxSubArray(vector& nums) {\n int maxSum = nums[0], curr = nums[0];\n for (int i = 1; i < nums.size(); i++) {\n curr = max(nums[i], curr + nums[i]);\n maxSum = max(maxSum, curr);\n }\n return maxSum;\n}", "test_cases": ["nums=[-2,1,-3,4,-1,2,1,-5,4] -> 6", "nums=[1] -> 1"], "key_points": ["Kadane算法", "动态规划基础题"], "tags": ["array", "medium", "Google", "Microsoft"]} {"problem_id": "algo_01724", "original_id": "valid-parentheses", "title": "有效的括号", "category": "string", "difficulty": "easy", "companies": ["Google", "Uber"], "description": "给定一个只包括 '(',')','{','}','[',']' 的字符串 s,判断字符串是否有效。", "solution_python": "def isValid(s):\n stack = []\n mapping = {')': '(', ']': '[', '}': '{'}\n for c in s:\n if c in mapping:\n if not stack or stack[-1] != mapping[c]: return False\n stack.pop()\n else: stack.append(c)\n return not stack", "solution_java": "public boolean isValid(String s) {\n Stack stack = new Stack<>();\n Map map = Map.of(')', '(', ']', '[', '}', '{');\n for (char c : s.toCharArray()) {\n if (map.containsValue(c)) stack.push(c);\n else if (!stack.isEmpty() && stack.pop() != map.get(c)) return false;\n }\n return stack.isEmpty();\n}", "solution_cpp": "bool isValid(string s) {\n stack st;\n unordered_map m = {{')','('},{']','['},{'}','{'}};\n for (char c : s) {\n if (m.find(c) == m.end()) st.push(c);\n else if (st.empty() || st.top() != m[c]) return false;\n else st.pop();\n }\n return st.empty();\n}", "test_cases": ["s=\"()\" -> true", "s=\"()[]{}\" -> true", "s=\"(]\" -> false"], "key_points": ["栈匹配法", "注意空栈边界"], "tags": ["string", "easy", "Google", "Uber"]} {"problem_id": "algo_01725", "original_id": "longest-palindrome", "title": "最长回文子串", "category": "string", "difficulty": "medium", "companies": ["Google", "Amazon"], "description": "给你一个字符串 s,找到 s 中最长的回文子串。", "solution_python": "def longestPalindrome(s):\n def expand(l, r):\n while l >= 0 and r < len(s) and s[l] == s[r]: l -= 1; r += 1\n return l + 1, r - 1\n start = end = 0\n for i in range(len(s)):\n l1, r1 = expand(i, i)\n l2, r2 = expand(i, i + 1)\n if r1 - l1 > end - start: start, end = l1, r1\n if r2 - l2 > end - start: start, end = l2, r2\n return s[start:end+1]", "solution_java": "public String longestPalindrome(String s) {\n int start = 0, end = 0;\n for (int i = 0; i < s.length(); i++) {\n int len1 = expand(s, i, i), len2 = expand(s, i, i+1);\n int len = Math.max(len1, len2);\n if (len > end - start) { start = i - (len-1)/2; end = i + len/2; }\n }\n return s.substring(start, end + 1);\n}\nprivate int expand(String s, int l, int r) {\n while (l >= 0 && r < s.length() && s.charAt(l) == s.charAt(r)) { l--; r++; }\n return r - l - 1;\n}", "solution_cpp": "string longestPalindrome(string s) {\n int start = 0, end = 0;\n for (int i = 0; i < s.size(); i++) {\n int len1 = expand(s, i, i), len2 = expand(s, i, i+1);\n if (max(len1, len2) > end - start) { start = i - (max(len1,len2)-1)/2; end = i + max(len1,len2)/2; }\n }\n return s.substr(start, end - start + 1);\n}", "test_cases": ["s=\"babad\" -> bab或aba", "s=\"cbbd\" -> bb"], "key_points": ["中心扩展法", "处理奇偶长度"], "tags": ["string", "medium", "Google", "Amazon"]} {"problem_id": "algo_01726", "original_id": "reverse-list", "title": "反转链表", "category": "linkedlist", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "给你单链表的头节点 head,请你反转链表,并返回反转后的链表。", "solution_python": "def reverseList(head):\n prev = None\n curr = head\n while curr:\n nxt = curr.next\n curr.next = prev\n prev = curr\n curr = nxt\n return prev", "solution_java": "public ListNode reverseList(ListNode head) {\n ListNode prev = null, curr = head;\n while (curr != null) {\n ListNode next = curr.next;\n curr.next = prev;\n prev = curr;\n curr = next;\n }\n return prev;\n}", "solution_cpp": "ListNode* reverseList(ListNode* head) {\n ListNode* prev = nullptr, *curr = head;\n while (curr) {\n ListNode* next = curr->next;\n curr->next = prev;\n prev = curr;\n curr = next;\n }\n return prev;\n}", "test_cases": ["head=[1,2,3,4,5] -> [5,4,3,2,1]", "head=[1,2] -> [2,1]"], "key_points": ["迭代法 O(1)空间", "递归法 O(n)空间"], "tags": ["linkedlist", "medium", "Google", "Microsoft"]} {"problem_id": "algo_01727", "original_id": "middle-node", "title": "链表的中间结点", "category": "linkedlist", "difficulty": "easy", "companies": ["Amazon", "Facebook"], "description": "给你单链表的头节点 head,请你找出并返回链表的中间结点。如果有两个中间结点,则返回第二个中间结点。", "solution_python": "def middleNode(head):\n slow = fast = head\n while fast and fast.next:\n slow = slow.next\n fast = fast.next.next\n return slow", "solution_java": "public ListNode middleNode(ListNode head) {\n ListNode slow = head, fast = head;\n while (fast != null && fast.next != null) {\n slow = slow.next;\n fast = fast.next.next;\n }\n return slow;\n}", "solution_cpp": "ListNode* middleNode(ListNode* head) {\n ListNode* slow = head, *fast = head;\n while (fast && fast->next) { slow = slow->next; fast = fast->next->next; }\n return slow;\n}", "test_cases": ["head=[1,2,3,4,5] -> 3", "head=[1,2,3,4,5,6] -> 4"], "key_points": ["快慢指针", "O(n)时间O(1)空间"], "tags": ["linkedlist", "easy", "Amazon", "Facebook"]} {"problem_id": "algo_01728", "original_id": "max-depth", "title": "二叉树的最大深度", "category": "tree", "difficulty": "easy", "companies": ["Microsoft", "Apple"], "description": "给定一个二叉树 root,返回其最大深度。", "solution_python": "def maxDepth(root):\n if not root: return 0\n return max(maxDepth(root.left), maxDepth(root.right)) + 1", "solution_java": "public int maxDepth(TreeNode root) {\n if (root == null) return 0;\n return Math.max(maxDepth(root.left), maxDepth(root.right)) + 1;\n}", "solution_cpp": "int maxDepth(TreeNode* root) {\n if (!root) return 0;\n return max(maxDepth(root->left), maxDepth(root->right)) + 1;\n}", "test_cases": ["root=[3,9,20,null,null,15,7] -> 3", "root=[1,null,2] -> 2"], "key_points": ["DFS递归", "层序遍历也可"], "tags": ["tree", "easy", "Microsoft", "Apple"]} {"problem_id": "algo_01729", "original_id": "inorder-traversal", "title": "二叉树的中序遍历", "category": "tree", "difficulty": "easy", "companies": ["Google", "Microsoft"], "description": "给定一个二叉树的根节点 root,返回它的中序遍历结果。", "solution_python": "def inorderTraversal(root):\n result = []\n def dfs(node):\n if node:\n dfs(node.left)\n result.append(node.val)\n dfs(node.right)\n dfs(root)\n return result", "solution_java": "public List inorderTraversal(TreeNode root) {\n List res = new ArrayList<>();\n dfs(root, res);\n return res;\n}\nprivate void dfs(TreeNode node, List res) {\n if (node == null) return;\n dfs(node.left, res); res.add(node.val); dfs(node.right, res);\n}", "solution_cpp": "vector inorderTraversal(TreeNode* root) {\n vector res;\n dfs(root, res);\n return res;\n}\nvoid dfs(TreeNode* node, vector& res) {\n if (!node) return;\n dfs(node->left, res); res.push_back(node->val); dfs(node->right, res);\n}", "test_cases": ["root=[1,null,2,3] -> [1,3,2]", "root=[] -> []"], "key_points": ["左-根-右顺序", "递归最简洁"], "tags": ["tree", "easy", "Google", "Microsoft"]} {"problem_id": "algo_01730", "original_id": "binary-search", "title": "二分查找", "category": "binarysearch", "difficulty": "easy", "companies": ["Google", "Amazon"], "description": "给定一个 n 个元素有序的(升序)整型数组 nums 和一个目标值 target,写一个函数搜索 nums 中的 target,如果目标值存在返回下标,否则返回 -1。", "solution_python": "def search(nums, target):\n left, right = 0, len(nums) - 1\n while left <= right:\n mid = (left + right) // 2\n if nums[mid] == target: return mid\n elif nums[mid] < target: left = mid + 1\n else: right = mid - 1\n return -1", "solution_java": "public int search(int[] nums, int target) {\n int left = 0, right = nums.length - 1;\n while (left <= right) {\n int mid = left + (right - left) / 2;\n if (nums[mid] == target) return mid;\n else if (nums[mid] < target) left = mid + 1;\n else right = mid - 1;\n }\n return -1;\n}", "solution_cpp": "int search(vector& nums, int target) {\n int left = 0, right = nums.size() - 1;\n while (left <= right) {\n int mid = left + (right - left) / 2;\n if (nums[mid] == target) return mid;\n else if (nums[mid] < target) left = mid + 1;\n else right = mid - 1;\n }\n return -1;\n}", "test_cases": ["nums=[-1,0,3,5,9,12], target=9 -> 4", "nums=[-1,0,3,5,9,12], target=2 -> -1"], "key_points": ["标准模板", "注意防溢出写法"], "tags": ["binarysearch", "easy", "Google", "Amazon"]} {"problem_id": "algo_01731", "original_id": "climbing-stairs", "title": "爬楼梯", "category": "dp", "difficulty": "easy", "companies": ["Amazon", "Google"], "description": "假设你正在爬楼梯。需要 n 阶你才能到达楼顶。每次你可以爬 1 或 2 个台阶。你有多少种不同的方法可以爬到楼顶?", "solution_python": "def climbStairs(n):\n if n <= 2: return n\n a, b = 1, 2\n for _ in range(3, n+1):\n a, b = b, a + b\n return b", "solution_java": "public int climbStairs(int n) {\n if (n <= 2) return n;\n int a = 1, b = 2;\n for (int i = 3; i <= n; i++) { int temp = a + b; a = b; b = temp; }\n return b;\n}", "solution_cpp": "int climbStairs(int n) {\n if (n <= 2) return n;\n int a = 1, b = 2;\n for (int i = 3; i <= n; i++) { int temp = a + b; a = b; b = temp; }\n return b;\n}", "test_cases": ["n=2 -> 2", "n=3 -> 3", "n=5 -> 8"], "key_points": ["斐波那契数列", "滚动数组优化空间"], "tags": ["dp", "easy", "Amazon", "Google"]} {"problem_id": "algo_01732", "original_id": "coin-change", "title": "零钱兑换", "category": "dp", "difficulty": "medium", "companies": ["Google", "Amazon"], "description": "给你一个整数数组 coins 表示不同面额的硬币,以及一个整数 amount 表示总金额。计算并返回可以凑成总金额所需的最少的硬币个数。如果没有任何一种硬币组合能组成总金额,返回 -1。", "solution_python": "def coinChange(coins, amount):\n dp = [float('inf')] * (amount + 1)\n dp[0] = 0\n for coin in coins:\n for x in range(coin, amount + 1):\n dp[x] = min(dp[x], dp[x - coin] + 1)\n return dp[amount] if dp[amount] != float('inf') else -1", "solution_java": "public int coinChange(int[] coins, int amount) {\n int[] dp = new int[amount + 1];\n Arrays.fill(dp, amount + 1);\n dp[0] = 0;\n for (int coin : coins) {\n for (int x = coin; x <= amount; x++) {\n dp[x] = Math.min(dp[x], dp[x - coin] + 1);\n }\n }\n return dp[amount] > amount ? -1 : dp[amount];\n}", "solution_cpp": "int coinChange(vector& coins, int amount) {\n vector dp(amount + 1, amount + 1);\n dp[0] = 0;\n for (int coin : coins) {\n for (int x = coin; x <= amount; x++) {\n dp[x] = min(dp[x], dp[x - coin] + 1);\n }\n }\n return dp[amount] > amount ? -1 : dp[amount];\n}", "test_cases": ["coins=[1,2,5], amount=11 -> 3", "coins=[2], amount=3 -> -1"], "key_points": ["完全背包问题", "dp[x] = min(dp[x-coin]+1)"], "tags": ["dp", "medium", "Google", "Amazon"]} {"problem_id": "algo_01733", "original_id": "subsets", "title": "子集", "category": "backtracking", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "给你一个整数数组 nums ,数组中的元素 互不相同 。返回该数组所有可能的子集(幂集)。", "solution_python": "def subsets(nums):\n result = []\n def backtrack(start, path):\n result.append(path[:])\n for i in range(start, len(nums)):\n path.append(nums[i])\n backtrack(i + 1, path)\n path.pop()\n backtrack(0, [])\n return result", "solution_java": "public List> subsets(int[] nums) {\n List> result = new ArrayList<>();\n backtrack(nums, 0, new ArrayList<>(), result);\n return result;\n}\nprivate void backtrack(int[] nums, int start, List path, List> result) {\n result.add(new ArrayList<>(path));\n for (int i = start; i < nums.length; i++) {\n path.add(nums[i]);\n backtrack(nums, i + 1, path, result);\n path.remove(path.size() - 1);\n }\n}", "solution_cpp": "vector> subsets(vector& nums) {\n vector> result;\n vector path;\n backtrack(nums, 0, path, result);\n return result;\n}\nvoid backtrack(vector& nums, int start, vector& path, vector>& result) {\n result.push_back(path);\n for (int i = start; i < nums.size(); i++) {\n path.push_back(nums[i]);\n backtrack(nums, i + 1, path, result);\n path.pop_back();\n }\n}", "test_cases": ["nums=[1,2,3] -> [[],[1],[2],[1,2],[3],[1,3],[2,3],[1,2,3]]"], "key_points": ["选或不选", "DFS遍历子集树"], "tags": ["backtracking", "medium", "Google", "Microsoft"]} {"problem_id": "algo_01734", "original_id": "permutations", "title": "全排列", "category": "backtracking", "difficulty": "medium", "companies": ["Google", "Facebook"], "description": "给定一个不含重复数字的数组 nums,返回其所有可能的全排列。", "solution_python": "def permute(nums):\n result = []\n def backtrack(path, used):\n if len(path) == len(nums):\n result.append(path[:])\n return\n for i in range(len(nums)):\n if used[i]: continue\n used[i] = True\n path.append(nums[i])\n backtrack(path, used)\n path.pop()\n used[i] = False\n backtrack([], [False]*len(nums))\n return result", "solution_java": "public List> permute(int[] nums) {\n List> result = new ArrayList<>();\n boolean[] used = new boolean[nums.length];\n backtrack(nums, used, new ArrayList<>(), result);\n return result;\n}\nprivate void backtrack(int[] nums, boolean[] used, List path, List> result) {\n if (path.size() == nums.length) { result.add(new ArrayList<>(path)); return; }\n for (int i = 0; i < nums.length; i++) {\n if (used[i]) continue;\n used[i] = true;\n path.add(nums[i]);\n backtrack(nums, used, path, result);\n path.remove(path.size() - 1);\n used[i] = false;\n }\n}", "solution_cpp": "vector> permute(vector& nums) {\n vector> result;\n vector used(nums.size(), false);\n vector path;\n backtrack(nums, used, path, result);\n return result;\n}\nvoid backtrack(vector& nums, vector& used, vector& path, vector>& result) {\n if (path.size() == nums.size()) { result.push_back(path); return; }\n for (int i = 0; i < nums.size(); i++) {\n if (used[i]) continue;\n used[i] = true;\n path.push_back(nums[i]);\n backtrack(nums, used, path, result);\n path.pop_back();\n used[i] = false;\n }\n}", "test_cases": ["nums=[1,2,3] -> [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]"], "key_points": ["标记已使用元素", "回溯经典模板"], "tags": ["backtracking", "medium", "Google", "Facebook"]} {"problem_id": "algo_01735", "original_id": "top-k-frequent", "title": "前K个高频元素", "category": "heap", "difficulty": "medium", "companies": ["Amazon", "Facebook"], "description": "给你一个整数数组 nums 和一个整数 k,请你返回其中出现频率前 k 高的元素。", "solution_python": "import heapq\nfrom collections import Counter\ndef topKFrequent(nums, k):\n count = Counter(nums)\n heap = []\n for num, freq in count.items():\n heapq.heappush(heap, (freq, num))\n if len(heap) > k: heapq.heappop(heap)\n return [num for freq, num in heap]", "solution_java": "public int[] topKFrequent(int[] nums, int k) {\n Map count = new HashMap<>();\n for (int n : nums) count.put(n, count.getOrDefault(n, 0) + 1);\n PriorityQueue> heap = \n new PriorityQueue<>((a, b) -> a.getValue() - b.getValue());\n for (Map.Entry e : count.entrySet()) {\n heap.offer(e);\n if (heap.size() > k) heap.poll();\n }\n int[] res = new int[k];\n for (int i = k - 1; i >= 0; i--) res[i] = heap.poll().getKey();\n return res;\n}", "solution_cpp": "vector topKFrequent(vector& nums, int k) {\n unordered_map count;\n for (int n : nums) count[n]++;\n priority_queue, vector>, greater>> heap;\n for (auto& [num, freq] : count) {\n heap.push({freq, num});\n if (heap.size() > k) heap.pop();\n }\n vector res;\n while (!heap.empty()) { res.push_back(heap.top().second); heap.pop(); }\n reverse(res.begin(), res.end());\n return res;\n}", "test_cases": ["nums=[1,1,1,2,2,3], k=2 -> [1,2]", "nums=[1], k=1 -> [1]"], "key_points": ["小顶堆保持大小k", "时间复杂度O(nlogk)"], "tags": ["heap", "medium", "Amazon", "Facebook"]} {"problem_id": "algo_01736", "original_id": "3sum", "title": "三数之和", "category": "two-pointers", "difficulty": "medium", "companies": ["Google", "Amazon"], "description": "给你一个整数数组 nums,判断是否存在三元组满足和为0,返回所有不重复的三元组。", "solution_python": "def threeSum(nums):\n nums.sort()\n result = []\n for i in range(len(nums) - 2):\n if i > 0 and nums[i] == nums[i-1]: continue\n left, right = i + 1, len(nums) - 1\n while left < right:\n total = nums[i] + nums[left] + nums[right]\n if total < 0: left += 1\n elif total > 0: right -= 1\n else:\n result.append([nums[i], nums[left], nums[right]])\n while left < right and nums[left] == nums[left+1]: left += 1\n while left < right and nums[right] == nums[right-1]: right -= 1\n left += 1; right -= 1\n return result", "solution_java": "public List> threeSum(int[] nums) {\n Arrays.sort(nums);\n List> result = new ArrayList<>();\n for (int i = 0; i < nums.length - 2; i++) {\n if (i > 0 && nums[i] == nums[i-1]) continue;\n int left = i + 1, right = nums.length - 1;\n while (left < right) {\n int total = nums[i] + nums[left] + nums[right];\n if (total < 0) left++;\n else if (total > 0) right--;\n else {\n result.add(Arrays.asList(nums[i], nums[left], nums[right]));\n while (left < right && nums[left] == nums[left+1]) left++;\n while (left < right && nums[right] == nums[right-1]) right--;\n left++; right--;\n }\n }\n }\n return result;\n}", "solution_cpp": "vector> threeSum(vector& nums) {\n sort(nums.begin(), nums.end());\n vector> result;\n for (int i = 0; i < nums.size() - 2; i++) {\n if (i > 0 && nums[i] == nums[i-1]) continue;\n int left = i + 1, right = nums.size() - 1;\n while (left < right) {\n int total = nums[i] + nums[left] + nums[right];\n if (total < 0) left++;\n else if (total > 0) right--;\n else {\n result.push_back({nums[i], nums[left], nums[right]});\n while (left < right && nums[left] == nums[left+1]) left++;\n while (left < right && nums[right] == nums[right-1]) right--;\n left++; right--;\n }\n }\n }\n return result;\n}", "test_cases": ["nums=[-1,0,1,2,-1,-4] -> [[-1,-1,2],[-1,0,1]]"], "key_points": ["排序+双指针", "去重是关键"], "tags": ["two-pointers", "medium", "Google", "Amazon"]} {"problem_id": "algo_01737", "original_id": "container-water", "title": "盛最多水的容器", "category": "two-pointers", "difficulty": "medium", "companies": ["Google", "Uber"], "description": "给定一个长度为 n 的整数数组 height,找出其中的两条线,使得它们与 x 轴共同构成的容器可以容纳最多的水。", "solution_python": "def maxArea(height):\n left, right = 0, len(height) - 1\n max_area = 0\n while left < right:\n h = min(height[left], height[right])\n max_area = max(max_area, h * (right - left))\n if height[left] < height[right]: left += 1\n else: right -= 1\n return max_area", "solution_java": "public int maxArea(int[] height) {\n int left = 0, right = height.length - 1, maxArea = 0;\n while (left < right) {\n int h = Math.min(height[left], height[right]);\n maxArea = Math.max(maxArea, h * (right - left));\n if (height[left] < height[right]) left++;\n else right--;\n }\n return maxArea;\n}", "solution_cpp": "int maxArea(vector& height) {\n int left = 0, right = height.size() - 1, maxArea = 0;\n while (left < right) {\n int h = min(height[left], height[right]);\n maxArea = max(maxArea, h * (right - left));\n if (height[left] < height[right]) left++;\n else right--;\n }\n return maxArea;\n}", "test_cases": ["height=[1,8,6,2,5,4,8,3,7] -> 49"], "key_points": ["移动短边指针", "面积=min(h1,h2)*width"], "tags": ["two-pointers", "medium", "Google", "Uber"]} {"problem_id": "algo_01738", "original_id": "min-stack", "title": "最小栈", "category": "stack", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "设计一个支持 push,pop,top 操作,并能在常数时间内检索到最小元素的栈。", "solution_python": "class MinStack:\n def __init__(self):\n self.stack = []\n self.min_stack = []\n def push(self, val):\n self.stack.append(val)\n self.min_stack.append(min(val, self.min_stack[-1] if self.min_stack else val))\n def pop(self):\n self.stack.pop(); self.min_stack.pop()\n def top(self): return self.stack[-1]\n def getMin(self): return self.min_stack[-1]", "solution_java": "class MinStack {\n Stack stack = new Stack<>();\n Stack minStack = new Stack<>();\n public void push(int val) { stack.push(val); minStack.push(Math.min(val, minStack.isEmpty() ? val : minStack.peek())); }\n public void pop() { stack.pop(); minStack.pop(); }\n public int top() { return stack.peek(); }\n public int getMin() { return minStack.peek(); }\n}", "solution_cpp": "class MinStack {\n stack st, minSt;\npublic:\n void push(int val) { st.push(val); minSt.push(min(val, minSt.empty() ? val : minSt.top())); }\n void pop() { st.pop(); minSt.pop(); }\n int top() { return st.top(); }\n int getMin() { return minSt.top(); }\n};", "test_cases": ["push(-2), push(0), push(-3) -> getMin() returns -3"], "key_points": ["辅助栈记录最小值", "O(1)时间获取最小值"], "tags": ["stack", "medium", "Google", "Microsoft"]} {"problem_id": "algo_01739", "original_id": "lru-cache", "title": "LRU缓存", "category": "design", "difficulty": "hard", "companies": ["Google", "Amazon"], "description": "设计和实现一个 LRU(最近最少使用)缓存机制。", "solution_python": "class LRUCache:\n def __init__(self, capacity):\n self.capacity = capacity\n self.cache = {}\n self.order = []\n def get(self, key):\n if key not in self.cache: return -1\n self.order.remove(key); self.order.append(key)\n return self.cache[key]\n def put(self, key, value):\n if key in self.cache:\n self.order.remove(key)\n elif len(self.cache) >= self.capacity:\n del self.cache[self.order.pop(0)]\n self.cache[key] = value; self.order.append(key)", "solution_java": "class LRUCache {\n int capacity;\n LinkedHashMap cache = new LinkedHashMap<>();\n public LRUCache(int cap) { capacity = cap; }\n public int get(int key) { return cache.containsKey(key) ? cache.remove(key) : -1; }\n public void put(int key, int val) {\n if (cache.containsKey(key)) cache.remove(key);\n else if (cache.size() >= capacity) cache.remove(cache.keySet().iterator().next());\n cache.put(key, val);\n }\n}", "solution_cpp": "class LRUCache {\n int cap;\n list> dll;\n unordered_map>::iterator> cache;\npublic:\n LRUCache(int capacity) : cap(capacity) {}\n int get(int key) {\n auto it = cache.find(key);\n if (it == cache.end()) return -1;\n dll.splice(dll.end(), dll, it->second);\n return it->second->second;\n }\n void put(int key, int value) {\n auto it = cache.find(key);\n if (it != cache.end()) dll.erase(it->second);\n else if (cache.size() >= cap) { cache.erase(dll.front().first); dll.pop_front(); }\n dll.push_back({key, value});\n cache[key] = --dll.end();\n }\n};", "test_cases": ["put(1,1), put(2,2), get(1) -> 1"], "key_points": ["HashMap + 双向链表", "O(1)时间操作"], "tags": ["design", "hard", "Google", "Amazon"]} {"problem_id": "algo_01740", "original_id": "num-islands", "title": "岛屿数量", "category": "graph", "difficulty": "medium", "companies": ["Google", "Facebook"], "description": "给你一个由 '1'(陆地)和 '0'(水)组成的二维网格,请你计算网格中岛屿的数量。岛屿总是被水包围,且只能由水平或垂直方向相邻的陆地连接形成。", "solution_python": "def numIslands(grid):\n if not grid: return 0\n rows, cols = len(grid), len(grid[0])\n count = 0\n def dfs(r, c):\n if r < 0 or r >= rows or c < 0 or c >= cols or grid[r][c] != '1': return\n grid[r][c] = '0'\n dfs(r+1, c); dfs(r-1, c); dfs(r, c+1); dfs(r, c-1)\n for r in range(rows):\n for c in range(cols):\n if grid[r][c] == '1': count += 1; dfs(r, c)\n return count", "solution_java": "public int numIslands(char[][] grid) {\n if (grid.length == 0) return 0;\n int count = 0;\n for (int i = 0; i < grid.length; i++)\n for (int j = 0; j < grid[0].length; j++)\n if (grid[i][j] == '1') { count++; dfs(grid, i, j); }\n return count;\n}\nprivate void dfs(char[][] grid, int r, int c) {\n if (r < 0 || r >= grid.length || c < 0 || c >= grid[0].length || grid[r][c] != '1') return;\n grid[r][c] = '0';\n dfs(grid, r+1, c); dfs(grid, r-1, c); dfs(grid, r, c+1); dfs(grid, r, c-1);\n}", "solution_cpp": "int numIslands(vector>& grid) {\n if (grid.empty()) return 0;\n int count = 0;\n for (int i = 0; i < grid.size(); i++)\n for (int j = 0; j < grid[0].size(); j++)\n if (grid[i][j] == '1') { count++; dfs(grid, i, j); }\n return count;\n}\nvoid dfs(vector>& grid, int r, int c) {\n if (r < 0 || r >= grid.size() || c < 0 || c >= grid[0].size() || grid[r][c] != '1') return;\n grid[r][c] = '0';\n dfs(grid, r+1, c); dfs(grid, r-1, c); dfs(grid, r, c+1); dfs(grid, r, c-1);\n}", "test_cases": ["grid=[[1,1,1,1,0],[1,1,0,1,0],[1,1,0,0,0],[0,0,0,0,0]] -> 1"], "key_points": ["DFS/BFS遍历", "访问后标记为0避免重复"], "tags": ["graph", "medium", "Google", "Facebook"]} {"problem_id": "algo_01741", "original_id": "two-sum", "title": "两数之和", "category": "array", "difficulty": "easy", "companies": ["Amazon", "Google"], "description": "给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那两个整数,并返回他们的数组下标。", "solution_python": "def twoSum(nums, target):\n hashmap = {}\n for i, num in enumerate(nums):\n complement = target - num\n if complement in hashmap:\n return [hashmap[complement], i]\n hashmap[num] = i\n return []", "solution_java": "public int[] twoSum(int[] nums, int target) {\n Map map = new HashMap<>();\n for (int i = 0; i < nums.length; i++) {\n int complement = target - nums[i];\n if (map.containsKey(complement)) return new int[]{map.get(complement), i};\n map.put(nums[i], i);\n }\n return new int[]{};\n}", "solution_cpp": "vector twoSum(vector& nums, int target) {\n unordered_map m;\n for (int i = 0; i < nums.size(); i++) {\n if (m.count(target - nums[i])) return {m[target - nums[i]], i};\n m[nums[i]] = i;\n }\n return {};\n}", "test_cases": ["nums=[2,7,11,15], target=9 -> [0,1]", "nums=[3,2,4], target=6 -> [1,2]"], "key_points": ["哈希表一次遍历", "空间换时间"], "tags": ["array", "easy", "Amazon", "Google"]} {"problem_id": "algo_01742", "original_id": "merge-sorted", "title": "合并两个有序数组", "category": "array", "difficulty": "easy", "companies": ["Microsoft", "Uber"], "description": "给你两个按非递减顺序排列的整数数组 nums1 和 nums2,另有两个整数 m 和 n,分别表示 nums1 和 nums2 中的元素数目。请你合并 nums2 到 nums1 中。", "solution_python": "def merge(nums1, m, nums2, n):\n p1, p2, p = m-1, n-1, m+n-1\n while p1 >= 0 and p2 >= 0:\n if nums1[p1] > nums2[p2]: nums1[p] = nums1[p1]; p1 -= 1\n else: nums1[p] = nums2[p2]; p2 -= 1\n p -= 1\n while p2 >= 0: nums1[p] = nums2[p2]; p2 -= 1; p -= 1", "solution_java": "public void merge(int[] nums1, int m, int[] nums2, int n) {\n int p1 = m-1, p2 = n-1, p = m+n-1;\n while (p1 >= 0 && p2 >= 0) {\n nums1[p--] = nums1[p1] > nums2[p2] ? nums1[p1--] : nums2[p2--];\n }\n while (p2 >= 0) nums1[p--] = nums2[p2--];\n}", "solution_cpp": "void merge(vector& nums1, int m, vector& nums2, int n) {\n int p1 = m-1, p2 = n-1, p = m+n-1;\n while (p1 >= 0 && p2 >= 0) nums1[p--] = nums1[p1] > nums2[p2] ? nums1[p1--] : nums2[p2--];\n while (p2 >= 0) nums1[p--] = nums2[p2--];\n}", "test_cases": ["nums1=[1,2,3], m=3, nums2=[2,5,6], n=3 -> [1,2,2,3,5,6]", "nums1=[], m=0, nums2=[1], n=1 -> [1]"], "key_points": ["从后往前合并", "三指针技巧"], "tags": ["array", "easy", "Microsoft", "Uber"]} {"problem_id": "algo_01743", "original_id": "max-subarray", "title": "最大子数组和", "category": "array", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "给你一个整数数组 nums ,请你找出一个具有最大和的连续子数组,返回其最大和。", "solution_python": "def maxSubArray(nums):\n max_sum = current = nums[0]\n for num in nums[1:]:\n current = max(num, current + num)\n max_sum = max(max_sum, current)\n return max_sum", "solution_java": "public int maxSubArray(int[] nums) {\n int maxSum = nums[0], curr = nums[0];\n for (int i = 1; i < nums.length; i++) {\n curr = Math.max(nums[i], curr + nums[i]);\n maxSum = Math.max(maxSum, curr);\n }\n return maxSum;\n}", "solution_cpp": "int maxSubArray(vector& nums) {\n int maxSum = nums[0], curr = nums[0];\n for (int i = 1; i < nums.size(); i++) {\n curr = max(nums[i], curr + nums[i]);\n maxSum = max(maxSum, curr);\n }\n return maxSum;\n}", "test_cases": ["nums=[-2,1,-3,4,-1,2,1,-5,4] -> 6", "nums=[1] -> 1"], "key_points": ["Kadane算法", "动态规划基础题"], "tags": ["array", "medium", "Google", "Microsoft"]} {"problem_id": "algo_01744", "original_id": "valid-parentheses", "title": "有效的括号", "category": "string", "difficulty": "easy", "companies": ["Google", "Uber"], "description": "给定一个只包括 '(',')','{','}','[',']' 的字符串 s,判断字符串是否有效。", "solution_python": "def isValid(s):\n stack = []\n mapping = {')': '(', ']': '[', '}': '{'}\n for c in s:\n if c in mapping:\n if not stack or stack[-1] != mapping[c]: return False\n stack.pop()\n else: stack.append(c)\n return not stack", "solution_java": "public boolean isValid(String s) {\n Stack stack = new Stack<>();\n Map map = Map.of(')', '(', ']', '[', '}', '{');\n for (char c : s.toCharArray()) {\n if (map.containsValue(c)) stack.push(c);\n else if (!stack.isEmpty() && stack.pop() != map.get(c)) return false;\n }\n return stack.isEmpty();\n}", "solution_cpp": "bool isValid(string s) {\n stack st;\n unordered_map m = {{')','('},{']','['},{'}','{'}};\n for (char c : s) {\n if (m.find(c) == m.end()) st.push(c);\n else if (st.empty() || st.top() != m[c]) return false;\n else st.pop();\n }\n return st.empty();\n}", "test_cases": ["s=\"()\" -> true", "s=\"()[]{}\" -> true", "s=\"(]\" -> false"], "key_points": ["栈匹配法", "注意空栈边界"], "tags": ["string", "easy", "Google", "Uber"]} {"problem_id": "algo_01745", "original_id": "longest-palindrome", "title": "最长回文子串", "category": "string", "difficulty": "medium", "companies": ["Google", "Amazon"], "description": "给你一个字符串 s,找到 s 中最长的回文子串。", "solution_python": "def longestPalindrome(s):\n def expand(l, r):\n while l >= 0 and r < len(s) and s[l] == s[r]: l -= 1; r += 1\n return l + 1, r - 1\n start = end = 0\n for i in range(len(s)):\n l1, r1 = expand(i, i)\n l2, r2 = expand(i, i + 1)\n if r1 - l1 > end - start: start, end = l1, r1\n if r2 - l2 > end - start: start, end = l2, r2\n return s[start:end+1]", "solution_java": "public String longestPalindrome(String s) {\n int start = 0, end = 0;\n for (int i = 0; i < s.length(); i++) {\n int len1 = expand(s, i, i), len2 = expand(s, i, i+1);\n int len = Math.max(len1, len2);\n if (len > end - start) { start = i - (len-1)/2; end = i + len/2; }\n }\n return s.substring(start, end + 1);\n}\nprivate int expand(String s, int l, int r) {\n while (l >= 0 && r < s.length() && s.charAt(l) == s.charAt(r)) { l--; r++; }\n return r - l - 1;\n}", "solution_cpp": "string longestPalindrome(string s) {\n int start = 0, end = 0;\n for (int i = 0; i < s.size(); i++) {\n int len1 = expand(s, i, i), len2 = expand(s, i, i+1);\n if (max(len1, len2) > end - start) { start = i - (max(len1,len2)-1)/2; end = i + max(len1,len2)/2; }\n }\n return s.substr(start, end - start + 1);\n}", "test_cases": ["s=\"babad\" -> bab或aba", "s=\"cbbd\" -> bb"], "key_points": ["中心扩展法", "处理奇偶长度"], "tags": ["string", "medium", "Google", "Amazon"]} {"problem_id": "algo_01746", "original_id": "reverse-list", "title": "反转链表", "category": "linkedlist", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "给你单链表的头节点 head,请你反转链表,并返回反转后的链表。", "solution_python": "def reverseList(head):\n prev = None\n curr = head\n while curr:\n nxt = curr.next\n curr.next = prev\n prev = curr\n curr = nxt\n return prev", "solution_java": "public ListNode reverseList(ListNode head) {\n ListNode prev = null, curr = head;\n while (curr != null) {\n ListNode next = curr.next;\n curr.next = prev;\n prev = curr;\n curr = next;\n }\n return prev;\n}", "solution_cpp": "ListNode* reverseList(ListNode* head) {\n ListNode* prev = nullptr, *curr = head;\n while (curr) {\n ListNode* next = curr->next;\n curr->next = prev;\n prev = curr;\n curr = next;\n }\n return prev;\n}", "test_cases": ["head=[1,2,3,4,5] -> [5,4,3,2,1]", "head=[1,2] -> [2,1]"], "key_points": ["迭代法 O(1)空间", "递归法 O(n)空间"], "tags": ["linkedlist", "medium", "Google", "Microsoft"]} {"problem_id": "algo_01747", "original_id": "middle-node", "title": "链表的中间结点", "category": "linkedlist", "difficulty": "easy", "companies": ["Amazon", "Facebook"], "description": "给你单链表的头节点 head,请你找出并返回链表的中间结点。如果有两个中间结点,则返回第二个中间结点。", "solution_python": "def middleNode(head):\n slow = fast = head\n while fast and fast.next:\n slow = slow.next\n fast = fast.next.next\n return slow", "solution_java": "public ListNode middleNode(ListNode head) {\n ListNode slow = head, fast = head;\n while (fast != null && fast.next != null) {\n slow = slow.next;\n fast = fast.next.next;\n }\n return slow;\n}", "solution_cpp": "ListNode* middleNode(ListNode* head) {\n ListNode* slow = head, *fast = head;\n while (fast && fast->next) { slow = slow->next; fast = fast->next->next; }\n return slow;\n}", "test_cases": ["head=[1,2,3,4,5] -> 3", "head=[1,2,3,4,5,6] -> 4"], "key_points": ["快慢指针", "O(n)时间O(1)空间"], "tags": ["linkedlist", "easy", "Amazon", "Facebook"]} {"problem_id": "algo_01748", "original_id": "max-depth", "title": "二叉树的最大深度", "category": "tree", "difficulty": "easy", "companies": ["Microsoft", "Apple"], "description": "给定一个二叉树 root,返回其最大深度。", "solution_python": "def maxDepth(root):\n if not root: return 0\n return max(maxDepth(root.left), maxDepth(root.right)) + 1", "solution_java": "public int maxDepth(TreeNode root) {\n if (root == null) return 0;\n return Math.max(maxDepth(root.left), maxDepth(root.right)) + 1;\n}", "solution_cpp": "int maxDepth(TreeNode* root) {\n if (!root) return 0;\n return max(maxDepth(root->left), maxDepth(root->right)) + 1;\n}", "test_cases": ["root=[3,9,20,null,null,15,7] -> 3", "root=[1,null,2] -> 2"], "key_points": ["DFS递归", "层序遍历也可"], "tags": ["tree", "easy", "Microsoft", "Apple"]} {"problem_id": "algo_01749", "original_id": "inorder-traversal", "title": "二叉树的中序遍历", "category": "tree", "difficulty": "easy", "companies": ["Google", "Microsoft"], "description": "给定一个二叉树的根节点 root,返回它的中序遍历结果。", "solution_python": "def inorderTraversal(root):\n result = []\n def dfs(node):\n if node:\n dfs(node.left)\n result.append(node.val)\n dfs(node.right)\n dfs(root)\n return result", "solution_java": "public List inorderTraversal(TreeNode root) {\n List res = new ArrayList<>();\n dfs(root, res);\n return res;\n}\nprivate void dfs(TreeNode node, List res) {\n if (node == null) return;\n dfs(node.left, res); res.add(node.val); dfs(node.right, res);\n}", "solution_cpp": "vector inorderTraversal(TreeNode* root) {\n vector res;\n dfs(root, res);\n return res;\n}\nvoid dfs(TreeNode* node, vector& res) {\n if (!node) return;\n dfs(node->left, res); res.push_back(node->val); dfs(node->right, res);\n}", "test_cases": ["root=[1,null,2,3] -> [1,3,2]", "root=[] -> []"], "key_points": ["左-根-右顺序", "递归最简洁"], "tags": ["tree", "easy", "Google", "Microsoft"]} {"problem_id": "algo_01750", "original_id": "binary-search", "title": "二分查找", "category": "binarysearch", "difficulty": "easy", "companies": ["Google", "Amazon"], "description": "给定一个 n 个元素有序的(升序)整型数组 nums 和一个目标值 target,写一个函数搜索 nums 中的 target,如果目标值存在返回下标,否则返回 -1。", "solution_python": "def search(nums, target):\n left, right = 0, len(nums) - 1\n while left <= right:\n mid = (left + right) // 2\n if nums[mid] == target: return mid\n elif nums[mid] < target: left = mid + 1\n else: right = mid - 1\n return -1", "solution_java": "public int search(int[] nums, int target) {\n int left = 0, right = nums.length - 1;\n while (left <= right) {\n int mid = left + (right - left) / 2;\n if (nums[mid] == target) return mid;\n else if (nums[mid] < target) left = mid + 1;\n else right = mid - 1;\n }\n return -1;\n}", "solution_cpp": "int search(vector& nums, int target) {\n int left = 0, right = nums.size() - 1;\n while (left <= right) {\n int mid = left + (right - left) / 2;\n if (nums[mid] == target) return mid;\n else if (nums[mid] < target) left = mid + 1;\n else right = mid - 1;\n }\n return -1;\n}", "test_cases": ["nums=[-1,0,3,5,9,12], target=9 -> 4", "nums=[-1,0,3,5,9,12], target=2 -> -1"], "key_points": ["标准模板", "注意防溢出写法"], "tags": ["binarysearch", "easy", "Google", "Amazon"]} {"problem_id": "algo_01751", "original_id": "climbing-stairs", "title": "爬楼梯", "category": "dp", "difficulty": "easy", "companies": ["Amazon", "Google"], "description": "假设你正在爬楼梯。需要 n 阶你才能到达楼顶。每次你可以爬 1 或 2 个台阶。你有多少种不同的方法可以爬到楼顶?", "solution_python": "def climbStairs(n):\n if n <= 2: return n\n a, b = 1, 2\n for _ in range(3, n+1):\n a, b = b, a + b\n return b", "solution_java": "public int climbStairs(int n) {\n if (n <= 2) return n;\n int a = 1, b = 2;\n for (int i = 3; i <= n; i++) { int temp = a + b; a = b; b = temp; }\n return b;\n}", "solution_cpp": "int climbStairs(int n) {\n if (n <= 2) return n;\n int a = 1, b = 2;\n for (int i = 3; i <= n; i++) { int temp = a + b; a = b; b = temp; }\n return b;\n}", "test_cases": ["n=2 -> 2", "n=3 -> 3", "n=5 -> 8"], "key_points": ["斐波那契数列", "滚动数组优化空间"], "tags": ["dp", "easy", "Amazon", "Google"]} {"problem_id": "algo_01752", "original_id": "coin-change", "title": "零钱兑换", "category": "dp", "difficulty": "medium", "companies": ["Google", "Amazon"], "description": "给你一个整数数组 coins 表示不同面额的硬币,以及一个整数 amount 表示总金额。计算并返回可以凑成总金额所需的最少的硬币个数。如果没有任何一种硬币组合能组成总金额,返回 -1。", "solution_python": "def coinChange(coins, amount):\n dp = [float('inf')] * (amount + 1)\n dp[0] = 0\n for coin in coins:\n for x in range(coin, amount + 1):\n dp[x] = min(dp[x], dp[x - coin] + 1)\n return dp[amount] if dp[amount] != float('inf') else -1", "solution_java": "public int coinChange(int[] coins, int amount) {\n int[] dp = new int[amount + 1];\n Arrays.fill(dp, amount + 1);\n dp[0] = 0;\n for (int coin : coins) {\n for (int x = coin; x <= amount; x++) {\n dp[x] = Math.min(dp[x], dp[x - coin] + 1);\n }\n }\n return dp[amount] > amount ? -1 : dp[amount];\n}", "solution_cpp": "int coinChange(vector& coins, int amount) {\n vector dp(amount + 1, amount + 1);\n dp[0] = 0;\n for (int coin : coins) {\n for (int x = coin; x <= amount; x++) {\n dp[x] = min(dp[x], dp[x - coin] + 1);\n }\n }\n return dp[amount] > amount ? -1 : dp[amount];\n}", "test_cases": ["coins=[1,2,5], amount=11 -> 3", "coins=[2], amount=3 -> -1"], "key_points": ["完全背包问题", "dp[x] = min(dp[x-coin]+1)"], "tags": ["dp", "medium", "Google", "Amazon"]} {"problem_id": "algo_01753", "original_id": "subsets", "title": "子集", "category": "backtracking", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "给你一个整数数组 nums ,数组中的元素 互不相同 。返回该数组所有可能的子集(幂集)。", "solution_python": "def subsets(nums):\n result = []\n def backtrack(start, path):\n result.append(path[:])\n for i in range(start, len(nums)):\n path.append(nums[i])\n backtrack(i + 1, path)\n path.pop()\n backtrack(0, [])\n return result", "solution_java": "public List> subsets(int[] nums) {\n List> result = new ArrayList<>();\n backtrack(nums, 0, new ArrayList<>(), result);\n return result;\n}\nprivate void backtrack(int[] nums, int start, List path, List> result) {\n result.add(new ArrayList<>(path));\n for (int i = start; i < nums.length; i++) {\n path.add(nums[i]);\n backtrack(nums, i + 1, path, result);\n path.remove(path.size() - 1);\n }\n}", "solution_cpp": "vector> subsets(vector& nums) {\n vector> result;\n vector path;\n backtrack(nums, 0, path, result);\n return result;\n}\nvoid backtrack(vector& nums, int start, vector& path, vector>& result) {\n result.push_back(path);\n for (int i = start; i < nums.size(); i++) {\n path.push_back(nums[i]);\n backtrack(nums, i + 1, path, result);\n path.pop_back();\n }\n}", "test_cases": ["nums=[1,2,3] -> [[],[1],[2],[1,2],[3],[1,3],[2,3],[1,2,3]]"], "key_points": ["选或不选", "DFS遍历子集树"], "tags": ["backtracking", "medium", "Google", "Microsoft"]} {"problem_id": "algo_01754", "original_id": "permutations", "title": "全排列", "category": "backtracking", "difficulty": "medium", "companies": ["Google", "Facebook"], "description": "给定一个不含重复数字的数组 nums,返回其所有可能的全排列。", "solution_python": "def permute(nums):\n result = []\n def backtrack(path, used):\n if len(path) == len(nums):\n result.append(path[:])\n return\n for i in range(len(nums)):\n if used[i]: continue\n used[i] = True\n path.append(nums[i])\n backtrack(path, used)\n path.pop()\n used[i] = False\n backtrack([], [False]*len(nums))\n return result", "solution_java": "public List> permute(int[] nums) {\n List> result = new ArrayList<>();\n boolean[] used = new boolean[nums.length];\n backtrack(nums, used, new ArrayList<>(), result);\n return result;\n}\nprivate void backtrack(int[] nums, boolean[] used, List path, List> result) {\n if (path.size() == nums.length) { result.add(new ArrayList<>(path)); return; }\n for (int i = 0; i < nums.length; i++) {\n if (used[i]) continue;\n used[i] = true;\n path.add(nums[i]);\n backtrack(nums, used, path, result);\n path.remove(path.size() - 1);\n used[i] = false;\n }\n}", "solution_cpp": "vector> permute(vector& nums) {\n vector> result;\n vector used(nums.size(), false);\n vector path;\n backtrack(nums, used, path, result);\n return result;\n}\nvoid backtrack(vector& nums, vector& used, vector& path, vector>& result) {\n if (path.size() == nums.size()) { result.push_back(path); return; }\n for (int i = 0; i < nums.size(); i++) {\n if (used[i]) continue;\n used[i] = true;\n path.push_back(nums[i]);\n backtrack(nums, used, path, result);\n path.pop_back();\n used[i] = false;\n }\n}", "test_cases": ["nums=[1,2,3] -> [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]"], "key_points": ["标记已使用元素", "回溯经典模板"], "tags": ["backtracking", "medium", "Google", "Facebook"]} {"problem_id": "algo_01755", "original_id": "top-k-frequent", "title": "前K个高频元素", "category": "heap", "difficulty": "medium", "companies": ["Amazon", "Facebook"], "description": "给你一个整数数组 nums 和一个整数 k,请你返回其中出现频率前 k 高的元素。", "solution_python": "import heapq\nfrom collections import Counter\ndef topKFrequent(nums, k):\n count = Counter(nums)\n heap = []\n for num, freq in count.items():\n heapq.heappush(heap, (freq, num))\n if len(heap) > k: heapq.heappop(heap)\n return [num for freq, num in heap]", "solution_java": "public int[] topKFrequent(int[] nums, int k) {\n Map count = new HashMap<>();\n for (int n : nums) count.put(n, count.getOrDefault(n, 0) + 1);\n PriorityQueue> heap = \n new PriorityQueue<>((a, b) -> a.getValue() - b.getValue());\n for (Map.Entry e : count.entrySet()) {\n heap.offer(e);\n if (heap.size() > k) heap.poll();\n }\n int[] res = new int[k];\n for (int i = k - 1; i >= 0; i--) res[i] = heap.poll().getKey();\n return res;\n}", "solution_cpp": "vector topKFrequent(vector& nums, int k) {\n unordered_map count;\n for (int n : nums) count[n]++;\n priority_queue, vector>, greater>> heap;\n for (auto& [num, freq] : count) {\n heap.push({freq, num});\n if (heap.size() > k) heap.pop();\n }\n vector res;\n while (!heap.empty()) { res.push_back(heap.top().second); heap.pop(); }\n reverse(res.begin(), res.end());\n return res;\n}", "test_cases": ["nums=[1,1,1,2,2,3], k=2 -> [1,2]", "nums=[1], k=1 -> [1]"], "key_points": ["小顶堆保持大小k", "时间复杂度O(nlogk)"], "tags": ["heap", "medium", "Amazon", "Facebook"]} {"problem_id": "algo_01756", "original_id": "3sum", "title": "三数之和", "category": "two-pointers", "difficulty": "medium", "companies": ["Google", "Amazon"], "description": "给你一个整数数组 nums,判断是否存在三元组满足和为0,返回所有不重复的三元组。", "solution_python": "def threeSum(nums):\n nums.sort()\n result = []\n for i in range(len(nums) - 2):\n if i > 0 and nums[i] == nums[i-1]: continue\n left, right = i + 1, len(nums) - 1\n while left < right:\n total = nums[i] + nums[left] + nums[right]\n if total < 0: left += 1\n elif total > 0: right -= 1\n else:\n result.append([nums[i], nums[left], nums[right]])\n while left < right and nums[left] == nums[left+1]: left += 1\n while left < right and nums[right] == nums[right-1]: right -= 1\n left += 1; right -= 1\n return result", "solution_java": "public List> threeSum(int[] nums) {\n Arrays.sort(nums);\n List> result = new ArrayList<>();\n for (int i = 0; i < nums.length - 2; i++) {\n if (i > 0 && nums[i] == nums[i-1]) continue;\n int left = i + 1, right = nums.length - 1;\n while (left < right) {\n int total = nums[i] + nums[left] + nums[right];\n if (total < 0) left++;\n else if (total > 0) right--;\n else {\n result.add(Arrays.asList(nums[i], nums[left], nums[right]));\n while (left < right && nums[left] == nums[left+1]) left++;\n while (left < right && nums[right] == nums[right-1]) right--;\n left++; right--;\n }\n }\n }\n return result;\n}", "solution_cpp": "vector> threeSum(vector& nums) {\n sort(nums.begin(), nums.end());\n vector> result;\n for (int i = 0; i < nums.size() - 2; i++) {\n if (i > 0 && nums[i] == nums[i-1]) continue;\n int left = i + 1, right = nums.size() - 1;\n while (left < right) {\n int total = nums[i] + nums[left] + nums[right];\n if (total < 0) left++;\n else if (total > 0) right--;\n else {\n result.push_back({nums[i], nums[left], nums[right]});\n while (left < right && nums[left] == nums[left+1]) left++;\n while (left < right && nums[right] == nums[right-1]) right--;\n left++; right--;\n }\n }\n }\n return result;\n}", "test_cases": ["nums=[-1,0,1,2,-1,-4] -> [[-1,-1,2],[-1,0,1]]"], "key_points": ["排序+双指针", "去重是关键"], "tags": ["two-pointers", "medium", "Google", "Amazon"]} {"problem_id": "algo_01757", "original_id": "container-water", "title": "盛最多水的容器", "category": "two-pointers", "difficulty": "medium", "companies": ["Google", "Uber"], "description": "给定一个长度为 n 的整数数组 height,找出其中的两条线,使得它们与 x 轴共同构成的容器可以容纳最多的水。", "solution_python": "def maxArea(height):\n left, right = 0, len(height) - 1\n max_area = 0\n while left < right:\n h = min(height[left], height[right])\n max_area = max(max_area, h * (right - left))\n if height[left] < height[right]: left += 1\n else: right -= 1\n return max_area", "solution_java": "public int maxArea(int[] height) {\n int left = 0, right = height.length - 1, maxArea = 0;\n while (left < right) {\n int h = Math.min(height[left], height[right]);\n maxArea = Math.max(maxArea, h * (right - left));\n if (height[left] < height[right]) left++;\n else right--;\n }\n return maxArea;\n}", "solution_cpp": "int maxArea(vector& height) {\n int left = 0, right = height.size() - 1, maxArea = 0;\n while (left < right) {\n int h = min(height[left], height[right]);\n maxArea = max(maxArea, h * (right - left));\n if (height[left] < height[right]) left++;\n else right--;\n }\n return maxArea;\n}", "test_cases": ["height=[1,8,6,2,5,4,8,3,7] -> 49"], "key_points": ["移动短边指针", "面积=min(h1,h2)*width"], "tags": ["two-pointers", "medium", "Google", "Uber"]} {"problem_id": "algo_01758", "original_id": "min-stack", "title": "最小栈", "category": "stack", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "设计一个支持 push,pop,top 操作,并能在常数时间内检索到最小元素的栈。", "solution_python": "class MinStack:\n def __init__(self):\n self.stack = []\n self.min_stack = []\n def push(self, val):\n self.stack.append(val)\n self.min_stack.append(min(val, self.min_stack[-1] if self.min_stack else val))\n def pop(self):\n self.stack.pop(); self.min_stack.pop()\n def top(self): return self.stack[-1]\n def getMin(self): return self.min_stack[-1]", "solution_java": "class MinStack {\n Stack stack = new Stack<>();\n Stack minStack = new Stack<>();\n public void push(int val) { stack.push(val); minStack.push(Math.min(val, minStack.isEmpty() ? val : minStack.peek())); }\n public void pop() { stack.pop(); minStack.pop(); }\n public int top() { return stack.peek(); }\n public int getMin() { return minStack.peek(); }\n}", "solution_cpp": "class MinStack {\n stack st, minSt;\npublic:\n void push(int val) { st.push(val); minSt.push(min(val, minSt.empty() ? val : minSt.top())); }\n void pop() { st.pop(); minSt.pop(); }\n int top() { return st.top(); }\n int getMin() { return minSt.top(); }\n};", "test_cases": ["push(-2), push(0), push(-3) -> getMin() returns -3"], "key_points": ["辅助栈记录最小值", "O(1)时间获取最小值"], "tags": ["stack", "medium", "Google", "Microsoft"]} {"problem_id": "algo_01759", "original_id": "lru-cache", "title": "LRU缓存", "category": "design", "difficulty": "hard", "companies": ["Google", "Amazon"], "description": "设计和实现一个 LRU(最近最少使用)缓存机制。", "solution_python": "class LRUCache:\n def __init__(self, capacity):\n self.capacity = capacity\n self.cache = {}\n self.order = []\n def get(self, key):\n if key not in self.cache: return -1\n self.order.remove(key); self.order.append(key)\n return self.cache[key]\n def put(self, key, value):\n if key in self.cache:\n self.order.remove(key)\n elif len(self.cache) >= self.capacity:\n del self.cache[self.order.pop(0)]\n self.cache[key] = value; self.order.append(key)", "solution_java": "class LRUCache {\n int capacity;\n LinkedHashMap cache = new LinkedHashMap<>();\n public LRUCache(int cap) { capacity = cap; }\n public int get(int key) { return cache.containsKey(key) ? cache.remove(key) : -1; }\n public void put(int key, int val) {\n if (cache.containsKey(key)) cache.remove(key);\n else if (cache.size() >= capacity) cache.remove(cache.keySet().iterator().next());\n cache.put(key, val);\n }\n}", "solution_cpp": "class LRUCache {\n int cap;\n list> dll;\n unordered_map>::iterator> cache;\npublic:\n LRUCache(int capacity) : cap(capacity) {}\n int get(int key) {\n auto it = cache.find(key);\n if (it == cache.end()) return -1;\n dll.splice(dll.end(), dll, it->second);\n return it->second->second;\n }\n void put(int key, int value) {\n auto it = cache.find(key);\n if (it != cache.end()) dll.erase(it->second);\n else if (cache.size() >= cap) { cache.erase(dll.front().first); dll.pop_front(); }\n dll.push_back({key, value});\n cache[key] = --dll.end();\n }\n};", "test_cases": ["put(1,1), put(2,2), get(1) -> 1"], "key_points": ["HashMap + 双向链表", "O(1)时间操作"], "tags": ["design", "hard", "Google", "Amazon"]} {"problem_id": "algo_01760", "original_id": "num-islands", "title": "岛屿数量", "category": "graph", "difficulty": "medium", "companies": ["Google", "Facebook"], "description": "给你一个由 '1'(陆地)和 '0'(水)组成的二维网格,请你计算网格中岛屿的数量。岛屿总是被水包围,且只能由水平或垂直方向相邻的陆地连接形成。", "solution_python": "def numIslands(grid):\n if not grid: return 0\n rows, cols = len(grid), len(grid[0])\n count = 0\n def dfs(r, c):\n if r < 0 or r >= rows or c < 0 or c >= cols or grid[r][c] != '1': return\n grid[r][c] = '0'\n dfs(r+1, c); dfs(r-1, c); dfs(r, c+1); dfs(r, c-1)\n for r in range(rows):\n for c in range(cols):\n if grid[r][c] == '1': count += 1; dfs(r, c)\n return count", "solution_java": "public int numIslands(char[][] grid) {\n if (grid.length == 0) return 0;\n int count = 0;\n for (int i = 0; i < grid.length; i++)\n for (int j = 0; j < grid[0].length; j++)\n if (grid[i][j] == '1') { count++; dfs(grid, i, j); }\n return count;\n}\nprivate void dfs(char[][] grid, int r, int c) {\n if (r < 0 || r >= grid.length || c < 0 || c >= grid[0].length || grid[r][c] != '1') return;\n grid[r][c] = '0';\n dfs(grid, r+1, c); dfs(grid, r-1, c); dfs(grid, r, c+1); dfs(grid, r, c-1);\n}", "solution_cpp": "int numIslands(vector>& grid) {\n if (grid.empty()) return 0;\n int count = 0;\n for (int i = 0; i < grid.size(); i++)\n for (int j = 0; j < grid[0].size(); j++)\n if (grid[i][j] == '1') { count++; dfs(grid, i, j); }\n return count;\n}\nvoid dfs(vector>& grid, int r, int c) {\n if (r < 0 || r >= grid.size() || c < 0 || c >= grid[0].size() || grid[r][c] != '1') return;\n grid[r][c] = '0';\n dfs(grid, r+1, c); dfs(grid, r-1, c); dfs(grid, r, c+1); dfs(grid, r, c-1);\n}", "test_cases": ["grid=[[1,1,1,1,0],[1,1,0,1,0],[1,1,0,0,0],[0,0,0,0,0]] -> 1"], "key_points": ["DFS/BFS遍历", "访问后标记为0避免重复"], "tags": ["graph", "medium", "Google", "Facebook"]} {"problem_id": "algo_01761", "original_id": "two-sum", "title": "两数之和", "category": "array", "difficulty": "easy", "companies": ["Amazon", "Google"], "description": "给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那两个整数,并返回他们的数组下标。", "solution_python": "def twoSum(nums, target):\n hashmap = {}\n for i, num in enumerate(nums):\n complement = target - num\n if complement in hashmap:\n return [hashmap[complement], i]\n hashmap[num] = i\n return []", "solution_java": "public int[] twoSum(int[] nums, int target) {\n Map map = new HashMap<>();\n for (int i = 0; i < nums.length; i++) {\n int complement = target - nums[i];\n if (map.containsKey(complement)) return new int[]{map.get(complement), i};\n map.put(nums[i], i);\n }\n return new int[]{};\n}", "solution_cpp": "vector twoSum(vector& nums, int target) {\n unordered_map m;\n for (int i = 0; i < nums.size(); i++) {\n if (m.count(target - nums[i])) return {m[target - nums[i]], i};\n m[nums[i]] = i;\n }\n return {};\n}", "test_cases": ["nums=[2,7,11,15], target=9 -> [0,1]", "nums=[3,2,4], target=6 -> [1,2]"], "key_points": ["哈希表一次遍历", "空间换时间"], "tags": ["array", "easy", "Amazon", "Google"]} {"problem_id": "algo_01762", "original_id": "merge-sorted", "title": "合并两个有序数组", "category": "array", "difficulty": "easy", "companies": ["Microsoft", "Uber"], "description": "给你两个按非递减顺序排列的整数数组 nums1 和 nums2,另有两个整数 m 和 n,分别表示 nums1 和 nums2 中的元素数目。请你合并 nums2 到 nums1 中。", "solution_python": "def merge(nums1, m, nums2, n):\n p1, p2, p = m-1, n-1, m+n-1\n while p1 >= 0 and p2 >= 0:\n if nums1[p1] > nums2[p2]: nums1[p] = nums1[p1]; p1 -= 1\n else: nums1[p] = nums2[p2]; p2 -= 1\n p -= 1\n while p2 >= 0: nums1[p] = nums2[p2]; p2 -= 1; p -= 1", "solution_java": "public void merge(int[] nums1, int m, int[] nums2, int n) {\n int p1 = m-1, p2 = n-1, p = m+n-1;\n while (p1 >= 0 && p2 >= 0) {\n nums1[p--] = nums1[p1] > nums2[p2] ? nums1[p1--] : nums2[p2--];\n }\n while (p2 >= 0) nums1[p--] = nums2[p2--];\n}", "solution_cpp": "void merge(vector& nums1, int m, vector& nums2, int n) {\n int p1 = m-1, p2 = n-1, p = m+n-1;\n while (p1 >= 0 && p2 >= 0) nums1[p--] = nums1[p1] > nums2[p2] ? nums1[p1--] : nums2[p2--];\n while (p2 >= 0) nums1[p--] = nums2[p2--];\n}", "test_cases": ["nums1=[1,2,3], m=3, nums2=[2,5,6], n=3 -> [1,2,2,3,5,6]", "nums1=[], m=0, nums2=[1], n=1 -> [1]"], "key_points": ["从后往前合并", "三指针技巧"], "tags": ["array", "easy", "Microsoft", "Uber"]} {"problem_id": "algo_01763", "original_id": "max-subarray", "title": "最大子数组和", "category": "array", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "给你一个整数数组 nums ,请你找出一个具有最大和的连续子数组,返回其最大和。", "solution_python": "def maxSubArray(nums):\n max_sum = current = nums[0]\n for num in nums[1:]:\n current = max(num, current + num)\n max_sum = max(max_sum, current)\n return max_sum", "solution_java": "public int maxSubArray(int[] nums) {\n int maxSum = nums[0], curr = nums[0];\n for (int i = 1; i < nums.length; i++) {\n curr = Math.max(nums[i], curr + nums[i]);\n maxSum = Math.max(maxSum, curr);\n }\n return maxSum;\n}", "solution_cpp": "int maxSubArray(vector& nums) {\n int maxSum = nums[0], curr = nums[0];\n for (int i = 1; i < nums.size(); i++) {\n curr = max(nums[i], curr + nums[i]);\n maxSum = max(maxSum, curr);\n }\n return maxSum;\n}", "test_cases": ["nums=[-2,1,-3,4,-1,2,1,-5,4] -> 6", "nums=[1] -> 1"], "key_points": ["Kadane算法", "动态规划基础题"], "tags": ["array", "medium", "Google", "Microsoft"]} {"problem_id": "algo_01764", "original_id": "valid-parentheses", "title": "有效的括号", "category": "string", "difficulty": "easy", "companies": ["Google", "Uber"], "description": "给定一个只包括 '(',')','{','}','[',']' 的字符串 s,判断字符串是否有效。", "solution_python": "def isValid(s):\n stack = []\n mapping = {')': '(', ']': '[', '}': '{'}\n for c in s:\n if c in mapping:\n if not stack or stack[-1] != mapping[c]: return False\n stack.pop()\n else: stack.append(c)\n return not stack", "solution_java": "public boolean isValid(String s) {\n Stack stack = new Stack<>();\n Map map = Map.of(')', '(', ']', '[', '}', '{');\n for (char c : s.toCharArray()) {\n if (map.containsValue(c)) stack.push(c);\n else if (!stack.isEmpty() && stack.pop() != map.get(c)) return false;\n }\n return stack.isEmpty();\n}", "solution_cpp": "bool isValid(string s) {\n stack st;\n unordered_map m = {{')','('},{']','['},{'}','{'}};\n for (char c : s) {\n if (m.find(c) == m.end()) st.push(c);\n else if (st.empty() || st.top() != m[c]) return false;\n else st.pop();\n }\n return st.empty();\n}", "test_cases": ["s=\"()\" -> true", "s=\"()[]{}\" -> true", "s=\"(]\" -> false"], "key_points": ["栈匹配法", "注意空栈边界"], "tags": ["string", "easy", "Google", "Uber"]} {"problem_id": "algo_01765", "original_id": "longest-palindrome", "title": "最长回文子串", "category": "string", "difficulty": "medium", "companies": ["Google", "Amazon"], "description": "给你一个字符串 s,找到 s 中最长的回文子串。", "solution_python": "def longestPalindrome(s):\n def expand(l, r):\n while l >= 0 and r < len(s) and s[l] == s[r]: l -= 1; r += 1\n return l + 1, r - 1\n start = end = 0\n for i in range(len(s)):\n l1, r1 = expand(i, i)\n l2, r2 = expand(i, i + 1)\n if r1 - l1 > end - start: start, end = l1, r1\n if r2 - l2 > end - start: start, end = l2, r2\n return s[start:end+1]", "solution_java": "public String longestPalindrome(String s) {\n int start = 0, end = 0;\n for (int i = 0; i < s.length(); i++) {\n int len1 = expand(s, i, i), len2 = expand(s, i, i+1);\n int len = Math.max(len1, len2);\n if (len > end - start) { start = i - (len-1)/2; end = i + len/2; }\n }\n return s.substring(start, end + 1);\n}\nprivate int expand(String s, int l, int r) {\n while (l >= 0 && r < s.length() && s.charAt(l) == s.charAt(r)) { l--; r++; }\n return r - l - 1;\n}", "solution_cpp": "string longestPalindrome(string s) {\n int start = 0, end = 0;\n for (int i = 0; i < s.size(); i++) {\n int len1 = expand(s, i, i), len2 = expand(s, i, i+1);\n if (max(len1, len2) > end - start) { start = i - (max(len1,len2)-1)/2; end = i + max(len1,len2)/2; }\n }\n return s.substr(start, end - start + 1);\n}", "test_cases": ["s=\"babad\" -> bab或aba", "s=\"cbbd\" -> bb"], "key_points": ["中心扩展法", "处理奇偶长度"], "tags": ["string", "medium", "Google", "Amazon"]} {"problem_id": "algo_01766", "original_id": "reverse-list", "title": "反转链表", "category": "linkedlist", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "给你单链表的头节点 head,请你反转链表,并返回反转后的链表。", "solution_python": "def reverseList(head):\n prev = None\n curr = head\n while curr:\n nxt = curr.next\n curr.next = prev\n prev = curr\n curr = nxt\n return prev", "solution_java": "public ListNode reverseList(ListNode head) {\n ListNode prev = null, curr = head;\n while (curr != null) {\n ListNode next = curr.next;\n curr.next = prev;\n prev = curr;\n curr = next;\n }\n return prev;\n}", "solution_cpp": "ListNode* reverseList(ListNode* head) {\n ListNode* prev = nullptr, *curr = head;\n while (curr) {\n ListNode* next = curr->next;\n curr->next = prev;\n prev = curr;\n curr = next;\n }\n return prev;\n}", "test_cases": ["head=[1,2,3,4,5] -> [5,4,3,2,1]", "head=[1,2] -> [2,1]"], "key_points": ["迭代法 O(1)空间", "递归法 O(n)空间"], "tags": ["linkedlist", "medium", "Google", "Microsoft"]} {"problem_id": "algo_01767", "original_id": "middle-node", "title": "链表的中间结点", "category": "linkedlist", "difficulty": "easy", "companies": ["Amazon", "Facebook"], "description": "给你单链表的头节点 head,请你找出并返回链表的中间结点。如果有两个中间结点,则返回第二个中间结点。", "solution_python": "def middleNode(head):\n slow = fast = head\n while fast and fast.next:\n slow = slow.next\n fast = fast.next.next\n return slow", "solution_java": "public ListNode middleNode(ListNode head) {\n ListNode slow = head, fast = head;\n while (fast != null && fast.next != null) {\n slow = slow.next;\n fast = fast.next.next;\n }\n return slow;\n}", "solution_cpp": "ListNode* middleNode(ListNode* head) {\n ListNode* slow = head, *fast = head;\n while (fast && fast->next) { slow = slow->next; fast = fast->next->next; }\n return slow;\n}", "test_cases": ["head=[1,2,3,4,5] -> 3", "head=[1,2,3,4,5,6] -> 4"], "key_points": ["快慢指针", "O(n)时间O(1)空间"], "tags": ["linkedlist", "easy", "Amazon", "Facebook"]} {"problem_id": "algo_01768", "original_id": "max-depth", "title": "二叉树的最大深度", "category": "tree", "difficulty": "easy", "companies": ["Microsoft", "Apple"], "description": "给定一个二叉树 root,返回其最大深度。", "solution_python": "def maxDepth(root):\n if not root: return 0\n return max(maxDepth(root.left), maxDepth(root.right)) + 1", "solution_java": "public int maxDepth(TreeNode root) {\n if (root == null) return 0;\n return Math.max(maxDepth(root.left), maxDepth(root.right)) + 1;\n}", "solution_cpp": "int maxDepth(TreeNode* root) {\n if (!root) return 0;\n return max(maxDepth(root->left), maxDepth(root->right)) + 1;\n}", "test_cases": ["root=[3,9,20,null,null,15,7] -> 3", "root=[1,null,2] -> 2"], "key_points": ["DFS递归", "层序遍历也可"], "tags": ["tree", "easy", "Microsoft", "Apple"]} {"problem_id": "algo_01769", "original_id": "inorder-traversal", "title": "二叉树的中序遍历", "category": "tree", "difficulty": "easy", "companies": ["Google", "Microsoft"], "description": "给定一个二叉树的根节点 root,返回它的中序遍历结果。", "solution_python": "def inorderTraversal(root):\n result = []\n def dfs(node):\n if node:\n dfs(node.left)\n result.append(node.val)\n dfs(node.right)\n dfs(root)\n return result", "solution_java": "public List inorderTraversal(TreeNode root) {\n List res = new ArrayList<>();\n dfs(root, res);\n return res;\n}\nprivate void dfs(TreeNode node, List res) {\n if (node == null) return;\n dfs(node.left, res); res.add(node.val); dfs(node.right, res);\n}", "solution_cpp": "vector inorderTraversal(TreeNode* root) {\n vector res;\n dfs(root, res);\n return res;\n}\nvoid dfs(TreeNode* node, vector& res) {\n if (!node) return;\n dfs(node->left, res); res.push_back(node->val); dfs(node->right, res);\n}", "test_cases": ["root=[1,null,2,3] -> [1,3,2]", "root=[] -> []"], "key_points": ["左-根-右顺序", "递归最简洁"], "tags": ["tree", "easy", "Google", "Microsoft"]} {"problem_id": "algo_01770", "original_id": "binary-search", "title": "二分查找", "category": "binarysearch", "difficulty": "easy", "companies": ["Google", "Amazon"], "description": "给定一个 n 个元素有序的(升序)整型数组 nums 和一个目标值 target,写一个函数搜索 nums 中的 target,如果目标值存在返回下标,否则返回 -1。", "solution_python": "def search(nums, target):\n left, right = 0, len(nums) - 1\n while left <= right:\n mid = (left + right) // 2\n if nums[mid] == target: return mid\n elif nums[mid] < target: left = mid + 1\n else: right = mid - 1\n return -1", "solution_java": "public int search(int[] nums, int target) {\n int left = 0, right = nums.length - 1;\n while (left <= right) {\n int mid = left + (right - left) / 2;\n if (nums[mid] == target) return mid;\n else if (nums[mid] < target) left = mid + 1;\n else right = mid - 1;\n }\n return -1;\n}", "solution_cpp": "int search(vector& nums, int target) {\n int left = 0, right = nums.size() - 1;\n while (left <= right) {\n int mid = left + (right - left) / 2;\n if (nums[mid] == target) return mid;\n else if (nums[mid] < target) left = mid + 1;\n else right = mid - 1;\n }\n return -1;\n}", "test_cases": ["nums=[-1,0,3,5,9,12], target=9 -> 4", "nums=[-1,0,3,5,9,12], target=2 -> -1"], "key_points": ["标准模板", "注意防溢出写法"], "tags": ["binarysearch", "easy", "Google", "Amazon"]} {"problem_id": "algo_01771", "original_id": "climbing-stairs", "title": "爬楼梯", "category": "dp", "difficulty": "easy", "companies": ["Amazon", "Google"], "description": "假设你正在爬楼梯。需要 n 阶你才能到达楼顶。每次你可以爬 1 或 2 个台阶。你有多少种不同的方法可以爬到楼顶?", "solution_python": "def climbStairs(n):\n if n <= 2: return n\n a, b = 1, 2\n for _ in range(3, n+1):\n a, b = b, a + b\n return b", "solution_java": "public int climbStairs(int n) {\n if (n <= 2) return n;\n int a = 1, b = 2;\n for (int i = 3; i <= n; i++) { int temp = a + b; a = b; b = temp; }\n return b;\n}", "solution_cpp": "int climbStairs(int n) {\n if (n <= 2) return n;\n int a = 1, b = 2;\n for (int i = 3; i <= n; i++) { int temp = a + b; a = b; b = temp; }\n return b;\n}", "test_cases": ["n=2 -> 2", "n=3 -> 3", "n=5 -> 8"], "key_points": ["斐波那契数列", "滚动数组优化空间"], "tags": ["dp", "easy", "Amazon", "Google"]} {"problem_id": "algo_01772", "original_id": "coin-change", "title": "零钱兑换", "category": "dp", "difficulty": "medium", "companies": ["Google", "Amazon"], "description": "给你一个整数数组 coins 表示不同面额的硬币,以及一个整数 amount 表示总金额。计算并返回可以凑成总金额所需的最少的硬币个数。如果没有任何一种硬币组合能组成总金额,返回 -1。", "solution_python": "def coinChange(coins, amount):\n dp = [float('inf')] * (amount + 1)\n dp[0] = 0\n for coin in coins:\n for x in range(coin, amount + 1):\n dp[x] = min(dp[x], dp[x - coin] + 1)\n return dp[amount] if dp[amount] != float('inf') else -1", "solution_java": "public int coinChange(int[] coins, int amount) {\n int[] dp = new int[amount + 1];\n Arrays.fill(dp, amount + 1);\n dp[0] = 0;\n for (int coin : coins) {\n for (int x = coin; x <= amount; x++) {\n dp[x] = Math.min(dp[x], dp[x - coin] + 1);\n }\n }\n return dp[amount] > amount ? -1 : dp[amount];\n}", "solution_cpp": "int coinChange(vector& coins, int amount) {\n vector dp(amount + 1, amount + 1);\n dp[0] = 0;\n for (int coin : coins) {\n for (int x = coin; x <= amount; x++) {\n dp[x] = min(dp[x], dp[x - coin] + 1);\n }\n }\n return dp[amount] > amount ? -1 : dp[amount];\n}", "test_cases": ["coins=[1,2,5], amount=11 -> 3", "coins=[2], amount=3 -> -1"], "key_points": ["完全背包问题", "dp[x] = min(dp[x-coin]+1)"], "tags": ["dp", "medium", "Google", "Amazon"]} {"problem_id": "algo_01773", "original_id": "subsets", "title": "子集", "category": "backtracking", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "给你一个整数数组 nums ,数组中的元素 互不相同 。返回该数组所有可能的子集(幂集)。", "solution_python": "def subsets(nums):\n result = []\n def backtrack(start, path):\n result.append(path[:])\n for i in range(start, len(nums)):\n path.append(nums[i])\n backtrack(i + 1, path)\n path.pop()\n backtrack(0, [])\n return result", "solution_java": "public List> subsets(int[] nums) {\n List> result = new ArrayList<>();\n backtrack(nums, 0, new ArrayList<>(), result);\n return result;\n}\nprivate void backtrack(int[] nums, int start, List path, List> result) {\n result.add(new ArrayList<>(path));\n for (int i = start; i < nums.length; i++) {\n path.add(nums[i]);\n backtrack(nums, i + 1, path, result);\n path.remove(path.size() - 1);\n }\n}", "solution_cpp": "vector> subsets(vector& nums) {\n vector> result;\n vector path;\n backtrack(nums, 0, path, result);\n return result;\n}\nvoid backtrack(vector& nums, int start, vector& path, vector>& result) {\n result.push_back(path);\n for (int i = start; i < nums.size(); i++) {\n path.push_back(nums[i]);\n backtrack(nums, i + 1, path, result);\n path.pop_back();\n }\n}", "test_cases": ["nums=[1,2,3] -> [[],[1],[2],[1,2],[3],[1,3],[2,3],[1,2,3]]"], "key_points": ["选或不选", "DFS遍历子集树"], "tags": ["backtracking", "medium", "Google", "Microsoft"]} {"problem_id": "algo_01774", "original_id": "permutations", "title": "全排列", "category": "backtracking", "difficulty": "medium", "companies": ["Google", "Facebook"], "description": "给定一个不含重复数字的数组 nums,返回其所有可能的全排列。", "solution_python": "def permute(nums):\n result = []\n def backtrack(path, used):\n if len(path) == len(nums):\n result.append(path[:])\n return\n for i in range(len(nums)):\n if used[i]: continue\n used[i] = True\n path.append(nums[i])\n backtrack(path, used)\n path.pop()\n used[i] = False\n backtrack([], [False]*len(nums))\n return result", "solution_java": "public List> permute(int[] nums) {\n List> result = new ArrayList<>();\n boolean[] used = new boolean[nums.length];\n backtrack(nums, used, new ArrayList<>(), result);\n return result;\n}\nprivate void backtrack(int[] nums, boolean[] used, List path, List> result) {\n if (path.size() == nums.length) { result.add(new ArrayList<>(path)); return; }\n for (int i = 0; i < nums.length; i++) {\n if (used[i]) continue;\n used[i] = true;\n path.add(nums[i]);\n backtrack(nums, used, path, result);\n path.remove(path.size() - 1);\n used[i] = false;\n }\n}", "solution_cpp": "vector> permute(vector& nums) {\n vector> result;\n vector used(nums.size(), false);\n vector path;\n backtrack(nums, used, path, result);\n return result;\n}\nvoid backtrack(vector& nums, vector& used, vector& path, vector>& result) {\n if (path.size() == nums.size()) { result.push_back(path); return; }\n for (int i = 0; i < nums.size(); i++) {\n if (used[i]) continue;\n used[i] = true;\n path.push_back(nums[i]);\n backtrack(nums, used, path, result);\n path.pop_back();\n used[i] = false;\n }\n}", "test_cases": ["nums=[1,2,3] -> [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]"], "key_points": ["标记已使用元素", "回溯经典模板"], "tags": ["backtracking", "medium", "Google", "Facebook"]} {"problem_id": "algo_01775", "original_id": "top-k-frequent", "title": "前K个高频元素", "category": "heap", "difficulty": "medium", "companies": ["Amazon", "Facebook"], "description": "给你一个整数数组 nums 和一个整数 k,请你返回其中出现频率前 k 高的元素。", "solution_python": "import heapq\nfrom collections import Counter\ndef topKFrequent(nums, k):\n count = Counter(nums)\n heap = []\n for num, freq in count.items():\n heapq.heappush(heap, (freq, num))\n if len(heap) > k: heapq.heappop(heap)\n return [num for freq, num in heap]", "solution_java": "public int[] topKFrequent(int[] nums, int k) {\n Map count = new HashMap<>();\n for (int n : nums) count.put(n, count.getOrDefault(n, 0) + 1);\n PriorityQueue> heap = \n new PriorityQueue<>((a, b) -> a.getValue() - b.getValue());\n for (Map.Entry e : count.entrySet()) {\n heap.offer(e);\n if (heap.size() > k) heap.poll();\n }\n int[] res = new int[k];\n for (int i = k - 1; i >= 0; i--) res[i] = heap.poll().getKey();\n return res;\n}", "solution_cpp": "vector topKFrequent(vector& nums, int k) {\n unordered_map count;\n for (int n : nums) count[n]++;\n priority_queue, vector>, greater>> heap;\n for (auto& [num, freq] : count) {\n heap.push({freq, num});\n if (heap.size() > k) heap.pop();\n }\n vector res;\n while (!heap.empty()) { res.push_back(heap.top().second); heap.pop(); }\n reverse(res.begin(), res.end());\n return res;\n}", "test_cases": ["nums=[1,1,1,2,2,3], k=2 -> [1,2]", "nums=[1], k=1 -> [1]"], "key_points": ["小顶堆保持大小k", "时间复杂度O(nlogk)"], "tags": ["heap", "medium", "Amazon", "Facebook"]} {"problem_id": "algo_01776", "original_id": "3sum", "title": "三数之和", "category": "two-pointers", "difficulty": "medium", "companies": ["Google", "Amazon"], "description": "给你一个整数数组 nums,判断是否存在三元组满足和为0,返回所有不重复的三元组。", "solution_python": "def threeSum(nums):\n nums.sort()\n result = []\n for i in range(len(nums) - 2):\n if i > 0 and nums[i] == nums[i-1]: continue\n left, right = i + 1, len(nums) - 1\n while left < right:\n total = nums[i] + nums[left] + nums[right]\n if total < 0: left += 1\n elif total > 0: right -= 1\n else:\n result.append([nums[i], nums[left], nums[right]])\n while left < right and nums[left] == nums[left+1]: left += 1\n while left < right and nums[right] == nums[right-1]: right -= 1\n left += 1; right -= 1\n return result", "solution_java": "public List> threeSum(int[] nums) {\n Arrays.sort(nums);\n List> result = new ArrayList<>();\n for (int i = 0; i < nums.length - 2; i++) {\n if (i > 0 && nums[i] == nums[i-1]) continue;\n int left = i + 1, right = nums.length - 1;\n while (left < right) {\n int total = nums[i] + nums[left] + nums[right];\n if (total < 0) left++;\n else if (total > 0) right--;\n else {\n result.add(Arrays.asList(nums[i], nums[left], nums[right]));\n while (left < right && nums[left] == nums[left+1]) left++;\n while (left < right && nums[right] == nums[right-1]) right--;\n left++; right--;\n }\n }\n }\n return result;\n}", "solution_cpp": "vector> threeSum(vector& nums) {\n sort(nums.begin(), nums.end());\n vector> result;\n for (int i = 0; i < nums.size() - 2; i++) {\n if (i > 0 && nums[i] == nums[i-1]) continue;\n int left = i + 1, right = nums.size() - 1;\n while (left < right) {\n int total = nums[i] + nums[left] + nums[right];\n if (total < 0) left++;\n else if (total > 0) right--;\n else {\n result.push_back({nums[i], nums[left], nums[right]});\n while (left < right && nums[left] == nums[left+1]) left++;\n while (left < right && nums[right] == nums[right-1]) right--;\n left++; right--;\n }\n }\n }\n return result;\n}", "test_cases": ["nums=[-1,0,1,2,-1,-4] -> [[-1,-1,2],[-1,0,1]]"], "key_points": ["排序+双指针", "去重是关键"], "tags": ["two-pointers", "medium", "Google", "Amazon"]} {"problem_id": "algo_01777", "original_id": "container-water", "title": "盛最多水的容器", "category": "two-pointers", "difficulty": "medium", "companies": ["Google", "Uber"], "description": "给定一个长度为 n 的整数数组 height,找出其中的两条线,使得它们与 x 轴共同构成的容器可以容纳最多的水。", "solution_python": "def maxArea(height):\n left, right = 0, len(height) - 1\n max_area = 0\n while left < right:\n h = min(height[left], height[right])\n max_area = max(max_area, h * (right - left))\n if height[left] < height[right]: left += 1\n else: right -= 1\n return max_area", "solution_java": "public int maxArea(int[] height) {\n int left = 0, right = height.length - 1, maxArea = 0;\n while (left < right) {\n int h = Math.min(height[left], height[right]);\n maxArea = Math.max(maxArea, h * (right - left));\n if (height[left] < height[right]) left++;\n else right--;\n }\n return maxArea;\n}", "solution_cpp": "int maxArea(vector& height) {\n int left = 0, right = height.size() - 1, maxArea = 0;\n while (left < right) {\n int h = min(height[left], height[right]);\n maxArea = max(maxArea, h * (right - left));\n if (height[left] < height[right]) left++;\n else right--;\n }\n return maxArea;\n}", "test_cases": ["height=[1,8,6,2,5,4,8,3,7] -> 49"], "key_points": ["移动短边指针", "面积=min(h1,h2)*width"], "tags": ["two-pointers", "medium", "Google", "Uber"]} {"problem_id": "algo_01778", "original_id": "min-stack", "title": "最小栈", "category": "stack", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "设计一个支持 push,pop,top 操作,并能在常数时间内检索到最小元素的栈。", "solution_python": "class MinStack:\n def __init__(self):\n self.stack = []\n self.min_stack = []\n def push(self, val):\n self.stack.append(val)\n self.min_stack.append(min(val, self.min_stack[-1] if self.min_stack else val))\n def pop(self):\n self.stack.pop(); self.min_stack.pop()\n def top(self): return self.stack[-1]\n def getMin(self): return self.min_stack[-1]", "solution_java": "class MinStack {\n Stack stack = new Stack<>();\n Stack minStack = new Stack<>();\n public void push(int val) { stack.push(val); minStack.push(Math.min(val, minStack.isEmpty() ? val : minStack.peek())); }\n public void pop() { stack.pop(); minStack.pop(); }\n public int top() { return stack.peek(); }\n public int getMin() { return minStack.peek(); }\n}", "solution_cpp": "class MinStack {\n stack st, minSt;\npublic:\n void push(int val) { st.push(val); minSt.push(min(val, minSt.empty() ? val : minSt.top())); }\n void pop() { st.pop(); minSt.pop(); }\n int top() { return st.top(); }\n int getMin() { return minSt.top(); }\n};", "test_cases": ["push(-2), push(0), push(-3) -> getMin() returns -3"], "key_points": ["辅助栈记录最小值", "O(1)时间获取最小值"], "tags": ["stack", "medium", "Google", "Microsoft"]} {"problem_id": "algo_01779", "original_id": "lru-cache", "title": "LRU缓存", "category": "design", "difficulty": "hard", "companies": ["Google", "Amazon"], "description": "设计和实现一个 LRU(最近最少使用)缓存机制。", "solution_python": "class LRUCache:\n def __init__(self, capacity):\n self.capacity = capacity\n self.cache = {}\n self.order = []\n def get(self, key):\n if key not in self.cache: return -1\n self.order.remove(key); self.order.append(key)\n return self.cache[key]\n def put(self, key, value):\n if key in self.cache:\n self.order.remove(key)\n elif len(self.cache) >= self.capacity:\n del self.cache[self.order.pop(0)]\n self.cache[key] = value; self.order.append(key)", "solution_java": "class LRUCache {\n int capacity;\n LinkedHashMap cache = new LinkedHashMap<>();\n public LRUCache(int cap) { capacity = cap; }\n public int get(int key) { return cache.containsKey(key) ? cache.remove(key) : -1; }\n public void put(int key, int val) {\n if (cache.containsKey(key)) cache.remove(key);\n else if (cache.size() >= capacity) cache.remove(cache.keySet().iterator().next());\n cache.put(key, val);\n }\n}", "solution_cpp": "class LRUCache {\n int cap;\n list> dll;\n unordered_map>::iterator> cache;\npublic:\n LRUCache(int capacity) : cap(capacity) {}\n int get(int key) {\n auto it = cache.find(key);\n if (it == cache.end()) return -1;\n dll.splice(dll.end(), dll, it->second);\n return it->second->second;\n }\n void put(int key, int value) {\n auto it = cache.find(key);\n if (it != cache.end()) dll.erase(it->second);\n else if (cache.size() >= cap) { cache.erase(dll.front().first); dll.pop_front(); }\n dll.push_back({key, value});\n cache[key] = --dll.end();\n }\n};", "test_cases": ["put(1,1), put(2,2), get(1) -> 1"], "key_points": ["HashMap + 双向链表", "O(1)时间操作"], "tags": ["design", "hard", "Google", "Amazon"]} {"problem_id": "algo_01780", "original_id": "num-islands", "title": "岛屿数量", "category": "graph", "difficulty": "medium", "companies": ["Google", "Facebook"], "description": "给你一个由 '1'(陆地)和 '0'(水)组成的二维网格,请你计算网格中岛屿的数量。岛屿总是被水包围,且只能由水平或垂直方向相邻的陆地连接形成。", "solution_python": "def numIslands(grid):\n if not grid: return 0\n rows, cols = len(grid), len(grid[0])\n count = 0\n def dfs(r, c):\n if r < 0 or r >= rows or c < 0 or c >= cols or grid[r][c] != '1': return\n grid[r][c] = '0'\n dfs(r+1, c); dfs(r-1, c); dfs(r, c+1); dfs(r, c-1)\n for r in range(rows):\n for c in range(cols):\n if grid[r][c] == '1': count += 1; dfs(r, c)\n return count", "solution_java": "public int numIslands(char[][] grid) {\n if (grid.length == 0) return 0;\n int count = 0;\n for (int i = 0; i < grid.length; i++)\n for (int j = 0; j < grid[0].length; j++)\n if (grid[i][j] == '1') { count++; dfs(grid, i, j); }\n return count;\n}\nprivate void dfs(char[][] grid, int r, int c) {\n if (r < 0 || r >= grid.length || c < 0 || c >= grid[0].length || grid[r][c] != '1') return;\n grid[r][c] = '0';\n dfs(grid, r+1, c); dfs(grid, r-1, c); dfs(grid, r, c+1); dfs(grid, r, c-1);\n}", "solution_cpp": "int numIslands(vector>& grid) {\n if (grid.empty()) return 0;\n int count = 0;\n for (int i = 0; i < grid.size(); i++)\n for (int j = 0; j < grid[0].size(); j++)\n if (grid[i][j] == '1') { count++; dfs(grid, i, j); }\n return count;\n}\nvoid dfs(vector>& grid, int r, int c) {\n if (r < 0 || r >= grid.size() || c < 0 || c >= grid[0].size() || grid[r][c] != '1') return;\n grid[r][c] = '0';\n dfs(grid, r+1, c); dfs(grid, r-1, c); dfs(grid, r, c+1); dfs(grid, r, c-1);\n}", "test_cases": ["grid=[[1,1,1,1,0],[1,1,0,1,0],[1,1,0,0,0],[0,0,0,0,0]] -> 1"], "key_points": ["DFS/BFS遍历", "访问后标记为0避免重复"], "tags": ["graph", "medium", "Google", "Facebook"]} {"problem_id": "algo_01781", "original_id": "two-sum", "title": "两数之和", "category": "array", "difficulty": "easy", "companies": ["Amazon", "Google"], "description": "给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那两个整数,并返回他们的数组下标。", "solution_python": "def twoSum(nums, target):\n hashmap = {}\n for i, num in enumerate(nums):\n complement = target - num\n if complement in hashmap:\n return [hashmap[complement], i]\n hashmap[num] = i\n return []", "solution_java": "public int[] twoSum(int[] nums, int target) {\n Map map = new HashMap<>();\n for (int i = 0; i < nums.length; i++) {\n int complement = target - nums[i];\n if (map.containsKey(complement)) return new int[]{map.get(complement), i};\n map.put(nums[i], i);\n }\n return new int[]{};\n}", "solution_cpp": "vector twoSum(vector& nums, int target) {\n unordered_map m;\n for (int i = 0; i < nums.size(); i++) {\n if (m.count(target - nums[i])) return {m[target - nums[i]], i};\n m[nums[i]] = i;\n }\n return {};\n}", "test_cases": ["nums=[2,7,11,15], target=9 -> [0,1]", "nums=[3,2,4], target=6 -> [1,2]"], "key_points": ["哈希表一次遍历", "空间换时间"], "tags": ["array", "easy", "Amazon", "Google"]} {"problem_id": "algo_01782", "original_id": "merge-sorted", "title": "合并两个有序数组", "category": "array", "difficulty": "easy", "companies": ["Microsoft", "Uber"], "description": "给你两个按非递减顺序排列的整数数组 nums1 和 nums2,另有两个整数 m 和 n,分别表示 nums1 和 nums2 中的元素数目。请你合并 nums2 到 nums1 中。", "solution_python": "def merge(nums1, m, nums2, n):\n p1, p2, p = m-1, n-1, m+n-1\n while p1 >= 0 and p2 >= 0:\n if nums1[p1] > nums2[p2]: nums1[p] = nums1[p1]; p1 -= 1\n else: nums1[p] = nums2[p2]; p2 -= 1\n p -= 1\n while p2 >= 0: nums1[p] = nums2[p2]; p2 -= 1; p -= 1", "solution_java": "public void merge(int[] nums1, int m, int[] nums2, int n) {\n int p1 = m-1, p2 = n-1, p = m+n-1;\n while (p1 >= 0 && p2 >= 0) {\n nums1[p--] = nums1[p1] > nums2[p2] ? nums1[p1--] : nums2[p2--];\n }\n while (p2 >= 0) nums1[p--] = nums2[p2--];\n}", "solution_cpp": "void merge(vector& nums1, int m, vector& nums2, int n) {\n int p1 = m-1, p2 = n-1, p = m+n-1;\n while (p1 >= 0 && p2 >= 0) nums1[p--] = nums1[p1] > nums2[p2] ? nums1[p1--] : nums2[p2--];\n while (p2 >= 0) nums1[p--] = nums2[p2--];\n}", "test_cases": ["nums1=[1,2,3], m=3, nums2=[2,5,6], n=3 -> [1,2,2,3,5,6]", "nums1=[], m=0, nums2=[1], n=1 -> [1]"], "key_points": ["从后往前合并", "三指针技巧"], "tags": ["array", "easy", "Microsoft", "Uber"]} {"problem_id": "algo_01783", "original_id": "max-subarray", "title": "最大子数组和", "category": "array", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "给你一个整数数组 nums ,请你找出一个具有最大和的连续子数组,返回其最大和。", "solution_python": "def maxSubArray(nums):\n max_sum = current = nums[0]\n for num in nums[1:]:\n current = max(num, current + num)\n max_sum = max(max_sum, current)\n return max_sum", "solution_java": "public int maxSubArray(int[] nums) {\n int maxSum = nums[0], curr = nums[0];\n for (int i = 1; i < nums.length; i++) {\n curr = Math.max(nums[i], curr + nums[i]);\n maxSum = Math.max(maxSum, curr);\n }\n return maxSum;\n}", "solution_cpp": "int maxSubArray(vector& nums) {\n int maxSum = nums[0], curr = nums[0];\n for (int i = 1; i < nums.size(); i++) {\n curr = max(nums[i], curr + nums[i]);\n maxSum = max(maxSum, curr);\n }\n return maxSum;\n}", "test_cases": ["nums=[-2,1,-3,4,-1,2,1,-5,4] -> 6", "nums=[1] -> 1"], "key_points": ["Kadane算法", "动态规划基础题"], "tags": ["array", "medium", "Google", "Microsoft"]} {"problem_id": "algo_01784", "original_id": "valid-parentheses", "title": "有效的括号", "category": "string", "difficulty": "easy", "companies": ["Google", "Uber"], "description": "给定一个只包括 '(',')','{','}','[',']' 的字符串 s,判断字符串是否有效。", "solution_python": "def isValid(s):\n stack = []\n mapping = {')': '(', ']': '[', '}': '{'}\n for c in s:\n if c in mapping:\n if not stack or stack[-1] != mapping[c]: return False\n stack.pop()\n else: stack.append(c)\n return not stack", "solution_java": "public boolean isValid(String s) {\n Stack stack = new Stack<>();\n Map map = Map.of(')', '(', ']', '[', '}', '{');\n for (char c : s.toCharArray()) {\n if (map.containsValue(c)) stack.push(c);\n else if (!stack.isEmpty() && stack.pop() != map.get(c)) return false;\n }\n return stack.isEmpty();\n}", "solution_cpp": "bool isValid(string s) {\n stack st;\n unordered_map m = {{')','('},{']','['},{'}','{'}};\n for (char c : s) {\n if (m.find(c) == m.end()) st.push(c);\n else if (st.empty() || st.top() != m[c]) return false;\n else st.pop();\n }\n return st.empty();\n}", "test_cases": ["s=\"()\" -> true", "s=\"()[]{}\" -> true", "s=\"(]\" -> false"], "key_points": ["栈匹配法", "注意空栈边界"], "tags": ["string", "easy", "Google", "Uber"]} {"problem_id": "algo_01785", "original_id": "longest-palindrome", "title": "最长回文子串", "category": "string", "difficulty": "medium", "companies": ["Google", "Amazon"], "description": "给你一个字符串 s,找到 s 中最长的回文子串。", "solution_python": "def longestPalindrome(s):\n def expand(l, r):\n while l >= 0 and r < len(s) and s[l] == s[r]: l -= 1; r += 1\n return l + 1, r - 1\n start = end = 0\n for i in range(len(s)):\n l1, r1 = expand(i, i)\n l2, r2 = expand(i, i + 1)\n if r1 - l1 > end - start: start, end = l1, r1\n if r2 - l2 > end - start: start, end = l2, r2\n return s[start:end+1]", "solution_java": "public String longestPalindrome(String s) {\n int start = 0, end = 0;\n for (int i = 0; i < s.length(); i++) {\n int len1 = expand(s, i, i), len2 = expand(s, i, i+1);\n int len = Math.max(len1, len2);\n if (len > end - start) { start = i - (len-1)/2; end = i + len/2; }\n }\n return s.substring(start, end + 1);\n}\nprivate int expand(String s, int l, int r) {\n while (l >= 0 && r < s.length() && s.charAt(l) == s.charAt(r)) { l--; r++; }\n return r - l - 1;\n}", "solution_cpp": "string longestPalindrome(string s) {\n int start = 0, end = 0;\n for (int i = 0; i < s.size(); i++) {\n int len1 = expand(s, i, i), len2 = expand(s, i, i+1);\n if (max(len1, len2) > end - start) { start = i - (max(len1,len2)-1)/2; end = i + max(len1,len2)/2; }\n }\n return s.substr(start, end - start + 1);\n}", "test_cases": ["s=\"babad\" -> bab或aba", "s=\"cbbd\" -> bb"], "key_points": ["中心扩展法", "处理奇偶长度"], "tags": ["string", "medium", "Google", "Amazon"]} {"problem_id": "algo_01786", "original_id": "reverse-list", "title": "反转链表", "category": "linkedlist", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "给你单链表的头节点 head,请你反转链表,并返回反转后的链表。", "solution_python": "def reverseList(head):\n prev = None\n curr = head\n while curr:\n nxt = curr.next\n curr.next = prev\n prev = curr\n curr = nxt\n return prev", "solution_java": "public ListNode reverseList(ListNode head) {\n ListNode prev = null, curr = head;\n while (curr != null) {\n ListNode next = curr.next;\n curr.next = prev;\n prev = curr;\n curr = next;\n }\n return prev;\n}", "solution_cpp": "ListNode* reverseList(ListNode* head) {\n ListNode* prev = nullptr, *curr = head;\n while (curr) {\n ListNode* next = curr->next;\n curr->next = prev;\n prev = curr;\n curr = next;\n }\n return prev;\n}", "test_cases": ["head=[1,2,3,4,5] -> [5,4,3,2,1]", "head=[1,2] -> [2,1]"], "key_points": ["迭代法 O(1)空间", "递归法 O(n)空间"], "tags": ["linkedlist", "medium", "Google", "Microsoft"]} {"problem_id": "algo_01787", "original_id": "middle-node", "title": "链表的中间结点", "category": "linkedlist", "difficulty": "easy", "companies": ["Amazon", "Facebook"], "description": "给你单链表的头节点 head,请你找出并返回链表的中间结点。如果有两个中间结点,则返回第二个中间结点。", "solution_python": "def middleNode(head):\n slow = fast = head\n while fast and fast.next:\n slow = slow.next\n fast = fast.next.next\n return slow", "solution_java": "public ListNode middleNode(ListNode head) {\n ListNode slow = head, fast = head;\n while (fast != null && fast.next != null) {\n slow = slow.next;\n fast = fast.next.next;\n }\n return slow;\n}", "solution_cpp": "ListNode* middleNode(ListNode* head) {\n ListNode* slow = head, *fast = head;\n while (fast && fast->next) { slow = slow->next; fast = fast->next->next; }\n return slow;\n}", "test_cases": ["head=[1,2,3,4,5] -> 3", "head=[1,2,3,4,5,6] -> 4"], "key_points": ["快慢指针", "O(n)时间O(1)空间"], "tags": ["linkedlist", "easy", "Amazon", "Facebook"]} {"problem_id": "algo_01788", "original_id": "max-depth", "title": "二叉树的最大深度", "category": "tree", "difficulty": "easy", "companies": ["Microsoft", "Apple"], "description": "给定一个二叉树 root,返回其最大深度。", "solution_python": "def maxDepth(root):\n if not root: return 0\n return max(maxDepth(root.left), maxDepth(root.right)) + 1", "solution_java": "public int maxDepth(TreeNode root) {\n if (root == null) return 0;\n return Math.max(maxDepth(root.left), maxDepth(root.right)) + 1;\n}", "solution_cpp": "int maxDepth(TreeNode* root) {\n if (!root) return 0;\n return max(maxDepth(root->left), maxDepth(root->right)) + 1;\n}", "test_cases": ["root=[3,9,20,null,null,15,7] -> 3", "root=[1,null,2] -> 2"], "key_points": ["DFS递归", "层序遍历也可"], "tags": ["tree", "easy", "Microsoft", "Apple"]} {"problem_id": "algo_01789", "original_id": "inorder-traversal", "title": "二叉树的中序遍历", "category": "tree", "difficulty": "easy", "companies": ["Google", "Microsoft"], "description": "给定一个二叉树的根节点 root,返回它的中序遍历结果。", "solution_python": "def inorderTraversal(root):\n result = []\n def dfs(node):\n if node:\n dfs(node.left)\n result.append(node.val)\n dfs(node.right)\n dfs(root)\n return result", "solution_java": "public List inorderTraversal(TreeNode root) {\n List res = new ArrayList<>();\n dfs(root, res);\n return res;\n}\nprivate void dfs(TreeNode node, List res) {\n if (node == null) return;\n dfs(node.left, res); res.add(node.val); dfs(node.right, res);\n}", "solution_cpp": "vector inorderTraversal(TreeNode* root) {\n vector res;\n dfs(root, res);\n return res;\n}\nvoid dfs(TreeNode* node, vector& res) {\n if (!node) return;\n dfs(node->left, res); res.push_back(node->val); dfs(node->right, res);\n}", "test_cases": ["root=[1,null,2,3] -> [1,3,2]", "root=[] -> []"], "key_points": ["左-根-右顺序", "递归最简洁"], "tags": ["tree", "easy", "Google", "Microsoft"]} {"problem_id": "algo_01790", "original_id": "binary-search", "title": "二分查找", "category": "binarysearch", "difficulty": "easy", "companies": ["Google", "Amazon"], "description": "给定一个 n 个元素有序的(升序)整型数组 nums 和一个目标值 target,写一个函数搜索 nums 中的 target,如果目标值存在返回下标,否则返回 -1。", "solution_python": "def search(nums, target):\n left, right = 0, len(nums) - 1\n while left <= right:\n mid = (left + right) // 2\n if nums[mid] == target: return mid\n elif nums[mid] < target: left = mid + 1\n else: right = mid - 1\n return -1", "solution_java": "public int search(int[] nums, int target) {\n int left = 0, right = nums.length - 1;\n while (left <= right) {\n int mid = left + (right - left) / 2;\n if (nums[mid] == target) return mid;\n else if (nums[mid] < target) left = mid + 1;\n else right = mid - 1;\n }\n return -1;\n}", "solution_cpp": "int search(vector& nums, int target) {\n int left = 0, right = nums.size() - 1;\n while (left <= right) {\n int mid = left + (right - left) / 2;\n if (nums[mid] == target) return mid;\n else if (nums[mid] < target) left = mid + 1;\n else right = mid - 1;\n }\n return -1;\n}", "test_cases": ["nums=[-1,0,3,5,9,12], target=9 -> 4", "nums=[-1,0,3,5,9,12], target=2 -> -1"], "key_points": ["标准模板", "注意防溢出写法"], "tags": ["binarysearch", "easy", "Google", "Amazon"]} {"problem_id": "algo_01791", "original_id": "climbing-stairs", "title": "爬楼梯", "category": "dp", "difficulty": "easy", "companies": ["Amazon", "Google"], "description": "假设你正在爬楼梯。需要 n 阶你才能到达楼顶。每次你可以爬 1 或 2 个台阶。你有多少种不同的方法可以爬到楼顶?", "solution_python": "def climbStairs(n):\n if n <= 2: return n\n a, b = 1, 2\n for _ in range(3, n+1):\n a, b = b, a + b\n return b", "solution_java": "public int climbStairs(int n) {\n if (n <= 2) return n;\n int a = 1, b = 2;\n for (int i = 3; i <= n; i++) { int temp = a + b; a = b; b = temp; }\n return b;\n}", "solution_cpp": "int climbStairs(int n) {\n if (n <= 2) return n;\n int a = 1, b = 2;\n for (int i = 3; i <= n; i++) { int temp = a + b; a = b; b = temp; }\n return b;\n}", "test_cases": ["n=2 -> 2", "n=3 -> 3", "n=5 -> 8"], "key_points": ["斐波那契数列", "滚动数组优化空间"], "tags": ["dp", "easy", "Amazon", "Google"]} {"problem_id": "algo_01792", "original_id": "coin-change", "title": "零钱兑换", "category": "dp", "difficulty": "medium", "companies": ["Google", "Amazon"], "description": "给你一个整数数组 coins 表示不同面额的硬币,以及一个整数 amount 表示总金额。计算并返回可以凑成总金额所需的最少的硬币个数。如果没有任何一种硬币组合能组成总金额,返回 -1。", "solution_python": "def coinChange(coins, amount):\n dp = [float('inf')] * (amount + 1)\n dp[0] = 0\n for coin in coins:\n for x in range(coin, amount + 1):\n dp[x] = min(dp[x], dp[x - coin] + 1)\n return dp[amount] if dp[amount] != float('inf') else -1", "solution_java": "public int coinChange(int[] coins, int amount) {\n int[] dp = new int[amount + 1];\n Arrays.fill(dp, amount + 1);\n dp[0] = 0;\n for (int coin : coins) {\n for (int x = coin; x <= amount; x++) {\n dp[x] = Math.min(dp[x], dp[x - coin] + 1);\n }\n }\n return dp[amount] > amount ? -1 : dp[amount];\n}", "solution_cpp": "int coinChange(vector& coins, int amount) {\n vector dp(amount + 1, amount + 1);\n dp[0] = 0;\n for (int coin : coins) {\n for (int x = coin; x <= amount; x++) {\n dp[x] = min(dp[x], dp[x - coin] + 1);\n }\n }\n return dp[amount] > amount ? -1 : dp[amount];\n}", "test_cases": ["coins=[1,2,5], amount=11 -> 3", "coins=[2], amount=3 -> -1"], "key_points": ["完全背包问题", "dp[x] = min(dp[x-coin]+1)"], "tags": ["dp", "medium", "Google", "Amazon"]} {"problem_id": "algo_01793", "original_id": "subsets", "title": "子集", "category": "backtracking", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "给你一个整数数组 nums ,数组中的元素 互不相同 。返回该数组所有可能的子集(幂集)。", "solution_python": "def subsets(nums):\n result = []\n def backtrack(start, path):\n result.append(path[:])\n for i in range(start, len(nums)):\n path.append(nums[i])\n backtrack(i + 1, path)\n path.pop()\n backtrack(0, [])\n return result", "solution_java": "public List> subsets(int[] nums) {\n List> result = new ArrayList<>();\n backtrack(nums, 0, new ArrayList<>(), result);\n return result;\n}\nprivate void backtrack(int[] nums, int start, List path, List> result) {\n result.add(new ArrayList<>(path));\n for (int i = start; i < nums.length; i++) {\n path.add(nums[i]);\n backtrack(nums, i + 1, path, result);\n path.remove(path.size() - 1);\n }\n}", "solution_cpp": "vector> subsets(vector& nums) {\n vector> result;\n vector path;\n backtrack(nums, 0, path, result);\n return result;\n}\nvoid backtrack(vector& nums, int start, vector& path, vector>& result) {\n result.push_back(path);\n for (int i = start; i < nums.size(); i++) {\n path.push_back(nums[i]);\n backtrack(nums, i + 1, path, result);\n path.pop_back();\n }\n}", "test_cases": ["nums=[1,2,3] -> [[],[1],[2],[1,2],[3],[1,3],[2,3],[1,2,3]]"], "key_points": ["选或不选", "DFS遍历子集树"], "tags": ["backtracking", "medium", "Google", "Microsoft"]} {"problem_id": "algo_01794", "original_id": "permutations", "title": "全排列", "category": "backtracking", "difficulty": "medium", "companies": ["Google", "Facebook"], "description": "给定一个不含重复数字的数组 nums,返回其所有可能的全排列。", "solution_python": "def permute(nums):\n result = []\n def backtrack(path, used):\n if len(path) == len(nums):\n result.append(path[:])\n return\n for i in range(len(nums)):\n if used[i]: continue\n used[i] = True\n path.append(nums[i])\n backtrack(path, used)\n path.pop()\n used[i] = False\n backtrack([], [False]*len(nums))\n return result", "solution_java": "public List> permute(int[] nums) {\n List> result = new ArrayList<>();\n boolean[] used = new boolean[nums.length];\n backtrack(nums, used, new ArrayList<>(), result);\n return result;\n}\nprivate void backtrack(int[] nums, boolean[] used, List path, List> result) {\n if (path.size() == nums.length) { result.add(new ArrayList<>(path)); return; }\n for (int i = 0; i < nums.length; i++) {\n if (used[i]) continue;\n used[i] = true;\n path.add(nums[i]);\n backtrack(nums, used, path, result);\n path.remove(path.size() - 1);\n used[i] = false;\n }\n}", "solution_cpp": "vector> permute(vector& nums) {\n vector> result;\n vector used(nums.size(), false);\n vector path;\n backtrack(nums, used, path, result);\n return result;\n}\nvoid backtrack(vector& nums, vector& used, vector& path, vector>& result) {\n if (path.size() == nums.size()) { result.push_back(path); return; }\n for (int i = 0; i < nums.size(); i++) {\n if (used[i]) continue;\n used[i] = true;\n path.push_back(nums[i]);\n backtrack(nums, used, path, result);\n path.pop_back();\n used[i] = false;\n }\n}", "test_cases": ["nums=[1,2,3] -> [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]"], "key_points": ["标记已使用元素", "回溯经典模板"], "tags": ["backtracking", "medium", "Google", "Facebook"]} {"problem_id": "algo_01795", "original_id": "top-k-frequent", "title": "前K个高频元素", "category": "heap", "difficulty": "medium", "companies": ["Amazon", "Facebook"], "description": "给你一个整数数组 nums 和一个整数 k,请你返回其中出现频率前 k 高的元素。", "solution_python": "import heapq\nfrom collections import Counter\ndef topKFrequent(nums, k):\n count = Counter(nums)\n heap = []\n for num, freq in count.items():\n heapq.heappush(heap, (freq, num))\n if len(heap) > k: heapq.heappop(heap)\n return [num for freq, num in heap]", "solution_java": "public int[] topKFrequent(int[] nums, int k) {\n Map count = new HashMap<>();\n for (int n : nums) count.put(n, count.getOrDefault(n, 0) + 1);\n PriorityQueue> heap = \n new PriorityQueue<>((a, b) -> a.getValue() - b.getValue());\n for (Map.Entry e : count.entrySet()) {\n heap.offer(e);\n if (heap.size() > k) heap.poll();\n }\n int[] res = new int[k];\n for (int i = k - 1; i >= 0; i--) res[i] = heap.poll().getKey();\n return res;\n}", "solution_cpp": "vector topKFrequent(vector& nums, int k) {\n unordered_map count;\n for (int n : nums) count[n]++;\n priority_queue, vector>, greater>> heap;\n for (auto& [num, freq] : count) {\n heap.push({freq, num});\n if (heap.size() > k) heap.pop();\n }\n vector res;\n while (!heap.empty()) { res.push_back(heap.top().second); heap.pop(); }\n reverse(res.begin(), res.end());\n return res;\n}", "test_cases": ["nums=[1,1,1,2,2,3], k=2 -> [1,2]", "nums=[1], k=1 -> [1]"], "key_points": ["小顶堆保持大小k", "时间复杂度O(nlogk)"], "tags": ["heap", "medium", "Amazon", "Facebook"]} {"problem_id": "algo_01796", "original_id": "3sum", "title": "三数之和", "category": "two-pointers", "difficulty": "medium", "companies": ["Google", "Amazon"], "description": "给你一个整数数组 nums,判断是否存在三元组满足和为0,返回所有不重复的三元组。", "solution_python": "def threeSum(nums):\n nums.sort()\n result = []\n for i in range(len(nums) - 2):\n if i > 0 and nums[i] == nums[i-1]: continue\n left, right = i + 1, len(nums) - 1\n while left < right:\n total = nums[i] + nums[left] + nums[right]\n if total < 0: left += 1\n elif total > 0: right -= 1\n else:\n result.append([nums[i], nums[left], nums[right]])\n while left < right and nums[left] == nums[left+1]: left += 1\n while left < right and nums[right] == nums[right-1]: right -= 1\n left += 1; right -= 1\n return result", "solution_java": "public List> threeSum(int[] nums) {\n Arrays.sort(nums);\n List> result = new ArrayList<>();\n for (int i = 0; i < nums.length - 2; i++) {\n if (i > 0 && nums[i] == nums[i-1]) continue;\n int left = i + 1, right = nums.length - 1;\n while (left < right) {\n int total = nums[i] + nums[left] + nums[right];\n if (total < 0) left++;\n else if (total > 0) right--;\n else {\n result.add(Arrays.asList(nums[i], nums[left], nums[right]));\n while (left < right && nums[left] == nums[left+1]) left++;\n while (left < right && nums[right] == nums[right-1]) right--;\n left++; right--;\n }\n }\n }\n return result;\n}", "solution_cpp": "vector> threeSum(vector& nums) {\n sort(nums.begin(), nums.end());\n vector> result;\n for (int i = 0; i < nums.size() - 2; i++) {\n if (i > 0 && nums[i] == nums[i-1]) continue;\n int left = i + 1, right = nums.size() - 1;\n while (left < right) {\n int total = nums[i] + nums[left] + nums[right];\n if (total < 0) left++;\n else if (total > 0) right--;\n else {\n result.push_back({nums[i], nums[left], nums[right]});\n while (left < right && nums[left] == nums[left+1]) left++;\n while (left < right && nums[right] == nums[right-1]) right--;\n left++; right--;\n }\n }\n }\n return result;\n}", "test_cases": ["nums=[-1,0,1,2,-1,-4] -> [[-1,-1,2],[-1,0,1]]"], "key_points": ["排序+双指针", "去重是关键"], "tags": ["two-pointers", "medium", "Google", "Amazon"]} {"problem_id": "algo_01797", "original_id": "container-water", "title": "盛最多水的容器", "category": "two-pointers", "difficulty": "medium", "companies": ["Google", "Uber"], "description": "给定一个长度为 n 的整数数组 height,找出其中的两条线,使得它们与 x 轴共同构成的容器可以容纳最多的水。", "solution_python": "def maxArea(height):\n left, right = 0, len(height) - 1\n max_area = 0\n while left < right:\n h = min(height[left], height[right])\n max_area = max(max_area, h * (right - left))\n if height[left] < height[right]: left += 1\n else: right -= 1\n return max_area", "solution_java": "public int maxArea(int[] height) {\n int left = 0, right = height.length - 1, maxArea = 0;\n while (left < right) {\n int h = Math.min(height[left], height[right]);\n maxArea = Math.max(maxArea, h * (right - left));\n if (height[left] < height[right]) left++;\n else right--;\n }\n return maxArea;\n}", "solution_cpp": "int maxArea(vector& height) {\n int left = 0, right = height.size() - 1, maxArea = 0;\n while (left < right) {\n int h = min(height[left], height[right]);\n maxArea = max(maxArea, h * (right - left));\n if (height[left] < height[right]) left++;\n else right--;\n }\n return maxArea;\n}", "test_cases": ["height=[1,8,6,2,5,4,8,3,7] -> 49"], "key_points": ["移动短边指针", "面积=min(h1,h2)*width"], "tags": ["two-pointers", "medium", "Google", "Uber"]} {"problem_id": "algo_01798", "original_id": "min-stack", "title": "最小栈", "category": "stack", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "设计一个支持 push,pop,top 操作,并能在常数时间内检索到最小元素的栈。", "solution_python": "class MinStack:\n def __init__(self):\n self.stack = []\n self.min_stack = []\n def push(self, val):\n self.stack.append(val)\n self.min_stack.append(min(val, self.min_stack[-1] if self.min_stack else val))\n def pop(self):\n self.stack.pop(); self.min_stack.pop()\n def top(self): return self.stack[-1]\n def getMin(self): return self.min_stack[-1]", "solution_java": "class MinStack {\n Stack stack = new Stack<>();\n Stack minStack = new Stack<>();\n public void push(int val) { stack.push(val); minStack.push(Math.min(val, minStack.isEmpty() ? val : minStack.peek())); }\n public void pop() { stack.pop(); minStack.pop(); }\n public int top() { return stack.peek(); }\n public int getMin() { return minStack.peek(); }\n}", "solution_cpp": "class MinStack {\n stack st, minSt;\npublic:\n void push(int val) { st.push(val); minSt.push(min(val, minSt.empty() ? val : minSt.top())); }\n void pop() { st.pop(); minSt.pop(); }\n int top() { return st.top(); }\n int getMin() { return minSt.top(); }\n};", "test_cases": ["push(-2), push(0), push(-3) -> getMin() returns -3"], "key_points": ["辅助栈记录最小值", "O(1)时间获取最小值"], "tags": ["stack", "medium", "Google", "Microsoft"]} {"problem_id": "algo_01799", "original_id": "lru-cache", "title": "LRU缓存", "category": "design", "difficulty": "hard", "companies": ["Google", "Amazon"], "description": "设计和实现一个 LRU(最近最少使用)缓存机制。", "solution_python": "class LRUCache:\n def __init__(self, capacity):\n self.capacity = capacity\n self.cache = {}\n self.order = []\n def get(self, key):\n if key not in self.cache: return -1\n self.order.remove(key); self.order.append(key)\n return self.cache[key]\n def put(self, key, value):\n if key in self.cache:\n self.order.remove(key)\n elif len(self.cache) >= self.capacity:\n del self.cache[self.order.pop(0)]\n self.cache[key] = value; self.order.append(key)", "solution_java": "class LRUCache {\n int capacity;\n LinkedHashMap cache = new LinkedHashMap<>();\n public LRUCache(int cap) { capacity = cap; }\n public int get(int key) { return cache.containsKey(key) ? cache.remove(key) : -1; }\n public void put(int key, int val) {\n if (cache.containsKey(key)) cache.remove(key);\n else if (cache.size() >= capacity) cache.remove(cache.keySet().iterator().next());\n cache.put(key, val);\n }\n}", "solution_cpp": "class LRUCache {\n int cap;\n list> dll;\n unordered_map>::iterator> cache;\npublic:\n LRUCache(int capacity) : cap(capacity) {}\n int get(int key) {\n auto it = cache.find(key);\n if (it == cache.end()) return -1;\n dll.splice(dll.end(), dll, it->second);\n return it->second->second;\n }\n void put(int key, int value) {\n auto it = cache.find(key);\n if (it != cache.end()) dll.erase(it->second);\n else if (cache.size() >= cap) { cache.erase(dll.front().first); dll.pop_front(); }\n dll.push_back({key, value});\n cache[key] = --dll.end();\n }\n};", "test_cases": ["put(1,1), put(2,2), get(1) -> 1"], "key_points": ["HashMap + 双向链表", "O(1)时间操作"], "tags": ["design", "hard", "Google", "Amazon"]} {"problem_id": "algo_01800", "original_id": "num-islands", "title": "岛屿数量", "category": "graph", "difficulty": "medium", "companies": ["Google", "Facebook"], "description": "给你一个由 '1'(陆地)和 '0'(水)组成的二维网格,请你计算网格中岛屿的数量。岛屿总是被水包围,且只能由水平或垂直方向相邻的陆地连接形成。", "solution_python": "def numIslands(grid):\n if not grid: return 0\n rows, cols = len(grid), len(grid[0])\n count = 0\n def dfs(r, c):\n if r < 0 or r >= rows or c < 0 or c >= cols or grid[r][c] != '1': return\n grid[r][c] = '0'\n dfs(r+1, c); dfs(r-1, c); dfs(r, c+1); dfs(r, c-1)\n for r in range(rows):\n for c in range(cols):\n if grid[r][c] == '1': count += 1; dfs(r, c)\n return count", "solution_java": "public int numIslands(char[][] grid) {\n if (grid.length == 0) return 0;\n int count = 0;\n for (int i = 0; i < grid.length; i++)\n for (int j = 0; j < grid[0].length; j++)\n if (grid[i][j] == '1') { count++; dfs(grid, i, j); }\n return count;\n}\nprivate void dfs(char[][] grid, int r, int c) {\n if (r < 0 || r >= grid.length || c < 0 || c >= grid[0].length || grid[r][c] != '1') return;\n grid[r][c] = '0';\n dfs(grid, r+1, c); dfs(grid, r-1, c); dfs(grid, r, c+1); dfs(grid, r, c-1);\n}", "solution_cpp": "int numIslands(vector>& grid) {\n if (grid.empty()) return 0;\n int count = 0;\n for (int i = 0; i < grid.size(); i++)\n for (int j = 0; j < grid[0].size(); j++)\n if (grid[i][j] == '1') { count++; dfs(grid, i, j); }\n return count;\n}\nvoid dfs(vector>& grid, int r, int c) {\n if (r < 0 || r >= grid.size() || c < 0 || c >= grid[0].size() || grid[r][c] != '1') return;\n grid[r][c] = '0';\n dfs(grid, r+1, c); dfs(grid, r-1, c); dfs(grid, r, c+1); dfs(grid, r, c-1);\n}", "test_cases": ["grid=[[1,1,1,1,0],[1,1,0,1,0],[1,1,0,0,0],[0,0,0,0,0]] -> 1"], "key_points": ["DFS/BFS遍历", "访问后标记为0避免重复"], "tags": ["graph", "medium", "Google", "Facebook"]} {"problem_id": "algo_01801", "original_id": "two-sum", "title": "两数之和", "category": "array", "difficulty": "easy", "companies": ["Amazon", "Google"], "description": "给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那两个整数,并返回他们的数组下标。", "solution_python": "def twoSum(nums, target):\n hashmap = {}\n for i, num in enumerate(nums):\n complement = target - num\n if complement in hashmap:\n return [hashmap[complement], i]\n hashmap[num] = i\n return []", "solution_java": "public int[] twoSum(int[] nums, int target) {\n Map map = new HashMap<>();\n for (int i = 0; i < nums.length; i++) {\n int complement = target - nums[i];\n if (map.containsKey(complement)) return new int[]{map.get(complement), i};\n map.put(nums[i], i);\n }\n return new int[]{};\n}", "solution_cpp": "vector twoSum(vector& nums, int target) {\n unordered_map m;\n for (int i = 0; i < nums.size(); i++) {\n if (m.count(target - nums[i])) return {m[target - nums[i]], i};\n m[nums[i]] = i;\n }\n return {};\n}", "test_cases": ["nums=[2,7,11,15], target=9 -> [0,1]", "nums=[3,2,4], target=6 -> [1,2]"], "key_points": ["哈希表一次遍历", "空间换时间"], "tags": ["array", "easy", "Amazon", "Google"]} {"problem_id": "algo_01802", "original_id": "merge-sorted", "title": "合并两个有序数组", "category": "array", "difficulty": "easy", "companies": ["Microsoft", "Uber"], "description": "给你两个按非递减顺序排列的整数数组 nums1 和 nums2,另有两个整数 m 和 n,分别表示 nums1 和 nums2 中的元素数目。请你合并 nums2 到 nums1 中。", "solution_python": "def merge(nums1, m, nums2, n):\n p1, p2, p = m-1, n-1, m+n-1\n while p1 >= 0 and p2 >= 0:\n if nums1[p1] > nums2[p2]: nums1[p] = nums1[p1]; p1 -= 1\n else: nums1[p] = nums2[p2]; p2 -= 1\n p -= 1\n while p2 >= 0: nums1[p] = nums2[p2]; p2 -= 1; p -= 1", "solution_java": "public void merge(int[] nums1, int m, int[] nums2, int n) {\n int p1 = m-1, p2 = n-1, p = m+n-1;\n while (p1 >= 0 && p2 >= 0) {\n nums1[p--] = nums1[p1] > nums2[p2] ? nums1[p1--] : nums2[p2--];\n }\n while (p2 >= 0) nums1[p--] = nums2[p2--];\n}", "solution_cpp": "void merge(vector& nums1, int m, vector& nums2, int n) {\n int p1 = m-1, p2 = n-1, p = m+n-1;\n while (p1 >= 0 && p2 >= 0) nums1[p--] = nums1[p1] > nums2[p2] ? nums1[p1--] : nums2[p2--];\n while (p2 >= 0) nums1[p--] = nums2[p2--];\n}", "test_cases": ["nums1=[1,2,3], m=3, nums2=[2,5,6], n=3 -> [1,2,2,3,5,6]", "nums1=[], m=0, nums2=[1], n=1 -> [1]"], "key_points": ["从后往前合并", "三指针技巧"], "tags": ["array", "easy", "Microsoft", "Uber"]} {"problem_id": "algo_01803", "original_id": "max-subarray", "title": "最大子数组和", "category": "array", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "给你一个整数数组 nums ,请你找出一个具有最大和的连续子数组,返回其最大和。", "solution_python": "def maxSubArray(nums):\n max_sum = current = nums[0]\n for num in nums[1:]:\n current = max(num, current + num)\n max_sum = max(max_sum, current)\n return max_sum", "solution_java": "public int maxSubArray(int[] nums) {\n int maxSum = nums[0], curr = nums[0];\n for (int i = 1; i < nums.length; i++) {\n curr = Math.max(nums[i], curr + nums[i]);\n maxSum = Math.max(maxSum, curr);\n }\n return maxSum;\n}", "solution_cpp": "int maxSubArray(vector& nums) {\n int maxSum = nums[0], curr = nums[0];\n for (int i = 1; i < nums.size(); i++) {\n curr = max(nums[i], curr + nums[i]);\n maxSum = max(maxSum, curr);\n }\n return maxSum;\n}", "test_cases": ["nums=[-2,1,-3,4,-1,2,1,-5,4] -> 6", "nums=[1] -> 1"], "key_points": ["Kadane算法", "动态规划基础题"], "tags": ["array", "medium", "Google", "Microsoft"]} {"problem_id": "algo_01804", "original_id": "valid-parentheses", "title": "有效的括号", "category": "string", "difficulty": "easy", "companies": ["Google", "Uber"], "description": "给定一个只包括 '(',')','{','}','[',']' 的字符串 s,判断字符串是否有效。", "solution_python": "def isValid(s):\n stack = []\n mapping = {')': '(', ']': '[', '}': '{'}\n for c in s:\n if c in mapping:\n if not stack or stack[-1] != mapping[c]: return False\n stack.pop()\n else: stack.append(c)\n return not stack", "solution_java": "public boolean isValid(String s) {\n Stack stack = new Stack<>();\n Map map = Map.of(')', '(', ']', '[', '}', '{');\n for (char c : s.toCharArray()) {\n if (map.containsValue(c)) stack.push(c);\n else if (!stack.isEmpty() && stack.pop() != map.get(c)) return false;\n }\n return stack.isEmpty();\n}", "solution_cpp": "bool isValid(string s) {\n stack st;\n unordered_map m = {{')','('},{']','['},{'}','{'}};\n for (char c : s) {\n if (m.find(c) == m.end()) st.push(c);\n else if (st.empty() || st.top() != m[c]) return false;\n else st.pop();\n }\n return st.empty();\n}", "test_cases": ["s=\"()\" -> true", "s=\"()[]{}\" -> true", "s=\"(]\" -> false"], "key_points": ["栈匹配法", "注意空栈边界"], "tags": ["string", "easy", "Google", "Uber"]} {"problem_id": "algo_01805", "original_id": "longest-palindrome", "title": "最长回文子串", "category": "string", "difficulty": "medium", "companies": ["Google", "Amazon"], "description": "给你一个字符串 s,找到 s 中最长的回文子串。", "solution_python": "def longestPalindrome(s):\n def expand(l, r):\n while l >= 0 and r < len(s) and s[l] == s[r]: l -= 1; r += 1\n return l + 1, r - 1\n start = end = 0\n for i in range(len(s)):\n l1, r1 = expand(i, i)\n l2, r2 = expand(i, i + 1)\n if r1 - l1 > end - start: start, end = l1, r1\n if r2 - l2 > end - start: start, end = l2, r2\n return s[start:end+1]", "solution_java": "public String longestPalindrome(String s) {\n int start = 0, end = 0;\n for (int i = 0; i < s.length(); i++) {\n int len1 = expand(s, i, i), len2 = expand(s, i, i+1);\n int len = Math.max(len1, len2);\n if (len > end - start) { start = i - (len-1)/2; end = i + len/2; }\n }\n return s.substring(start, end + 1);\n}\nprivate int expand(String s, int l, int r) {\n while (l >= 0 && r < s.length() && s.charAt(l) == s.charAt(r)) { l--; r++; }\n return r - l - 1;\n}", "solution_cpp": "string longestPalindrome(string s) {\n int start = 0, end = 0;\n for (int i = 0; i < s.size(); i++) {\n int len1 = expand(s, i, i), len2 = expand(s, i, i+1);\n if (max(len1, len2) > end - start) { start = i - (max(len1,len2)-1)/2; end = i + max(len1,len2)/2; }\n }\n return s.substr(start, end - start + 1);\n}", "test_cases": ["s=\"babad\" -> bab或aba", "s=\"cbbd\" -> bb"], "key_points": ["中心扩展法", "处理奇偶长度"], "tags": ["string", "medium", "Google", "Amazon"]} {"problem_id": "algo_01806", "original_id": "reverse-list", "title": "反转链表", "category": "linkedlist", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "给你单链表的头节点 head,请你反转链表,并返回反转后的链表。", "solution_python": "def reverseList(head):\n prev = None\n curr = head\n while curr:\n nxt = curr.next\n curr.next = prev\n prev = curr\n curr = nxt\n return prev", "solution_java": "public ListNode reverseList(ListNode head) {\n ListNode prev = null, curr = head;\n while (curr != null) {\n ListNode next = curr.next;\n curr.next = prev;\n prev = curr;\n curr = next;\n }\n return prev;\n}", "solution_cpp": "ListNode* reverseList(ListNode* head) {\n ListNode* prev = nullptr, *curr = head;\n while (curr) {\n ListNode* next = curr->next;\n curr->next = prev;\n prev = curr;\n curr = next;\n }\n return prev;\n}", "test_cases": ["head=[1,2,3,4,5] -> [5,4,3,2,1]", "head=[1,2] -> [2,1]"], "key_points": ["迭代法 O(1)空间", "递归法 O(n)空间"], "tags": ["linkedlist", "medium", "Google", "Microsoft"]} {"problem_id": "algo_01807", "original_id": "middle-node", "title": "链表的中间结点", "category": "linkedlist", "difficulty": "easy", "companies": ["Amazon", "Facebook"], "description": "给你单链表的头节点 head,请你找出并返回链表的中间结点。如果有两个中间结点,则返回第二个中间结点。", "solution_python": "def middleNode(head):\n slow = fast = head\n while fast and fast.next:\n slow = slow.next\n fast = fast.next.next\n return slow", "solution_java": "public ListNode middleNode(ListNode head) {\n ListNode slow = head, fast = head;\n while (fast != null && fast.next != null) {\n slow = slow.next;\n fast = fast.next.next;\n }\n return slow;\n}", "solution_cpp": "ListNode* middleNode(ListNode* head) {\n ListNode* slow = head, *fast = head;\n while (fast && fast->next) { slow = slow->next; fast = fast->next->next; }\n return slow;\n}", "test_cases": ["head=[1,2,3,4,5] -> 3", "head=[1,2,3,4,5,6] -> 4"], "key_points": ["快慢指针", "O(n)时间O(1)空间"], "tags": ["linkedlist", "easy", "Amazon", "Facebook"]} {"problem_id": "algo_01808", "original_id": "max-depth", "title": "二叉树的最大深度", "category": "tree", "difficulty": "easy", "companies": ["Microsoft", "Apple"], "description": "给定一个二叉树 root,返回其最大深度。", "solution_python": "def maxDepth(root):\n if not root: return 0\n return max(maxDepth(root.left), maxDepth(root.right)) + 1", "solution_java": "public int maxDepth(TreeNode root) {\n if (root == null) return 0;\n return Math.max(maxDepth(root.left), maxDepth(root.right)) + 1;\n}", "solution_cpp": "int maxDepth(TreeNode* root) {\n if (!root) return 0;\n return max(maxDepth(root->left), maxDepth(root->right)) + 1;\n}", "test_cases": ["root=[3,9,20,null,null,15,7] -> 3", "root=[1,null,2] -> 2"], "key_points": ["DFS递归", "层序遍历也可"], "tags": ["tree", "easy", "Microsoft", "Apple"]} {"problem_id": "algo_01809", "original_id": "inorder-traversal", "title": "二叉树的中序遍历", "category": "tree", "difficulty": "easy", "companies": ["Google", "Microsoft"], "description": "给定一个二叉树的根节点 root,返回它的中序遍历结果。", "solution_python": "def inorderTraversal(root):\n result = []\n def dfs(node):\n if node:\n dfs(node.left)\n result.append(node.val)\n dfs(node.right)\n dfs(root)\n return result", "solution_java": "public List inorderTraversal(TreeNode root) {\n List res = new ArrayList<>();\n dfs(root, res);\n return res;\n}\nprivate void dfs(TreeNode node, List res) {\n if (node == null) return;\n dfs(node.left, res); res.add(node.val); dfs(node.right, res);\n}", "solution_cpp": "vector inorderTraversal(TreeNode* root) {\n vector res;\n dfs(root, res);\n return res;\n}\nvoid dfs(TreeNode* node, vector& res) {\n if (!node) return;\n dfs(node->left, res); res.push_back(node->val); dfs(node->right, res);\n}", "test_cases": ["root=[1,null,2,3] -> [1,3,2]", "root=[] -> []"], "key_points": ["左-根-右顺序", "递归最简洁"], "tags": ["tree", "easy", "Google", "Microsoft"]} {"problem_id": "algo_01810", "original_id": "binary-search", "title": "二分查找", "category": "binarysearch", "difficulty": "easy", "companies": ["Google", "Amazon"], "description": "给定一个 n 个元素有序的(升序)整型数组 nums 和一个目标值 target,写一个函数搜索 nums 中的 target,如果目标值存在返回下标,否则返回 -1。", "solution_python": "def search(nums, target):\n left, right = 0, len(nums) - 1\n while left <= right:\n mid = (left + right) // 2\n if nums[mid] == target: return mid\n elif nums[mid] < target: left = mid + 1\n else: right = mid - 1\n return -1", "solution_java": "public int search(int[] nums, int target) {\n int left = 0, right = nums.length - 1;\n while (left <= right) {\n int mid = left + (right - left) / 2;\n if (nums[mid] == target) return mid;\n else if (nums[mid] < target) left = mid + 1;\n else right = mid - 1;\n }\n return -1;\n}", "solution_cpp": "int search(vector& nums, int target) {\n int left = 0, right = nums.size() - 1;\n while (left <= right) {\n int mid = left + (right - left) / 2;\n if (nums[mid] == target) return mid;\n else if (nums[mid] < target) left = mid + 1;\n else right = mid - 1;\n }\n return -1;\n}", "test_cases": ["nums=[-1,0,3,5,9,12], target=9 -> 4", "nums=[-1,0,3,5,9,12], target=2 -> -1"], "key_points": ["标准模板", "注意防溢出写法"], "tags": ["binarysearch", "easy", "Google", "Amazon"]} {"problem_id": "algo_01811", "original_id": "climbing-stairs", "title": "爬楼梯", "category": "dp", "difficulty": "easy", "companies": ["Amazon", "Google"], "description": "假设你正在爬楼梯。需要 n 阶你才能到达楼顶。每次你可以爬 1 或 2 个台阶。你有多少种不同的方法可以爬到楼顶?", "solution_python": "def climbStairs(n):\n if n <= 2: return n\n a, b = 1, 2\n for _ in range(3, n+1):\n a, b = b, a + b\n return b", "solution_java": "public int climbStairs(int n) {\n if (n <= 2) return n;\n int a = 1, b = 2;\n for (int i = 3; i <= n; i++) { int temp = a + b; a = b; b = temp; }\n return b;\n}", "solution_cpp": "int climbStairs(int n) {\n if (n <= 2) return n;\n int a = 1, b = 2;\n for (int i = 3; i <= n; i++) { int temp = a + b; a = b; b = temp; }\n return b;\n}", "test_cases": ["n=2 -> 2", "n=3 -> 3", "n=5 -> 8"], "key_points": ["斐波那契数列", "滚动数组优化空间"], "tags": ["dp", "easy", "Amazon", "Google"]} {"problem_id": "algo_01812", "original_id": "coin-change", "title": "零钱兑换", "category": "dp", "difficulty": "medium", "companies": ["Google", "Amazon"], "description": "给你一个整数数组 coins 表示不同面额的硬币,以及一个整数 amount 表示总金额。计算并返回可以凑成总金额所需的最少的硬币个数。如果没有任何一种硬币组合能组成总金额,返回 -1。", "solution_python": "def coinChange(coins, amount):\n dp = [float('inf')] * (amount + 1)\n dp[0] = 0\n for coin in coins:\n for x in range(coin, amount + 1):\n dp[x] = min(dp[x], dp[x - coin] + 1)\n return dp[amount] if dp[amount] != float('inf') else -1", "solution_java": "public int coinChange(int[] coins, int amount) {\n int[] dp = new int[amount + 1];\n Arrays.fill(dp, amount + 1);\n dp[0] = 0;\n for (int coin : coins) {\n for (int x = coin; x <= amount; x++) {\n dp[x] = Math.min(dp[x], dp[x - coin] + 1);\n }\n }\n return dp[amount] > amount ? -1 : dp[amount];\n}", "solution_cpp": "int coinChange(vector& coins, int amount) {\n vector dp(amount + 1, amount + 1);\n dp[0] = 0;\n for (int coin : coins) {\n for (int x = coin; x <= amount; x++) {\n dp[x] = min(dp[x], dp[x - coin] + 1);\n }\n }\n return dp[amount] > amount ? -1 : dp[amount];\n}", "test_cases": ["coins=[1,2,5], amount=11 -> 3", "coins=[2], amount=3 -> -1"], "key_points": ["完全背包问题", "dp[x] = min(dp[x-coin]+1)"], "tags": ["dp", "medium", "Google", "Amazon"]} {"problem_id": "algo_01813", "original_id": "subsets", "title": "子集", "category": "backtracking", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "给你一个整数数组 nums ,数组中的元素 互不相同 。返回该数组所有可能的子集(幂集)。", "solution_python": "def subsets(nums):\n result = []\n def backtrack(start, path):\n result.append(path[:])\n for i in range(start, len(nums)):\n path.append(nums[i])\n backtrack(i + 1, path)\n path.pop()\n backtrack(0, [])\n return result", "solution_java": "public List> subsets(int[] nums) {\n List> result = new ArrayList<>();\n backtrack(nums, 0, new ArrayList<>(), result);\n return result;\n}\nprivate void backtrack(int[] nums, int start, List path, List> result) {\n result.add(new ArrayList<>(path));\n for (int i = start; i < nums.length; i++) {\n path.add(nums[i]);\n backtrack(nums, i + 1, path, result);\n path.remove(path.size() - 1);\n }\n}", "solution_cpp": "vector> subsets(vector& nums) {\n vector> result;\n vector path;\n backtrack(nums, 0, path, result);\n return result;\n}\nvoid backtrack(vector& nums, int start, vector& path, vector>& result) {\n result.push_back(path);\n for (int i = start; i < nums.size(); i++) {\n path.push_back(nums[i]);\n backtrack(nums, i + 1, path, result);\n path.pop_back();\n }\n}", "test_cases": ["nums=[1,2,3] -> [[],[1],[2],[1,2],[3],[1,3],[2,3],[1,2,3]]"], "key_points": ["选或不选", "DFS遍历子集树"], "tags": ["backtracking", "medium", "Google", "Microsoft"]} {"problem_id": "algo_01814", "original_id": "permutations", "title": "全排列", "category": "backtracking", "difficulty": "medium", "companies": ["Google", "Facebook"], "description": "给定一个不含重复数字的数组 nums,返回其所有可能的全排列。", "solution_python": "def permute(nums):\n result = []\n def backtrack(path, used):\n if len(path) == len(nums):\n result.append(path[:])\n return\n for i in range(len(nums)):\n if used[i]: continue\n used[i] = True\n path.append(nums[i])\n backtrack(path, used)\n path.pop()\n used[i] = False\n backtrack([], [False]*len(nums))\n return result", "solution_java": "public List> permute(int[] nums) {\n List> result = new ArrayList<>();\n boolean[] used = new boolean[nums.length];\n backtrack(nums, used, new ArrayList<>(), result);\n return result;\n}\nprivate void backtrack(int[] nums, boolean[] used, List path, List> result) {\n if (path.size() == nums.length) { result.add(new ArrayList<>(path)); return; }\n for (int i = 0; i < nums.length; i++) {\n if (used[i]) continue;\n used[i] = true;\n path.add(nums[i]);\n backtrack(nums, used, path, result);\n path.remove(path.size() - 1);\n used[i] = false;\n }\n}", "solution_cpp": "vector> permute(vector& nums) {\n vector> result;\n vector used(nums.size(), false);\n vector path;\n backtrack(nums, used, path, result);\n return result;\n}\nvoid backtrack(vector& nums, vector& used, vector& path, vector>& result) {\n if (path.size() == nums.size()) { result.push_back(path); return; }\n for (int i = 0; i < nums.size(); i++) {\n if (used[i]) continue;\n used[i] = true;\n path.push_back(nums[i]);\n backtrack(nums, used, path, result);\n path.pop_back();\n used[i] = false;\n }\n}", "test_cases": ["nums=[1,2,3] -> [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]"], "key_points": ["标记已使用元素", "回溯经典模板"], "tags": ["backtracking", "medium", "Google", "Facebook"]} {"problem_id": "algo_01815", "original_id": "top-k-frequent", "title": "前K个高频元素", "category": "heap", "difficulty": "medium", "companies": ["Amazon", "Facebook"], "description": "给你一个整数数组 nums 和一个整数 k,请你返回其中出现频率前 k 高的元素。", "solution_python": "import heapq\nfrom collections import Counter\ndef topKFrequent(nums, k):\n count = Counter(nums)\n heap = []\n for num, freq in count.items():\n heapq.heappush(heap, (freq, num))\n if len(heap) > k: heapq.heappop(heap)\n return [num for freq, num in heap]", "solution_java": "public int[] topKFrequent(int[] nums, int k) {\n Map count = new HashMap<>();\n for (int n : nums) count.put(n, count.getOrDefault(n, 0) + 1);\n PriorityQueue> heap = \n new PriorityQueue<>((a, b) -> a.getValue() - b.getValue());\n for (Map.Entry e : count.entrySet()) {\n heap.offer(e);\n if (heap.size() > k) heap.poll();\n }\n int[] res = new int[k];\n for (int i = k - 1; i >= 0; i--) res[i] = heap.poll().getKey();\n return res;\n}", "solution_cpp": "vector topKFrequent(vector& nums, int k) {\n unordered_map count;\n for (int n : nums) count[n]++;\n priority_queue, vector>, greater>> heap;\n for (auto& [num, freq] : count) {\n heap.push({freq, num});\n if (heap.size() > k) heap.pop();\n }\n vector res;\n while (!heap.empty()) { res.push_back(heap.top().second); heap.pop(); }\n reverse(res.begin(), res.end());\n return res;\n}", "test_cases": ["nums=[1,1,1,2,2,3], k=2 -> [1,2]", "nums=[1], k=1 -> [1]"], "key_points": ["小顶堆保持大小k", "时间复杂度O(nlogk)"], "tags": ["heap", "medium", "Amazon", "Facebook"]} {"problem_id": "algo_01816", "original_id": "3sum", "title": "三数之和", "category": "two-pointers", "difficulty": "medium", "companies": ["Google", "Amazon"], "description": "给你一个整数数组 nums,判断是否存在三元组满足和为0,返回所有不重复的三元组。", "solution_python": "def threeSum(nums):\n nums.sort()\n result = []\n for i in range(len(nums) - 2):\n if i > 0 and nums[i] == nums[i-1]: continue\n left, right = i + 1, len(nums) - 1\n while left < right:\n total = nums[i] + nums[left] + nums[right]\n if total < 0: left += 1\n elif total > 0: right -= 1\n else:\n result.append([nums[i], nums[left], nums[right]])\n while left < right and nums[left] == nums[left+1]: left += 1\n while left < right and nums[right] == nums[right-1]: right -= 1\n left += 1; right -= 1\n return result", "solution_java": "public List> threeSum(int[] nums) {\n Arrays.sort(nums);\n List> result = new ArrayList<>();\n for (int i = 0; i < nums.length - 2; i++) {\n if (i > 0 && nums[i] == nums[i-1]) continue;\n int left = i + 1, right = nums.length - 1;\n while (left < right) {\n int total = nums[i] + nums[left] + nums[right];\n if (total < 0) left++;\n else if (total > 0) right--;\n else {\n result.add(Arrays.asList(nums[i], nums[left], nums[right]));\n while (left < right && nums[left] == nums[left+1]) left++;\n while (left < right && nums[right] == nums[right-1]) right--;\n left++; right--;\n }\n }\n }\n return result;\n}", "solution_cpp": "vector> threeSum(vector& nums) {\n sort(nums.begin(), nums.end());\n vector> result;\n for (int i = 0; i < nums.size() - 2; i++) {\n if (i > 0 && nums[i] == nums[i-1]) continue;\n int left = i + 1, right = nums.size() - 1;\n while (left < right) {\n int total = nums[i] + nums[left] + nums[right];\n if (total < 0) left++;\n else if (total > 0) right--;\n else {\n result.push_back({nums[i], nums[left], nums[right]});\n while (left < right && nums[left] == nums[left+1]) left++;\n while (left < right && nums[right] == nums[right-1]) right--;\n left++; right--;\n }\n }\n }\n return result;\n}", "test_cases": ["nums=[-1,0,1,2,-1,-4] -> [[-1,-1,2],[-1,0,1]]"], "key_points": ["排序+双指针", "去重是关键"], "tags": ["two-pointers", "medium", "Google", "Amazon"]} {"problem_id": "algo_01817", "original_id": "container-water", "title": "盛最多水的容器", "category": "two-pointers", "difficulty": "medium", "companies": ["Google", "Uber"], "description": "给定一个长度为 n 的整数数组 height,找出其中的两条线,使得它们与 x 轴共同构成的容器可以容纳最多的水。", "solution_python": "def maxArea(height):\n left, right = 0, len(height) - 1\n max_area = 0\n while left < right:\n h = min(height[left], height[right])\n max_area = max(max_area, h * (right - left))\n if height[left] < height[right]: left += 1\n else: right -= 1\n return max_area", "solution_java": "public int maxArea(int[] height) {\n int left = 0, right = height.length - 1, maxArea = 0;\n while (left < right) {\n int h = Math.min(height[left], height[right]);\n maxArea = Math.max(maxArea, h * (right - left));\n if (height[left] < height[right]) left++;\n else right--;\n }\n return maxArea;\n}", "solution_cpp": "int maxArea(vector& height) {\n int left = 0, right = height.size() - 1, maxArea = 0;\n while (left < right) {\n int h = min(height[left], height[right]);\n maxArea = max(maxArea, h * (right - left));\n if (height[left] < height[right]) left++;\n else right--;\n }\n return maxArea;\n}", "test_cases": ["height=[1,8,6,2,5,4,8,3,7] -> 49"], "key_points": ["移动短边指针", "面积=min(h1,h2)*width"], "tags": ["two-pointers", "medium", "Google", "Uber"]} {"problem_id": "algo_01818", "original_id": "min-stack", "title": "最小栈", "category": "stack", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "设计一个支持 push,pop,top 操作,并能在常数时间内检索到最小元素的栈。", "solution_python": "class MinStack:\n def __init__(self):\n self.stack = []\n self.min_stack = []\n def push(self, val):\n self.stack.append(val)\n self.min_stack.append(min(val, self.min_stack[-1] if self.min_stack else val))\n def pop(self):\n self.stack.pop(); self.min_stack.pop()\n def top(self): return self.stack[-1]\n def getMin(self): return self.min_stack[-1]", "solution_java": "class MinStack {\n Stack stack = new Stack<>();\n Stack minStack = new Stack<>();\n public void push(int val) { stack.push(val); minStack.push(Math.min(val, minStack.isEmpty() ? val : minStack.peek())); }\n public void pop() { stack.pop(); minStack.pop(); }\n public int top() { return stack.peek(); }\n public int getMin() { return minStack.peek(); }\n}", "solution_cpp": "class MinStack {\n stack st, minSt;\npublic:\n void push(int val) { st.push(val); minSt.push(min(val, minSt.empty() ? val : minSt.top())); }\n void pop() { st.pop(); minSt.pop(); }\n int top() { return st.top(); }\n int getMin() { return minSt.top(); }\n};", "test_cases": ["push(-2), push(0), push(-3) -> getMin() returns -3"], "key_points": ["辅助栈记录最小值", "O(1)时间获取最小值"], "tags": ["stack", "medium", "Google", "Microsoft"]} {"problem_id": "algo_01819", "original_id": "lru-cache", "title": "LRU缓存", "category": "design", "difficulty": "hard", "companies": ["Google", "Amazon"], "description": "设计和实现一个 LRU(最近最少使用)缓存机制。", "solution_python": "class LRUCache:\n def __init__(self, capacity):\n self.capacity = capacity\n self.cache = {}\n self.order = []\n def get(self, key):\n if key not in self.cache: return -1\n self.order.remove(key); self.order.append(key)\n return self.cache[key]\n def put(self, key, value):\n if key in self.cache:\n self.order.remove(key)\n elif len(self.cache) >= self.capacity:\n del self.cache[self.order.pop(0)]\n self.cache[key] = value; self.order.append(key)", "solution_java": "class LRUCache {\n int capacity;\n LinkedHashMap cache = new LinkedHashMap<>();\n public LRUCache(int cap) { capacity = cap; }\n public int get(int key) { return cache.containsKey(key) ? cache.remove(key) : -1; }\n public void put(int key, int val) {\n if (cache.containsKey(key)) cache.remove(key);\n else if (cache.size() >= capacity) cache.remove(cache.keySet().iterator().next());\n cache.put(key, val);\n }\n}", "solution_cpp": "class LRUCache {\n int cap;\n list> dll;\n unordered_map>::iterator> cache;\npublic:\n LRUCache(int capacity) : cap(capacity) {}\n int get(int key) {\n auto it = cache.find(key);\n if (it == cache.end()) return -1;\n dll.splice(dll.end(), dll, it->second);\n return it->second->second;\n }\n void put(int key, int value) {\n auto it = cache.find(key);\n if (it != cache.end()) dll.erase(it->second);\n else if (cache.size() >= cap) { cache.erase(dll.front().first); dll.pop_front(); }\n dll.push_back({key, value});\n cache[key] = --dll.end();\n }\n};", "test_cases": ["put(1,1), put(2,2), get(1) -> 1"], "key_points": ["HashMap + 双向链表", "O(1)时间操作"], "tags": ["design", "hard", "Google", "Amazon"]} {"problem_id": "algo_01820", "original_id": "num-islands", "title": "岛屿数量", "category": "graph", "difficulty": "medium", "companies": ["Google", "Facebook"], "description": "给你一个由 '1'(陆地)和 '0'(水)组成的二维网格,请你计算网格中岛屿的数量。岛屿总是被水包围,且只能由水平或垂直方向相邻的陆地连接形成。", "solution_python": "def numIslands(grid):\n if not grid: return 0\n rows, cols = len(grid), len(grid[0])\n count = 0\n def dfs(r, c):\n if r < 0 or r >= rows or c < 0 or c >= cols or grid[r][c] != '1': return\n grid[r][c] = '0'\n dfs(r+1, c); dfs(r-1, c); dfs(r, c+1); dfs(r, c-1)\n for r in range(rows):\n for c in range(cols):\n if grid[r][c] == '1': count += 1; dfs(r, c)\n return count", "solution_java": "public int numIslands(char[][] grid) {\n if (grid.length == 0) return 0;\n int count = 0;\n for (int i = 0; i < grid.length; i++)\n for (int j = 0; j < grid[0].length; j++)\n if (grid[i][j] == '1') { count++; dfs(grid, i, j); }\n return count;\n}\nprivate void dfs(char[][] grid, int r, int c) {\n if (r < 0 || r >= grid.length || c < 0 || c >= grid[0].length || grid[r][c] != '1') return;\n grid[r][c] = '0';\n dfs(grid, r+1, c); dfs(grid, r-1, c); dfs(grid, r, c+1); dfs(grid, r, c-1);\n}", "solution_cpp": "int numIslands(vector>& grid) {\n if (grid.empty()) return 0;\n int count = 0;\n for (int i = 0; i < grid.size(); i++)\n for (int j = 0; j < grid[0].size(); j++)\n if (grid[i][j] == '1') { count++; dfs(grid, i, j); }\n return count;\n}\nvoid dfs(vector>& grid, int r, int c) {\n if (r < 0 || r >= grid.size() || c < 0 || c >= grid[0].size() || grid[r][c] != '1') return;\n grid[r][c] = '0';\n dfs(grid, r+1, c); dfs(grid, r-1, c); dfs(grid, r, c+1); dfs(grid, r, c-1);\n}", "test_cases": ["grid=[[1,1,1,1,0],[1,1,0,1,0],[1,1,0,0,0],[0,0,0,0,0]] -> 1"], "key_points": ["DFS/BFS遍历", "访问后标记为0避免重复"], "tags": ["graph", "medium", "Google", "Facebook"]} {"problem_id": "algo_01821", "original_id": "two-sum", "title": "两数之和", "category": "array", "difficulty": "easy", "companies": ["Amazon", "Google"], "description": "给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那两个整数,并返回他们的数组下标。", "solution_python": "def twoSum(nums, target):\n hashmap = {}\n for i, num in enumerate(nums):\n complement = target - num\n if complement in hashmap:\n return [hashmap[complement], i]\n hashmap[num] = i\n return []", "solution_java": "public int[] twoSum(int[] nums, int target) {\n Map map = new HashMap<>();\n for (int i = 0; i < nums.length; i++) {\n int complement = target - nums[i];\n if (map.containsKey(complement)) return new int[]{map.get(complement), i};\n map.put(nums[i], i);\n }\n return new int[]{};\n}", "solution_cpp": "vector twoSum(vector& nums, int target) {\n unordered_map m;\n for (int i = 0; i < nums.size(); i++) {\n if (m.count(target - nums[i])) return {m[target - nums[i]], i};\n m[nums[i]] = i;\n }\n return {};\n}", "test_cases": ["nums=[2,7,11,15], target=9 -> [0,1]", "nums=[3,2,4], target=6 -> [1,2]"], "key_points": ["哈希表一次遍历", "空间换时间"], "tags": ["array", "easy", "Amazon", "Google"]} {"problem_id": "algo_01822", "original_id": "merge-sorted", "title": "合并两个有序数组", "category": "array", "difficulty": "easy", "companies": ["Microsoft", "Uber"], "description": "给你两个按非递减顺序排列的整数数组 nums1 和 nums2,另有两个整数 m 和 n,分别表示 nums1 和 nums2 中的元素数目。请你合并 nums2 到 nums1 中。", "solution_python": "def merge(nums1, m, nums2, n):\n p1, p2, p = m-1, n-1, m+n-1\n while p1 >= 0 and p2 >= 0:\n if nums1[p1] > nums2[p2]: nums1[p] = nums1[p1]; p1 -= 1\n else: nums1[p] = nums2[p2]; p2 -= 1\n p -= 1\n while p2 >= 0: nums1[p] = nums2[p2]; p2 -= 1; p -= 1", "solution_java": "public void merge(int[] nums1, int m, int[] nums2, int n) {\n int p1 = m-1, p2 = n-1, p = m+n-1;\n while (p1 >= 0 && p2 >= 0) {\n nums1[p--] = nums1[p1] > nums2[p2] ? nums1[p1--] : nums2[p2--];\n }\n while (p2 >= 0) nums1[p--] = nums2[p2--];\n}", "solution_cpp": "void merge(vector& nums1, int m, vector& nums2, int n) {\n int p1 = m-1, p2 = n-1, p = m+n-1;\n while (p1 >= 0 && p2 >= 0) nums1[p--] = nums1[p1] > nums2[p2] ? nums1[p1--] : nums2[p2--];\n while (p2 >= 0) nums1[p--] = nums2[p2--];\n}", "test_cases": ["nums1=[1,2,3], m=3, nums2=[2,5,6], n=3 -> [1,2,2,3,5,6]", "nums1=[], m=0, nums2=[1], n=1 -> [1]"], "key_points": ["从后往前合并", "三指针技巧"], "tags": ["array", "easy", "Microsoft", "Uber"]} {"problem_id": "algo_01823", "original_id": "max-subarray", "title": "最大子数组和", "category": "array", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "给你一个整数数组 nums ,请你找出一个具有最大和的连续子数组,返回其最大和。", "solution_python": "def maxSubArray(nums):\n max_sum = current = nums[0]\n for num in nums[1:]:\n current = max(num, current + num)\n max_sum = max(max_sum, current)\n return max_sum", "solution_java": "public int maxSubArray(int[] nums) {\n int maxSum = nums[0], curr = nums[0];\n for (int i = 1; i < nums.length; i++) {\n curr = Math.max(nums[i], curr + nums[i]);\n maxSum = Math.max(maxSum, curr);\n }\n return maxSum;\n}", "solution_cpp": "int maxSubArray(vector& nums) {\n int maxSum = nums[0], curr = nums[0];\n for (int i = 1; i < nums.size(); i++) {\n curr = max(nums[i], curr + nums[i]);\n maxSum = max(maxSum, curr);\n }\n return maxSum;\n}", "test_cases": ["nums=[-2,1,-3,4,-1,2,1,-5,4] -> 6", "nums=[1] -> 1"], "key_points": ["Kadane算法", "动态规划基础题"], "tags": ["array", "medium", "Google", "Microsoft"]} {"problem_id": "algo_01824", "original_id": "valid-parentheses", "title": "有效的括号", "category": "string", "difficulty": "easy", "companies": ["Google", "Uber"], "description": "给定一个只包括 '(',')','{','}','[',']' 的字符串 s,判断字符串是否有效。", "solution_python": "def isValid(s):\n stack = []\n mapping = {')': '(', ']': '[', '}': '{'}\n for c in s:\n if c in mapping:\n if not stack or stack[-1] != mapping[c]: return False\n stack.pop()\n else: stack.append(c)\n return not stack", "solution_java": "public boolean isValid(String s) {\n Stack stack = new Stack<>();\n Map map = Map.of(')', '(', ']', '[', '}', '{');\n for (char c : s.toCharArray()) {\n if (map.containsValue(c)) stack.push(c);\n else if (!stack.isEmpty() && stack.pop() != map.get(c)) return false;\n }\n return stack.isEmpty();\n}", "solution_cpp": "bool isValid(string s) {\n stack st;\n unordered_map m = {{')','('},{']','['},{'}','{'}};\n for (char c : s) {\n if (m.find(c) == m.end()) st.push(c);\n else if (st.empty() || st.top() != m[c]) return false;\n else st.pop();\n }\n return st.empty();\n}", "test_cases": ["s=\"()\" -> true", "s=\"()[]{}\" -> true", "s=\"(]\" -> false"], "key_points": ["栈匹配法", "注意空栈边界"], "tags": ["string", "easy", "Google", "Uber"]} {"problem_id": "algo_01825", "original_id": "longest-palindrome", "title": "最长回文子串", "category": "string", "difficulty": "medium", "companies": ["Google", "Amazon"], "description": "给你一个字符串 s,找到 s 中最长的回文子串。", "solution_python": "def longestPalindrome(s):\n def expand(l, r):\n while l >= 0 and r < len(s) and s[l] == s[r]: l -= 1; r += 1\n return l + 1, r - 1\n start = end = 0\n for i in range(len(s)):\n l1, r1 = expand(i, i)\n l2, r2 = expand(i, i + 1)\n if r1 - l1 > end - start: start, end = l1, r1\n if r2 - l2 > end - start: start, end = l2, r2\n return s[start:end+1]", "solution_java": "public String longestPalindrome(String s) {\n int start = 0, end = 0;\n for (int i = 0; i < s.length(); i++) {\n int len1 = expand(s, i, i), len2 = expand(s, i, i+1);\n int len = Math.max(len1, len2);\n if (len > end - start) { start = i - (len-1)/2; end = i + len/2; }\n }\n return s.substring(start, end + 1);\n}\nprivate int expand(String s, int l, int r) {\n while (l >= 0 && r < s.length() && s.charAt(l) == s.charAt(r)) { l--; r++; }\n return r - l - 1;\n}", "solution_cpp": "string longestPalindrome(string s) {\n int start = 0, end = 0;\n for (int i = 0; i < s.size(); i++) {\n int len1 = expand(s, i, i), len2 = expand(s, i, i+1);\n if (max(len1, len2) > end - start) { start = i - (max(len1,len2)-1)/2; end = i + max(len1,len2)/2; }\n }\n return s.substr(start, end - start + 1);\n}", "test_cases": ["s=\"babad\" -> bab或aba", "s=\"cbbd\" -> bb"], "key_points": ["中心扩展法", "处理奇偶长度"], "tags": ["string", "medium", "Google", "Amazon"]} {"problem_id": "algo_01826", "original_id": "reverse-list", "title": "反转链表", "category": "linkedlist", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "给你单链表的头节点 head,请你反转链表,并返回反转后的链表。", "solution_python": "def reverseList(head):\n prev = None\n curr = head\n while curr:\n nxt = curr.next\n curr.next = prev\n prev = curr\n curr = nxt\n return prev", "solution_java": "public ListNode reverseList(ListNode head) {\n ListNode prev = null, curr = head;\n while (curr != null) {\n ListNode next = curr.next;\n curr.next = prev;\n prev = curr;\n curr = next;\n }\n return prev;\n}", "solution_cpp": "ListNode* reverseList(ListNode* head) {\n ListNode* prev = nullptr, *curr = head;\n while (curr) {\n ListNode* next = curr->next;\n curr->next = prev;\n prev = curr;\n curr = next;\n }\n return prev;\n}", "test_cases": ["head=[1,2,3,4,5] -> [5,4,3,2,1]", "head=[1,2] -> [2,1]"], "key_points": ["迭代法 O(1)空间", "递归法 O(n)空间"], "tags": ["linkedlist", "medium", "Google", "Microsoft"]} {"problem_id": "algo_01827", "original_id": "middle-node", "title": "链表的中间结点", "category": "linkedlist", "difficulty": "easy", "companies": ["Amazon", "Facebook"], "description": "给你单链表的头节点 head,请你找出并返回链表的中间结点。如果有两个中间结点,则返回第二个中间结点。", "solution_python": "def middleNode(head):\n slow = fast = head\n while fast and fast.next:\n slow = slow.next\n fast = fast.next.next\n return slow", "solution_java": "public ListNode middleNode(ListNode head) {\n ListNode slow = head, fast = head;\n while (fast != null && fast.next != null) {\n slow = slow.next;\n fast = fast.next.next;\n }\n return slow;\n}", "solution_cpp": "ListNode* middleNode(ListNode* head) {\n ListNode* slow = head, *fast = head;\n while (fast && fast->next) { slow = slow->next; fast = fast->next->next; }\n return slow;\n}", "test_cases": ["head=[1,2,3,4,5] -> 3", "head=[1,2,3,4,5,6] -> 4"], "key_points": ["快慢指针", "O(n)时间O(1)空间"], "tags": ["linkedlist", "easy", "Amazon", "Facebook"]} {"problem_id": "algo_01828", "original_id": "max-depth", "title": "二叉树的最大深度", "category": "tree", "difficulty": "easy", "companies": ["Microsoft", "Apple"], "description": "给定一个二叉树 root,返回其最大深度。", "solution_python": "def maxDepth(root):\n if not root: return 0\n return max(maxDepth(root.left), maxDepth(root.right)) + 1", "solution_java": "public int maxDepth(TreeNode root) {\n if (root == null) return 0;\n return Math.max(maxDepth(root.left), maxDepth(root.right)) + 1;\n}", "solution_cpp": "int maxDepth(TreeNode* root) {\n if (!root) return 0;\n return max(maxDepth(root->left), maxDepth(root->right)) + 1;\n}", "test_cases": ["root=[3,9,20,null,null,15,7] -> 3", "root=[1,null,2] -> 2"], "key_points": ["DFS递归", "层序遍历也可"], "tags": ["tree", "easy", "Microsoft", "Apple"]} {"problem_id": "algo_01829", "original_id": "inorder-traversal", "title": "二叉树的中序遍历", "category": "tree", "difficulty": "easy", "companies": ["Google", "Microsoft"], "description": "给定一个二叉树的根节点 root,返回它的中序遍历结果。", "solution_python": "def inorderTraversal(root):\n result = []\n def dfs(node):\n if node:\n dfs(node.left)\n result.append(node.val)\n dfs(node.right)\n dfs(root)\n return result", "solution_java": "public List inorderTraversal(TreeNode root) {\n List res = new ArrayList<>();\n dfs(root, res);\n return res;\n}\nprivate void dfs(TreeNode node, List res) {\n if (node == null) return;\n dfs(node.left, res); res.add(node.val); dfs(node.right, res);\n}", "solution_cpp": "vector inorderTraversal(TreeNode* root) {\n vector res;\n dfs(root, res);\n return res;\n}\nvoid dfs(TreeNode* node, vector& res) {\n if (!node) return;\n dfs(node->left, res); res.push_back(node->val); dfs(node->right, res);\n}", "test_cases": ["root=[1,null,2,3] -> [1,3,2]", "root=[] -> []"], "key_points": ["左-根-右顺序", "递归最简洁"], "tags": ["tree", "easy", "Google", "Microsoft"]} {"problem_id": "algo_01830", "original_id": "binary-search", "title": "二分查找", "category": "binarysearch", "difficulty": "easy", "companies": ["Google", "Amazon"], "description": "给定一个 n 个元素有序的(升序)整型数组 nums 和一个目标值 target,写一个函数搜索 nums 中的 target,如果目标值存在返回下标,否则返回 -1。", "solution_python": "def search(nums, target):\n left, right = 0, len(nums) - 1\n while left <= right:\n mid = (left + right) // 2\n if nums[mid] == target: return mid\n elif nums[mid] < target: left = mid + 1\n else: right = mid - 1\n return -1", "solution_java": "public int search(int[] nums, int target) {\n int left = 0, right = nums.length - 1;\n while (left <= right) {\n int mid = left + (right - left) / 2;\n if (nums[mid] == target) return mid;\n else if (nums[mid] < target) left = mid + 1;\n else right = mid - 1;\n }\n return -1;\n}", "solution_cpp": "int search(vector& nums, int target) {\n int left = 0, right = nums.size() - 1;\n while (left <= right) {\n int mid = left + (right - left) / 2;\n if (nums[mid] == target) return mid;\n else if (nums[mid] < target) left = mid + 1;\n else right = mid - 1;\n }\n return -1;\n}", "test_cases": ["nums=[-1,0,3,5,9,12], target=9 -> 4", "nums=[-1,0,3,5,9,12], target=2 -> -1"], "key_points": ["标准模板", "注意防溢出写法"], "tags": ["binarysearch", "easy", "Google", "Amazon"]} {"problem_id": "algo_01831", "original_id": "climbing-stairs", "title": "爬楼梯", "category": "dp", "difficulty": "easy", "companies": ["Amazon", "Google"], "description": "假设你正在爬楼梯。需要 n 阶你才能到达楼顶。每次你可以爬 1 或 2 个台阶。你有多少种不同的方法可以爬到楼顶?", "solution_python": "def climbStairs(n):\n if n <= 2: return n\n a, b = 1, 2\n for _ in range(3, n+1):\n a, b = b, a + b\n return b", "solution_java": "public int climbStairs(int n) {\n if (n <= 2) return n;\n int a = 1, b = 2;\n for (int i = 3; i <= n; i++) { int temp = a + b; a = b; b = temp; }\n return b;\n}", "solution_cpp": "int climbStairs(int n) {\n if (n <= 2) return n;\n int a = 1, b = 2;\n for (int i = 3; i <= n; i++) { int temp = a + b; a = b; b = temp; }\n return b;\n}", "test_cases": ["n=2 -> 2", "n=3 -> 3", "n=5 -> 8"], "key_points": ["斐波那契数列", "滚动数组优化空间"], "tags": ["dp", "easy", "Amazon", "Google"]} {"problem_id": "algo_01832", "original_id": "coin-change", "title": "零钱兑换", "category": "dp", "difficulty": "medium", "companies": ["Google", "Amazon"], "description": "给你一个整数数组 coins 表示不同面额的硬币,以及一个整数 amount 表示总金额。计算并返回可以凑成总金额所需的最少的硬币个数。如果没有任何一种硬币组合能组成总金额,返回 -1。", "solution_python": "def coinChange(coins, amount):\n dp = [float('inf')] * (amount + 1)\n dp[0] = 0\n for coin in coins:\n for x in range(coin, amount + 1):\n dp[x] = min(dp[x], dp[x - coin] + 1)\n return dp[amount] if dp[amount] != float('inf') else -1", "solution_java": "public int coinChange(int[] coins, int amount) {\n int[] dp = new int[amount + 1];\n Arrays.fill(dp, amount + 1);\n dp[0] = 0;\n for (int coin : coins) {\n for (int x = coin; x <= amount; x++) {\n dp[x] = Math.min(dp[x], dp[x - coin] + 1);\n }\n }\n return dp[amount] > amount ? -1 : dp[amount];\n}", "solution_cpp": "int coinChange(vector& coins, int amount) {\n vector dp(amount + 1, amount + 1);\n dp[0] = 0;\n for (int coin : coins) {\n for (int x = coin; x <= amount; x++) {\n dp[x] = min(dp[x], dp[x - coin] + 1);\n }\n }\n return dp[amount] > amount ? -1 : dp[amount];\n}", "test_cases": ["coins=[1,2,5], amount=11 -> 3", "coins=[2], amount=3 -> -1"], "key_points": ["完全背包问题", "dp[x] = min(dp[x-coin]+1)"], "tags": ["dp", "medium", "Google", "Amazon"]} {"problem_id": "algo_01833", "original_id": "subsets", "title": "子集", "category": "backtracking", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "给你一个整数数组 nums ,数组中的元素 互不相同 。返回该数组所有可能的子集(幂集)。", "solution_python": "def subsets(nums):\n result = []\n def backtrack(start, path):\n result.append(path[:])\n for i in range(start, len(nums)):\n path.append(nums[i])\n backtrack(i + 1, path)\n path.pop()\n backtrack(0, [])\n return result", "solution_java": "public List> subsets(int[] nums) {\n List> result = new ArrayList<>();\n backtrack(nums, 0, new ArrayList<>(), result);\n return result;\n}\nprivate void backtrack(int[] nums, int start, List path, List> result) {\n result.add(new ArrayList<>(path));\n for (int i = start; i < nums.length; i++) {\n path.add(nums[i]);\n backtrack(nums, i + 1, path, result);\n path.remove(path.size() - 1);\n }\n}", "solution_cpp": "vector> subsets(vector& nums) {\n vector> result;\n vector path;\n backtrack(nums, 0, path, result);\n return result;\n}\nvoid backtrack(vector& nums, int start, vector& path, vector>& result) {\n result.push_back(path);\n for (int i = start; i < nums.size(); i++) {\n path.push_back(nums[i]);\n backtrack(nums, i + 1, path, result);\n path.pop_back();\n }\n}", "test_cases": ["nums=[1,2,3] -> [[],[1],[2],[1,2],[3],[1,3],[2,3],[1,2,3]]"], "key_points": ["选或不选", "DFS遍历子集树"], "tags": ["backtracking", "medium", "Google", "Microsoft"]} {"problem_id": "algo_01834", "original_id": "permutations", "title": "全排列", "category": "backtracking", "difficulty": "medium", "companies": ["Google", "Facebook"], "description": "给定一个不含重复数字的数组 nums,返回其所有可能的全排列。", "solution_python": "def permute(nums):\n result = []\n def backtrack(path, used):\n if len(path) == len(nums):\n result.append(path[:])\n return\n for i in range(len(nums)):\n if used[i]: continue\n used[i] = True\n path.append(nums[i])\n backtrack(path, used)\n path.pop()\n used[i] = False\n backtrack([], [False]*len(nums))\n return result", "solution_java": "public List> permute(int[] nums) {\n List> result = new ArrayList<>();\n boolean[] used = new boolean[nums.length];\n backtrack(nums, used, new ArrayList<>(), result);\n return result;\n}\nprivate void backtrack(int[] nums, boolean[] used, List path, List> result) {\n if (path.size() == nums.length) { result.add(new ArrayList<>(path)); return; }\n for (int i = 0; i < nums.length; i++) {\n if (used[i]) continue;\n used[i] = true;\n path.add(nums[i]);\n backtrack(nums, used, path, result);\n path.remove(path.size() - 1);\n used[i] = false;\n }\n}", "solution_cpp": "vector> permute(vector& nums) {\n vector> result;\n vector used(nums.size(), false);\n vector path;\n backtrack(nums, used, path, result);\n return result;\n}\nvoid backtrack(vector& nums, vector& used, vector& path, vector>& result) {\n if (path.size() == nums.size()) { result.push_back(path); return; }\n for (int i = 0; i < nums.size(); i++) {\n if (used[i]) continue;\n used[i] = true;\n path.push_back(nums[i]);\n backtrack(nums, used, path, result);\n path.pop_back();\n used[i] = false;\n }\n}", "test_cases": ["nums=[1,2,3] -> [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]"], "key_points": ["标记已使用元素", "回溯经典模板"], "tags": ["backtracking", "medium", "Google", "Facebook"]} {"problem_id": "algo_01835", "original_id": "top-k-frequent", "title": "前K个高频元素", "category": "heap", "difficulty": "medium", "companies": ["Amazon", "Facebook"], "description": "给你一个整数数组 nums 和一个整数 k,请你返回其中出现频率前 k 高的元素。", "solution_python": "import heapq\nfrom collections import Counter\ndef topKFrequent(nums, k):\n count = Counter(nums)\n heap = []\n for num, freq in count.items():\n heapq.heappush(heap, (freq, num))\n if len(heap) > k: heapq.heappop(heap)\n return [num for freq, num in heap]", "solution_java": "public int[] topKFrequent(int[] nums, int k) {\n Map count = new HashMap<>();\n for (int n : nums) count.put(n, count.getOrDefault(n, 0) + 1);\n PriorityQueue> heap = \n new PriorityQueue<>((a, b) -> a.getValue() - b.getValue());\n for (Map.Entry e : count.entrySet()) {\n heap.offer(e);\n if (heap.size() > k) heap.poll();\n }\n int[] res = new int[k];\n for (int i = k - 1; i >= 0; i--) res[i] = heap.poll().getKey();\n return res;\n}", "solution_cpp": "vector topKFrequent(vector& nums, int k) {\n unordered_map count;\n for (int n : nums) count[n]++;\n priority_queue, vector>, greater>> heap;\n for (auto& [num, freq] : count) {\n heap.push({freq, num});\n if (heap.size() > k) heap.pop();\n }\n vector res;\n while (!heap.empty()) { res.push_back(heap.top().second); heap.pop(); }\n reverse(res.begin(), res.end());\n return res;\n}", "test_cases": ["nums=[1,1,1,2,2,3], k=2 -> [1,2]", "nums=[1], k=1 -> [1]"], "key_points": ["小顶堆保持大小k", "时间复杂度O(nlogk)"], "tags": ["heap", "medium", "Amazon", "Facebook"]} {"problem_id": "algo_01836", "original_id": "3sum", "title": "三数之和", "category": "two-pointers", "difficulty": "medium", "companies": ["Google", "Amazon"], "description": "给你一个整数数组 nums,判断是否存在三元组满足和为0,返回所有不重复的三元组。", "solution_python": "def threeSum(nums):\n nums.sort()\n result = []\n for i in range(len(nums) - 2):\n if i > 0 and nums[i] == nums[i-1]: continue\n left, right = i + 1, len(nums) - 1\n while left < right:\n total = nums[i] + nums[left] + nums[right]\n if total < 0: left += 1\n elif total > 0: right -= 1\n else:\n result.append([nums[i], nums[left], nums[right]])\n while left < right and nums[left] == nums[left+1]: left += 1\n while left < right and nums[right] == nums[right-1]: right -= 1\n left += 1; right -= 1\n return result", "solution_java": "public List> threeSum(int[] nums) {\n Arrays.sort(nums);\n List> result = new ArrayList<>();\n for (int i = 0; i < nums.length - 2; i++) {\n if (i > 0 && nums[i] == nums[i-1]) continue;\n int left = i + 1, right = nums.length - 1;\n while (left < right) {\n int total = nums[i] + nums[left] + nums[right];\n if (total < 0) left++;\n else if (total > 0) right--;\n else {\n result.add(Arrays.asList(nums[i], nums[left], nums[right]));\n while (left < right && nums[left] == nums[left+1]) left++;\n while (left < right && nums[right] == nums[right-1]) right--;\n left++; right--;\n }\n }\n }\n return result;\n}", "solution_cpp": "vector> threeSum(vector& nums) {\n sort(nums.begin(), nums.end());\n vector> result;\n for (int i = 0; i < nums.size() - 2; i++) {\n if (i > 0 && nums[i] == nums[i-1]) continue;\n int left = i + 1, right = nums.size() - 1;\n while (left < right) {\n int total = nums[i] + nums[left] + nums[right];\n if (total < 0) left++;\n else if (total > 0) right--;\n else {\n result.push_back({nums[i], nums[left], nums[right]});\n while (left < right && nums[left] == nums[left+1]) left++;\n while (left < right && nums[right] == nums[right-1]) right--;\n left++; right--;\n }\n }\n }\n return result;\n}", "test_cases": ["nums=[-1,0,1,2,-1,-4] -> [[-1,-1,2],[-1,0,1]]"], "key_points": ["排序+双指针", "去重是关键"], "tags": ["two-pointers", "medium", "Google", "Amazon"]} {"problem_id": "algo_01837", "original_id": "container-water", "title": "盛最多水的容器", "category": "two-pointers", "difficulty": "medium", "companies": ["Google", "Uber"], "description": "给定一个长度为 n 的整数数组 height,找出其中的两条线,使得它们与 x 轴共同构成的容器可以容纳最多的水。", "solution_python": "def maxArea(height):\n left, right = 0, len(height) - 1\n max_area = 0\n while left < right:\n h = min(height[left], height[right])\n max_area = max(max_area, h * (right - left))\n if height[left] < height[right]: left += 1\n else: right -= 1\n return max_area", "solution_java": "public int maxArea(int[] height) {\n int left = 0, right = height.length - 1, maxArea = 0;\n while (left < right) {\n int h = Math.min(height[left], height[right]);\n maxArea = Math.max(maxArea, h * (right - left));\n if (height[left] < height[right]) left++;\n else right--;\n }\n return maxArea;\n}", "solution_cpp": "int maxArea(vector& height) {\n int left = 0, right = height.size() - 1, maxArea = 0;\n while (left < right) {\n int h = min(height[left], height[right]);\n maxArea = max(maxArea, h * (right - left));\n if (height[left] < height[right]) left++;\n else right--;\n }\n return maxArea;\n}", "test_cases": ["height=[1,8,6,2,5,4,8,3,7] -> 49"], "key_points": ["移动短边指针", "面积=min(h1,h2)*width"], "tags": ["two-pointers", "medium", "Google", "Uber"]} {"problem_id": "algo_01838", "original_id": "min-stack", "title": "最小栈", "category": "stack", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "设计一个支持 push,pop,top 操作,并能在常数时间内检索到最小元素的栈。", "solution_python": "class MinStack:\n def __init__(self):\n self.stack = []\n self.min_stack = []\n def push(self, val):\n self.stack.append(val)\n self.min_stack.append(min(val, self.min_stack[-1] if self.min_stack else val))\n def pop(self):\n self.stack.pop(); self.min_stack.pop()\n def top(self): return self.stack[-1]\n def getMin(self): return self.min_stack[-1]", "solution_java": "class MinStack {\n Stack stack = new Stack<>();\n Stack minStack = new Stack<>();\n public void push(int val) { stack.push(val); minStack.push(Math.min(val, minStack.isEmpty() ? val : minStack.peek())); }\n public void pop() { stack.pop(); minStack.pop(); }\n public int top() { return stack.peek(); }\n public int getMin() { return minStack.peek(); }\n}", "solution_cpp": "class MinStack {\n stack st, minSt;\npublic:\n void push(int val) { st.push(val); minSt.push(min(val, minSt.empty() ? val : minSt.top())); }\n void pop() { st.pop(); minSt.pop(); }\n int top() { return st.top(); }\n int getMin() { return minSt.top(); }\n};", "test_cases": ["push(-2), push(0), push(-3) -> getMin() returns -3"], "key_points": ["辅助栈记录最小值", "O(1)时间获取最小值"], "tags": ["stack", "medium", "Google", "Microsoft"]} {"problem_id": "algo_01839", "original_id": "lru-cache", "title": "LRU缓存", "category": "design", "difficulty": "hard", "companies": ["Google", "Amazon"], "description": "设计和实现一个 LRU(最近最少使用)缓存机制。", "solution_python": "class LRUCache:\n def __init__(self, capacity):\n self.capacity = capacity\n self.cache = {}\n self.order = []\n def get(self, key):\n if key not in self.cache: return -1\n self.order.remove(key); self.order.append(key)\n return self.cache[key]\n def put(self, key, value):\n if key in self.cache:\n self.order.remove(key)\n elif len(self.cache) >= self.capacity:\n del self.cache[self.order.pop(0)]\n self.cache[key] = value; self.order.append(key)", "solution_java": "class LRUCache {\n int capacity;\n LinkedHashMap cache = new LinkedHashMap<>();\n public LRUCache(int cap) { capacity = cap; }\n public int get(int key) { return cache.containsKey(key) ? cache.remove(key) : -1; }\n public void put(int key, int val) {\n if (cache.containsKey(key)) cache.remove(key);\n else if (cache.size() >= capacity) cache.remove(cache.keySet().iterator().next());\n cache.put(key, val);\n }\n}", "solution_cpp": "class LRUCache {\n int cap;\n list> dll;\n unordered_map>::iterator> cache;\npublic:\n LRUCache(int capacity) : cap(capacity) {}\n int get(int key) {\n auto it = cache.find(key);\n if (it == cache.end()) return -1;\n dll.splice(dll.end(), dll, it->second);\n return it->second->second;\n }\n void put(int key, int value) {\n auto it = cache.find(key);\n if (it != cache.end()) dll.erase(it->second);\n else if (cache.size() >= cap) { cache.erase(dll.front().first); dll.pop_front(); }\n dll.push_back({key, value});\n cache[key] = --dll.end();\n }\n};", "test_cases": ["put(1,1), put(2,2), get(1) -> 1"], "key_points": ["HashMap + 双向链表", "O(1)时间操作"], "tags": ["design", "hard", "Google", "Amazon"]} {"problem_id": "algo_01840", "original_id": "num-islands", "title": "岛屿数量", "category": "graph", "difficulty": "medium", "companies": ["Google", "Facebook"], "description": "给你一个由 '1'(陆地)和 '0'(水)组成的二维网格,请你计算网格中岛屿的数量。岛屿总是被水包围,且只能由水平或垂直方向相邻的陆地连接形成。", "solution_python": "def numIslands(grid):\n if not grid: return 0\n rows, cols = len(grid), len(grid[0])\n count = 0\n def dfs(r, c):\n if r < 0 or r >= rows or c < 0 or c >= cols or grid[r][c] != '1': return\n grid[r][c] = '0'\n dfs(r+1, c); dfs(r-1, c); dfs(r, c+1); dfs(r, c-1)\n for r in range(rows):\n for c in range(cols):\n if grid[r][c] == '1': count += 1; dfs(r, c)\n return count", "solution_java": "public int numIslands(char[][] grid) {\n if (grid.length == 0) return 0;\n int count = 0;\n for (int i = 0; i < grid.length; i++)\n for (int j = 0; j < grid[0].length; j++)\n if (grid[i][j] == '1') { count++; dfs(grid, i, j); }\n return count;\n}\nprivate void dfs(char[][] grid, int r, int c) {\n if (r < 0 || r >= grid.length || c < 0 || c >= grid[0].length || grid[r][c] != '1') return;\n grid[r][c] = '0';\n dfs(grid, r+1, c); dfs(grid, r-1, c); dfs(grid, r, c+1); dfs(grid, r, c-1);\n}", "solution_cpp": "int numIslands(vector>& grid) {\n if (grid.empty()) return 0;\n int count = 0;\n for (int i = 0; i < grid.size(); i++)\n for (int j = 0; j < grid[0].size(); j++)\n if (grid[i][j] == '1') { count++; dfs(grid, i, j); }\n return count;\n}\nvoid dfs(vector>& grid, int r, int c) {\n if (r < 0 || r >= grid.size() || c < 0 || c >= grid[0].size() || grid[r][c] != '1') return;\n grid[r][c] = '0';\n dfs(grid, r+1, c); dfs(grid, r-1, c); dfs(grid, r, c+1); dfs(grid, r, c-1);\n}", "test_cases": ["grid=[[1,1,1,1,0],[1,1,0,1,0],[1,1,0,0,0],[0,0,0,0,0]] -> 1"], "key_points": ["DFS/BFS遍历", "访问后标记为0避免重复"], "tags": ["graph", "medium", "Google", "Facebook"]} {"problem_id": "algo_01841", "original_id": "two-sum", "title": "两数之和", "category": "array", "difficulty": "easy", "companies": ["Amazon", "Google"], "description": "给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那两个整数,并返回他们的数组下标。", "solution_python": "def twoSum(nums, target):\n hashmap = {}\n for i, num in enumerate(nums):\n complement = target - num\n if complement in hashmap:\n return [hashmap[complement], i]\n hashmap[num] = i\n return []", "solution_java": "public int[] twoSum(int[] nums, int target) {\n Map map = new HashMap<>();\n for (int i = 0; i < nums.length; i++) {\n int complement = target - nums[i];\n if (map.containsKey(complement)) return new int[]{map.get(complement), i};\n map.put(nums[i], i);\n }\n return new int[]{};\n}", "solution_cpp": "vector twoSum(vector& nums, int target) {\n unordered_map m;\n for (int i = 0; i < nums.size(); i++) {\n if (m.count(target - nums[i])) return {m[target - nums[i]], i};\n m[nums[i]] = i;\n }\n return {};\n}", "test_cases": ["nums=[2,7,11,15], target=9 -> [0,1]", "nums=[3,2,4], target=6 -> [1,2]"], "key_points": ["哈希表一次遍历", "空间换时间"], "tags": ["array", "easy", "Amazon", "Google"]} {"problem_id": "algo_01842", "original_id": "merge-sorted", "title": "合并两个有序数组", "category": "array", "difficulty": "easy", "companies": ["Microsoft", "Uber"], "description": "给你两个按非递减顺序排列的整数数组 nums1 和 nums2,另有两个整数 m 和 n,分别表示 nums1 和 nums2 中的元素数目。请你合并 nums2 到 nums1 中。", "solution_python": "def merge(nums1, m, nums2, n):\n p1, p2, p = m-1, n-1, m+n-1\n while p1 >= 0 and p2 >= 0:\n if nums1[p1] > nums2[p2]: nums1[p] = nums1[p1]; p1 -= 1\n else: nums1[p] = nums2[p2]; p2 -= 1\n p -= 1\n while p2 >= 0: nums1[p] = nums2[p2]; p2 -= 1; p -= 1", "solution_java": "public void merge(int[] nums1, int m, int[] nums2, int n) {\n int p1 = m-1, p2 = n-1, p = m+n-1;\n while (p1 >= 0 && p2 >= 0) {\n nums1[p--] = nums1[p1] > nums2[p2] ? nums1[p1--] : nums2[p2--];\n }\n while (p2 >= 0) nums1[p--] = nums2[p2--];\n}", "solution_cpp": "void merge(vector& nums1, int m, vector& nums2, int n) {\n int p1 = m-1, p2 = n-1, p = m+n-1;\n while (p1 >= 0 && p2 >= 0) nums1[p--] = nums1[p1] > nums2[p2] ? nums1[p1--] : nums2[p2--];\n while (p2 >= 0) nums1[p--] = nums2[p2--];\n}", "test_cases": ["nums1=[1,2,3], m=3, nums2=[2,5,6], n=3 -> [1,2,2,3,5,6]", "nums1=[], m=0, nums2=[1], n=1 -> [1]"], "key_points": ["从后往前合并", "三指针技巧"], "tags": ["array", "easy", "Microsoft", "Uber"]} {"problem_id": "algo_01843", "original_id": "max-subarray", "title": "最大子数组和", "category": "array", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "给你一个整数数组 nums ,请你找出一个具有最大和的连续子数组,返回其最大和。", "solution_python": "def maxSubArray(nums):\n max_sum = current = nums[0]\n for num in nums[1:]:\n current = max(num, current + num)\n max_sum = max(max_sum, current)\n return max_sum", "solution_java": "public int maxSubArray(int[] nums) {\n int maxSum = nums[0], curr = nums[0];\n for (int i = 1; i < nums.length; i++) {\n curr = Math.max(nums[i], curr + nums[i]);\n maxSum = Math.max(maxSum, curr);\n }\n return maxSum;\n}", "solution_cpp": "int maxSubArray(vector& nums) {\n int maxSum = nums[0], curr = nums[0];\n for (int i = 1; i < nums.size(); i++) {\n curr = max(nums[i], curr + nums[i]);\n maxSum = max(maxSum, curr);\n }\n return maxSum;\n}", "test_cases": ["nums=[-2,1,-3,4,-1,2,1,-5,4] -> 6", "nums=[1] -> 1"], "key_points": ["Kadane算法", "动态规划基础题"], "tags": ["array", "medium", "Google", "Microsoft"]} {"problem_id": "algo_01844", "original_id": "valid-parentheses", "title": "有效的括号", "category": "string", "difficulty": "easy", "companies": ["Google", "Uber"], "description": "给定一个只包括 '(',')','{','}','[',']' 的字符串 s,判断字符串是否有效。", "solution_python": "def isValid(s):\n stack = []\n mapping = {')': '(', ']': '[', '}': '{'}\n for c in s:\n if c in mapping:\n if not stack or stack[-1] != mapping[c]: return False\n stack.pop()\n else: stack.append(c)\n return not stack", "solution_java": "public boolean isValid(String s) {\n Stack stack = new Stack<>();\n Map map = Map.of(')', '(', ']', '[', '}', '{');\n for (char c : s.toCharArray()) {\n if (map.containsValue(c)) stack.push(c);\n else if (!stack.isEmpty() && stack.pop() != map.get(c)) return false;\n }\n return stack.isEmpty();\n}", "solution_cpp": "bool isValid(string s) {\n stack st;\n unordered_map m = {{')','('},{']','['},{'}','{'}};\n for (char c : s) {\n if (m.find(c) == m.end()) st.push(c);\n else if (st.empty() || st.top() != m[c]) return false;\n else st.pop();\n }\n return st.empty();\n}", "test_cases": ["s=\"()\" -> true", "s=\"()[]{}\" -> true", "s=\"(]\" -> false"], "key_points": ["栈匹配法", "注意空栈边界"], "tags": ["string", "easy", "Google", "Uber"]} {"problem_id": "algo_01845", "original_id": "longest-palindrome", "title": "最长回文子串", "category": "string", "difficulty": "medium", "companies": ["Google", "Amazon"], "description": "给你一个字符串 s,找到 s 中最长的回文子串。", "solution_python": "def longestPalindrome(s):\n def expand(l, r):\n while l >= 0 and r < len(s) and s[l] == s[r]: l -= 1; r += 1\n return l + 1, r - 1\n start = end = 0\n for i in range(len(s)):\n l1, r1 = expand(i, i)\n l2, r2 = expand(i, i + 1)\n if r1 - l1 > end - start: start, end = l1, r1\n if r2 - l2 > end - start: start, end = l2, r2\n return s[start:end+1]", "solution_java": "public String longestPalindrome(String s) {\n int start = 0, end = 0;\n for (int i = 0; i < s.length(); i++) {\n int len1 = expand(s, i, i), len2 = expand(s, i, i+1);\n int len = Math.max(len1, len2);\n if (len > end - start) { start = i - (len-1)/2; end = i + len/2; }\n }\n return s.substring(start, end + 1);\n}\nprivate int expand(String s, int l, int r) {\n while (l >= 0 && r < s.length() && s.charAt(l) == s.charAt(r)) { l--; r++; }\n return r - l - 1;\n}", "solution_cpp": "string longestPalindrome(string s) {\n int start = 0, end = 0;\n for (int i = 0; i < s.size(); i++) {\n int len1 = expand(s, i, i), len2 = expand(s, i, i+1);\n if (max(len1, len2) > end - start) { start = i - (max(len1,len2)-1)/2; end = i + max(len1,len2)/2; }\n }\n return s.substr(start, end - start + 1);\n}", "test_cases": ["s=\"babad\" -> bab或aba", "s=\"cbbd\" -> bb"], "key_points": ["中心扩展法", "处理奇偶长度"], "tags": ["string", "medium", "Google", "Amazon"]} {"problem_id": "algo_01846", "original_id": "reverse-list", "title": "反转链表", "category": "linkedlist", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "给你单链表的头节点 head,请你反转链表,并返回反转后的链表。", "solution_python": "def reverseList(head):\n prev = None\n curr = head\n while curr:\n nxt = curr.next\n curr.next = prev\n prev = curr\n curr = nxt\n return prev", "solution_java": "public ListNode reverseList(ListNode head) {\n ListNode prev = null, curr = head;\n while (curr != null) {\n ListNode next = curr.next;\n curr.next = prev;\n prev = curr;\n curr = next;\n }\n return prev;\n}", "solution_cpp": "ListNode* reverseList(ListNode* head) {\n ListNode* prev = nullptr, *curr = head;\n while (curr) {\n ListNode* next = curr->next;\n curr->next = prev;\n prev = curr;\n curr = next;\n }\n return prev;\n}", "test_cases": ["head=[1,2,3,4,5] -> [5,4,3,2,1]", "head=[1,2] -> [2,1]"], "key_points": ["迭代法 O(1)空间", "递归法 O(n)空间"], "tags": ["linkedlist", "medium", "Google", "Microsoft"]} {"problem_id": "algo_01847", "original_id": "middle-node", "title": "链表的中间结点", "category": "linkedlist", "difficulty": "easy", "companies": ["Amazon", "Facebook"], "description": "给你单链表的头节点 head,请你找出并返回链表的中间结点。如果有两个中间结点,则返回第二个中间结点。", "solution_python": "def middleNode(head):\n slow = fast = head\n while fast and fast.next:\n slow = slow.next\n fast = fast.next.next\n return slow", "solution_java": "public ListNode middleNode(ListNode head) {\n ListNode slow = head, fast = head;\n while (fast != null && fast.next != null) {\n slow = slow.next;\n fast = fast.next.next;\n }\n return slow;\n}", "solution_cpp": "ListNode* middleNode(ListNode* head) {\n ListNode* slow = head, *fast = head;\n while (fast && fast->next) { slow = slow->next; fast = fast->next->next; }\n return slow;\n}", "test_cases": ["head=[1,2,3,4,5] -> 3", "head=[1,2,3,4,5,6] -> 4"], "key_points": ["快慢指针", "O(n)时间O(1)空间"], "tags": ["linkedlist", "easy", "Amazon", "Facebook"]} {"problem_id": "algo_01848", "original_id": "max-depth", "title": "二叉树的最大深度", "category": "tree", "difficulty": "easy", "companies": ["Microsoft", "Apple"], "description": "给定一个二叉树 root,返回其最大深度。", "solution_python": "def maxDepth(root):\n if not root: return 0\n return max(maxDepth(root.left), maxDepth(root.right)) + 1", "solution_java": "public int maxDepth(TreeNode root) {\n if (root == null) return 0;\n return Math.max(maxDepth(root.left), maxDepth(root.right)) + 1;\n}", "solution_cpp": "int maxDepth(TreeNode* root) {\n if (!root) return 0;\n return max(maxDepth(root->left), maxDepth(root->right)) + 1;\n}", "test_cases": ["root=[3,9,20,null,null,15,7] -> 3", "root=[1,null,2] -> 2"], "key_points": ["DFS递归", "层序遍历也可"], "tags": ["tree", "easy", "Microsoft", "Apple"]} {"problem_id": "algo_01849", "original_id": "inorder-traversal", "title": "二叉树的中序遍历", "category": "tree", "difficulty": "easy", "companies": ["Google", "Microsoft"], "description": "给定一个二叉树的根节点 root,返回它的中序遍历结果。", "solution_python": "def inorderTraversal(root):\n result = []\n def dfs(node):\n if node:\n dfs(node.left)\n result.append(node.val)\n dfs(node.right)\n dfs(root)\n return result", "solution_java": "public List inorderTraversal(TreeNode root) {\n List res = new ArrayList<>();\n dfs(root, res);\n return res;\n}\nprivate void dfs(TreeNode node, List res) {\n if (node == null) return;\n dfs(node.left, res); res.add(node.val); dfs(node.right, res);\n}", "solution_cpp": "vector inorderTraversal(TreeNode* root) {\n vector res;\n dfs(root, res);\n return res;\n}\nvoid dfs(TreeNode* node, vector& res) {\n if (!node) return;\n dfs(node->left, res); res.push_back(node->val); dfs(node->right, res);\n}", "test_cases": ["root=[1,null,2,3] -> [1,3,2]", "root=[] -> []"], "key_points": ["左-根-右顺序", "递归最简洁"], "tags": ["tree", "easy", "Google", "Microsoft"]} {"problem_id": "algo_01850", "original_id": "binary-search", "title": "二分查找", "category": "binarysearch", "difficulty": "easy", "companies": ["Google", "Amazon"], "description": "给定一个 n 个元素有序的(升序)整型数组 nums 和一个目标值 target,写一个函数搜索 nums 中的 target,如果目标值存在返回下标,否则返回 -1。", "solution_python": "def search(nums, target):\n left, right = 0, len(nums) - 1\n while left <= right:\n mid = (left + right) // 2\n if nums[mid] == target: return mid\n elif nums[mid] < target: left = mid + 1\n else: right = mid - 1\n return -1", "solution_java": "public int search(int[] nums, int target) {\n int left = 0, right = nums.length - 1;\n while (left <= right) {\n int mid = left + (right - left) / 2;\n if (nums[mid] == target) return mid;\n else if (nums[mid] < target) left = mid + 1;\n else right = mid - 1;\n }\n return -1;\n}", "solution_cpp": "int search(vector& nums, int target) {\n int left = 0, right = nums.size() - 1;\n while (left <= right) {\n int mid = left + (right - left) / 2;\n if (nums[mid] == target) return mid;\n else if (nums[mid] < target) left = mid + 1;\n else right = mid - 1;\n }\n return -1;\n}", "test_cases": ["nums=[-1,0,3,5,9,12], target=9 -> 4", "nums=[-1,0,3,5,9,12], target=2 -> -1"], "key_points": ["标准模板", "注意防溢出写法"], "tags": ["binarysearch", "easy", "Google", "Amazon"]} {"problem_id": "algo_01851", "original_id": "climbing-stairs", "title": "爬楼梯", "category": "dp", "difficulty": "easy", "companies": ["Amazon", "Google"], "description": "假设你正在爬楼梯。需要 n 阶你才能到达楼顶。每次你可以爬 1 或 2 个台阶。你有多少种不同的方法可以爬到楼顶?", "solution_python": "def climbStairs(n):\n if n <= 2: return n\n a, b = 1, 2\n for _ in range(3, n+1):\n a, b = b, a + b\n return b", "solution_java": "public int climbStairs(int n) {\n if (n <= 2) return n;\n int a = 1, b = 2;\n for (int i = 3; i <= n; i++) { int temp = a + b; a = b; b = temp; }\n return b;\n}", "solution_cpp": "int climbStairs(int n) {\n if (n <= 2) return n;\n int a = 1, b = 2;\n for (int i = 3; i <= n; i++) { int temp = a + b; a = b; b = temp; }\n return b;\n}", "test_cases": ["n=2 -> 2", "n=3 -> 3", "n=5 -> 8"], "key_points": ["斐波那契数列", "滚动数组优化空间"], "tags": ["dp", "easy", "Amazon", "Google"]} {"problem_id": "algo_01852", "original_id": "coin-change", "title": "零钱兑换", "category": "dp", "difficulty": "medium", "companies": ["Google", "Amazon"], "description": "给你一个整数数组 coins 表示不同面额的硬币,以及一个整数 amount 表示总金额。计算并返回可以凑成总金额所需的最少的硬币个数。如果没有任何一种硬币组合能组成总金额,返回 -1。", "solution_python": "def coinChange(coins, amount):\n dp = [float('inf')] * (amount + 1)\n dp[0] = 0\n for coin in coins:\n for x in range(coin, amount + 1):\n dp[x] = min(dp[x], dp[x - coin] + 1)\n return dp[amount] if dp[amount] != float('inf') else -1", "solution_java": "public int coinChange(int[] coins, int amount) {\n int[] dp = new int[amount + 1];\n Arrays.fill(dp, amount + 1);\n dp[0] = 0;\n for (int coin : coins) {\n for (int x = coin; x <= amount; x++) {\n dp[x] = Math.min(dp[x], dp[x - coin] + 1);\n }\n }\n return dp[amount] > amount ? -1 : dp[amount];\n}", "solution_cpp": "int coinChange(vector& coins, int amount) {\n vector dp(amount + 1, amount + 1);\n dp[0] = 0;\n for (int coin : coins) {\n for (int x = coin; x <= amount; x++) {\n dp[x] = min(dp[x], dp[x - coin] + 1);\n }\n }\n return dp[amount] > amount ? -1 : dp[amount];\n}", "test_cases": ["coins=[1,2,5], amount=11 -> 3", "coins=[2], amount=3 -> -1"], "key_points": ["完全背包问题", "dp[x] = min(dp[x-coin]+1)"], "tags": ["dp", "medium", "Google", "Amazon"]} {"problem_id": "algo_01853", "original_id": "subsets", "title": "子集", "category": "backtracking", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "给你一个整数数组 nums ,数组中的元素 互不相同 。返回该数组所有可能的子集(幂集)。", "solution_python": "def subsets(nums):\n result = []\n def backtrack(start, path):\n result.append(path[:])\n for i in range(start, len(nums)):\n path.append(nums[i])\n backtrack(i + 1, path)\n path.pop()\n backtrack(0, [])\n return result", "solution_java": "public List> subsets(int[] nums) {\n List> result = new ArrayList<>();\n backtrack(nums, 0, new ArrayList<>(), result);\n return result;\n}\nprivate void backtrack(int[] nums, int start, List path, List> result) {\n result.add(new ArrayList<>(path));\n for (int i = start; i < nums.length; i++) {\n path.add(nums[i]);\n backtrack(nums, i + 1, path, result);\n path.remove(path.size() - 1);\n }\n}", "solution_cpp": "vector> subsets(vector& nums) {\n vector> result;\n vector path;\n backtrack(nums, 0, path, result);\n return result;\n}\nvoid backtrack(vector& nums, int start, vector& path, vector>& result) {\n result.push_back(path);\n for (int i = start; i < nums.size(); i++) {\n path.push_back(nums[i]);\n backtrack(nums, i + 1, path, result);\n path.pop_back();\n }\n}", "test_cases": ["nums=[1,2,3] -> [[],[1],[2],[1,2],[3],[1,3],[2,3],[1,2,3]]"], "key_points": ["选或不选", "DFS遍历子集树"], "tags": ["backtracking", "medium", "Google", "Microsoft"]} {"problem_id": "algo_01854", "original_id": "permutations", "title": "全排列", "category": "backtracking", "difficulty": "medium", "companies": ["Google", "Facebook"], "description": "给定一个不含重复数字的数组 nums,返回其所有可能的全排列。", "solution_python": "def permute(nums):\n result = []\n def backtrack(path, used):\n if len(path) == len(nums):\n result.append(path[:])\n return\n for i in range(len(nums)):\n if used[i]: continue\n used[i] = True\n path.append(nums[i])\n backtrack(path, used)\n path.pop()\n used[i] = False\n backtrack([], [False]*len(nums))\n return result", "solution_java": "public List> permute(int[] nums) {\n List> result = new ArrayList<>();\n boolean[] used = new boolean[nums.length];\n backtrack(nums, used, new ArrayList<>(), result);\n return result;\n}\nprivate void backtrack(int[] nums, boolean[] used, List path, List> result) {\n if (path.size() == nums.length) { result.add(new ArrayList<>(path)); return; }\n for (int i = 0; i < nums.length; i++) {\n if (used[i]) continue;\n used[i] = true;\n path.add(nums[i]);\n backtrack(nums, used, path, result);\n path.remove(path.size() - 1);\n used[i] = false;\n }\n}", "solution_cpp": "vector> permute(vector& nums) {\n vector> result;\n vector used(nums.size(), false);\n vector path;\n backtrack(nums, used, path, result);\n return result;\n}\nvoid backtrack(vector& nums, vector& used, vector& path, vector>& result) {\n if (path.size() == nums.size()) { result.push_back(path); return; }\n for (int i = 0; i < nums.size(); i++) {\n if (used[i]) continue;\n used[i] = true;\n path.push_back(nums[i]);\n backtrack(nums, used, path, result);\n path.pop_back();\n used[i] = false;\n }\n}", "test_cases": ["nums=[1,2,3] -> [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]"], "key_points": ["标记已使用元素", "回溯经典模板"], "tags": ["backtracking", "medium", "Google", "Facebook"]} {"problem_id": "algo_01855", "original_id": "top-k-frequent", "title": "前K个高频元素", "category": "heap", "difficulty": "medium", "companies": ["Amazon", "Facebook"], "description": "给你一个整数数组 nums 和一个整数 k,请你返回其中出现频率前 k 高的元素。", "solution_python": "import heapq\nfrom collections import Counter\ndef topKFrequent(nums, k):\n count = Counter(nums)\n heap = []\n for num, freq in count.items():\n heapq.heappush(heap, (freq, num))\n if len(heap) > k: heapq.heappop(heap)\n return [num for freq, num in heap]", "solution_java": "public int[] topKFrequent(int[] nums, int k) {\n Map count = new HashMap<>();\n for (int n : nums) count.put(n, count.getOrDefault(n, 0) + 1);\n PriorityQueue> heap = \n new PriorityQueue<>((a, b) -> a.getValue() - b.getValue());\n for (Map.Entry e : count.entrySet()) {\n heap.offer(e);\n if (heap.size() > k) heap.poll();\n }\n int[] res = new int[k];\n for (int i = k - 1; i >= 0; i--) res[i] = heap.poll().getKey();\n return res;\n}", "solution_cpp": "vector topKFrequent(vector& nums, int k) {\n unordered_map count;\n for (int n : nums) count[n]++;\n priority_queue, vector>, greater>> heap;\n for (auto& [num, freq] : count) {\n heap.push({freq, num});\n if (heap.size() > k) heap.pop();\n }\n vector res;\n while (!heap.empty()) { res.push_back(heap.top().second); heap.pop(); }\n reverse(res.begin(), res.end());\n return res;\n}", "test_cases": ["nums=[1,1,1,2,2,3], k=2 -> [1,2]", "nums=[1], k=1 -> [1]"], "key_points": ["小顶堆保持大小k", "时间复杂度O(nlogk)"], "tags": ["heap", "medium", "Amazon", "Facebook"]} {"problem_id": "algo_01856", "original_id": "3sum", "title": "三数之和", "category": "two-pointers", "difficulty": "medium", "companies": ["Google", "Amazon"], "description": "给你一个整数数组 nums,判断是否存在三元组满足和为0,返回所有不重复的三元组。", "solution_python": "def threeSum(nums):\n nums.sort()\n result = []\n for i in range(len(nums) - 2):\n if i > 0 and nums[i] == nums[i-1]: continue\n left, right = i + 1, len(nums) - 1\n while left < right:\n total = nums[i] + nums[left] + nums[right]\n if total < 0: left += 1\n elif total > 0: right -= 1\n else:\n result.append([nums[i], nums[left], nums[right]])\n while left < right and nums[left] == nums[left+1]: left += 1\n while left < right and nums[right] == nums[right-1]: right -= 1\n left += 1; right -= 1\n return result", "solution_java": "public List> threeSum(int[] nums) {\n Arrays.sort(nums);\n List> result = new ArrayList<>();\n for (int i = 0; i < nums.length - 2; i++) {\n if (i > 0 && nums[i] == nums[i-1]) continue;\n int left = i + 1, right = nums.length - 1;\n while (left < right) {\n int total = nums[i] + nums[left] + nums[right];\n if (total < 0) left++;\n else if (total > 0) right--;\n else {\n result.add(Arrays.asList(nums[i], nums[left], nums[right]));\n while (left < right && nums[left] == nums[left+1]) left++;\n while (left < right && nums[right] == nums[right-1]) right--;\n left++; right--;\n }\n }\n }\n return result;\n}", "solution_cpp": "vector> threeSum(vector& nums) {\n sort(nums.begin(), nums.end());\n vector> result;\n for (int i = 0; i < nums.size() - 2; i++) {\n if (i > 0 && nums[i] == nums[i-1]) continue;\n int left = i + 1, right = nums.size() - 1;\n while (left < right) {\n int total = nums[i] + nums[left] + nums[right];\n if (total < 0) left++;\n else if (total > 0) right--;\n else {\n result.push_back({nums[i], nums[left], nums[right]});\n while (left < right && nums[left] == nums[left+1]) left++;\n while (left < right && nums[right] == nums[right-1]) right--;\n left++; right--;\n }\n }\n }\n return result;\n}", "test_cases": ["nums=[-1,0,1,2,-1,-4] -> [[-1,-1,2],[-1,0,1]]"], "key_points": ["排序+双指针", "去重是关键"], "tags": ["two-pointers", "medium", "Google", "Amazon"]} {"problem_id": "algo_01857", "original_id": "container-water", "title": "盛最多水的容器", "category": "two-pointers", "difficulty": "medium", "companies": ["Google", "Uber"], "description": "给定一个长度为 n 的整数数组 height,找出其中的两条线,使得它们与 x 轴共同构成的容器可以容纳最多的水。", "solution_python": "def maxArea(height):\n left, right = 0, len(height) - 1\n max_area = 0\n while left < right:\n h = min(height[left], height[right])\n max_area = max(max_area, h * (right - left))\n if height[left] < height[right]: left += 1\n else: right -= 1\n return max_area", "solution_java": "public int maxArea(int[] height) {\n int left = 0, right = height.length - 1, maxArea = 0;\n while (left < right) {\n int h = Math.min(height[left], height[right]);\n maxArea = Math.max(maxArea, h * (right - left));\n if (height[left] < height[right]) left++;\n else right--;\n }\n return maxArea;\n}", "solution_cpp": "int maxArea(vector& height) {\n int left = 0, right = height.size() - 1, maxArea = 0;\n while (left < right) {\n int h = min(height[left], height[right]);\n maxArea = max(maxArea, h * (right - left));\n if (height[left] < height[right]) left++;\n else right--;\n }\n return maxArea;\n}", "test_cases": ["height=[1,8,6,2,5,4,8,3,7] -> 49"], "key_points": ["移动短边指针", "面积=min(h1,h2)*width"], "tags": ["two-pointers", "medium", "Google", "Uber"]} {"problem_id": "algo_01858", "original_id": "min-stack", "title": "最小栈", "category": "stack", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "设计一个支持 push,pop,top 操作,并能在常数时间内检索到最小元素的栈。", "solution_python": "class MinStack:\n def __init__(self):\n self.stack = []\n self.min_stack = []\n def push(self, val):\n self.stack.append(val)\n self.min_stack.append(min(val, self.min_stack[-1] if self.min_stack else val))\n def pop(self):\n self.stack.pop(); self.min_stack.pop()\n def top(self): return self.stack[-1]\n def getMin(self): return self.min_stack[-1]", "solution_java": "class MinStack {\n Stack stack = new Stack<>();\n Stack minStack = new Stack<>();\n public void push(int val) { stack.push(val); minStack.push(Math.min(val, minStack.isEmpty() ? val : minStack.peek())); }\n public void pop() { stack.pop(); minStack.pop(); }\n public int top() { return stack.peek(); }\n public int getMin() { return minStack.peek(); }\n}", "solution_cpp": "class MinStack {\n stack st, minSt;\npublic:\n void push(int val) { st.push(val); minSt.push(min(val, minSt.empty() ? val : minSt.top())); }\n void pop() { st.pop(); minSt.pop(); }\n int top() { return st.top(); }\n int getMin() { return minSt.top(); }\n};", "test_cases": ["push(-2), push(0), push(-3) -> getMin() returns -3"], "key_points": ["辅助栈记录最小值", "O(1)时间获取最小值"], "tags": ["stack", "medium", "Google", "Microsoft"]} {"problem_id": "algo_01859", "original_id": "lru-cache", "title": "LRU缓存", "category": "design", "difficulty": "hard", "companies": ["Google", "Amazon"], "description": "设计和实现一个 LRU(最近最少使用)缓存机制。", "solution_python": "class LRUCache:\n def __init__(self, capacity):\n self.capacity = capacity\n self.cache = {}\n self.order = []\n def get(self, key):\n if key not in self.cache: return -1\n self.order.remove(key); self.order.append(key)\n return self.cache[key]\n def put(self, key, value):\n if key in self.cache:\n self.order.remove(key)\n elif len(self.cache) >= self.capacity:\n del self.cache[self.order.pop(0)]\n self.cache[key] = value; self.order.append(key)", "solution_java": "class LRUCache {\n int capacity;\n LinkedHashMap cache = new LinkedHashMap<>();\n public LRUCache(int cap) { capacity = cap; }\n public int get(int key) { return cache.containsKey(key) ? cache.remove(key) : -1; }\n public void put(int key, int val) {\n if (cache.containsKey(key)) cache.remove(key);\n else if (cache.size() >= capacity) cache.remove(cache.keySet().iterator().next());\n cache.put(key, val);\n }\n}", "solution_cpp": "class LRUCache {\n int cap;\n list> dll;\n unordered_map>::iterator> cache;\npublic:\n LRUCache(int capacity) : cap(capacity) {}\n int get(int key) {\n auto it = cache.find(key);\n if (it == cache.end()) return -1;\n dll.splice(dll.end(), dll, it->second);\n return it->second->second;\n }\n void put(int key, int value) {\n auto it = cache.find(key);\n if (it != cache.end()) dll.erase(it->second);\n else if (cache.size() >= cap) { cache.erase(dll.front().first); dll.pop_front(); }\n dll.push_back({key, value});\n cache[key] = --dll.end();\n }\n};", "test_cases": ["put(1,1), put(2,2), get(1) -> 1"], "key_points": ["HashMap + 双向链表", "O(1)时间操作"], "tags": ["design", "hard", "Google", "Amazon"]} {"problem_id": "algo_01860", "original_id": "num-islands", "title": "岛屿数量", "category": "graph", "difficulty": "medium", "companies": ["Google", "Facebook"], "description": "给你一个由 '1'(陆地)和 '0'(水)组成的二维网格,请你计算网格中岛屿的数量。岛屿总是被水包围,且只能由水平或垂直方向相邻的陆地连接形成。", "solution_python": "def numIslands(grid):\n if not grid: return 0\n rows, cols = len(grid), len(grid[0])\n count = 0\n def dfs(r, c):\n if r < 0 or r >= rows or c < 0 or c >= cols or grid[r][c] != '1': return\n grid[r][c] = '0'\n dfs(r+1, c); dfs(r-1, c); dfs(r, c+1); dfs(r, c-1)\n for r in range(rows):\n for c in range(cols):\n if grid[r][c] == '1': count += 1; dfs(r, c)\n return count", "solution_java": "public int numIslands(char[][] grid) {\n if (grid.length == 0) return 0;\n int count = 0;\n for (int i = 0; i < grid.length; i++)\n for (int j = 0; j < grid[0].length; j++)\n if (grid[i][j] == '1') { count++; dfs(grid, i, j); }\n return count;\n}\nprivate void dfs(char[][] grid, int r, int c) {\n if (r < 0 || r >= grid.length || c < 0 || c >= grid[0].length || grid[r][c] != '1') return;\n grid[r][c] = '0';\n dfs(grid, r+1, c); dfs(grid, r-1, c); dfs(grid, r, c+1); dfs(grid, r, c-1);\n}", "solution_cpp": "int numIslands(vector>& grid) {\n if (grid.empty()) return 0;\n int count = 0;\n for (int i = 0; i < grid.size(); i++)\n for (int j = 0; j < grid[0].size(); j++)\n if (grid[i][j] == '1') { count++; dfs(grid, i, j); }\n return count;\n}\nvoid dfs(vector>& grid, int r, int c) {\n if (r < 0 || r >= grid.size() || c < 0 || c >= grid[0].size() || grid[r][c] != '1') return;\n grid[r][c] = '0';\n dfs(grid, r+1, c); dfs(grid, r-1, c); dfs(grid, r, c+1); dfs(grid, r, c-1);\n}", "test_cases": ["grid=[[1,1,1,1,0],[1,1,0,1,0],[1,1,0,0,0],[0,0,0,0,0]] -> 1"], "key_points": ["DFS/BFS遍历", "访问后标记为0避免重复"], "tags": ["graph", "medium", "Google", "Facebook"]} {"problem_id": "algo_01861", "original_id": "two-sum", "title": "两数之和", "category": "array", "difficulty": "easy", "companies": ["Amazon", "Google"], "description": "给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那两个整数,并返回他们的数组下标。", "solution_python": "def twoSum(nums, target):\n hashmap = {}\n for i, num in enumerate(nums):\n complement = target - num\n if complement in hashmap:\n return [hashmap[complement], i]\n hashmap[num] = i\n return []", "solution_java": "public int[] twoSum(int[] nums, int target) {\n Map map = new HashMap<>();\n for (int i = 0; i < nums.length; i++) {\n int complement = target - nums[i];\n if (map.containsKey(complement)) return new int[]{map.get(complement), i};\n map.put(nums[i], i);\n }\n return new int[]{};\n}", "solution_cpp": "vector twoSum(vector& nums, int target) {\n unordered_map m;\n for (int i = 0; i < nums.size(); i++) {\n if (m.count(target - nums[i])) return {m[target - nums[i]], i};\n m[nums[i]] = i;\n }\n return {};\n}", "test_cases": ["nums=[2,7,11,15], target=9 -> [0,1]", "nums=[3,2,4], target=6 -> [1,2]"], "key_points": ["哈希表一次遍历", "空间换时间"], "tags": ["array", "easy", "Amazon", "Google"]} {"problem_id": "algo_01862", "original_id": "merge-sorted", "title": "合并两个有序数组", "category": "array", "difficulty": "easy", "companies": ["Microsoft", "Uber"], "description": "给你两个按非递减顺序排列的整数数组 nums1 和 nums2,另有两个整数 m 和 n,分别表示 nums1 和 nums2 中的元素数目。请你合并 nums2 到 nums1 中。", "solution_python": "def merge(nums1, m, nums2, n):\n p1, p2, p = m-1, n-1, m+n-1\n while p1 >= 0 and p2 >= 0:\n if nums1[p1] > nums2[p2]: nums1[p] = nums1[p1]; p1 -= 1\n else: nums1[p] = nums2[p2]; p2 -= 1\n p -= 1\n while p2 >= 0: nums1[p] = nums2[p2]; p2 -= 1; p -= 1", "solution_java": "public void merge(int[] nums1, int m, int[] nums2, int n) {\n int p1 = m-1, p2 = n-1, p = m+n-1;\n while (p1 >= 0 && p2 >= 0) {\n nums1[p--] = nums1[p1] > nums2[p2] ? nums1[p1--] : nums2[p2--];\n }\n while (p2 >= 0) nums1[p--] = nums2[p2--];\n}", "solution_cpp": "void merge(vector& nums1, int m, vector& nums2, int n) {\n int p1 = m-1, p2 = n-1, p = m+n-1;\n while (p1 >= 0 && p2 >= 0) nums1[p--] = nums1[p1] > nums2[p2] ? nums1[p1--] : nums2[p2--];\n while (p2 >= 0) nums1[p--] = nums2[p2--];\n}", "test_cases": ["nums1=[1,2,3], m=3, nums2=[2,5,6], n=3 -> [1,2,2,3,5,6]", "nums1=[], m=0, nums2=[1], n=1 -> [1]"], "key_points": ["从后往前合并", "三指针技巧"], "tags": ["array", "easy", "Microsoft", "Uber"]} {"problem_id": "algo_01863", "original_id": "max-subarray", "title": "最大子数组和", "category": "array", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "给你一个整数数组 nums ,请你找出一个具有最大和的连续子数组,返回其最大和。", "solution_python": "def maxSubArray(nums):\n max_sum = current = nums[0]\n for num in nums[1:]:\n current = max(num, current + num)\n max_sum = max(max_sum, current)\n return max_sum", "solution_java": "public int maxSubArray(int[] nums) {\n int maxSum = nums[0], curr = nums[0];\n for (int i = 1; i < nums.length; i++) {\n curr = Math.max(nums[i], curr + nums[i]);\n maxSum = Math.max(maxSum, curr);\n }\n return maxSum;\n}", "solution_cpp": "int maxSubArray(vector& nums) {\n int maxSum = nums[0], curr = nums[0];\n for (int i = 1; i < nums.size(); i++) {\n curr = max(nums[i], curr + nums[i]);\n maxSum = max(maxSum, curr);\n }\n return maxSum;\n}", "test_cases": ["nums=[-2,1,-3,4,-1,2,1,-5,4] -> 6", "nums=[1] -> 1"], "key_points": ["Kadane算法", "动态规划基础题"], "tags": ["array", "medium", "Google", "Microsoft"]} {"problem_id": "algo_01864", "original_id": "valid-parentheses", "title": "有效的括号", "category": "string", "difficulty": "easy", "companies": ["Google", "Uber"], "description": "给定一个只包括 '(',')','{','}','[',']' 的字符串 s,判断字符串是否有效。", "solution_python": "def isValid(s):\n stack = []\n mapping = {')': '(', ']': '[', '}': '{'}\n for c in s:\n if c in mapping:\n if not stack or stack[-1] != mapping[c]: return False\n stack.pop()\n else: stack.append(c)\n return not stack", "solution_java": "public boolean isValid(String s) {\n Stack stack = new Stack<>();\n Map map = Map.of(')', '(', ']', '[', '}', '{');\n for (char c : s.toCharArray()) {\n if (map.containsValue(c)) stack.push(c);\n else if (!stack.isEmpty() && stack.pop() != map.get(c)) return false;\n }\n return stack.isEmpty();\n}", "solution_cpp": "bool isValid(string s) {\n stack st;\n unordered_map m = {{')','('},{']','['},{'}','{'}};\n for (char c : s) {\n if (m.find(c) == m.end()) st.push(c);\n else if (st.empty() || st.top() != m[c]) return false;\n else st.pop();\n }\n return st.empty();\n}", "test_cases": ["s=\"()\" -> true", "s=\"()[]{}\" -> true", "s=\"(]\" -> false"], "key_points": ["栈匹配法", "注意空栈边界"], "tags": ["string", "easy", "Google", "Uber"]} {"problem_id": "algo_01865", "original_id": "longest-palindrome", "title": "最长回文子串", "category": "string", "difficulty": "medium", "companies": ["Google", "Amazon"], "description": "给你一个字符串 s,找到 s 中最长的回文子串。", "solution_python": "def longestPalindrome(s):\n def expand(l, r):\n while l >= 0 and r < len(s) and s[l] == s[r]: l -= 1; r += 1\n return l + 1, r - 1\n start = end = 0\n for i in range(len(s)):\n l1, r1 = expand(i, i)\n l2, r2 = expand(i, i + 1)\n if r1 - l1 > end - start: start, end = l1, r1\n if r2 - l2 > end - start: start, end = l2, r2\n return s[start:end+1]", "solution_java": "public String longestPalindrome(String s) {\n int start = 0, end = 0;\n for (int i = 0; i < s.length(); i++) {\n int len1 = expand(s, i, i), len2 = expand(s, i, i+1);\n int len = Math.max(len1, len2);\n if (len > end - start) { start = i - (len-1)/2; end = i + len/2; }\n }\n return s.substring(start, end + 1);\n}\nprivate int expand(String s, int l, int r) {\n while (l >= 0 && r < s.length() && s.charAt(l) == s.charAt(r)) { l--; r++; }\n return r - l - 1;\n}", "solution_cpp": "string longestPalindrome(string s) {\n int start = 0, end = 0;\n for (int i = 0; i < s.size(); i++) {\n int len1 = expand(s, i, i), len2 = expand(s, i, i+1);\n if (max(len1, len2) > end - start) { start = i - (max(len1,len2)-1)/2; end = i + max(len1,len2)/2; }\n }\n return s.substr(start, end - start + 1);\n}", "test_cases": ["s=\"babad\" -> bab或aba", "s=\"cbbd\" -> bb"], "key_points": ["中心扩展法", "处理奇偶长度"], "tags": ["string", "medium", "Google", "Amazon"]} {"problem_id": "algo_01866", "original_id": "reverse-list", "title": "反转链表", "category": "linkedlist", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "给你单链表的头节点 head,请你反转链表,并返回反转后的链表。", "solution_python": "def reverseList(head):\n prev = None\n curr = head\n while curr:\n nxt = curr.next\n curr.next = prev\n prev = curr\n curr = nxt\n return prev", "solution_java": "public ListNode reverseList(ListNode head) {\n ListNode prev = null, curr = head;\n while (curr != null) {\n ListNode next = curr.next;\n curr.next = prev;\n prev = curr;\n curr = next;\n }\n return prev;\n}", "solution_cpp": "ListNode* reverseList(ListNode* head) {\n ListNode* prev = nullptr, *curr = head;\n while (curr) {\n ListNode* next = curr->next;\n curr->next = prev;\n prev = curr;\n curr = next;\n }\n return prev;\n}", "test_cases": ["head=[1,2,3,4,5] -> [5,4,3,2,1]", "head=[1,2] -> [2,1]"], "key_points": ["迭代法 O(1)空间", "递归法 O(n)空间"], "tags": ["linkedlist", "medium", "Google", "Microsoft"]} {"problem_id": "algo_01867", "original_id": "middle-node", "title": "链表的中间结点", "category": "linkedlist", "difficulty": "easy", "companies": ["Amazon", "Facebook"], "description": "给你单链表的头节点 head,请你找出并返回链表的中间结点。如果有两个中间结点,则返回第二个中间结点。", "solution_python": "def middleNode(head):\n slow = fast = head\n while fast and fast.next:\n slow = slow.next\n fast = fast.next.next\n return slow", "solution_java": "public ListNode middleNode(ListNode head) {\n ListNode slow = head, fast = head;\n while (fast != null && fast.next != null) {\n slow = slow.next;\n fast = fast.next.next;\n }\n return slow;\n}", "solution_cpp": "ListNode* middleNode(ListNode* head) {\n ListNode* slow = head, *fast = head;\n while (fast && fast->next) { slow = slow->next; fast = fast->next->next; }\n return slow;\n}", "test_cases": ["head=[1,2,3,4,5] -> 3", "head=[1,2,3,4,5,6] -> 4"], "key_points": ["快慢指针", "O(n)时间O(1)空间"], "tags": ["linkedlist", "easy", "Amazon", "Facebook"]} {"problem_id": "algo_01868", "original_id": "max-depth", "title": "二叉树的最大深度", "category": "tree", "difficulty": "easy", "companies": ["Microsoft", "Apple"], "description": "给定一个二叉树 root,返回其最大深度。", "solution_python": "def maxDepth(root):\n if not root: return 0\n return max(maxDepth(root.left), maxDepth(root.right)) + 1", "solution_java": "public int maxDepth(TreeNode root) {\n if (root == null) return 0;\n return Math.max(maxDepth(root.left), maxDepth(root.right)) + 1;\n}", "solution_cpp": "int maxDepth(TreeNode* root) {\n if (!root) return 0;\n return max(maxDepth(root->left), maxDepth(root->right)) + 1;\n}", "test_cases": ["root=[3,9,20,null,null,15,7] -> 3", "root=[1,null,2] -> 2"], "key_points": ["DFS递归", "层序遍历也可"], "tags": ["tree", "easy", "Microsoft", "Apple"]} {"problem_id": "algo_01869", "original_id": "inorder-traversal", "title": "二叉树的中序遍历", "category": "tree", "difficulty": "easy", "companies": ["Google", "Microsoft"], "description": "给定一个二叉树的根节点 root,返回它的中序遍历结果。", "solution_python": "def inorderTraversal(root):\n result = []\n def dfs(node):\n if node:\n dfs(node.left)\n result.append(node.val)\n dfs(node.right)\n dfs(root)\n return result", "solution_java": "public List inorderTraversal(TreeNode root) {\n List res = new ArrayList<>();\n dfs(root, res);\n return res;\n}\nprivate void dfs(TreeNode node, List res) {\n if (node == null) return;\n dfs(node.left, res); res.add(node.val); dfs(node.right, res);\n}", "solution_cpp": "vector inorderTraversal(TreeNode* root) {\n vector res;\n dfs(root, res);\n return res;\n}\nvoid dfs(TreeNode* node, vector& res) {\n if (!node) return;\n dfs(node->left, res); res.push_back(node->val); dfs(node->right, res);\n}", "test_cases": ["root=[1,null,2,3] -> [1,3,2]", "root=[] -> []"], "key_points": ["左-根-右顺序", "递归最简洁"], "tags": ["tree", "easy", "Google", "Microsoft"]} {"problem_id": "algo_01870", "original_id": "binary-search", "title": "二分查找", "category": "binarysearch", "difficulty": "easy", "companies": ["Google", "Amazon"], "description": "给定一个 n 个元素有序的(升序)整型数组 nums 和一个目标值 target,写一个函数搜索 nums 中的 target,如果目标值存在返回下标,否则返回 -1。", "solution_python": "def search(nums, target):\n left, right = 0, len(nums) - 1\n while left <= right:\n mid = (left + right) // 2\n if nums[mid] == target: return mid\n elif nums[mid] < target: left = mid + 1\n else: right = mid - 1\n return -1", "solution_java": "public int search(int[] nums, int target) {\n int left = 0, right = nums.length - 1;\n while (left <= right) {\n int mid = left + (right - left) / 2;\n if (nums[mid] == target) return mid;\n else if (nums[mid] < target) left = mid + 1;\n else right = mid - 1;\n }\n return -1;\n}", "solution_cpp": "int search(vector& nums, int target) {\n int left = 0, right = nums.size() - 1;\n while (left <= right) {\n int mid = left + (right - left) / 2;\n if (nums[mid] == target) return mid;\n else if (nums[mid] < target) left = mid + 1;\n else right = mid - 1;\n }\n return -1;\n}", "test_cases": ["nums=[-1,0,3,5,9,12], target=9 -> 4", "nums=[-1,0,3,5,9,12], target=2 -> -1"], "key_points": ["标准模板", "注意防溢出写法"], "tags": ["binarysearch", "easy", "Google", "Amazon"]} {"problem_id": "algo_01871", "original_id": "climbing-stairs", "title": "爬楼梯", "category": "dp", "difficulty": "easy", "companies": ["Amazon", "Google"], "description": "假设你正在爬楼梯。需要 n 阶你才能到达楼顶。每次你可以爬 1 或 2 个台阶。你有多少种不同的方法可以爬到楼顶?", "solution_python": "def climbStairs(n):\n if n <= 2: return n\n a, b = 1, 2\n for _ in range(3, n+1):\n a, b = b, a + b\n return b", "solution_java": "public int climbStairs(int n) {\n if (n <= 2) return n;\n int a = 1, b = 2;\n for (int i = 3; i <= n; i++) { int temp = a + b; a = b; b = temp; }\n return b;\n}", "solution_cpp": "int climbStairs(int n) {\n if (n <= 2) return n;\n int a = 1, b = 2;\n for (int i = 3; i <= n; i++) { int temp = a + b; a = b; b = temp; }\n return b;\n}", "test_cases": ["n=2 -> 2", "n=3 -> 3", "n=5 -> 8"], "key_points": ["斐波那契数列", "滚动数组优化空间"], "tags": ["dp", "easy", "Amazon", "Google"]} {"problem_id": "algo_01872", "original_id": "coin-change", "title": "零钱兑换", "category": "dp", "difficulty": "medium", "companies": ["Google", "Amazon"], "description": "给你一个整数数组 coins 表示不同面额的硬币,以及一个整数 amount 表示总金额。计算并返回可以凑成总金额所需的最少的硬币个数。如果没有任何一种硬币组合能组成总金额,返回 -1。", "solution_python": "def coinChange(coins, amount):\n dp = [float('inf')] * (amount + 1)\n dp[0] = 0\n for coin in coins:\n for x in range(coin, amount + 1):\n dp[x] = min(dp[x], dp[x - coin] + 1)\n return dp[amount] if dp[amount] != float('inf') else -1", "solution_java": "public int coinChange(int[] coins, int amount) {\n int[] dp = new int[amount + 1];\n Arrays.fill(dp, amount + 1);\n dp[0] = 0;\n for (int coin : coins) {\n for (int x = coin; x <= amount; x++) {\n dp[x] = Math.min(dp[x], dp[x - coin] + 1);\n }\n }\n return dp[amount] > amount ? -1 : dp[amount];\n}", "solution_cpp": "int coinChange(vector& coins, int amount) {\n vector dp(amount + 1, amount + 1);\n dp[0] = 0;\n for (int coin : coins) {\n for (int x = coin; x <= amount; x++) {\n dp[x] = min(dp[x], dp[x - coin] + 1);\n }\n }\n return dp[amount] > amount ? -1 : dp[amount];\n}", "test_cases": ["coins=[1,2,5], amount=11 -> 3", "coins=[2], amount=3 -> -1"], "key_points": ["完全背包问题", "dp[x] = min(dp[x-coin]+1)"], "tags": ["dp", "medium", "Google", "Amazon"]} {"problem_id": "algo_01873", "original_id": "subsets", "title": "子集", "category": "backtracking", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "给你一个整数数组 nums ,数组中的元素 互不相同 。返回该数组所有可能的子集(幂集)。", "solution_python": "def subsets(nums):\n result = []\n def backtrack(start, path):\n result.append(path[:])\n for i in range(start, len(nums)):\n path.append(nums[i])\n backtrack(i + 1, path)\n path.pop()\n backtrack(0, [])\n return result", "solution_java": "public List> subsets(int[] nums) {\n List> result = new ArrayList<>();\n backtrack(nums, 0, new ArrayList<>(), result);\n return result;\n}\nprivate void backtrack(int[] nums, int start, List path, List> result) {\n result.add(new ArrayList<>(path));\n for (int i = start; i < nums.length; i++) {\n path.add(nums[i]);\n backtrack(nums, i + 1, path, result);\n path.remove(path.size() - 1);\n }\n}", "solution_cpp": "vector> subsets(vector& nums) {\n vector> result;\n vector path;\n backtrack(nums, 0, path, result);\n return result;\n}\nvoid backtrack(vector& nums, int start, vector& path, vector>& result) {\n result.push_back(path);\n for (int i = start; i < nums.size(); i++) {\n path.push_back(nums[i]);\n backtrack(nums, i + 1, path, result);\n path.pop_back();\n }\n}", "test_cases": ["nums=[1,2,3] -> [[],[1],[2],[1,2],[3],[1,3],[2,3],[1,2,3]]"], "key_points": ["选或不选", "DFS遍历子集树"], "tags": ["backtracking", "medium", "Google", "Microsoft"]} {"problem_id": "algo_01874", "original_id": "permutations", "title": "全排列", "category": "backtracking", "difficulty": "medium", "companies": ["Google", "Facebook"], "description": "给定一个不含重复数字的数组 nums,返回其所有可能的全排列。", "solution_python": "def permute(nums):\n result = []\n def backtrack(path, used):\n if len(path) == len(nums):\n result.append(path[:])\n return\n for i in range(len(nums)):\n if used[i]: continue\n used[i] = True\n path.append(nums[i])\n backtrack(path, used)\n path.pop()\n used[i] = False\n backtrack([], [False]*len(nums))\n return result", "solution_java": "public List> permute(int[] nums) {\n List> result = new ArrayList<>();\n boolean[] used = new boolean[nums.length];\n backtrack(nums, used, new ArrayList<>(), result);\n return result;\n}\nprivate void backtrack(int[] nums, boolean[] used, List path, List> result) {\n if (path.size() == nums.length) { result.add(new ArrayList<>(path)); return; }\n for (int i = 0; i < nums.length; i++) {\n if (used[i]) continue;\n used[i] = true;\n path.add(nums[i]);\n backtrack(nums, used, path, result);\n path.remove(path.size() - 1);\n used[i] = false;\n }\n}", "solution_cpp": "vector> permute(vector& nums) {\n vector> result;\n vector used(nums.size(), false);\n vector path;\n backtrack(nums, used, path, result);\n return result;\n}\nvoid backtrack(vector& nums, vector& used, vector& path, vector>& result) {\n if (path.size() == nums.size()) { result.push_back(path); return; }\n for (int i = 0; i < nums.size(); i++) {\n if (used[i]) continue;\n used[i] = true;\n path.push_back(nums[i]);\n backtrack(nums, used, path, result);\n path.pop_back();\n used[i] = false;\n }\n}", "test_cases": ["nums=[1,2,3] -> [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]"], "key_points": ["标记已使用元素", "回溯经典模板"], "tags": ["backtracking", "medium", "Google", "Facebook"]} {"problem_id": "algo_01875", "original_id": "top-k-frequent", "title": "前K个高频元素", "category": "heap", "difficulty": "medium", "companies": ["Amazon", "Facebook"], "description": "给你一个整数数组 nums 和一个整数 k,请你返回其中出现频率前 k 高的元素。", "solution_python": "import heapq\nfrom collections import Counter\ndef topKFrequent(nums, k):\n count = Counter(nums)\n heap = []\n for num, freq in count.items():\n heapq.heappush(heap, (freq, num))\n if len(heap) > k: heapq.heappop(heap)\n return [num for freq, num in heap]", "solution_java": "public int[] topKFrequent(int[] nums, int k) {\n Map count = new HashMap<>();\n for (int n : nums) count.put(n, count.getOrDefault(n, 0) + 1);\n PriorityQueue> heap = \n new PriorityQueue<>((a, b) -> a.getValue() - b.getValue());\n for (Map.Entry e : count.entrySet()) {\n heap.offer(e);\n if (heap.size() > k) heap.poll();\n }\n int[] res = new int[k];\n for (int i = k - 1; i >= 0; i--) res[i] = heap.poll().getKey();\n return res;\n}", "solution_cpp": "vector topKFrequent(vector& nums, int k) {\n unordered_map count;\n for (int n : nums) count[n]++;\n priority_queue, vector>, greater>> heap;\n for (auto& [num, freq] : count) {\n heap.push({freq, num});\n if (heap.size() > k) heap.pop();\n }\n vector res;\n while (!heap.empty()) { res.push_back(heap.top().second); heap.pop(); }\n reverse(res.begin(), res.end());\n return res;\n}", "test_cases": ["nums=[1,1,1,2,2,3], k=2 -> [1,2]", "nums=[1], k=1 -> [1]"], "key_points": ["小顶堆保持大小k", "时间复杂度O(nlogk)"], "tags": ["heap", "medium", "Amazon", "Facebook"]} {"problem_id": "algo_01876", "original_id": "3sum", "title": "三数之和", "category": "two-pointers", "difficulty": "medium", "companies": ["Google", "Amazon"], "description": "给你一个整数数组 nums,判断是否存在三元组满足和为0,返回所有不重复的三元组。", "solution_python": "def threeSum(nums):\n nums.sort()\n result = []\n for i in range(len(nums) - 2):\n if i > 0 and nums[i] == nums[i-1]: continue\n left, right = i + 1, len(nums) - 1\n while left < right:\n total = nums[i] + nums[left] + nums[right]\n if total < 0: left += 1\n elif total > 0: right -= 1\n else:\n result.append([nums[i], nums[left], nums[right]])\n while left < right and nums[left] == nums[left+1]: left += 1\n while left < right and nums[right] == nums[right-1]: right -= 1\n left += 1; right -= 1\n return result", "solution_java": "public List> threeSum(int[] nums) {\n Arrays.sort(nums);\n List> result = new ArrayList<>();\n for (int i = 0; i < nums.length - 2; i++) {\n if (i > 0 && nums[i] == nums[i-1]) continue;\n int left = i + 1, right = nums.length - 1;\n while (left < right) {\n int total = nums[i] + nums[left] + nums[right];\n if (total < 0) left++;\n else if (total > 0) right--;\n else {\n result.add(Arrays.asList(nums[i], nums[left], nums[right]));\n while (left < right && nums[left] == nums[left+1]) left++;\n while (left < right && nums[right] == nums[right-1]) right--;\n left++; right--;\n }\n }\n }\n return result;\n}", "solution_cpp": "vector> threeSum(vector& nums) {\n sort(nums.begin(), nums.end());\n vector> result;\n for (int i = 0; i < nums.size() - 2; i++) {\n if (i > 0 && nums[i] == nums[i-1]) continue;\n int left = i + 1, right = nums.size() - 1;\n while (left < right) {\n int total = nums[i] + nums[left] + nums[right];\n if (total < 0) left++;\n else if (total > 0) right--;\n else {\n result.push_back({nums[i], nums[left], nums[right]});\n while (left < right && nums[left] == nums[left+1]) left++;\n while (left < right && nums[right] == nums[right-1]) right--;\n left++; right--;\n }\n }\n }\n return result;\n}", "test_cases": ["nums=[-1,0,1,2,-1,-4] -> [[-1,-1,2],[-1,0,1]]"], "key_points": ["排序+双指针", "去重是关键"], "tags": ["two-pointers", "medium", "Google", "Amazon"]} {"problem_id": "algo_01877", "original_id": "container-water", "title": "盛最多水的容器", "category": "two-pointers", "difficulty": "medium", "companies": ["Google", "Uber"], "description": "给定一个长度为 n 的整数数组 height,找出其中的两条线,使得它们与 x 轴共同构成的容器可以容纳最多的水。", "solution_python": "def maxArea(height):\n left, right = 0, len(height) - 1\n max_area = 0\n while left < right:\n h = min(height[left], height[right])\n max_area = max(max_area, h * (right - left))\n if height[left] < height[right]: left += 1\n else: right -= 1\n return max_area", "solution_java": "public int maxArea(int[] height) {\n int left = 0, right = height.length - 1, maxArea = 0;\n while (left < right) {\n int h = Math.min(height[left], height[right]);\n maxArea = Math.max(maxArea, h * (right - left));\n if (height[left] < height[right]) left++;\n else right--;\n }\n return maxArea;\n}", "solution_cpp": "int maxArea(vector& height) {\n int left = 0, right = height.size() - 1, maxArea = 0;\n while (left < right) {\n int h = min(height[left], height[right]);\n maxArea = max(maxArea, h * (right - left));\n if (height[left] < height[right]) left++;\n else right--;\n }\n return maxArea;\n}", "test_cases": ["height=[1,8,6,2,5,4,8,3,7] -> 49"], "key_points": ["移动短边指针", "面积=min(h1,h2)*width"], "tags": ["two-pointers", "medium", "Google", "Uber"]} {"problem_id": "algo_01878", "original_id": "min-stack", "title": "最小栈", "category": "stack", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "设计一个支持 push,pop,top 操作,并能在常数时间内检索到最小元素的栈。", "solution_python": "class MinStack:\n def __init__(self):\n self.stack = []\n self.min_stack = []\n def push(self, val):\n self.stack.append(val)\n self.min_stack.append(min(val, self.min_stack[-1] if self.min_stack else val))\n def pop(self):\n self.stack.pop(); self.min_stack.pop()\n def top(self): return self.stack[-1]\n def getMin(self): return self.min_stack[-1]", "solution_java": "class MinStack {\n Stack stack = new Stack<>();\n Stack minStack = new Stack<>();\n public void push(int val) { stack.push(val); minStack.push(Math.min(val, minStack.isEmpty() ? val : minStack.peek())); }\n public void pop() { stack.pop(); minStack.pop(); }\n public int top() { return stack.peek(); }\n public int getMin() { return minStack.peek(); }\n}", "solution_cpp": "class MinStack {\n stack st, minSt;\npublic:\n void push(int val) { st.push(val); minSt.push(min(val, minSt.empty() ? val : minSt.top())); }\n void pop() { st.pop(); minSt.pop(); }\n int top() { return st.top(); }\n int getMin() { return minSt.top(); }\n};", "test_cases": ["push(-2), push(0), push(-3) -> getMin() returns -3"], "key_points": ["辅助栈记录最小值", "O(1)时间获取最小值"], "tags": ["stack", "medium", "Google", "Microsoft"]} {"problem_id": "algo_01879", "original_id": "lru-cache", "title": "LRU缓存", "category": "design", "difficulty": "hard", "companies": ["Google", "Amazon"], "description": "设计和实现一个 LRU(最近最少使用)缓存机制。", "solution_python": "class LRUCache:\n def __init__(self, capacity):\n self.capacity = capacity\n self.cache = {}\n self.order = []\n def get(self, key):\n if key not in self.cache: return -1\n self.order.remove(key); self.order.append(key)\n return self.cache[key]\n def put(self, key, value):\n if key in self.cache:\n self.order.remove(key)\n elif len(self.cache) >= self.capacity:\n del self.cache[self.order.pop(0)]\n self.cache[key] = value; self.order.append(key)", "solution_java": "class LRUCache {\n int capacity;\n LinkedHashMap cache = new LinkedHashMap<>();\n public LRUCache(int cap) { capacity = cap; }\n public int get(int key) { return cache.containsKey(key) ? cache.remove(key) : -1; }\n public void put(int key, int val) {\n if (cache.containsKey(key)) cache.remove(key);\n else if (cache.size() >= capacity) cache.remove(cache.keySet().iterator().next());\n cache.put(key, val);\n }\n}", "solution_cpp": "class LRUCache {\n int cap;\n list> dll;\n unordered_map>::iterator> cache;\npublic:\n LRUCache(int capacity) : cap(capacity) {}\n int get(int key) {\n auto it = cache.find(key);\n if (it == cache.end()) return -1;\n dll.splice(dll.end(), dll, it->second);\n return it->second->second;\n }\n void put(int key, int value) {\n auto it = cache.find(key);\n if (it != cache.end()) dll.erase(it->second);\n else if (cache.size() >= cap) { cache.erase(dll.front().first); dll.pop_front(); }\n dll.push_back({key, value});\n cache[key] = --dll.end();\n }\n};", "test_cases": ["put(1,1), put(2,2), get(1) -> 1"], "key_points": ["HashMap + 双向链表", "O(1)时间操作"], "tags": ["design", "hard", "Google", "Amazon"]} {"problem_id": "algo_01880", "original_id": "num-islands", "title": "岛屿数量", "category": "graph", "difficulty": "medium", "companies": ["Google", "Facebook"], "description": "给你一个由 '1'(陆地)和 '0'(水)组成的二维网格,请你计算网格中岛屿的数量。岛屿总是被水包围,且只能由水平或垂直方向相邻的陆地连接形成。", "solution_python": "def numIslands(grid):\n if not grid: return 0\n rows, cols = len(grid), len(grid[0])\n count = 0\n def dfs(r, c):\n if r < 0 or r >= rows or c < 0 or c >= cols or grid[r][c] != '1': return\n grid[r][c] = '0'\n dfs(r+1, c); dfs(r-1, c); dfs(r, c+1); dfs(r, c-1)\n for r in range(rows):\n for c in range(cols):\n if grid[r][c] == '1': count += 1; dfs(r, c)\n return count", "solution_java": "public int numIslands(char[][] grid) {\n if (grid.length == 0) return 0;\n int count = 0;\n for (int i = 0; i < grid.length; i++)\n for (int j = 0; j < grid[0].length; j++)\n if (grid[i][j] == '1') { count++; dfs(grid, i, j); }\n return count;\n}\nprivate void dfs(char[][] grid, int r, int c) {\n if (r < 0 || r >= grid.length || c < 0 || c >= grid[0].length || grid[r][c] != '1') return;\n grid[r][c] = '0';\n dfs(grid, r+1, c); dfs(grid, r-1, c); dfs(grid, r, c+1); dfs(grid, r, c-1);\n}", "solution_cpp": "int numIslands(vector>& grid) {\n if (grid.empty()) return 0;\n int count = 0;\n for (int i = 0; i < grid.size(); i++)\n for (int j = 0; j < grid[0].size(); j++)\n if (grid[i][j] == '1') { count++; dfs(grid, i, j); }\n return count;\n}\nvoid dfs(vector>& grid, int r, int c) {\n if (r < 0 || r >= grid.size() || c < 0 || c >= grid[0].size() || grid[r][c] != '1') return;\n grid[r][c] = '0';\n dfs(grid, r+1, c); dfs(grid, r-1, c); dfs(grid, r, c+1); dfs(grid, r, c-1);\n}", "test_cases": ["grid=[[1,1,1,1,0],[1,1,0,1,0],[1,1,0,0,0],[0,0,0,0,0]] -> 1"], "key_points": ["DFS/BFS遍历", "访问后标记为0避免重复"], "tags": ["graph", "medium", "Google", "Facebook"]} {"problem_id": "algo_01881", "original_id": "two-sum", "title": "两数之和", "category": "array", "difficulty": "easy", "companies": ["Amazon", "Google"], "description": "给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那两个整数,并返回他们的数组下标。", "solution_python": "def twoSum(nums, target):\n hashmap = {}\n for i, num in enumerate(nums):\n complement = target - num\n if complement in hashmap:\n return [hashmap[complement], i]\n hashmap[num] = i\n return []", "solution_java": "public int[] twoSum(int[] nums, int target) {\n Map map = new HashMap<>();\n for (int i = 0; i < nums.length; i++) {\n int complement = target - nums[i];\n if (map.containsKey(complement)) return new int[]{map.get(complement), i};\n map.put(nums[i], i);\n }\n return new int[]{};\n}", "solution_cpp": "vector twoSum(vector& nums, int target) {\n unordered_map m;\n for (int i = 0; i < nums.size(); i++) {\n if (m.count(target - nums[i])) return {m[target - nums[i]], i};\n m[nums[i]] = i;\n }\n return {};\n}", "test_cases": ["nums=[2,7,11,15], target=9 -> [0,1]", "nums=[3,2,4], target=6 -> [1,2]"], "key_points": ["哈希表一次遍历", "空间换时间"], "tags": ["array", "easy", "Amazon", "Google"]} {"problem_id": "algo_01882", "original_id": "merge-sorted", "title": "合并两个有序数组", "category": "array", "difficulty": "easy", "companies": ["Microsoft", "Uber"], "description": "给你两个按非递减顺序排列的整数数组 nums1 和 nums2,另有两个整数 m 和 n,分别表示 nums1 和 nums2 中的元素数目。请你合并 nums2 到 nums1 中。", "solution_python": "def merge(nums1, m, nums2, n):\n p1, p2, p = m-1, n-1, m+n-1\n while p1 >= 0 and p2 >= 0:\n if nums1[p1] > nums2[p2]: nums1[p] = nums1[p1]; p1 -= 1\n else: nums1[p] = nums2[p2]; p2 -= 1\n p -= 1\n while p2 >= 0: nums1[p] = nums2[p2]; p2 -= 1; p -= 1", "solution_java": "public void merge(int[] nums1, int m, int[] nums2, int n) {\n int p1 = m-1, p2 = n-1, p = m+n-1;\n while (p1 >= 0 && p2 >= 0) {\n nums1[p--] = nums1[p1] > nums2[p2] ? nums1[p1--] : nums2[p2--];\n }\n while (p2 >= 0) nums1[p--] = nums2[p2--];\n}", "solution_cpp": "void merge(vector& nums1, int m, vector& nums2, int n) {\n int p1 = m-1, p2 = n-1, p = m+n-1;\n while (p1 >= 0 && p2 >= 0) nums1[p--] = nums1[p1] > nums2[p2] ? nums1[p1--] : nums2[p2--];\n while (p2 >= 0) nums1[p--] = nums2[p2--];\n}", "test_cases": ["nums1=[1,2,3], m=3, nums2=[2,5,6], n=3 -> [1,2,2,3,5,6]", "nums1=[], m=0, nums2=[1], n=1 -> [1]"], "key_points": ["从后往前合并", "三指针技巧"], "tags": ["array", "easy", "Microsoft", "Uber"]} {"problem_id": "algo_01883", "original_id": "max-subarray", "title": "最大子数组和", "category": "array", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "给你一个整数数组 nums ,请你找出一个具有最大和的连续子数组,返回其最大和。", "solution_python": "def maxSubArray(nums):\n max_sum = current = nums[0]\n for num in nums[1:]:\n current = max(num, current + num)\n max_sum = max(max_sum, current)\n return max_sum", "solution_java": "public int maxSubArray(int[] nums) {\n int maxSum = nums[0], curr = nums[0];\n for (int i = 1; i < nums.length; i++) {\n curr = Math.max(nums[i], curr + nums[i]);\n maxSum = Math.max(maxSum, curr);\n }\n return maxSum;\n}", "solution_cpp": "int maxSubArray(vector& nums) {\n int maxSum = nums[0], curr = nums[0];\n for (int i = 1; i < nums.size(); i++) {\n curr = max(nums[i], curr + nums[i]);\n maxSum = max(maxSum, curr);\n }\n return maxSum;\n}", "test_cases": ["nums=[-2,1,-3,4,-1,2,1,-5,4] -> 6", "nums=[1] -> 1"], "key_points": ["Kadane算法", "动态规划基础题"], "tags": ["array", "medium", "Google", "Microsoft"]} {"problem_id": "algo_01884", "original_id": "valid-parentheses", "title": "有效的括号", "category": "string", "difficulty": "easy", "companies": ["Google", "Uber"], "description": "给定一个只包括 '(',')','{','}','[',']' 的字符串 s,判断字符串是否有效。", "solution_python": "def isValid(s):\n stack = []\n mapping = {')': '(', ']': '[', '}': '{'}\n for c in s:\n if c in mapping:\n if not stack or stack[-1] != mapping[c]: return False\n stack.pop()\n else: stack.append(c)\n return not stack", "solution_java": "public boolean isValid(String s) {\n Stack stack = new Stack<>();\n Map map = Map.of(')', '(', ']', '[', '}', '{');\n for (char c : s.toCharArray()) {\n if (map.containsValue(c)) stack.push(c);\n else if (!stack.isEmpty() && stack.pop() != map.get(c)) return false;\n }\n return stack.isEmpty();\n}", "solution_cpp": "bool isValid(string s) {\n stack st;\n unordered_map m = {{')','('},{']','['},{'}','{'}};\n for (char c : s) {\n if (m.find(c) == m.end()) st.push(c);\n else if (st.empty() || st.top() != m[c]) return false;\n else st.pop();\n }\n return st.empty();\n}", "test_cases": ["s=\"()\" -> true", "s=\"()[]{}\" -> true", "s=\"(]\" -> false"], "key_points": ["栈匹配法", "注意空栈边界"], "tags": ["string", "easy", "Google", "Uber"]} {"problem_id": "algo_01885", "original_id": "longest-palindrome", "title": "最长回文子串", "category": "string", "difficulty": "medium", "companies": ["Google", "Amazon"], "description": "给你一个字符串 s,找到 s 中最长的回文子串。", "solution_python": "def longestPalindrome(s):\n def expand(l, r):\n while l >= 0 and r < len(s) and s[l] == s[r]: l -= 1; r += 1\n return l + 1, r - 1\n start = end = 0\n for i in range(len(s)):\n l1, r1 = expand(i, i)\n l2, r2 = expand(i, i + 1)\n if r1 - l1 > end - start: start, end = l1, r1\n if r2 - l2 > end - start: start, end = l2, r2\n return s[start:end+1]", "solution_java": "public String longestPalindrome(String s) {\n int start = 0, end = 0;\n for (int i = 0; i < s.length(); i++) {\n int len1 = expand(s, i, i), len2 = expand(s, i, i+1);\n int len = Math.max(len1, len2);\n if (len > end - start) { start = i - (len-1)/2; end = i + len/2; }\n }\n return s.substring(start, end + 1);\n}\nprivate int expand(String s, int l, int r) {\n while (l >= 0 && r < s.length() && s.charAt(l) == s.charAt(r)) { l--; r++; }\n return r - l - 1;\n}", "solution_cpp": "string longestPalindrome(string s) {\n int start = 0, end = 0;\n for (int i = 0; i < s.size(); i++) {\n int len1 = expand(s, i, i), len2 = expand(s, i, i+1);\n if (max(len1, len2) > end - start) { start = i - (max(len1,len2)-1)/2; end = i + max(len1,len2)/2; }\n }\n return s.substr(start, end - start + 1);\n}", "test_cases": ["s=\"babad\" -> bab或aba", "s=\"cbbd\" -> bb"], "key_points": ["中心扩展法", "处理奇偶长度"], "tags": ["string", "medium", "Google", "Amazon"]} {"problem_id": "algo_01886", "original_id": "reverse-list", "title": "反转链表", "category": "linkedlist", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "给你单链表的头节点 head,请你反转链表,并返回反转后的链表。", "solution_python": "def reverseList(head):\n prev = None\n curr = head\n while curr:\n nxt = curr.next\n curr.next = prev\n prev = curr\n curr = nxt\n return prev", "solution_java": "public ListNode reverseList(ListNode head) {\n ListNode prev = null, curr = head;\n while (curr != null) {\n ListNode next = curr.next;\n curr.next = prev;\n prev = curr;\n curr = next;\n }\n return prev;\n}", "solution_cpp": "ListNode* reverseList(ListNode* head) {\n ListNode* prev = nullptr, *curr = head;\n while (curr) {\n ListNode* next = curr->next;\n curr->next = prev;\n prev = curr;\n curr = next;\n }\n return prev;\n}", "test_cases": ["head=[1,2,3,4,5] -> [5,4,3,2,1]", "head=[1,2] -> [2,1]"], "key_points": ["迭代法 O(1)空间", "递归法 O(n)空间"], "tags": ["linkedlist", "medium", "Google", "Microsoft"]} {"problem_id": "algo_01887", "original_id": "middle-node", "title": "链表的中间结点", "category": "linkedlist", "difficulty": "easy", "companies": ["Amazon", "Facebook"], "description": "给你单链表的头节点 head,请你找出并返回链表的中间结点。如果有两个中间结点,则返回第二个中间结点。", "solution_python": "def middleNode(head):\n slow = fast = head\n while fast and fast.next:\n slow = slow.next\n fast = fast.next.next\n return slow", "solution_java": "public ListNode middleNode(ListNode head) {\n ListNode slow = head, fast = head;\n while (fast != null && fast.next != null) {\n slow = slow.next;\n fast = fast.next.next;\n }\n return slow;\n}", "solution_cpp": "ListNode* middleNode(ListNode* head) {\n ListNode* slow = head, *fast = head;\n while (fast && fast->next) { slow = slow->next; fast = fast->next->next; }\n return slow;\n}", "test_cases": ["head=[1,2,3,4,5] -> 3", "head=[1,2,3,4,5,6] -> 4"], "key_points": ["快慢指针", "O(n)时间O(1)空间"], "tags": ["linkedlist", "easy", "Amazon", "Facebook"]} {"problem_id": "algo_01888", "original_id": "max-depth", "title": "二叉树的最大深度", "category": "tree", "difficulty": "easy", "companies": ["Microsoft", "Apple"], "description": "给定一个二叉树 root,返回其最大深度。", "solution_python": "def maxDepth(root):\n if not root: return 0\n return max(maxDepth(root.left), maxDepth(root.right)) + 1", "solution_java": "public int maxDepth(TreeNode root) {\n if (root == null) return 0;\n return Math.max(maxDepth(root.left), maxDepth(root.right)) + 1;\n}", "solution_cpp": "int maxDepth(TreeNode* root) {\n if (!root) return 0;\n return max(maxDepth(root->left), maxDepth(root->right)) + 1;\n}", "test_cases": ["root=[3,9,20,null,null,15,7] -> 3", "root=[1,null,2] -> 2"], "key_points": ["DFS递归", "层序遍历也可"], "tags": ["tree", "easy", "Microsoft", "Apple"]} {"problem_id": "algo_01889", "original_id": "inorder-traversal", "title": "二叉树的中序遍历", "category": "tree", "difficulty": "easy", "companies": ["Google", "Microsoft"], "description": "给定一个二叉树的根节点 root,返回它的中序遍历结果。", "solution_python": "def inorderTraversal(root):\n result = []\n def dfs(node):\n if node:\n dfs(node.left)\n result.append(node.val)\n dfs(node.right)\n dfs(root)\n return result", "solution_java": "public List inorderTraversal(TreeNode root) {\n List res = new ArrayList<>();\n dfs(root, res);\n return res;\n}\nprivate void dfs(TreeNode node, List res) {\n if (node == null) return;\n dfs(node.left, res); res.add(node.val); dfs(node.right, res);\n}", "solution_cpp": "vector inorderTraversal(TreeNode* root) {\n vector res;\n dfs(root, res);\n return res;\n}\nvoid dfs(TreeNode* node, vector& res) {\n if (!node) return;\n dfs(node->left, res); res.push_back(node->val); dfs(node->right, res);\n}", "test_cases": ["root=[1,null,2,3] -> [1,3,2]", "root=[] -> []"], "key_points": ["左-根-右顺序", "递归最简洁"], "tags": ["tree", "easy", "Google", "Microsoft"]} {"problem_id": "algo_01890", "original_id": "binary-search", "title": "二分查找", "category": "binarysearch", "difficulty": "easy", "companies": ["Google", "Amazon"], "description": "给定一个 n 个元素有序的(升序)整型数组 nums 和一个目标值 target,写一个函数搜索 nums 中的 target,如果目标值存在返回下标,否则返回 -1。", "solution_python": "def search(nums, target):\n left, right = 0, len(nums) - 1\n while left <= right:\n mid = (left + right) // 2\n if nums[mid] == target: return mid\n elif nums[mid] < target: left = mid + 1\n else: right = mid - 1\n return -1", "solution_java": "public int search(int[] nums, int target) {\n int left = 0, right = nums.length - 1;\n while (left <= right) {\n int mid = left + (right - left) / 2;\n if (nums[mid] == target) return mid;\n else if (nums[mid] < target) left = mid + 1;\n else right = mid - 1;\n }\n return -1;\n}", "solution_cpp": "int search(vector& nums, int target) {\n int left = 0, right = nums.size() - 1;\n while (left <= right) {\n int mid = left + (right - left) / 2;\n if (nums[mid] == target) return mid;\n else if (nums[mid] < target) left = mid + 1;\n else right = mid - 1;\n }\n return -1;\n}", "test_cases": ["nums=[-1,0,3,5,9,12], target=9 -> 4", "nums=[-1,0,3,5,9,12], target=2 -> -1"], "key_points": ["标准模板", "注意防溢出写法"], "tags": ["binarysearch", "easy", "Google", "Amazon"]} {"problem_id": "algo_01891", "original_id": "climbing-stairs", "title": "爬楼梯", "category": "dp", "difficulty": "easy", "companies": ["Amazon", "Google"], "description": "假设你正在爬楼梯。需要 n 阶你才能到达楼顶。每次你可以爬 1 或 2 个台阶。你有多少种不同的方法可以爬到楼顶?", "solution_python": "def climbStairs(n):\n if n <= 2: return n\n a, b = 1, 2\n for _ in range(3, n+1):\n a, b = b, a + b\n return b", "solution_java": "public int climbStairs(int n) {\n if (n <= 2) return n;\n int a = 1, b = 2;\n for (int i = 3; i <= n; i++) { int temp = a + b; a = b; b = temp; }\n return b;\n}", "solution_cpp": "int climbStairs(int n) {\n if (n <= 2) return n;\n int a = 1, b = 2;\n for (int i = 3; i <= n; i++) { int temp = a + b; a = b; b = temp; }\n return b;\n}", "test_cases": ["n=2 -> 2", "n=3 -> 3", "n=5 -> 8"], "key_points": ["斐波那契数列", "滚动数组优化空间"], "tags": ["dp", "easy", "Amazon", "Google"]} {"problem_id": "algo_01892", "original_id": "coin-change", "title": "零钱兑换", "category": "dp", "difficulty": "medium", "companies": ["Google", "Amazon"], "description": "给你一个整数数组 coins 表示不同面额的硬币,以及一个整数 amount 表示总金额。计算并返回可以凑成总金额所需的最少的硬币个数。如果没有任何一种硬币组合能组成总金额,返回 -1。", "solution_python": "def coinChange(coins, amount):\n dp = [float('inf')] * (amount + 1)\n dp[0] = 0\n for coin in coins:\n for x in range(coin, amount + 1):\n dp[x] = min(dp[x], dp[x - coin] + 1)\n return dp[amount] if dp[amount] != float('inf') else -1", "solution_java": "public int coinChange(int[] coins, int amount) {\n int[] dp = new int[amount + 1];\n Arrays.fill(dp, amount + 1);\n dp[0] = 0;\n for (int coin : coins) {\n for (int x = coin; x <= amount; x++) {\n dp[x] = Math.min(dp[x], dp[x - coin] + 1);\n }\n }\n return dp[amount] > amount ? -1 : dp[amount];\n}", "solution_cpp": "int coinChange(vector& coins, int amount) {\n vector dp(amount + 1, amount + 1);\n dp[0] = 0;\n for (int coin : coins) {\n for (int x = coin; x <= amount; x++) {\n dp[x] = min(dp[x], dp[x - coin] + 1);\n }\n }\n return dp[amount] > amount ? -1 : dp[amount];\n}", "test_cases": ["coins=[1,2,5], amount=11 -> 3", "coins=[2], amount=3 -> -1"], "key_points": ["完全背包问题", "dp[x] = min(dp[x-coin]+1)"], "tags": ["dp", "medium", "Google", "Amazon"]} {"problem_id": "algo_01893", "original_id": "subsets", "title": "子集", "category": "backtracking", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "给你一个整数数组 nums ,数组中的元素 互不相同 。返回该数组所有可能的子集(幂集)。", "solution_python": "def subsets(nums):\n result = []\n def backtrack(start, path):\n result.append(path[:])\n for i in range(start, len(nums)):\n path.append(nums[i])\n backtrack(i + 1, path)\n path.pop()\n backtrack(0, [])\n return result", "solution_java": "public List> subsets(int[] nums) {\n List> result = new ArrayList<>();\n backtrack(nums, 0, new ArrayList<>(), result);\n return result;\n}\nprivate void backtrack(int[] nums, int start, List path, List> result) {\n result.add(new ArrayList<>(path));\n for (int i = start; i < nums.length; i++) {\n path.add(nums[i]);\n backtrack(nums, i + 1, path, result);\n path.remove(path.size() - 1);\n }\n}", "solution_cpp": "vector> subsets(vector& nums) {\n vector> result;\n vector path;\n backtrack(nums, 0, path, result);\n return result;\n}\nvoid backtrack(vector& nums, int start, vector& path, vector>& result) {\n result.push_back(path);\n for (int i = start; i < nums.size(); i++) {\n path.push_back(nums[i]);\n backtrack(nums, i + 1, path, result);\n path.pop_back();\n }\n}", "test_cases": ["nums=[1,2,3] -> [[],[1],[2],[1,2],[3],[1,3],[2,3],[1,2,3]]"], "key_points": ["选或不选", "DFS遍历子集树"], "tags": ["backtracking", "medium", "Google", "Microsoft"]} {"problem_id": "algo_01894", "original_id": "permutations", "title": "全排列", "category": "backtracking", "difficulty": "medium", "companies": ["Google", "Facebook"], "description": "给定一个不含重复数字的数组 nums,返回其所有可能的全排列。", "solution_python": "def permute(nums):\n result = []\n def backtrack(path, used):\n if len(path) == len(nums):\n result.append(path[:])\n return\n for i in range(len(nums)):\n if used[i]: continue\n used[i] = True\n path.append(nums[i])\n backtrack(path, used)\n path.pop()\n used[i] = False\n backtrack([], [False]*len(nums))\n return result", "solution_java": "public List> permute(int[] nums) {\n List> result = new ArrayList<>();\n boolean[] used = new boolean[nums.length];\n backtrack(nums, used, new ArrayList<>(), result);\n return result;\n}\nprivate void backtrack(int[] nums, boolean[] used, List path, List> result) {\n if (path.size() == nums.length) { result.add(new ArrayList<>(path)); return; }\n for (int i = 0; i < nums.length; i++) {\n if (used[i]) continue;\n used[i] = true;\n path.add(nums[i]);\n backtrack(nums, used, path, result);\n path.remove(path.size() - 1);\n used[i] = false;\n }\n}", "solution_cpp": "vector> permute(vector& nums) {\n vector> result;\n vector used(nums.size(), false);\n vector path;\n backtrack(nums, used, path, result);\n return result;\n}\nvoid backtrack(vector& nums, vector& used, vector& path, vector>& result) {\n if (path.size() == nums.size()) { result.push_back(path); return; }\n for (int i = 0; i < nums.size(); i++) {\n if (used[i]) continue;\n used[i] = true;\n path.push_back(nums[i]);\n backtrack(nums, used, path, result);\n path.pop_back();\n used[i] = false;\n }\n}", "test_cases": ["nums=[1,2,3] -> [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]"], "key_points": ["标记已使用元素", "回溯经典模板"], "tags": ["backtracking", "medium", "Google", "Facebook"]} {"problem_id": "algo_01895", "original_id": "top-k-frequent", "title": "前K个高频元素", "category": "heap", "difficulty": "medium", "companies": ["Amazon", "Facebook"], "description": "给你一个整数数组 nums 和一个整数 k,请你返回其中出现频率前 k 高的元素。", "solution_python": "import heapq\nfrom collections import Counter\ndef topKFrequent(nums, k):\n count = Counter(nums)\n heap = []\n for num, freq in count.items():\n heapq.heappush(heap, (freq, num))\n if len(heap) > k: heapq.heappop(heap)\n return [num for freq, num in heap]", "solution_java": "public int[] topKFrequent(int[] nums, int k) {\n Map count = new HashMap<>();\n for (int n : nums) count.put(n, count.getOrDefault(n, 0) + 1);\n PriorityQueue> heap = \n new PriorityQueue<>((a, b) -> a.getValue() - b.getValue());\n for (Map.Entry e : count.entrySet()) {\n heap.offer(e);\n if (heap.size() > k) heap.poll();\n }\n int[] res = new int[k];\n for (int i = k - 1; i >= 0; i--) res[i] = heap.poll().getKey();\n return res;\n}", "solution_cpp": "vector topKFrequent(vector& nums, int k) {\n unordered_map count;\n for (int n : nums) count[n]++;\n priority_queue, vector>, greater>> heap;\n for (auto& [num, freq] : count) {\n heap.push({freq, num});\n if (heap.size() > k) heap.pop();\n }\n vector res;\n while (!heap.empty()) { res.push_back(heap.top().second); heap.pop(); }\n reverse(res.begin(), res.end());\n return res;\n}", "test_cases": ["nums=[1,1,1,2,2,3], k=2 -> [1,2]", "nums=[1], k=1 -> [1]"], "key_points": ["小顶堆保持大小k", "时间复杂度O(nlogk)"], "tags": ["heap", "medium", "Amazon", "Facebook"]} {"problem_id": "algo_01896", "original_id": "3sum", "title": "三数之和", "category": "two-pointers", "difficulty": "medium", "companies": ["Google", "Amazon"], "description": "给你一个整数数组 nums,判断是否存在三元组满足和为0,返回所有不重复的三元组。", "solution_python": "def threeSum(nums):\n nums.sort()\n result = []\n for i in range(len(nums) - 2):\n if i > 0 and nums[i] == nums[i-1]: continue\n left, right = i + 1, len(nums) - 1\n while left < right:\n total = nums[i] + nums[left] + nums[right]\n if total < 0: left += 1\n elif total > 0: right -= 1\n else:\n result.append([nums[i], nums[left], nums[right]])\n while left < right and nums[left] == nums[left+1]: left += 1\n while left < right and nums[right] == nums[right-1]: right -= 1\n left += 1; right -= 1\n return result", "solution_java": "public List> threeSum(int[] nums) {\n Arrays.sort(nums);\n List> result = new ArrayList<>();\n for (int i = 0; i < nums.length - 2; i++) {\n if (i > 0 && nums[i] == nums[i-1]) continue;\n int left = i + 1, right = nums.length - 1;\n while (left < right) {\n int total = nums[i] + nums[left] + nums[right];\n if (total < 0) left++;\n else if (total > 0) right--;\n else {\n result.add(Arrays.asList(nums[i], nums[left], nums[right]));\n while (left < right && nums[left] == nums[left+1]) left++;\n while (left < right && nums[right] == nums[right-1]) right--;\n left++; right--;\n }\n }\n }\n return result;\n}", "solution_cpp": "vector> threeSum(vector& nums) {\n sort(nums.begin(), nums.end());\n vector> result;\n for (int i = 0; i < nums.size() - 2; i++) {\n if (i > 0 && nums[i] == nums[i-1]) continue;\n int left = i + 1, right = nums.size() - 1;\n while (left < right) {\n int total = nums[i] + nums[left] + nums[right];\n if (total < 0) left++;\n else if (total > 0) right--;\n else {\n result.push_back({nums[i], nums[left], nums[right]});\n while (left < right && nums[left] == nums[left+1]) left++;\n while (left < right && nums[right] == nums[right-1]) right--;\n left++; right--;\n }\n }\n }\n return result;\n}", "test_cases": ["nums=[-1,0,1,2,-1,-4] -> [[-1,-1,2],[-1,0,1]]"], "key_points": ["排序+双指针", "去重是关键"], "tags": ["two-pointers", "medium", "Google", "Amazon"]} {"problem_id": "algo_01897", "original_id": "container-water", "title": "盛最多水的容器", "category": "two-pointers", "difficulty": "medium", "companies": ["Google", "Uber"], "description": "给定一个长度为 n 的整数数组 height,找出其中的两条线,使得它们与 x 轴共同构成的容器可以容纳最多的水。", "solution_python": "def maxArea(height):\n left, right = 0, len(height) - 1\n max_area = 0\n while left < right:\n h = min(height[left], height[right])\n max_area = max(max_area, h * (right - left))\n if height[left] < height[right]: left += 1\n else: right -= 1\n return max_area", "solution_java": "public int maxArea(int[] height) {\n int left = 0, right = height.length - 1, maxArea = 0;\n while (left < right) {\n int h = Math.min(height[left], height[right]);\n maxArea = Math.max(maxArea, h * (right - left));\n if (height[left] < height[right]) left++;\n else right--;\n }\n return maxArea;\n}", "solution_cpp": "int maxArea(vector& height) {\n int left = 0, right = height.size() - 1, maxArea = 0;\n while (left < right) {\n int h = min(height[left], height[right]);\n maxArea = max(maxArea, h * (right - left));\n if (height[left] < height[right]) left++;\n else right--;\n }\n return maxArea;\n}", "test_cases": ["height=[1,8,6,2,5,4,8,3,7] -> 49"], "key_points": ["移动短边指针", "面积=min(h1,h2)*width"], "tags": ["two-pointers", "medium", "Google", "Uber"]} {"problem_id": "algo_01898", "original_id": "min-stack", "title": "最小栈", "category": "stack", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "设计一个支持 push,pop,top 操作,并能在常数时间内检索到最小元素的栈。", "solution_python": "class MinStack:\n def __init__(self):\n self.stack = []\n self.min_stack = []\n def push(self, val):\n self.stack.append(val)\n self.min_stack.append(min(val, self.min_stack[-1] if self.min_stack else val))\n def pop(self):\n self.stack.pop(); self.min_stack.pop()\n def top(self): return self.stack[-1]\n def getMin(self): return self.min_stack[-1]", "solution_java": "class MinStack {\n Stack stack = new Stack<>();\n Stack minStack = new Stack<>();\n public void push(int val) { stack.push(val); minStack.push(Math.min(val, minStack.isEmpty() ? val : minStack.peek())); }\n public void pop() { stack.pop(); minStack.pop(); }\n public int top() { return stack.peek(); }\n public int getMin() { return minStack.peek(); }\n}", "solution_cpp": "class MinStack {\n stack st, minSt;\npublic:\n void push(int val) { st.push(val); minSt.push(min(val, minSt.empty() ? val : minSt.top())); }\n void pop() { st.pop(); minSt.pop(); }\n int top() { return st.top(); }\n int getMin() { return minSt.top(); }\n};", "test_cases": ["push(-2), push(0), push(-3) -> getMin() returns -3"], "key_points": ["辅助栈记录最小值", "O(1)时间获取最小值"], "tags": ["stack", "medium", "Google", "Microsoft"]} {"problem_id": "algo_01899", "original_id": "lru-cache", "title": "LRU缓存", "category": "design", "difficulty": "hard", "companies": ["Google", "Amazon"], "description": "设计和实现一个 LRU(最近最少使用)缓存机制。", "solution_python": "class LRUCache:\n def __init__(self, capacity):\n self.capacity = capacity\n self.cache = {}\n self.order = []\n def get(self, key):\n if key not in self.cache: return -1\n self.order.remove(key); self.order.append(key)\n return self.cache[key]\n def put(self, key, value):\n if key in self.cache:\n self.order.remove(key)\n elif len(self.cache) >= self.capacity:\n del self.cache[self.order.pop(0)]\n self.cache[key] = value; self.order.append(key)", "solution_java": "class LRUCache {\n int capacity;\n LinkedHashMap cache = new LinkedHashMap<>();\n public LRUCache(int cap) { capacity = cap; }\n public int get(int key) { return cache.containsKey(key) ? cache.remove(key) : -1; }\n public void put(int key, int val) {\n if (cache.containsKey(key)) cache.remove(key);\n else if (cache.size() >= capacity) cache.remove(cache.keySet().iterator().next());\n cache.put(key, val);\n }\n}", "solution_cpp": "class LRUCache {\n int cap;\n list> dll;\n unordered_map>::iterator> cache;\npublic:\n LRUCache(int capacity) : cap(capacity) {}\n int get(int key) {\n auto it = cache.find(key);\n if (it == cache.end()) return -1;\n dll.splice(dll.end(), dll, it->second);\n return it->second->second;\n }\n void put(int key, int value) {\n auto it = cache.find(key);\n if (it != cache.end()) dll.erase(it->second);\n else if (cache.size() >= cap) { cache.erase(dll.front().first); dll.pop_front(); }\n dll.push_back({key, value});\n cache[key] = --dll.end();\n }\n};", "test_cases": ["put(1,1), put(2,2), get(1) -> 1"], "key_points": ["HashMap + 双向链表", "O(1)时间操作"], "tags": ["design", "hard", "Google", "Amazon"]} {"problem_id": "algo_01900", "original_id": "num-islands", "title": "岛屿数量", "category": "graph", "difficulty": "medium", "companies": ["Google", "Facebook"], "description": "给你一个由 '1'(陆地)和 '0'(水)组成的二维网格,请你计算网格中岛屿的数量。岛屿总是被水包围,且只能由水平或垂直方向相邻的陆地连接形成。", "solution_python": "def numIslands(grid):\n if not grid: return 0\n rows, cols = len(grid), len(grid[0])\n count = 0\n def dfs(r, c):\n if r < 0 or r >= rows or c < 0 or c >= cols or grid[r][c] != '1': return\n grid[r][c] = '0'\n dfs(r+1, c); dfs(r-1, c); dfs(r, c+1); dfs(r, c-1)\n for r in range(rows):\n for c in range(cols):\n if grid[r][c] == '1': count += 1; dfs(r, c)\n return count", "solution_java": "public int numIslands(char[][] grid) {\n if (grid.length == 0) return 0;\n int count = 0;\n for (int i = 0; i < grid.length; i++)\n for (int j = 0; j < grid[0].length; j++)\n if (grid[i][j] == '1') { count++; dfs(grid, i, j); }\n return count;\n}\nprivate void dfs(char[][] grid, int r, int c) {\n if (r < 0 || r >= grid.length || c < 0 || c >= grid[0].length || grid[r][c] != '1') return;\n grid[r][c] = '0';\n dfs(grid, r+1, c); dfs(grid, r-1, c); dfs(grid, r, c+1); dfs(grid, r, c-1);\n}", "solution_cpp": "int numIslands(vector>& grid) {\n if (grid.empty()) return 0;\n int count = 0;\n for (int i = 0; i < grid.size(); i++)\n for (int j = 0; j < grid[0].size(); j++)\n if (grid[i][j] == '1') { count++; dfs(grid, i, j); }\n return count;\n}\nvoid dfs(vector>& grid, int r, int c) {\n if (r < 0 || r >= grid.size() || c < 0 || c >= grid[0].size() || grid[r][c] != '1') return;\n grid[r][c] = '0';\n dfs(grid, r+1, c); dfs(grid, r-1, c); dfs(grid, r, c+1); dfs(grid, r, c-1);\n}", "test_cases": ["grid=[[1,1,1,1,0],[1,1,0,1,0],[1,1,0,0,0],[0,0,0,0,0]] -> 1"], "key_points": ["DFS/BFS遍历", "访问后标记为0避免重复"], "tags": ["graph", "medium", "Google", "Facebook"]} {"problem_id": "algo_01901", "original_id": "two-sum", "title": "两数之和", "category": "array", "difficulty": "easy", "companies": ["Amazon", "Google"], "description": "给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那两个整数,并返回他们的数组下标。", "solution_python": "def twoSum(nums, target):\n hashmap = {}\n for i, num in enumerate(nums):\n complement = target - num\n if complement in hashmap:\n return [hashmap[complement], i]\n hashmap[num] = i\n return []", "solution_java": "public int[] twoSum(int[] nums, int target) {\n Map map = new HashMap<>();\n for (int i = 0; i < nums.length; i++) {\n int complement = target - nums[i];\n if (map.containsKey(complement)) return new int[]{map.get(complement), i};\n map.put(nums[i], i);\n }\n return new int[]{};\n}", "solution_cpp": "vector twoSum(vector& nums, int target) {\n unordered_map m;\n for (int i = 0; i < nums.size(); i++) {\n if (m.count(target - nums[i])) return {m[target - nums[i]], i};\n m[nums[i]] = i;\n }\n return {};\n}", "test_cases": ["nums=[2,7,11,15], target=9 -> [0,1]", "nums=[3,2,4], target=6 -> [1,2]"], "key_points": ["哈希表一次遍历", "空间换时间"], "tags": ["array", "easy", "Amazon", "Google"]} {"problem_id": "algo_01902", "original_id": "merge-sorted", "title": "合并两个有序数组", "category": "array", "difficulty": "easy", "companies": ["Microsoft", "Uber"], "description": "给你两个按非递减顺序排列的整数数组 nums1 和 nums2,另有两个整数 m 和 n,分别表示 nums1 和 nums2 中的元素数目。请你合并 nums2 到 nums1 中。", "solution_python": "def merge(nums1, m, nums2, n):\n p1, p2, p = m-1, n-1, m+n-1\n while p1 >= 0 and p2 >= 0:\n if nums1[p1] > nums2[p2]: nums1[p] = nums1[p1]; p1 -= 1\n else: nums1[p] = nums2[p2]; p2 -= 1\n p -= 1\n while p2 >= 0: nums1[p] = nums2[p2]; p2 -= 1; p -= 1", "solution_java": "public void merge(int[] nums1, int m, int[] nums2, int n) {\n int p1 = m-1, p2 = n-1, p = m+n-1;\n while (p1 >= 0 && p2 >= 0) {\n nums1[p--] = nums1[p1] > nums2[p2] ? nums1[p1--] : nums2[p2--];\n }\n while (p2 >= 0) nums1[p--] = nums2[p2--];\n}", "solution_cpp": "void merge(vector& nums1, int m, vector& nums2, int n) {\n int p1 = m-1, p2 = n-1, p = m+n-1;\n while (p1 >= 0 && p2 >= 0) nums1[p--] = nums1[p1] > nums2[p2] ? nums1[p1--] : nums2[p2--];\n while (p2 >= 0) nums1[p--] = nums2[p2--];\n}", "test_cases": ["nums1=[1,2,3], m=3, nums2=[2,5,6], n=3 -> [1,2,2,3,5,6]", "nums1=[], m=0, nums2=[1], n=1 -> [1]"], "key_points": ["从后往前合并", "三指针技巧"], "tags": ["array", "easy", "Microsoft", "Uber"]} {"problem_id": "algo_01903", "original_id": "max-subarray", "title": "最大子数组和", "category": "array", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "给你一个整数数组 nums ,请你找出一个具有最大和的连续子数组,返回其最大和。", "solution_python": "def maxSubArray(nums):\n max_sum = current = nums[0]\n for num in nums[1:]:\n current = max(num, current + num)\n max_sum = max(max_sum, current)\n return max_sum", "solution_java": "public int maxSubArray(int[] nums) {\n int maxSum = nums[0], curr = nums[0];\n for (int i = 1; i < nums.length; i++) {\n curr = Math.max(nums[i], curr + nums[i]);\n maxSum = Math.max(maxSum, curr);\n }\n return maxSum;\n}", "solution_cpp": "int maxSubArray(vector& nums) {\n int maxSum = nums[0], curr = nums[0];\n for (int i = 1; i < nums.size(); i++) {\n curr = max(nums[i], curr + nums[i]);\n maxSum = max(maxSum, curr);\n }\n return maxSum;\n}", "test_cases": ["nums=[-2,1,-3,4,-1,2,1,-5,4] -> 6", "nums=[1] -> 1"], "key_points": ["Kadane算法", "动态规划基础题"], "tags": ["array", "medium", "Google", "Microsoft"]} {"problem_id": "algo_01904", "original_id": "valid-parentheses", "title": "有效的括号", "category": "string", "difficulty": "easy", "companies": ["Google", "Uber"], "description": "给定一个只包括 '(',')','{','}','[',']' 的字符串 s,判断字符串是否有效。", "solution_python": "def isValid(s):\n stack = []\n mapping = {')': '(', ']': '[', '}': '{'}\n for c in s:\n if c in mapping:\n if not stack or stack[-1] != mapping[c]: return False\n stack.pop()\n else: stack.append(c)\n return not stack", "solution_java": "public boolean isValid(String s) {\n Stack stack = new Stack<>();\n Map map = Map.of(')', '(', ']', '[', '}', '{');\n for (char c : s.toCharArray()) {\n if (map.containsValue(c)) stack.push(c);\n else if (!stack.isEmpty() && stack.pop() != map.get(c)) return false;\n }\n return stack.isEmpty();\n}", "solution_cpp": "bool isValid(string s) {\n stack st;\n unordered_map m = {{')','('},{']','['},{'}','{'}};\n for (char c : s) {\n if (m.find(c) == m.end()) st.push(c);\n else if (st.empty() || st.top() != m[c]) return false;\n else st.pop();\n }\n return st.empty();\n}", "test_cases": ["s=\"()\" -> true", "s=\"()[]{}\" -> true", "s=\"(]\" -> false"], "key_points": ["栈匹配法", "注意空栈边界"], "tags": ["string", "easy", "Google", "Uber"]} {"problem_id": "algo_01905", "original_id": "longest-palindrome", "title": "最长回文子串", "category": "string", "difficulty": "medium", "companies": ["Google", "Amazon"], "description": "给你一个字符串 s,找到 s 中最长的回文子串。", "solution_python": "def longestPalindrome(s):\n def expand(l, r):\n while l >= 0 and r < len(s) and s[l] == s[r]: l -= 1; r += 1\n return l + 1, r - 1\n start = end = 0\n for i in range(len(s)):\n l1, r1 = expand(i, i)\n l2, r2 = expand(i, i + 1)\n if r1 - l1 > end - start: start, end = l1, r1\n if r2 - l2 > end - start: start, end = l2, r2\n return s[start:end+1]", "solution_java": "public String longestPalindrome(String s) {\n int start = 0, end = 0;\n for (int i = 0; i < s.length(); i++) {\n int len1 = expand(s, i, i), len2 = expand(s, i, i+1);\n int len = Math.max(len1, len2);\n if (len > end - start) { start = i - (len-1)/2; end = i + len/2; }\n }\n return s.substring(start, end + 1);\n}\nprivate int expand(String s, int l, int r) {\n while (l >= 0 && r < s.length() && s.charAt(l) == s.charAt(r)) { l--; r++; }\n return r - l - 1;\n}", "solution_cpp": "string longestPalindrome(string s) {\n int start = 0, end = 0;\n for (int i = 0; i < s.size(); i++) {\n int len1 = expand(s, i, i), len2 = expand(s, i, i+1);\n if (max(len1, len2) > end - start) { start = i - (max(len1,len2)-1)/2; end = i + max(len1,len2)/2; }\n }\n return s.substr(start, end - start + 1);\n}", "test_cases": ["s=\"babad\" -> bab或aba", "s=\"cbbd\" -> bb"], "key_points": ["中心扩展法", "处理奇偶长度"], "tags": ["string", "medium", "Google", "Amazon"]} {"problem_id": "algo_01906", "original_id": "reverse-list", "title": "反转链表", "category": "linkedlist", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "给你单链表的头节点 head,请你反转链表,并返回反转后的链表。", "solution_python": "def reverseList(head):\n prev = None\n curr = head\n while curr:\n nxt = curr.next\n curr.next = prev\n prev = curr\n curr = nxt\n return prev", "solution_java": "public ListNode reverseList(ListNode head) {\n ListNode prev = null, curr = head;\n while (curr != null) {\n ListNode next = curr.next;\n curr.next = prev;\n prev = curr;\n curr = next;\n }\n return prev;\n}", "solution_cpp": "ListNode* reverseList(ListNode* head) {\n ListNode* prev = nullptr, *curr = head;\n while (curr) {\n ListNode* next = curr->next;\n curr->next = prev;\n prev = curr;\n curr = next;\n }\n return prev;\n}", "test_cases": ["head=[1,2,3,4,5] -> [5,4,3,2,1]", "head=[1,2] -> [2,1]"], "key_points": ["迭代法 O(1)空间", "递归法 O(n)空间"], "tags": ["linkedlist", "medium", "Google", "Microsoft"]} {"problem_id": "algo_01907", "original_id": "middle-node", "title": "链表的中间结点", "category": "linkedlist", "difficulty": "easy", "companies": ["Amazon", "Facebook"], "description": "给你单链表的头节点 head,请你找出并返回链表的中间结点。如果有两个中间结点,则返回第二个中间结点。", "solution_python": "def middleNode(head):\n slow = fast = head\n while fast and fast.next:\n slow = slow.next\n fast = fast.next.next\n return slow", "solution_java": "public ListNode middleNode(ListNode head) {\n ListNode slow = head, fast = head;\n while (fast != null && fast.next != null) {\n slow = slow.next;\n fast = fast.next.next;\n }\n return slow;\n}", "solution_cpp": "ListNode* middleNode(ListNode* head) {\n ListNode* slow = head, *fast = head;\n while (fast && fast->next) { slow = slow->next; fast = fast->next->next; }\n return slow;\n}", "test_cases": ["head=[1,2,3,4,5] -> 3", "head=[1,2,3,4,5,6] -> 4"], "key_points": ["快慢指针", "O(n)时间O(1)空间"], "tags": ["linkedlist", "easy", "Amazon", "Facebook"]} {"problem_id": "algo_01908", "original_id": "max-depth", "title": "二叉树的最大深度", "category": "tree", "difficulty": "easy", "companies": ["Microsoft", "Apple"], "description": "给定一个二叉树 root,返回其最大深度。", "solution_python": "def maxDepth(root):\n if not root: return 0\n return max(maxDepth(root.left), maxDepth(root.right)) + 1", "solution_java": "public int maxDepth(TreeNode root) {\n if (root == null) return 0;\n return Math.max(maxDepth(root.left), maxDepth(root.right)) + 1;\n}", "solution_cpp": "int maxDepth(TreeNode* root) {\n if (!root) return 0;\n return max(maxDepth(root->left), maxDepth(root->right)) + 1;\n}", "test_cases": ["root=[3,9,20,null,null,15,7] -> 3", "root=[1,null,2] -> 2"], "key_points": ["DFS递归", "层序遍历也可"], "tags": ["tree", "easy", "Microsoft", "Apple"]} {"problem_id": "algo_01909", "original_id": "inorder-traversal", "title": "二叉树的中序遍历", "category": "tree", "difficulty": "easy", "companies": ["Google", "Microsoft"], "description": "给定一个二叉树的根节点 root,返回它的中序遍历结果。", "solution_python": "def inorderTraversal(root):\n result = []\n def dfs(node):\n if node:\n dfs(node.left)\n result.append(node.val)\n dfs(node.right)\n dfs(root)\n return result", "solution_java": "public List inorderTraversal(TreeNode root) {\n List res = new ArrayList<>();\n dfs(root, res);\n return res;\n}\nprivate void dfs(TreeNode node, List res) {\n if (node == null) return;\n dfs(node.left, res); res.add(node.val); dfs(node.right, res);\n}", "solution_cpp": "vector inorderTraversal(TreeNode* root) {\n vector res;\n dfs(root, res);\n return res;\n}\nvoid dfs(TreeNode* node, vector& res) {\n if (!node) return;\n dfs(node->left, res); res.push_back(node->val); dfs(node->right, res);\n}", "test_cases": ["root=[1,null,2,3] -> [1,3,2]", "root=[] -> []"], "key_points": ["左-根-右顺序", "递归最简洁"], "tags": ["tree", "easy", "Google", "Microsoft"]} {"problem_id": "algo_01910", "original_id": "binary-search", "title": "二分查找", "category": "binarysearch", "difficulty": "easy", "companies": ["Google", "Amazon"], "description": "给定一个 n 个元素有序的(升序)整型数组 nums 和一个目标值 target,写一个函数搜索 nums 中的 target,如果目标值存在返回下标,否则返回 -1。", "solution_python": "def search(nums, target):\n left, right = 0, len(nums) - 1\n while left <= right:\n mid = (left + right) // 2\n if nums[mid] == target: return mid\n elif nums[mid] < target: left = mid + 1\n else: right = mid - 1\n return -1", "solution_java": "public int search(int[] nums, int target) {\n int left = 0, right = nums.length - 1;\n while (left <= right) {\n int mid = left + (right - left) / 2;\n if (nums[mid] == target) return mid;\n else if (nums[mid] < target) left = mid + 1;\n else right = mid - 1;\n }\n return -1;\n}", "solution_cpp": "int search(vector& nums, int target) {\n int left = 0, right = nums.size() - 1;\n while (left <= right) {\n int mid = left + (right - left) / 2;\n if (nums[mid] == target) return mid;\n else if (nums[mid] < target) left = mid + 1;\n else right = mid - 1;\n }\n return -1;\n}", "test_cases": ["nums=[-1,0,3,5,9,12], target=9 -> 4", "nums=[-1,0,3,5,9,12], target=2 -> -1"], "key_points": ["标准模板", "注意防溢出写法"], "tags": ["binarysearch", "easy", "Google", "Amazon"]} {"problem_id": "algo_01911", "original_id": "climbing-stairs", "title": "爬楼梯", "category": "dp", "difficulty": "easy", "companies": ["Amazon", "Google"], "description": "假设你正在爬楼梯。需要 n 阶你才能到达楼顶。每次你可以爬 1 或 2 个台阶。你有多少种不同的方法可以爬到楼顶?", "solution_python": "def climbStairs(n):\n if n <= 2: return n\n a, b = 1, 2\n for _ in range(3, n+1):\n a, b = b, a + b\n return b", "solution_java": "public int climbStairs(int n) {\n if (n <= 2) return n;\n int a = 1, b = 2;\n for (int i = 3; i <= n; i++) { int temp = a + b; a = b; b = temp; }\n return b;\n}", "solution_cpp": "int climbStairs(int n) {\n if (n <= 2) return n;\n int a = 1, b = 2;\n for (int i = 3; i <= n; i++) { int temp = a + b; a = b; b = temp; }\n return b;\n}", "test_cases": ["n=2 -> 2", "n=3 -> 3", "n=5 -> 8"], "key_points": ["斐波那契数列", "滚动数组优化空间"], "tags": ["dp", "easy", "Amazon", "Google"]} {"problem_id": "algo_01912", "original_id": "coin-change", "title": "零钱兑换", "category": "dp", "difficulty": "medium", "companies": ["Google", "Amazon"], "description": "给你一个整数数组 coins 表示不同面额的硬币,以及一个整数 amount 表示总金额。计算并返回可以凑成总金额所需的最少的硬币个数。如果没有任何一种硬币组合能组成总金额,返回 -1。", "solution_python": "def coinChange(coins, amount):\n dp = [float('inf')] * (amount + 1)\n dp[0] = 0\n for coin in coins:\n for x in range(coin, amount + 1):\n dp[x] = min(dp[x], dp[x - coin] + 1)\n return dp[amount] if dp[amount] != float('inf') else -1", "solution_java": "public int coinChange(int[] coins, int amount) {\n int[] dp = new int[amount + 1];\n Arrays.fill(dp, amount + 1);\n dp[0] = 0;\n for (int coin : coins) {\n for (int x = coin; x <= amount; x++) {\n dp[x] = Math.min(dp[x], dp[x - coin] + 1);\n }\n }\n return dp[amount] > amount ? -1 : dp[amount];\n}", "solution_cpp": "int coinChange(vector& coins, int amount) {\n vector dp(amount + 1, amount + 1);\n dp[0] = 0;\n for (int coin : coins) {\n for (int x = coin; x <= amount; x++) {\n dp[x] = min(dp[x], dp[x - coin] + 1);\n }\n }\n return dp[amount] > amount ? -1 : dp[amount];\n}", "test_cases": ["coins=[1,2,5], amount=11 -> 3", "coins=[2], amount=3 -> -1"], "key_points": ["完全背包问题", "dp[x] = min(dp[x-coin]+1)"], "tags": ["dp", "medium", "Google", "Amazon"]} {"problem_id": "algo_01913", "original_id": "subsets", "title": "子集", "category": "backtracking", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "给你一个整数数组 nums ,数组中的元素 互不相同 。返回该数组所有可能的子集(幂集)。", "solution_python": "def subsets(nums):\n result = []\n def backtrack(start, path):\n result.append(path[:])\n for i in range(start, len(nums)):\n path.append(nums[i])\n backtrack(i + 1, path)\n path.pop()\n backtrack(0, [])\n return result", "solution_java": "public List> subsets(int[] nums) {\n List> result = new ArrayList<>();\n backtrack(nums, 0, new ArrayList<>(), result);\n return result;\n}\nprivate void backtrack(int[] nums, int start, List path, List> result) {\n result.add(new ArrayList<>(path));\n for (int i = start; i < nums.length; i++) {\n path.add(nums[i]);\n backtrack(nums, i + 1, path, result);\n path.remove(path.size() - 1);\n }\n}", "solution_cpp": "vector> subsets(vector& nums) {\n vector> result;\n vector path;\n backtrack(nums, 0, path, result);\n return result;\n}\nvoid backtrack(vector& nums, int start, vector& path, vector>& result) {\n result.push_back(path);\n for (int i = start; i < nums.size(); i++) {\n path.push_back(nums[i]);\n backtrack(nums, i + 1, path, result);\n path.pop_back();\n }\n}", "test_cases": ["nums=[1,2,3] -> [[],[1],[2],[1,2],[3],[1,3],[2,3],[1,2,3]]"], "key_points": ["选或不选", "DFS遍历子集树"], "tags": ["backtracking", "medium", "Google", "Microsoft"]} {"problem_id": "algo_01914", "original_id": "permutations", "title": "全排列", "category": "backtracking", "difficulty": "medium", "companies": ["Google", "Facebook"], "description": "给定一个不含重复数字的数组 nums,返回其所有可能的全排列。", "solution_python": "def permute(nums):\n result = []\n def backtrack(path, used):\n if len(path) == len(nums):\n result.append(path[:])\n return\n for i in range(len(nums)):\n if used[i]: continue\n used[i] = True\n path.append(nums[i])\n backtrack(path, used)\n path.pop()\n used[i] = False\n backtrack([], [False]*len(nums))\n return result", "solution_java": "public List> permute(int[] nums) {\n List> result = new ArrayList<>();\n boolean[] used = new boolean[nums.length];\n backtrack(nums, used, new ArrayList<>(), result);\n return result;\n}\nprivate void backtrack(int[] nums, boolean[] used, List path, List> result) {\n if (path.size() == nums.length) { result.add(new ArrayList<>(path)); return; }\n for (int i = 0; i < nums.length; i++) {\n if (used[i]) continue;\n used[i] = true;\n path.add(nums[i]);\n backtrack(nums, used, path, result);\n path.remove(path.size() - 1);\n used[i] = false;\n }\n}", "solution_cpp": "vector> permute(vector& nums) {\n vector> result;\n vector used(nums.size(), false);\n vector path;\n backtrack(nums, used, path, result);\n return result;\n}\nvoid backtrack(vector& nums, vector& used, vector& path, vector>& result) {\n if (path.size() == nums.size()) { result.push_back(path); return; }\n for (int i = 0; i < nums.size(); i++) {\n if (used[i]) continue;\n used[i] = true;\n path.push_back(nums[i]);\n backtrack(nums, used, path, result);\n path.pop_back();\n used[i] = false;\n }\n}", "test_cases": ["nums=[1,2,3] -> [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]"], "key_points": ["标记已使用元素", "回溯经典模板"], "tags": ["backtracking", "medium", "Google", "Facebook"]} {"problem_id": "algo_01915", "original_id": "top-k-frequent", "title": "前K个高频元素", "category": "heap", "difficulty": "medium", "companies": ["Amazon", "Facebook"], "description": "给你一个整数数组 nums 和一个整数 k,请你返回其中出现频率前 k 高的元素。", "solution_python": "import heapq\nfrom collections import Counter\ndef topKFrequent(nums, k):\n count = Counter(nums)\n heap = []\n for num, freq in count.items():\n heapq.heappush(heap, (freq, num))\n if len(heap) > k: heapq.heappop(heap)\n return [num for freq, num in heap]", "solution_java": "public int[] topKFrequent(int[] nums, int k) {\n Map count = new HashMap<>();\n for (int n : nums) count.put(n, count.getOrDefault(n, 0) + 1);\n PriorityQueue> heap = \n new PriorityQueue<>((a, b) -> a.getValue() - b.getValue());\n for (Map.Entry e : count.entrySet()) {\n heap.offer(e);\n if (heap.size() > k) heap.poll();\n }\n int[] res = new int[k];\n for (int i = k - 1; i >= 0; i--) res[i] = heap.poll().getKey();\n return res;\n}", "solution_cpp": "vector topKFrequent(vector& nums, int k) {\n unordered_map count;\n for (int n : nums) count[n]++;\n priority_queue, vector>, greater>> heap;\n for (auto& [num, freq] : count) {\n heap.push({freq, num});\n if (heap.size() > k) heap.pop();\n }\n vector res;\n while (!heap.empty()) { res.push_back(heap.top().second); heap.pop(); }\n reverse(res.begin(), res.end());\n return res;\n}", "test_cases": ["nums=[1,1,1,2,2,3], k=2 -> [1,2]", "nums=[1], k=1 -> [1]"], "key_points": ["小顶堆保持大小k", "时间复杂度O(nlogk)"], "tags": ["heap", "medium", "Amazon", "Facebook"]} {"problem_id": "algo_01916", "original_id": "3sum", "title": "三数之和", "category": "two-pointers", "difficulty": "medium", "companies": ["Google", "Amazon"], "description": "给你一个整数数组 nums,判断是否存在三元组满足和为0,返回所有不重复的三元组。", "solution_python": "def threeSum(nums):\n nums.sort()\n result = []\n for i in range(len(nums) - 2):\n if i > 0 and nums[i] == nums[i-1]: continue\n left, right = i + 1, len(nums) - 1\n while left < right:\n total = nums[i] + nums[left] + nums[right]\n if total < 0: left += 1\n elif total > 0: right -= 1\n else:\n result.append([nums[i], nums[left], nums[right]])\n while left < right and nums[left] == nums[left+1]: left += 1\n while left < right and nums[right] == nums[right-1]: right -= 1\n left += 1; right -= 1\n return result", "solution_java": "public List> threeSum(int[] nums) {\n Arrays.sort(nums);\n List> result = new ArrayList<>();\n for (int i = 0; i < nums.length - 2; i++) {\n if (i > 0 && nums[i] == nums[i-1]) continue;\n int left = i + 1, right = nums.length - 1;\n while (left < right) {\n int total = nums[i] + nums[left] + nums[right];\n if (total < 0) left++;\n else if (total > 0) right--;\n else {\n result.add(Arrays.asList(nums[i], nums[left], nums[right]));\n while (left < right && nums[left] == nums[left+1]) left++;\n while (left < right && nums[right] == nums[right-1]) right--;\n left++; right--;\n }\n }\n }\n return result;\n}", "solution_cpp": "vector> threeSum(vector& nums) {\n sort(nums.begin(), nums.end());\n vector> result;\n for (int i = 0; i < nums.size() - 2; i++) {\n if (i > 0 && nums[i] == nums[i-1]) continue;\n int left = i + 1, right = nums.size() - 1;\n while (left < right) {\n int total = nums[i] + nums[left] + nums[right];\n if (total < 0) left++;\n else if (total > 0) right--;\n else {\n result.push_back({nums[i], nums[left], nums[right]});\n while (left < right && nums[left] == nums[left+1]) left++;\n while (left < right && nums[right] == nums[right-1]) right--;\n left++; right--;\n }\n }\n }\n return result;\n}", "test_cases": ["nums=[-1,0,1,2,-1,-4] -> [[-1,-1,2],[-1,0,1]]"], "key_points": ["排序+双指针", "去重是关键"], "tags": ["two-pointers", "medium", "Google", "Amazon"]} {"problem_id": "algo_01917", "original_id": "container-water", "title": "盛最多水的容器", "category": "two-pointers", "difficulty": "medium", "companies": ["Google", "Uber"], "description": "给定一个长度为 n 的整数数组 height,找出其中的两条线,使得它们与 x 轴共同构成的容器可以容纳最多的水。", "solution_python": "def maxArea(height):\n left, right = 0, len(height) - 1\n max_area = 0\n while left < right:\n h = min(height[left], height[right])\n max_area = max(max_area, h * (right - left))\n if height[left] < height[right]: left += 1\n else: right -= 1\n return max_area", "solution_java": "public int maxArea(int[] height) {\n int left = 0, right = height.length - 1, maxArea = 0;\n while (left < right) {\n int h = Math.min(height[left], height[right]);\n maxArea = Math.max(maxArea, h * (right - left));\n if (height[left] < height[right]) left++;\n else right--;\n }\n return maxArea;\n}", "solution_cpp": "int maxArea(vector& height) {\n int left = 0, right = height.size() - 1, maxArea = 0;\n while (left < right) {\n int h = min(height[left], height[right]);\n maxArea = max(maxArea, h * (right - left));\n if (height[left] < height[right]) left++;\n else right--;\n }\n return maxArea;\n}", "test_cases": ["height=[1,8,6,2,5,4,8,3,7] -> 49"], "key_points": ["移动短边指针", "面积=min(h1,h2)*width"], "tags": ["two-pointers", "medium", "Google", "Uber"]} {"problem_id": "algo_01918", "original_id": "min-stack", "title": "最小栈", "category": "stack", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "设计一个支持 push,pop,top 操作,并能在常数时间内检索到最小元素的栈。", "solution_python": "class MinStack:\n def __init__(self):\n self.stack = []\n self.min_stack = []\n def push(self, val):\n self.stack.append(val)\n self.min_stack.append(min(val, self.min_stack[-1] if self.min_stack else val))\n def pop(self):\n self.stack.pop(); self.min_stack.pop()\n def top(self): return self.stack[-1]\n def getMin(self): return self.min_stack[-1]", "solution_java": "class MinStack {\n Stack stack = new Stack<>();\n Stack minStack = new Stack<>();\n public void push(int val) { stack.push(val); minStack.push(Math.min(val, minStack.isEmpty() ? val : minStack.peek())); }\n public void pop() { stack.pop(); minStack.pop(); }\n public int top() { return stack.peek(); }\n public int getMin() { return minStack.peek(); }\n}", "solution_cpp": "class MinStack {\n stack st, minSt;\npublic:\n void push(int val) { st.push(val); minSt.push(min(val, minSt.empty() ? val : minSt.top())); }\n void pop() { st.pop(); minSt.pop(); }\n int top() { return st.top(); }\n int getMin() { return minSt.top(); }\n};", "test_cases": ["push(-2), push(0), push(-3) -> getMin() returns -3"], "key_points": ["辅助栈记录最小值", "O(1)时间获取最小值"], "tags": ["stack", "medium", "Google", "Microsoft"]} {"problem_id": "algo_01919", "original_id": "lru-cache", "title": "LRU缓存", "category": "design", "difficulty": "hard", "companies": ["Google", "Amazon"], "description": "设计和实现一个 LRU(最近最少使用)缓存机制。", "solution_python": "class LRUCache:\n def __init__(self, capacity):\n self.capacity = capacity\n self.cache = {}\n self.order = []\n def get(self, key):\n if key not in self.cache: return -1\n self.order.remove(key); self.order.append(key)\n return self.cache[key]\n def put(self, key, value):\n if key in self.cache:\n self.order.remove(key)\n elif len(self.cache) >= self.capacity:\n del self.cache[self.order.pop(0)]\n self.cache[key] = value; self.order.append(key)", "solution_java": "class LRUCache {\n int capacity;\n LinkedHashMap cache = new LinkedHashMap<>();\n public LRUCache(int cap) { capacity = cap; }\n public int get(int key) { return cache.containsKey(key) ? cache.remove(key) : -1; }\n public void put(int key, int val) {\n if (cache.containsKey(key)) cache.remove(key);\n else if (cache.size() >= capacity) cache.remove(cache.keySet().iterator().next());\n cache.put(key, val);\n }\n}", "solution_cpp": "class LRUCache {\n int cap;\n list> dll;\n unordered_map>::iterator> cache;\npublic:\n LRUCache(int capacity) : cap(capacity) {}\n int get(int key) {\n auto it = cache.find(key);\n if (it == cache.end()) return -1;\n dll.splice(dll.end(), dll, it->second);\n return it->second->second;\n }\n void put(int key, int value) {\n auto it = cache.find(key);\n if (it != cache.end()) dll.erase(it->second);\n else if (cache.size() >= cap) { cache.erase(dll.front().first); dll.pop_front(); }\n dll.push_back({key, value});\n cache[key] = --dll.end();\n }\n};", "test_cases": ["put(1,1), put(2,2), get(1) -> 1"], "key_points": ["HashMap + 双向链表", "O(1)时间操作"], "tags": ["design", "hard", "Google", "Amazon"]} {"problem_id": "algo_01920", "original_id": "num-islands", "title": "岛屿数量", "category": "graph", "difficulty": "medium", "companies": ["Google", "Facebook"], "description": "给你一个由 '1'(陆地)和 '0'(水)组成的二维网格,请你计算网格中岛屿的数量。岛屿总是被水包围,且只能由水平或垂直方向相邻的陆地连接形成。", "solution_python": "def numIslands(grid):\n if not grid: return 0\n rows, cols = len(grid), len(grid[0])\n count = 0\n def dfs(r, c):\n if r < 0 or r >= rows or c < 0 or c >= cols or grid[r][c] != '1': return\n grid[r][c] = '0'\n dfs(r+1, c); dfs(r-1, c); dfs(r, c+1); dfs(r, c-1)\n for r in range(rows):\n for c in range(cols):\n if grid[r][c] == '1': count += 1; dfs(r, c)\n return count", "solution_java": "public int numIslands(char[][] grid) {\n if (grid.length == 0) return 0;\n int count = 0;\n for (int i = 0; i < grid.length; i++)\n for (int j = 0; j < grid[0].length; j++)\n if (grid[i][j] == '1') { count++; dfs(grid, i, j); }\n return count;\n}\nprivate void dfs(char[][] grid, int r, int c) {\n if (r < 0 || r >= grid.length || c < 0 || c >= grid[0].length || grid[r][c] != '1') return;\n grid[r][c] = '0';\n dfs(grid, r+1, c); dfs(grid, r-1, c); dfs(grid, r, c+1); dfs(grid, r, c-1);\n}", "solution_cpp": "int numIslands(vector>& grid) {\n if (grid.empty()) return 0;\n int count = 0;\n for (int i = 0; i < grid.size(); i++)\n for (int j = 0; j < grid[0].size(); j++)\n if (grid[i][j] == '1') { count++; dfs(grid, i, j); }\n return count;\n}\nvoid dfs(vector>& grid, int r, int c) {\n if (r < 0 || r >= grid.size() || c < 0 || c >= grid[0].size() || grid[r][c] != '1') return;\n grid[r][c] = '0';\n dfs(grid, r+1, c); dfs(grid, r-1, c); dfs(grid, r, c+1); dfs(grid, r, c-1);\n}", "test_cases": ["grid=[[1,1,1,1,0],[1,1,0,1,0],[1,1,0,0,0],[0,0,0,0,0]] -> 1"], "key_points": ["DFS/BFS遍历", "访问后标记为0避免重复"], "tags": ["graph", "medium", "Google", "Facebook"]} {"problem_id": "algo_01921", "original_id": "two-sum", "title": "两数之和", "category": "array", "difficulty": "easy", "companies": ["Amazon", "Google"], "description": "给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那两个整数,并返回他们的数组下标。", "solution_python": "def twoSum(nums, target):\n hashmap = {}\n for i, num in enumerate(nums):\n complement = target - num\n if complement in hashmap:\n return [hashmap[complement], i]\n hashmap[num] = i\n return []", "solution_java": "public int[] twoSum(int[] nums, int target) {\n Map map = new HashMap<>();\n for (int i = 0; i < nums.length; i++) {\n int complement = target - nums[i];\n if (map.containsKey(complement)) return new int[]{map.get(complement), i};\n map.put(nums[i], i);\n }\n return new int[]{};\n}", "solution_cpp": "vector twoSum(vector& nums, int target) {\n unordered_map m;\n for (int i = 0; i < nums.size(); i++) {\n if (m.count(target - nums[i])) return {m[target - nums[i]], i};\n m[nums[i]] = i;\n }\n return {};\n}", "test_cases": ["nums=[2,7,11,15], target=9 -> [0,1]", "nums=[3,2,4], target=6 -> [1,2]"], "key_points": ["哈希表一次遍历", "空间换时间"], "tags": ["array", "easy", "Amazon", "Google"]} {"problem_id": "algo_01922", "original_id": "merge-sorted", "title": "合并两个有序数组", "category": "array", "difficulty": "easy", "companies": ["Microsoft", "Uber"], "description": "给你两个按非递减顺序排列的整数数组 nums1 和 nums2,另有两个整数 m 和 n,分别表示 nums1 和 nums2 中的元素数目。请你合并 nums2 到 nums1 中。", "solution_python": "def merge(nums1, m, nums2, n):\n p1, p2, p = m-1, n-1, m+n-1\n while p1 >= 0 and p2 >= 0:\n if nums1[p1] > nums2[p2]: nums1[p] = nums1[p1]; p1 -= 1\n else: nums1[p] = nums2[p2]; p2 -= 1\n p -= 1\n while p2 >= 0: nums1[p] = nums2[p2]; p2 -= 1; p -= 1", "solution_java": "public void merge(int[] nums1, int m, int[] nums2, int n) {\n int p1 = m-1, p2 = n-1, p = m+n-1;\n while (p1 >= 0 && p2 >= 0) {\n nums1[p--] = nums1[p1] > nums2[p2] ? nums1[p1--] : nums2[p2--];\n }\n while (p2 >= 0) nums1[p--] = nums2[p2--];\n}", "solution_cpp": "void merge(vector& nums1, int m, vector& nums2, int n) {\n int p1 = m-1, p2 = n-1, p = m+n-1;\n while (p1 >= 0 && p2 >= 0) nums1[p--] = nums1[p1] > nums2[p2] ? nums1[p1--] : nums2[p2--];\n while (p2 >= 0) nums1[p--] = nums2[p2--];\n}", "test_cases": ["nums1=[1,2,3], m=3, nums2=[2,5,6], n=3 -> [1,2,2,3,5,6]", "nums1=[], m=0, nums2=[1], n=1 -> [1]"], "key_points": ["从后往前合并", "三指针技巧"], "tags": ["array", "easy", "Microsoft", "Uber"]} {"problem_id": "algo_01923", "original_id": "max-subarray", "title": "最大子数组和", "category": "array", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "给你一个整数数组 nums ,请你找出一个具有最大和的连续子数组,返回其最大和。", "solution_python": "def maxSubArray(nums):\n max_sum = current = nums[0]\n for num in nums[1:]:\n current = max(num, current + num)\n max_sum = max(max_sum, current)\n return max_sum", "solution_java": "public int maxSubArray(int[] nums) {\n int maxSum = nums[0], curr = nums[0];\n for (int i = 1; i < nums.length; i++) {\n curr = Math.max(nums[i], curr + nums[i]);\n maxSum = Math.max(maxSum, curr);\n }\n return maxSum;\n}", "solution_cpp": "int maxSubArray(vector& nums) {\n int maxSum = nums[0], curr = nums[0];\n for (int i = 1; i < nums.size(); i++) {\n curr = max(nums[i], curr + nums[i]);\n maxSum = max(maxSum, curr);\n }\n return maxSum;\n}", "test_cases": ["nums=[-2,1,-3,4,-1,2,1,-5,4] -> 6", "nums=[1] -> 1"], "key_points": ["Kadane算法", "动态规划基础题"], "tags": ["array", "medium", "Google", "Microsoft"]} {"problem_id": "algo_01924", "original_id": "valid-parentheses", "title": "有效的括号", "category": "string", "difficulty": "easy", "companies": ["Google", "Uber"], "description": "给定一个只包括 '(',')','{','}','[',']' 的字符串 s,判断字符串是否有效。", "solution_python": "def isValid(s):\n stack = []\n mapping = {')': '(', ']': '[', '}': '{'}\n for c in s:\n if c in mapping:\n if not stack or stack[-1] != mapping[c]: return False\n stack.pop()\n else: stack.append(c)\n return not stack", "solution_java": "public boolean isValid(String s) {\n Stack stack = new Stack<>();\n Map map = Map.of(')', '(', ']', '[', '}', '{');\n for (char c : s.toCharArray()) {\n if (map.containsValue(c)) stack.push(c);\n else if (!stack.isEmpty() && stack.pop() != map.get(c)) return false;\n }\n return stack.isEmpty();\n}", "solution_cpp": "bool isValid(string s) {\n stack st;\n unordered_map m = {{')','('},{']','['},{'}','{'}};\n for (char c : s) {\n if (m.find(c) == m.end()) st.push(c);\n else if (st.empty() || st.top() != m[c]) return false;\n else st.pop();\n }\n return st.empty();\n}", "test_cases": ["s=\"()\" -> true", "s=\"()[]{}\" -> true", "s=\"(]\" -> false"], "key_points": ["栈匹配法", "注意空栈边界"], "tags": ["string", "easy", "Google", "Uber"]} {"problem_id": "algo_01925", "original_id": "longest-palindrome", "title": "最长回文子串", "category": "string", "difficulty": "medium", "companies": ["Google", "Amazon"], "description": "给你一个字符串 s,找到 s 中最长的回文子串。", "solution_python": "def longestPalindrome(s):\n def expand(l, r):\n while l >= 0 and r < len(s) and s[l] == s[r]: l -= 1; r += 1\n return l + 1, r - 1\n start = end = 0\n for i in range(len(s)):\n l1, r1 = expand(i, i)\n l2, r2 = expand(i, i + 1)\n if r1 - l1 > end - start: start, end = l1, r1\n if r2 - l2 > end - start: start, end = l2, r2\n return s[start:end+1]", "solution_java": "public String longestPalindrome(String s) {\n int start = 0, end = 0;\n for (int i = 0; i < s.length(); i++) {\n int len1 = expand(s, i, i), len2 = expand(s, i, i+1);\n int len = Math.max(len1, len2);\n if (len > end - start) { start = i - (len-1)/2; end = i + len/2; }\n }\n return s.substring(start, end + 1);\n}\nprivate int expand(String s, int l, int r) {\n while (l >= 0 && r < s.length() && s.charAt(l) == s.charAt(r)) { l--; r++; }\n return r - l - 1;\n}", "solution_cpp": "string longestPalindrome(string s) {\n int start = 0, end = 0;\n for (int i = 0; i < s.size(); i++) {\n int len1 = expand(s, i, i), len2 = expand(s, i, i+1);\n if (max(len1, len2) > end - start) { start = i - (max(len1,len2)-1)/2; end = i + max(len1,len2)/2; }\n }\n return s.substr(start, end - start + 1);\n}", "test_cases": ["s=\"babad\" -> bab或aba", "s=\"cbbd\" -> bb"], "key_points": ["中心扩展法", "处理奇偶长度"], "tags": ["string", "medium", "Google", "Amazon"]} {"problem_id": "algo_01926", "original_id": "reverse-list", "title": "反转链表", "category": "linkedlist", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "给你单链表的头节点 head,请你反转链表,并返回反转后的链表。", "solution_python": "def reverseList(head):\n prev = None\n curr = head\n while curr:\n nxt = curr.next\n curr.next = prev\n prev = curr\n curr = nxt\n return prev", "solution_java": "public ListNode reverseList(ListNode head) {\n ListNode prev = null, curr = head;\n while (curr != null) {\n ListNode next = curr.next;\n curr.next = prev;\n prev = curr;\n curr = next;\n }\n return prev;\n}", "solution_cpp": "ListNode* reverseList(ListNode* head) {\n ListNode* prev = nullptr, *curr = head;\n while (curr) {\n ListNode* next = curr->next;\n curr->next = prev;\n prev = curr;\n curr = next;\n }\n return prev;\n}", "test_cases": ["head=[1,2,3,4,5] -> [5,4,3,2,1]", "head=[1,2] -> [2,1]"], "key_points": ["迭代法 O(1)空间", "递归法 O(n)空间"], "tags": ["linkedlist", "medium", "Google", "Microsoft"]} {"problem_id": "algo_01927", "original_id": "middle-node", "title": "链表的中间结点", "category": "linkedlist", "difficulty": "easy", "companies": ["Amazon", "Facebook"], "description": "给你单链表的头节点 head,请你找出并返回链表的中间结点。如果有两个中间结点,则返回第二个中间结点。", "solution_python": "def middleNode(head):\n slow = fast = head\n while fast and fast.next:\n slow = slow.next\n fast = fast.next.next\n return slow", "solution_java": "public ListNode middleNode(ListNode head) {\n ListNode slow = head, fast = head;\n while (fast != null && fast.next != null) {\n slow = slow.next;\n fast = fast.next.next;\n }\n return slow;\n}", "solution_cpp": "ListNode* middleNode(ListNode* head) {\n ListNode* slow = head, *fast = head;\n while (fast && fast->next) { slow = slow->next; fast = fast->next->next; }\n return slow;\n}", "test_cases": ["head=[1,2,3,4,5] -> 3", "head=[1,2,3,4,5,6] -> 4"], "key_points": ["快慢指针", "O(n)时间O(1)空间"], "tags": ["linkedlist", "easy", "Amazon", "Facebook"]} {"problem_id": "algo_01928", "original_id": "max-depth", "title": "二叉树的最大深度", "category": "tree", "difficulty": "easy", "companies": ["Microsoft", "Apple"], "description": "给定一个二叉树 root,返回其最大深度。", "solution_python": "def maxDepth(root):\n if not root: return 0\n return max(maxDepth(root.left), maxDepth(root.right)) + 1", "solution_java": "public int maxDepth(TreeNode root) {\n if (root == null) return 0;\n return Math.max(maxDepth(root.left), maxDepth(root.right)) + 1;\n}", "solution_cpp": "int maxDepth(TreeNode* root) {\n if (!root) return 0;\n return max(maxDepth(root->left), maxDepth(root->right)) + 1;\n}", "test_cases": ["root=[3,9,20,null,null,15,7] -> 3", "root=[1,null,2] -> 2"], "key_points": ["DFS递归", "层序遍历也可"], "tags": ["tree", "easy", "Microsoft", "Apple"]} {"problem_id": "algo_01929", "original_id": "inorder-traversal", "title": "二叉树的中序遍历", "category": "tree", "difficulty": "easy", "companies": ["Google", "Microsoft"], "description": "给定一个二叉树的根节点 root,返回它的中序遍历结果。", "solution_python": "def inorderTraversal(root):\n result = []\n def dfs(node):\n if node:\n dfs(node.left)\n result.append(node.val)\n dfs(node.right)\n dfs(root)\n return result", "solution_java": "public List inorderTraversal(TreeNode root) {\n List res = new ArrayList<>();\n dfs(root, res);\n return res;\n}\nprivate void dfs(TreeNode node, List res) {\n if (node == null) return;\n dfs(node.left, res); res.add(node.val); dfs(node.right, res);\n}", "solution_cpp": "vector inorderTraversal(TreeNode* root) {\n vector res;\n dfs(root, res);\n return res;\n}\nvoid dfs(TreeNode* node, vector& res) {\n if (!node) return;\n dfs(node->left, res); res.push_back(node->val); dfs(node->right, res);\n}", "test_cases": ["root=[1,null,2,3] -> [1,3,2]", "root=[] -> []"], "key_points": ["左-根-右顺序", "递归最简洁"], "tags": ["tree", "easy", "Google", "Microsoft"]} {"problem_id": "algo_01930", "original_id": "binary-search", "title": "二分查找", "category": "binarysearch", "difficulty": "easy", "companies": ["Google", "Amazon"], "description": "给定一个 n 个元素有序的(升序)整型数组 nums 和一个目标值 target,写一个函数搜索 nums 中的 target,如果目标值存在返回下标,否则返回 -1。", "solution_python": "def search(nums, target):\n left, right = 0, len(nums) - 1\n while left <= right:\n mid = (left + right) // 2\n if nums[mid] == target: return mid\n elif nums[mid] < target: left = mid + 1\n else: right = mid - 1\n return -1", "solution_java": "public int search(int[] nums, int target) {\n int left = 0, right = nums.length - 1;\n while (left <= right) {\n int mid = left + (right - left) / 2;\n if (nums[mid] == target) return mid;\n else if (nums[mid] < target) left = mid + 1;\n else right = mid - 1;\n }\n return -1;\n}", "solution_cpp": "int search(vector& nums, int target) {\n int left = 0, right = nums.size() - 1;\n while (left <= right) {\n int mid = left + (right - left) / 2;\n if (nums[mid] == target) return mid;\n else if (nums[mid] < target) left = mid + 1;\n else right = mid - 1;\n }\n return -1;\n}", "test_cases": ["nums=[-1,0,3,5,9,12], target=9 -> 4", "nums=[-1,0,3,5,9,12], target=2 -> -1"], "key_points": ["标准模板", "注意防溢出写法"], "tags": ["binarysearch", "easy", "Google", "Amazon"]} {"problem_id": "algo_01931", "original_id": "climbing-stairs", "title": "爬楼梯", "category": "dp", "difficulty": "easy", "companies": ["Amazon", "Google"], "description": "假设你正在爬楼梯。需要 n 阶你才能到达楼顶。每次你可以爬 1 或 2 个台阶。你有多少种不同的方法可以爬到楼顶?", "solution_python": "def climbStairs(n):\n if n <= 2: return n\n a, b = 1, 2\n for _ in range(3, n+1):\n a, b = b, a + b\n return b", "solution_java": "public int climbStairs(int n) {\n if (n <= 2) return n;\n int a = 1, b = 2;\n for (int i = 3; i <= n; i++) { int temp = a + b; a = b; b = temp; }\n return b;\n}", "solution_cpp": "int climbStairs(int n) {\n if (n <= 2) return n;\n int a = 1, b = 2;\n for (int i = 3; i <= n; i++) { int temp = a + b; a = b; b = temp; }\n return b;\n}", "test_cases": ["n=2 -> 2", "n=3 -> 3", "n=5 -> 8"], "key_points": ["斐波那契数列", "滚动数组优化空间"], "tags": ["dp", "easy", "Amazon", "Google"]} {"problem_id": "algo_01932", "original_id": "coin-change", "title": "零钱兑换", "category": "dp", "difficulty": "medium", "companies": ["Google", "Amazon"], "description": "给你一个整数数组 coins 表示不同面额的硬币,以及一个整数 amount 表示总金额。计算并返回可以凑成总金额所需的最少的硬币个数。如果没有任何一种硬币组合能组成总金额,返回 -1。", "solution_python": "def coinChange(coins, amount):\n dp = [float('inf')] * (amount + 1)\n dp[0] = 0\n for coin in coins:\n for x in range(coin, amount + 1):\n dp[x] = min(dp[x], dp[x - coin] + 1)\n return dp[amount] if dp[amount] != float('inf') else -1", "solution_java": "public int coinChange(int[] coins, int amount) {\n int[] dp = new int[amount + 1];\n Arrays.fill(dp, amount + 1);\n dp[0] = 0;\n for (int coin : coins) {\n for (int x = coin; x <= amount; x++) {\n dp[x] = Math.min(dp[x], dp[x - coin] + 1);\n }\n }\n return dp[amount] > amount ? -1 : dp[amount];\n}", "solution_cpp": "int coinChange(vector& coins, int amount) {\n vector dp(amount + 1, amount + 1);\n dp[0] = 0;\n for (int coin : coins) {\n for (int x = coin; x <= amount; x++) {\n dp[x] = min(dp[x], dp[x - coin] + 1);\n }\n }\n return dp[amount] > amount ? -1 : dp[amount];\n}", "test_cases": ["coins=[1,2,5], amount=11 -> 3", "coins=[2], amount=3 -> -1"], "key_points": ["完全背包问题", "dp[x] = min(dp[x-coin]+1)"], "tags": ["dp", "medium", "Google", "Amazon"]} {"problem_id": "algo_01933", "original_id": "subsets", "title": "子集", "category": "backtracking", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "给你一个整数数组 nums ,数组中的元素 互不相同 。返回该数组所有可能的子集(幂集)。", "solution_python": "def subsets(nums):\n result = []\n def backtrack(start, path):\n result.append(path[:])\n for i in range(start, len(nums)):\n path.append(nums[i])\n backtrack(i + 1, path)\n path.pop()\n backtrack(0, [])\n return result", "solution_java": "public List> subsets(int[] nums) {\n List> result = new ArrayList<>();\n backtrack(nums, 0, new ArrayList<>(), result);\n return result;\n}\nprivate void backtrack(int[] nums, int start, List path, List> result) {\n result.add(new ArrayList<>(path));\n for (int i = start; i < nums.length; i++) {\n path.add(nums[i]);\n backtrack(nums, i + 1, path, result);\n path.remove(path.size() - 1);\n }\n}", "solution_cpp": "vector> subsets(vector& nums) {\n vector> result;\n vector path;\n backtrack(nums, 0, path, result);\n return result;\n}\nvoid backtrack(vector& nums, int start, vector& path, vector>& result) {\n result.push_back(path);\n for (int i = start; i < nums.size(); i++) {\n path.push_back(nums[i]);\n backtrack(nums, i + 1, path, result);\n path.pop_back();\n }\n}", "test_cases": ["nums=[1,2,3] -> [[],[1],[2],[1,2],[3],[1,3],[2,3],[1,2,3]]"], "key_points": ["选或不选", "DFS遍历子集树"], "tags": ["backtracking", "medium", "Google", "Microsoft"]} {"problem_id": "algo_01934", "original_id": "permutations", "title": "全排列", "category": "backtracking", "difficulty": "medium", "companies": ["Google", "Facebook"], "description": "给定一个不含重复数字的数组 nums,返回其所有可能的全排列。", "solution_python": "def permute(nums):\n result = []\n def backtrack(path, used):\n if len(path) == len(nums):\n result.append(path[:])\n return\n for i in range(len(nums)):\n if used[i]: continue\n used[i] = True\n path.append(nums[i])\n backtrack(path, used)\n path.pop()\n used[i] = False\n backtrack([], [False]*len(nums))\n return result", "solution_java": "public List> permute(int[] nums) {\n List> result = new ArrayList<>();\n boolean[] used = new boolean[nums.length];\n backtrack(nums, used, new ArrayList<>(), result);\n return result;\n}\nprivate void backtrack(int[] nums, boolean[] used, List path, List> result) {\n if (path.size() == nums.length) { result.add(new ArrayList<>(path)); return; }\n for (int i = 0; i < nums.length; i++) {\n if (used[i]) continue;\n used[i] = true;\n path.add(nums[i]);\n backtrack(nums, used, path, result);\n path.remove(path.size() - 1);\n used[i] = false;\n }\n}", "solution_cpp": "vector> permute(vector& nums) {\n vector> result;\n vector used(nums.size(), false);\n vector path;\n backtrack(nums, used, path, result);\n return result;\n}\nvoid backtrack(vector& nums, vector& used, vector& path, vector>& result) {\n if (path.size() == nums.size()) { result.push_back(path); return; }\n for (int i = 0; i < nums.size(); i++) {\n if (used[i]) continue;\n used[i] = true;\n path.push_back(nums[i]);\n backtrack(nums, used, path, result);\n path.pop_back();\n used[i] = false;\n }\n}", "test_cases": ["nums=[1,2,3] -> [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]"], "key_points": ["标记已使用元素", "回溯经典模板"], "tags": ["backtracking", "medium", "Google", "Facebook"]} {"problem_id": "algo_01935", "original_id": "top-k-frequent", "title": "前K个高频元素", "category": "heap", "difficulty": "medium", "companies": ["Amazon", "Facebook"], "description": "给你一个整数数组 nums 和一个整数 k,请你返回其中出现频率前 k 高的元素。", "solution_python": "import heapq\nfrom collections import Counter\ndef topKFrequent(nums, k):\n count = Counter(nums)\n heap = []\n for num, freq in count.items():\n heapq.heappush(heap, (freq, num))\n if len(heap) > k: heapq.heappop(heap)\n return [num for freq, num in heap]", "solution_java": "public int[] topKFrequent(int[] nums, int k) {\n Map count = new HashMap<>();\n for (int n : nums) count.put(n, count.getOrDefault(n, 0) + 1);\n PriorityQueue> heap = \n new PriorityQueue<>((a, b) -> a.getValue() - b.getValue());\n for (Map.Entry e : count.entrySet()) {\n heap.offer(e);\n if (heap.size() > k) heap.poll();\n }\n int[] res = new int[k];\n for (int i = k - 1; i >= 0; i--) res[i] = heap.poll().getKey();\n return res;\n}", "solution_cpp": "vector topKFrequent(vector& nums, int k) {\n unordered_map count;\n for (int n : nums) count[n]++;\n priority_queue, vector>, greater>> heap;\n for (auto& [num, freq] : count) {\n heap.push({freq, num});\n if (heap.size() > k) heap.pop();\n }\n vector res;\n while (!heap.empty()) { res.push_back(heap.top().second); heap.pop(); }\n reverse(res.begin(), res.end());\n return res;\n}", "test_cases": ["nums=[1,1,1,2,2,3], k=2 -> [1,2]", "nums=[1], k=1 -> [1]"], "key_points": ["小顶堆保持大小k", "时间复杂度O(nlogk)"], "tags": ["heap", "medium", "Amazon", "Facebook"]} {"problem_id": "algo_01936", "original_id": "3sum", "title": "三数之和", "category": "two-pointers", "difficulty": "medium", "companies": ["Google", "Amazon"], "description": "给你一个整数数组 nums,判断是否存在三元组满足和为0,返回所有不重复的三元组。", "solution_python": "def threeSum(nums):\n nums.sort()\n result = []\n for i in range(len(nums) - 2):\n if i > 0 and nums[i] == nums[i-1]: continue\n left, right = i + 1, len(nums) - 1\n while left < right:\n total = nums[i] + nums[left] + nums[right]\n if total < 0: left += 1\n elif total > 0: right -= 1\n else:\n result.append([nums[i], nums[left], nums[right]])\n while left < right and nums[left] == nums[left+1]: left += 1\n while left < right and nums[right] == nums[right-1]: right -= 1\n left += 1; right -= 1\n return result", "solution_java": "public List> threeSum(int[] nums) {\n Arrays.sort(nums);\n List> result = new ArrayList<>();\n for (int i = 0; i < nums.length - 2; i++) {\n if (i > 0 && nums[i] == nums[i-1]) continue;\n int left = i + 1, right = nums.length - 1;\n while (left < right) {\n int total = nums[i] + nums[left] + nums[right];\n if (total < 0) left++;\n else if (total > 0) right--;\n else {\n result.add(Arrays.asList(nums[i], nums[left], nums[right]));\n while (left < right && nums[left] == nums[left+1]) left++;\n while (left < right && nums[right] == nums[right-1]) right--;\n left++; right--;\n }\n }\n }\n return result;\n}", "solution_cpp": "vector> threeSum(vector& nums) {\n sort(nums.begin(), nums.end());\n vector> result;\n for (int i = 0; i < nums.size() - 2; i++) {\n if (i > 0 && nums[i] == nums[i-1]) continue;\n int left = i + 1, right = nums.size() - 1;\n while (left < right) {\n int total = nums[i] + nums[left] + nums[right];\n if (total < 0) left++;\n else if (total > 0) right--;\n else {\n result.push_back({nums[i], nums[left], nums[right]});\n while (left < right && nums[left] == nums[left+1]) left++;\n while (left < right && nums[right] == nums[right-1]) right--;\n left++; right--;\n }\n }\n }\n return result;\n}", "test_cases": ["nums=[-1,0,1,2,-1,-4] -> [[-1,-1,2],[-1,0,1]]"], "key_points": ["排序+双指针", "去重是关键"], "tags": ["two-pointers", "medium", "Google", "Amazon"]} {"problem_id": "algo_01937", "original_id": "container-water", "title": "盛最多水的容器", "category": "two-pointers", "difficulty": "medium", "companies": ["Google", "Uber"], "description": "给定一个长度为 n 的整数数组 height,找出其中的两条线,使得它们与 x 轴共同构成的容器可以容纳最多的水。", "solution_python": "def maxArea(height):\n left, right = 0, len(height) - 1\n max_area = 0\n while left < right:\n h = min(height[left], height[right])\n max_area = max(max_area, h * (right - left))\n if height[left] < height[right]: left += 1\n else: right -= 1\n return max_area", "solution_java": "public int maxArea(int[] height) {\n int left = 0, right = height.length - 1, maxArea = 0;\n while (left < right) {\n int h = Math.min(height[left], height[right]);\n maxArea = Math.max(maxArea, h * (right - left));\n if (height[left] < height[right]) left++;\n else right--;\n }\n return maxArea;\n}", "solution_cpp": "int maxArea(vector& height) {\n int left = 0, right = height.size() - 1, maxArea = 0;\n while (left < right) {\n int h = min(height[left], height[right]);\n maxArea = max(maxArea, h * (right - left));\n if (height[left] < height[right]) left++;\n else right--;\n }\n return maxArea;\n}", "test_cases": ["height=[1,8,6,2,5,4,8,3,7] -> 49"], "key_points": ["移动短边指针", "面积=min(h1,h2)*width"], "tags": ["two-pointers", "medium", "Google", "Uber"]} {"problem_id": "algo_01938", "original_id": "min-stack", "title": "最小栈", "category": "stack", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "设计一个支持 push,pop,top 操作,并能在常数时间内检索到最小元素的栈。", "solution_python": "class MinStack:\n def __init__(self):\n self.stack = []\n self.min_stack = []\n def push(self, val):\n self.stack.append(val)\n self.min_stack.append(min(val, self.min_stack[-1] if self.min_stack else val))\n def pop(self):\n self.stack.pop(); self.min_stack.pop()\n def top(self): return self.stack[-1]\n def getMin(self): return self.min_stack[-1]", "solution_java": "class MinStack {\n Stack stack = new Stack<>();\n Stack minStack = new Stack<>();\n public void push(int val) { stack.push(val); minStack.push(Math.min(val, minStack.isEmpty() ? val : minStack.peek())); }\n public void pop() { stack.pop(); minStack.pop(); }\n public int top() { return stack.peek(); }\n public int getMin() { return minStack.peek(); }\n}", "solution_cpp": "class MinStack {\n stack st, minSt;\npublic:\n void push(int val) { st.push(val); minSt.push(min(val, minSt.empty() ? val : minSt.top())); }\n void pop() { st.pop(); minSt.pop(); }\n int top() { return st.top(); }\n int getMin() { return minSt.top(); }\n};", "test_cases": ["push(-2), push(0), push(-3) -> getMin() returns -3"], "key_points": ["辅助栈记录最小值", "O(1)时间获取最小值"], "tags": ["stack", "medium", "Google", "Microsoft"]} {"problem_id": "algo_01939", "original_id": "lru-cache", "title": "LRU缓存", "category": "design", "difficulty": "hard", "companies": ["Google", "Amazon"], "description": "设计和实现一个 LRU(最近最少使用)缓存机制。", "solution_python": "class LRUCache:\n def __init__(self, capacity):\n self.capacity = capacity\n self.cache = {}\n self.order = []\n def get(self, key):\n if key not in self.cache: return -1\n self.order.remove(key); self.order.append(key)\n return self.cache[key]\n def put(self, key, value):\n if key in self.cache:\n self.order.remove(key)\n elif len(self.cache) >= self.capacity:\n del self.cache[self.order.pop(0)]\n self.cache[key] = value; self.order.append(key)", "solution_java": "class LRUCache {\n int capacity;\n LinkedHashMap cache = new LinkedHashMap<>();\n public LRUCache(int cap) { capacity = cap; }\n public int get(int key) { return cache.containsKey(key) ? cache.remove(key) : -1; }\n public void put(int key, int val) {\n if (cache.containsKey(key)) cache.remove(key);\n else if (cache.size() >= capacity) cache.remove(cache.keySet().iterator().next());\n cache.put(key, val);\n }\n}", "solution_cpp": "class LRUCache {\n int cap;\n list> dll;\n unordered_map>::iterator> cache;\npublic:\n LRUCache(int capacity) : cap(capacity) {}\n int get(int key) {\n auto it = cache.find(key);\n if (it == cache.end()) return -1;\n dll.splice(dll.end(), dll, it->second);\n return it->second->second;\n }\n void put(int key, int value) {\n auto it = cache.find(key);\n if (it != cache.end()) dll.erase(it->second);\n else if (cache.size() >= cap) { cache.erase(dll.front().first); dll.pop_front(); }\n dll.push_back({key, value});\n cache[key] = --dll.end();\n }\n};", "test_cases": ["put(1,1), put(2,2), get(1) -> 1"], "key_points": ["HashMap + 双向链表", "O(1)时间操作"], "tags": ["design", "hard", "Google", "Amazon"]} {"problem_id": "algo_01940", "original_id": "num-islands", "title": "岛屿数量", "category": "graph", "difficulty": "medium", "companies": ["Google", "Facebook"], "description": "给你一个由 '1'(陆地)和 '0'(水)组成的二维网格,请你计算网格中岛屿的数量。岛屿总是被水包围,且只能由水平或垂直方向相邻的陆地连接形成。", "solution_python": "def numIslands(grid):\n if not grid: return 0\n rows, cols = len(grid), len(grid[0])\n count = 0\n def dfs(r, c):\n if r < 0 or r >= rows or c < 0 or c >= cols or grid[r][c] != '1': return\n grid[r][c] = '0'\n dfs(r+1, c); dfs(r-1, c); dfs(r, c+1); dfs(r, c-1)\n for r in range(rows):\n for c in range(cols):\n if grid[r][c] == '1': count += 1; dfs(r, c)\n return count", "solution_java": "public int numIslands(char[][] grid) {\n if (grid.length == 0) return 0;\n int count = 0;\n for (int i = 0; i < grid.length; i++)\n for (int j = 0; j < grid[0].length; j++)\n if (grid[i][j] == '1') { count++; dfs(grid, i, j); }\n return count;\n}\nprivate void dfs(char[][] grid, int r, int c) {\n if (r < 0 || r >= grid.length || c < 0 || c >= grid[0].length || grid[r][c] != '1') return;\n grid[r][c] = '0';\n dfs(grid, r+1, c); dfs(grid, r-1, c); dfs(grid, r, c+1); dfs(grid, r, c-1);\n}", "solution_cpp": "int numIslands(vector>& grid) {\n if (grid.empty()) return 0;\n int count = 0;\n for (int i = 0; i < grid.size(); i++)\n for (int j = 0; j < grid[0].size(); j++)\n if (grid[i][j] == '1') { count++; dfs(grid, i, j); }\n return count;\n}\nvoid dfs(vector>& grid, int r, int c) {\n if (r < 0 || r >= grid.size() || c < 0 || c >= grid[0].size() || grid[r][c] != '1') return;\n grid[r][c] = '0';\n dfs(grid, r+1, c); dfs(grid, r-1, c); dfs(grid, r, c+1); dfs(grid, r, c-1);\n}", "test_cases": ["grid=[[1,1,1,1,0],[1,1,0,1,0],[1,1,0,0,0],[0,0,0,0,0]] -> 1"], "key_points": ["DFS/BFS遍历", "访问后标记为0避免重复"], "tags": ["graph", "medium", "Google", "Facebook"]} {"problem_id": "algo_01941", "original_id": "two-sum", "title": "两数之和", "category": "array", "difficulty": "easy", "companies": ["Amazon", "Google"], "description": "给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那两个整数,并返回他们的数组下标。", "solution_python": "def twoSum(nums, target):\n hashmap = {}\n for i, num in enumerate(nums):\n complement = target - num\n if complement in hashmap:\n return [hashmap[complement], i]\n hashmap[num] = i\n return []", "solution_java": "public int[] twoSum(int[] nums, int target) {\n Map map = new HashMap<>();\n for (int i = 0; i < nums.length; i++) {\n int complement = target - nums[i];\n if (map.containsKey(complement)) return new int[]{map.get(complement), i};\n map.put(nums[i], i);\n }\n return new int[]{};\n}", "solution_cpp": "vector twoSum(vector& nums, int target) {\n unordered_map m;\n for (int i = 0; i < nums.size(); i++) {\n if (m.count(target - nums[i])) return {m[target - nums[i]], i};\n m[nums[i]] = i;\n }\n return {};\n}", "test_cases": ["nums=[2,7,11,15], target=9 -> [0,1]", "nums=[3,2,4], target=6 -> [1,2]"], "key_points": ["哈希表一次遍历", "空间换时间"], "tags": ["array", "easy", "Amazon", "Google"]} {"problem_id": "algo_01942", "original_id": "merge-sorted", "title": "合并两个有序数组", "category": "array", "difficulty": "easy", "companies": ["Microsoft", "Uber"], "description": "给你两个按非递减顺序排列的整数数组 nums1 和 nums2,另有两个整数 m 和 n,分别表示 nums1 和 nums2 中的元素数目。请你合并 nums2 到 nums1 中。", "solution_python": "def merge(nums1, m, nums2, n):\n p1, p2, p = m-1, n-1, m+n-1\n while p1 >= 0 and p2 >= 0:\n if nums1[p1] > nums2[p2]: nums1[p] = nums1[p1]; p1 -= 1\n else: nums1[p] = nums2[p2]; p2 -= 1\n p -= 1\n while p2 >= 0: nums1[p] = nums2[p2]; p2 -= 1; p -= 1", "solution_java": "public void merge(int[] nums1, int m, int[] nums2, int n) {\n int p1 = m-1, p2 = n-1, p = m+n-1;\n while (p1 >= 0 && p2 >= 0) {\n nums1[p--] = nums1[p1] > nums2[p2] ? nums1[p1--] : nums2[p2--];\n }\n while (p2 >= 0) nums1[p--] = nums2[p2--];\n}", "solution_cpp": "void merge(vector& nums1, int m, vector& nums2, int n) {\n int p1 = m-1, p2 = n-1, p = m+n-1;\n while (p1 >= 0 && p2 >= 0) nums1[p--] = nums1[p1] > nums2[p2] ? nums1[p1--] : nums2[p2--];\n while (p2 >= 0) nums1[p--] = nums2[p2--];\n}", "test_cases": ["nums1=[1,2,3], m=3, nums2=[2,5,6], n=3 -> [1,2,2,3,5,6]", "nums1=[], m=0, nums2=[1], n=1 -> [1]"], "key_points": ["从后往前合并", "三指针技巧"], "tags": ["array", "easy", "Microsoft", "Uber"]} {"problem_id": "algo_01943", "original_id": "max-subarray", "title": "最大子数组和", "category": "array", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "给你一个整数数组 nums ,请你找出一个具有最大和的连续子数组,返回其最大和。", "solution_python": "def maxSubArray(nums):\n max_sum = current = nums[0]\n for num in nums[1:]:\n current = max(num, current + num)\n max_sum = max(max_sum, current)\n return max_sum", "solution_java": "public int maxSubArray(int[] nums) {\n int maxSum = nums[0], curr = nums[0];\n for (int i = 1; i < nums.length; i++) {\n curr = Math.max(nums[i], curr + nums[i]);\n maxSum = Math.max(maxSum, curr);\n }\n return maxSum;\n}", "solution_cpp": "int maxSubArray(vector& nums) {\n int maxSum = nums[0], curr = nums[0];\n for (int i = 1; i < nums.size(); i++) {\n curr = max(nums[i], curr + nums[i]);\n maxSum = max(maxSum, curr);\n }\n return maxSum;\n}", "test_cases": ["nums=[-2,1,-3,4,-1,2,1,-5,4] -> 6", "nums=[1] -> 1"], "key_points": ["Kadane算法", "动态规划基础题"], "tags": ["array", "medium", "Google", "Microsoft"]} {"problem_id": "algo_01944", "original_id": "valid-parentheses", "title": "有效的括号", "category": "string", "difficulty": "easy", "companies": ["Google", "Uber"], "description": "给定一个只包括 '(',')','{','}','[',']' 的字符串 s,判断字符串是否有效。", "solution_python": "def isValid(s):\n stack = []\n mapping = {')': '(', ']': '[', '}': '{'}\n for c in s:\n if c in mapping:\n if not stack or stack[-1] != mapping[c]: return False\n stack.pop()\n else: stack.append(c)\n return not stack", "solution_java": "public boolean isValid(String s) {\n Stack stack = new Stack<>();\n Map map = Map.of(')', '(', ']', '[', '}', '{');\n for (char c : s.toCharArray()) {\n if (map.containsValue(c)) stack.push(c);\n else if (!stack.isEmpty() && stack.pop() != map.get(c)) return false;\n }\n return stack.isEmpty();\n}", "solution_cpp": "bool isValid(string s) {\n stack st;\n unordered_map m = {{')','('},{']','['},{'}','{'}};\n for (char c : s) {\n if (m.find(c) == m.end()) st.push(c);\n else if (st.empty() || st.top() != m[c]) return false;\n else st.pop();\n }\n return st.empty();\n}", "test_cases": ["s=\"()\" -> true", "s=\"()[]{}\" -> true", "s=\"(]\" -> false"], "key_points": ["栈匹配法", "注意空栈边界"], "tags": ["string", "easy", "Google", "Uber"]} {"problem_id": "algo_01945", "original_id": "longest-palindrome", "title": "最长回文子串", "category": "string", "difficulty": "medium", "companies": ["Google", "Amazon"], "description": "给你一个字符串 s,找到 s 中最长的回文子串。", "solution_python": "def longestPalindrome(s):\n def expand(l, r):\n while l >= 0 and r < len(s) and s[l] == s[r]: l -= 1; r += 1\n return l + 1, r - 1\n start = end = 0\n for i in range(len(s)):\n l1, r1 = expand(i, i)\n l2, r2 = expand(i, i + 1)\n if r1 - l1 > end - start: start, end = l1, r1\n if r2 - l2 > end - start: start, end = l2, r2\n return s[start:end+1]", "solution_java": "public String longestPalindrome(String s) {\n int start = 0, end = 0;\n for (int i = 0; i < s.length(); i++) {\n int len1 = expand(s, i, i), len2 = expand(s, i, i+1);\n int len = Math.max(len1, len2);\n if (len > end - start) { start = i - (len-1)/2; end = i + len/2; }\n }\n return s.substring(start, end + 1);\n}\nprivate int expand(String s, int l, int r) {\n while (l >= 0 && r < s.length() && s.charAt(l) == s.charAt(r)) { l--; r++; }\n return r - l - 1;\n}", "solution_cpp": "string longestPalindrome(string s) {\n int start = 0, end = 0;\n for (int i = 0; i < s.size(); i++) {\n int len1 = expand(s, i, i), len2 = expand(s, i, i+1);\n if (max(len1, len2) > end - start) { start = i - (max(len1,len2)-1)/2; end = i + max(len1,len2)/2; }\n }\n return s.substr(start, end - start + 1);\n}", "test_cases": ["s=\"babad\" -> bab或aba", "s=\"cbbd\" -> bb"], "key_points": ["中心扩展法", "处理奇偶长度"], "tags": ["string", "medium", "Google", "Amazon"]} {"problem_id": "algo_01946", "original_id": "reverse-list", "title": "反转链表", "category": "linkedlist", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "给你单链表的头节点 head,请你反转链表,并返回反转后的链表。", "solution_python": "def reverseList(head):\n prev = None\n curr = head\n while curr:\n nxt = curr.next\n curr.next = prev\n prev = curr\n curr = nxt\n return prev", "solution_java": "public ListNode reverseList(ListNode head) {\n ListNode prev = null, curr = head;\n while (curr != null) {\n ListNode next = curr.next;\n curr.next = prev;\n prev = curr;\n curr = next;\n }\n return prev;\n}", "solution_cpp": "ListNode* reverseList(ListNode* head) {\n ListNode* prev = nullptr, *curr = head;\n while (curr) {\n ListNode* next = curr->next;\n curr->next = prev;\n prev = curr;\n curr = next;\n }\n return prev;\n}", "test_cases": ["head=[1,2,3,4,5] -> [5,4,3,2,1]", "head=[1,2] -> [2,1]"], "key_points": ["迭代法 O(1)空间", "递归法 O(n)空间"], "tags": ["linkedlist", "medium", "Google", "Microsoft"]} {"problem_id": "algo_01947", "original_id": "middle-node", "title": "链表的中间结点", "category": "linkedlist", "difficulty": "easy", "companies": ["Amazon", "Facebook"], "description": "给你单链表的头节点 head,请你找出并返回链表的中间结点。如果有两个中间结点,则返回第二个中间结点。", "solution_python": "def middleNode(head):\n slow = fast = head\n while fast and fast.next:\n slow = slow.next\n fast = fast.next.next\n return slow", "solution_java": "public ListNode middleNode(ListNode head) {\n ListNode slow = head, fast = head;\n while (fast != null && fast.next != null) {\n slow = slow.next;\n fast = fast.next.next;\n }\n return slow;\n}", "solution_cpp": "ListNode* middleNode(ListNode* head) {\n ListNode* slow = head, *fast = head;\n while (fast && fast->next) { slow = slow->next; fast = fast->next->next; }\n return slow;\n}", "test_cases": ["head=[1,2,3,4,5] -> 3", "head=[1,2,3,4,5,6] -> 4"], "key_points": ["快慢指针", "O(n)时间O(1)空间"], "tags": ["linkedlist", "easy", "Amazon", "Facebook"]} {"problem_id": "algo_01948", "original_id": "max-depth", "title": "二叉树的最大深度", "category": "tree", "difficulty": "easy", "companies": ["Microsoft", "Apple"], "description": "给定一个二叉树 root,返回其最大深度。", "solution_python": "def maxDepth(root):\n if not root: return 0\n return max(maxDepth(root.left), maxDepth(root.right)) + 1", "solution_java": "public int maxDepth(TreeNode root) {\n if (root == null) return 0;\n return Math.max(maxDepth(root.left), maxDepth(root.right)) + 1;\n}", "solution_cpp": "int maxDepth(TreeNode* root) {\n if (!root) return 0;\n return max(maxDepth(root->left), maxDepth(root->right)) + 1;\n}", "test_cases": ["root=[3,9,20,null,null,15,7] -> 3", "root=[1,null,2] -> 2"], "key_points": ["DFS递归", "层序遍历也可"], "tags": ["tree", "easy", "Microsoft", "Apple"]} {"problem_id": "algo_01949", "original_id": "inorder-traversal", "title": "二叉树的中序遍历", "category": "tree", "difficulty": "easy", "companies": ["Google", "Microsoft"], "description": "给定一个二叉树的根节点 root,返回它的中序遍历结果。", "solution_python": "def inorderTraversal(root):\n result = []\n def dfs(node):\n if node:\n dfs(node.left)\n result.append(node.val)\n dfs(node.right)\n dfs(root)\n return result", "solution_java": "public List inorderTraversal(TreeNode root) {\n List res = new ArrayList<>();\n dfs(root, res);\n return res;\n}\nprivate void dfs(TreeNode node, List res) {\n if (node == null) return;\n dfs(node.left, res); res.add(node.val); dfs(node.right, res);\n}", "solution_cpp": "vector inorderTraversal(TreeNode* root) {\n vector res;\n dfs(root, res);\n return res;\n}\nvoid dfs(TreeNode* node, vector& res) {\n if (!node) return;\n dfs(node->left, res); res.push_back(node->val); dfs(node->right, res);\n}", "test_cases": ["root=[1,null,2,3] -> [1,3,2]", "root=[] -> []"], "key_points": ["左-根-右顺序", "递归最简洁"], "tags": ["tree", "easy", "Google", "Microsoft"]} {"problem_id": "algo_01950", "original_id": "binary-search", "title": "二分查找", "category": "binarysearch", "difficulty": "easy", "companies": ["Google", "Amazon"], "description": "给定一个 n 个元素有序的(升序)整型数组 nums 和一个目标值 target,写一个函数搜索 nums 中的 target,如果目标值存在返回下标,否则返回 -1。", "solution_python": "def search(nums, target):\n left, right = 0, len(nums) - 1\n while left <= right:\n mid = (left + right) // 2\n if nums[mid] == target: return mid\n elif nums[mid] < target: left = mid + 1\n else: right = mid - 1\n return -1", "solution_java": "public int search(int[] nums, int target) {\n int left = 0, right = nums.length - 1;\n while (left <= right) {\n int mid = left + (right - left) / 2;\n if (nums[mid] == target) return mid;\n else if (nums[mid] < target) left = mid + 1;\n else right = mid - 1;\n }\n return -1;\n}", "solution_cpp": "int search(vector& nums, int target) {\n int left = 0, right = nums.size() - 1;\n while (left <= right) {\n int mid = left + (right - left) / 2;\n if (nums[mid] == target) return mid;\n else if (nums[mid] < target) left = mid + 1;\n else right = mid - 1;\n }\n return -1;\n}", "test_cases": ["nums=[-1,0,3,5,9,12], target=9 -> 4", "nums=[-1,0,3,5,9,12], target=2 -> -1"], "key_points": ["标准模板", "注意防溢出写法"], "tags": ["binarysearch", "easy", "Google", "Amazon"]} {"problem_id": "algo_01951", "original_id": "climbing-stairs", "title": "爬楼梯", "category": "dp", "difficulty": "easy", "companies": ["Amazon", "Google"], "description": "假设你正在爬楼梯。需要 n 阶你才能到达楼顶。每次你可以爬 1 或 2 个台阶。你有多少种不同的方法可以爬到楼顶?", "solution_python": "def climbStairs(n):\n if n <= 2: return n\n a, b = 1, 2\n for _ in range(3, n+1):\n a, b = b, a + b\n return b", "solution_java": "public int climbStairs(int n) {\n if (n <= 2) return n;\n int a = 1, b = 2;\n for (int i = 3; i <= n; i++) { int temp = a + b; a = b; b = temp; }\n return b;\n}", "solution_cpp": "int climbStairs(int n) {\n if (n <= 2) return n;\n int a = 1, b = 2;\n for (int i = 3; i <= n; i++) { int temp = a + b; a = b; b = temp; }\n return b;\n}", "test_cases": ["n=2 -> 2", "n=3 -> 3", "n=5 -> 8"], "key_points": ["斐波那契数列", "滚动数组优化空间"], "tags": ["dp", "easy", "Amazon", "Google"]} {"problem_id": "algo_01952", "original_id": "coin-change", "title": "零钱兑换", "category": "dp", "difficulty": "medium", "companies": ["Google", "Amazon"], "description": "给你一个整数数组 coins 表示不同面额的硬币,以及一个整数 amount 表示总金额。计算并返回可以凑成总金额所需的最少的硬币个数。如果没有任何一种硬币组合能组成总金额,返回 -1。", "solution_python": "def coinChange(coins, amount):\n dp = [float('inf')] * (amount + 1)\n dp[0] = 0\n for coin in coins:\n for x in range(coin, amount + 1):\n dp[x] = min(dp[x], dp[x - coin] + 1)\n return dp[amount] if dp[amount] != float('inf') else -1", "solution_java": "public int coinChange(int[] coins, int amount) {\n int[] dp = new int[amount + 1];\n Arrays.fill(dp, amount + 1);\n dp[0] = 0;\n for (int coin : coins) {\n for (int x = coin; x <= amount; x++) {\n dp[x] = Math.min(dp[x], dp[x - coin] + 1);\n }\n }\n return dp[amount] > amount ? -1 : dp[amount];\n}", "solution_cpp": "int coinChange(vector& coins, int amount) {\n vector dp(amount + 1, amount + 1);\n dp[0] = 0;\n for (int coin : coins) {\n for (int x = coin; x <= amount; x++) {\n dp[x] = min(dp[x], dp[x - coin] + 1);\n }\n }\n return dp[amount] > amount ? -1 : dp[amount];\n}", "test_cases": ["coins=[1,2,5], amount=11 -> 3", "coins=[2], amount=3 -> -1"], "key_points": ["完全背包问题", "dp[x] = min(dp[x-coin]+1)"], "tags": ["dp", "medium", "Google", "Amazon"]} {"problem_id": "algo_01953", "original_id": "subsets", "title": "子集", "category": "backtracking", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "给你一个整数数组 nums ,数组中的元素 互不相同 。返回该数组所有可能的子集(幂集)。", "solution_python": "def subsets(nums):\n result = []\n def backtrack(start, path):\n result.append(path[:])\n for i in range(start, len(nums)):\n path.append(nums[i])\n backtrack(i + 1, path)\n path.pop()\n backtrack(0, [])\n return result", "solution_java": "public List> subsets(int[] nums) {\n List> result = new ArrayList<>();\n backtrack(nums, 0, new ArrayList<>(), result);\n return result;\n}\nprivate void backtrack(int[] nums, int start, List path, List> result) {\n result.add(new ArrayList<>(path));\n for (int i = start; i < nums.length; i++) {\n path.add(nums[i]);\n backtrack(nums, i + 1, path, result);\n path.remove(path.size() - 1);\n }\n}", "solution_cpp": "vector> subsets(vector& nums) {\n vector> result;\n vector path;\n backtrack(nums, 0, path, result);\n return result;\n}\nvoid backtrack(vector& nums, int start, vector& path, vector>& result) {\n result.push_back(path);\n for (int i = start; i < nums.size(); i++) {\n path.push_back(nums[i]);\n backtrack(nums, i + 1, path, result);\n path.pop_back();\n }\n}", "test_cases": ["nums=[1,2,3] -> [[],[1],[2],[1,2],[3],[1,3],[2,3],[1,2,3]]"], "key_points": ["选或不选", "DFS遍历子集树"], "tags": ["backtracking", "medium", "Google", "Microsoft"]} {"problem_id": "algo_01954", "original_id": "permutations", "title": "全排列", "category": "backtracking", "difficulty": "medium", "companies": ["Google", "Facebook"], "description": "给定一个不含重复数字的数组 nums,返回其所有可能的全排列。", "solution_python": "def permute(nums):\n result = []\n def backtrack(path, used):\n if len(path) == len(nums):\n result.append(path[:])\n return\n for i in range(len(nums)):\n if used[i]: continue\n used[i] = True\n path.append(nums[i])\n backtrack(path, used)\n path.pop()\n used[i] = False\n backtrack([], [False]*len(nums))\n return result", "solution_java": "public List> permute(int[] nums) {\n List> result = new ArrayList<>();\n boolean[] used = new boolean[nums.length];\n backtrack(nums, used, new ArrayList<>(), result);\n return result;\n}\nprivate void backtrack(int[] nums, boolean[] used, List path, List> result) {\n if (path.size() == nums.length) { result.add(new ArrayList<>(path)); return; }\n for (int i = 0; i < nums.length; i++) {\n if (used[i]) continue;\n used[i] = true;\n path.add(nums[i]);\n backtrack(nums, used, path, result);\n path.remove(path.size() - 1);\n used[i] = false;\n }\n}", "solution_cpp": "vector> permute(vector& nums) {\n vector> result;\n vector used(nums.size(), false);\n vector path;\n backtrack(nums, used, path, result);\n return result;\n}\nvoid backtrack(vector& nums, vector& used, vector& path, vector>& result) {\n if (path.size() == nums.size()) { result.push_back(path); return; }\n for (int i = 0; i < nums.size(); i++) {\n if (used[i]) continue;\n used[i] = true;\n path.push_back(nums[i]);\n backtrack(nums, used, path, result);\n path.pop_back();\n used[i] = false;\n }\n}", "test_cases": ["nums=[1,2,3] -> [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]"], "key_points": ["标记已使用元素", "回溯经典模板"], "tags": ["backtracking", "medium", "Google", "Facebook"]} {"problem_id": "algo_01955", "original_id": "top-k-frequent", "title": "前K个高频元素", "category": "heap", "difficulty": "medium", "companies": ["Amazon", "Facebook"], "description": "给你一个整数数组 nums 和一个整数 k,请你返回其中出现频率前 k 高的元素。", "solution_python": "import heapq\nfrom collections import Counter\ndef topKFrequent(nums, k):\n count = Counter(nums)\n heap = []\n for num, freq in count.items():\n heapq.heappush(heap, (freq, num))\n if len(heap) > k: heapq.heappop(heap)\n return [num for freq, num in heap]", "solution_java": "public int[] topKFrequent(int[] nums, int k) {\n Map count = new HashMap<>();\n for (int n : nums) count.put(n, count.getOrDefault(n, 0) + 1);\n PriorityQueue> heap = \n new PriorityQueue<>((a, b) -> a.getValue() - b.getValue());\n for (Map.Entry e : count.entrySet()) {\n heap.offer(e);\n if (heap.size() > k) heap.poll();\n }\n int[] res = new int[k];\n for (int i = k - 1; i >= 0; i--) res[i] = heap.poll().getKey();\n return res;\n}", "solution_cpp": "vector topKFrequent(vector& nums, int k) {\n unordered_map count;\n for (int n : nums) count[n]++;\n priority_queue, vector>, greater>> heap;\n for (auto& [num, freq] : count) {\n heap.push({freq, num});\n if (heap.size() > k) heap.pop();\n }\n vector res;\n while (!heap.empty()) { res.push_back(heap.top().second); heap.pop(); }\n reverse(res.begin(), res.end());\n return res;\n}", "test_cases": ["nums=[1,1,1,2,2,3], k=2 -> [1,2]", "nums=[1], k=1 -> [1]"], "key_points": ["小顶堆保持大小k", "时间复杂度O(nlogk)"], "tags": ["heap", "medium", "Amazon", "Facebook"]} {"problem_id": "algo_01956", "original_id": "3sum", "title": "三数之和", "category": "two-pointers", "difficulty": "medium", "companies": ["Google", "Amazon"], "description": "给你一个整数数组 nums,判断是否存在三元组满足和为0,返回所有不重复的三元组。", "solution_python": "def threeSum(nums):\n nums.sort()\n result = []\n for i in range(len(nums) - 2):\n if i > 0 and nums[i] == nums[i-1]: continue\n left, right = i + 1, len(nums) - 1\n while left < right:\n total = nums[i] + nums[left] + nums[right]\n if total < 0: left += 1\n elif total > 0: right -= 1\n else:\n result.append([nums[i], nums[left], nums[right]])\n while left < right and nums[left] == nums[left+1]: left += 1\n while left < right and nums[right] == nums[right-1]: right -= 1\n left += 1; right -= 1\n return result", "solution_java": "public List> threeSum(int[] nums) {\n Arrays.sort(nums);\n List> result = new ArrayList<>();\n for (int i = 0; i < nums.length - 2; i++) {\n if (i > 0 && nums[i] == nums[i-1]) continue;\n int left = i + 1, right = nums.length - 1;\n while (left < right) {\n int total = nums[i] + nums[left] + nums[right];\n if (total < 0) left++;\n else if (total > 0) right--;\n else {\n result.add(Arrays.asList(nums[i], nums[left], nums[right]));\n while (left < right && nums[left] == nums[left+1]) left++;\n while (left < right && nums[right] == nums[right-1]) right--;\n left++; right--;\n }\n }\n }\n return result;\n}", "solution_cpp": "vector> threeSum(vector& nums) {\n sort(nums.begin(), nums.end());\n vector> result;\n for (int i = 0; i < nums.size() - 2; i++) {\n if (i > 0 && nums[i] == nums[i-1]) continue;\n int left = i + 1, right = nums.size() - 1;\n while (left < right) {\n int total = nums[i] + nums[left] + nums[right];\n if (total < 0) left++;\n else if (total > 0) right--;\n else {\n result.push_back({nums[i], nums[left], nums[right]});\n while (left < right && nums[left] == nums[left+1]) left++;\n while (left < right && nums[right] == nums[right-1]) right--;\n left++; right--;\n }\n }\n }\n return result;\n}", "test_cases": ["nums=[-1,0,1,2,-1,-4] -> [[-1,-1,2],[-1,0,1]]"], "key_points": ["排序+双指针", "去重是关键"], "tags": ["two-pointers", "medium", "Google", "Amazon"]} {"problem_id": "algo_01957", "original_id": "container-water", "title": "盛最多水的容器", "category": "two-pointers", "difficulty": "medium", "companies": ["Google", "Uber"], "description": "给定一个长度为 n 的整数数组 height,找出其中的两条线,使得它们与 x 轴共同构成的容器可以容纳最多的水。", "solution_python": "def maxArea(height):\n left, right = 0, len(height) - 1\n max_area = 0\n while left < right:\n h = min(height[left], height[right])\n max_area = max(max_area, h * (right - left))\n if height[left] < height[right]: left += 1\n else: right -= 1\n return max_area", "solution_java": "public int maxArea(int[] height) {\n int left = 0, right = height.length - 1, maxArea = 0;\n while (left < right) {\n int h = Math.min(height[left], height[right]);\n maxArea = Math.max(maxArea, h * (right - left));\n if (height[left] < height[right]) left++;\n else right--;\n }\n return maxArea;\n}", "solution_cpp": "int maxArea(vector& height) {\n int left = 0, right = height.size() - 1, maxArea = 0;\n while (left < right) {\n int h = min(height[left], height[right]);\n maxArea = max(maxArea, h * (right - left));\n if (height[left] < height[right]) left++;\n else right--;\n }\n return maxArea;\n}", "test_cases": ["height=[1,8,6,2,5,4,8,3,7] -> 49"], "key_points": ["移动短边指针", "面积=min(h1,h2)*width"], "tags": ["two-pointers", "medium", "Google", "Uber"]} {"problem_id": "algo_01958", "original_id": "min-stack", "title": "最小栈", "category": "stack", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "设计一个支持 push,pop,top 操作,并能在常数时间内检索到最小元素的栈。", "solution_python": "class MinStack:\n def __init__(self):\n self.stack = []\n self.min_stack = []\n def push(self, val):\n self.stack.append(val)\n self.min_stack.append(min(val, self.min_stack[-1] if self.min_stack else val))\n def pop(self):\n self.stack.pop(); self.min_stack.pop()\n def top(self): return self.stack[-1]\n def getMin(self): return self.min_stack[-1]", "solution_java": "class MinStack {\n Stack stack = new Stack<>();\n Stack minStack = new Stack<>();\n public void push(int val) { stack.push(val); minStack.push(Math.min(val, minStack.isEmpty() ? val : minStack.peek())); }\n public void pop() { stack.pop(); minStack.pop(); }\n public int top() { return stack.peek(); }\n public int getMin() { return minStack.peek(); }\n}", "solution_cpp": "class MinStack {\n stack st, minSt;\npublic:\n void push(int val) { st.push(val); minSt.push(min(val, minSt.empty() ? val : minSt.top())); }\n void pop() { st.pop(); minSt.pop(); }\n int top() { return st.top(); }\n int getMin() { return minSt.top(); }\n};", "test_cases": ["push(-2), push(0), push(-3) -> getMin() returns -3"], "key_points": ["辅助栈记录最小值", "O(1)时间获取最小值"], "tags": ["stack", "medium", "Google", "Microsoft"]} {"problem_id": "algo_01959", "original_id": "lru-cache", "title": "LRU缓存", "category": "design", "difficulty": "hard", "companies": ["Google", "Amazon"], "description": "设计和实现一个 LRU(最近最少使用)缓存机制。", "solution_python": "class LRUCache:\n def __init__(self, capacity):\n self.capacity = capacity\n self.cache = {}\n self.order = []\n def get(self, key):\n if key not in self.cache: return -1\n self.order.remove(key); self.order.append(key)\n return self.cache[key]\n def put(self, key, value):\n if key in self.cache:\n self.order.remove(key)\n elif len(self.cache) >= self.capacity:\n del self.cache[self.order.pop(0)]\n self.cache[key] = value; self.order.append(key)", "solution_java": "class LRUCache {\n int capacity;\n LinkedHashMap cache = new LinkedHashMap<>();\n public LRUCache(int cap) { capacity = cap; }\n public int get(int key) { return cache.containsKey(key) ? cache.remove(key) : -1; }\n public void put(int key, int val) {\n if (cache.containsKey(key)) cache.remove(key);\n else if (cache.size() >= capacity) cache.remove(cache.keySet().iterator().next());\n cache.put(key, val);\n }\n}", "solution_cpp": "class LRUCache {\n int cap;\n list> dll;\n unordered_map>::iterator> cache;\npublic:\n LRUCache(int capacity) : cap(capacity) {}\n int get(int key) {\n auto it = cache.find(key);\n if (it == cache.end()) return -1;\n dll.splice(dll.end(), dll, it->second);\n return it->second->second;\n }\n void put(int key, int value) {\n auto it = cache.find(key);\n if (it != cache.end()) dll.erase(it->second);\n else if (cache.size() >= cap) { cache.erase(dll.front().first); dll.pop_front(); }\n dll.push_back({key, value});\n cache[key] = --dll.end();\n }\n};", "test_cases": ["put(1,1), put(2,2), get(1) -> 1"], "key_points": ["HashMap + 双向链表", "O(1)时间操作"], "tags": ["design", "hard", "Google", "Amazon"]} {"problem_id": "algo_01960", "original_id": "num-islands", "title": "岛屿数量", "category": "graph", "difficulty": "medium", "companies": ["Google", "Facebook"], "description": "给你一个由 '1'(陆地)和 '0'(水)组成的二维网格,请你计算网格中岛屿的数量。岛屿总是被水包围,且只能由水平或垂直方向相邻的陆地连接形成。", "solution_python": "def numIslands(grid):\n if not grid: return 0\n rows, cols = len(grid), len(grid[0])\n count = 0\n def dfs(r, c):\n if r < 0 or r >= rows or c < 0 or c >= cols or grid[r][c] != '1': return\n grid[r][c] = '0'\n dfs(r+1, c); dfs(r-1, c); dfs(r, c+1); dfs(r, c-1)\n for r in range(rows):\n for c in range(cols):\n if grid[r][c] == '1': count += 1; dfs(r, c)\n return count", "solution_java": "public int numIslands(char[][] grid) {\n if (grid.length == 0) return 0;\n int count = 0;\n for (int i = 0; i < grid.length; i++)\n for (int j = 0; j < grid[0].length; j++)\n if (grid[i][j] == '1') { count++; dfs(grid, i, j); }\n return count;\n}\nprivate void dfs(char[][] grid, int r, int c) {\n if (r < 0 || r >= grid.length || c < 0 || c >= grid[0].length || grid[r][c] != '1') return;\n grid[r][c] = '0';\n dfs(grid, r+1, c); dfs(grid, r-1, c); dfs(grid, r, c+1); dfs(grid, r, c-1);\n}", "solution_cpp": "int numIslands(vector>& grid) {\n if (grid.empty()) return 0;\n int count = 0;\n for (int i = 0; i < grid.size(); i++)\n for (int j = 0; j < grid[0].size(); j++)\n if (grid[i][j] == '1') { count++; dfs(grid, i, j); }\n return count;\n}\nvoid dfs(vector>& grid, int r, int c) {\n if (r < 0 || r >= grid.size() || c < 0 || c >= grid[0].size() || grid[r][c] != '1') return;\n grid[r][c] = '0';\n dfs(grid, r+1, c); dfs(grid, r-1, c); dfs(grid, r, c+1); dfs(grid, r, c-1);\n}", "test_cases": ["grid=[[1,1,1,1,0],[1,1,0,1,0],[1,1,0,0,0],[0,0,0,0,0]] -> 1"], "key_points": ["DFS/BFS遍历", "访问后标记为0避免重复"], "tags": ["graph", "medium", "Google", "Facebook"]} {"problem_id": "algo_01961", "original_id": "two-sum", "title": "两数之和", "category": "array", "difficulty": "easy", "companies": ["Amazon", "Google"], "description": "给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那两个整数,并返回他们的数组下标。", "solution_python": "def twoSum(nums, target):\n hashmap = {}\n for i, num in enumerate(nums):\n complement = target - num\n if complement in hashmap:\n return [hashmap[complement], i]\n hashmap[num] = i\n return []", "solution_java": "public int[] twoSum(int[] nums, int target) {\n Map map = new HashMap<>();\n for (int i = 0; i < nums.length; i++) {\n int complement = target - nums[i];\n if (map.containsKey(complement)) return new int[]{map.get(complement), i};\n map.put(nums[i], i);\n }\n return new int[]{};\n}", "solution_cpp": "vector twoSum(vector& nums, int target) {\n unordered_map m;\n for (int i = 0; i < nums.size(); i++) {\n if (m.count(target - nums[i])) return {m[target - nums[i]], i};\n m[nums[i]] = i;\n }\n return {};\n}", "test_cases": ["nums=[2,7,11,15], target=9 -> [0,1]", "nums=[3,2,4], target=6 -> [1,2]"], "key_points": ["哈希表一次遍历", "空间换时间"], "tags": ["array", "easy", "Amazon", "Google"]} {"problem_id": "algo_01962", "original_id": "merge-sorted", "title": "合并两个有序数组", "category": "array", "difficulty": "easy", "companies": ["Microsoft", "Uber"], "description": "给你两个按非递减顺序排列的整数数组 nums1 和 nums2,另有两个整数 m 和 n,分别表示 nums1 和 nums2 中的元素数目。请你合并 nums2 到 nums1 中。", "solution_python": "def merge(nums1, m, nums2, n):\n p1, p2, p = m-1, n-1, m+n-1\n while p1 >= 0 and p2 >= 0:\n if nums1[p1] > nums2[p2]: nums1[p] = nums1[p1]; p1 -= 1\n else: nums1[p] = nums2[p2]; p2 -= 1\n p -= 1\n while p2 >= 0: nums1[p] = nums2[p2]; p2 -= 1; p -= 1", "solution_java": "public void merge(int[] nums1, int m, int[] nums2, int n) {\n int p1 = m-1, p2 = n-1, p = m+n-1;\n while (p1 >= 0 && p2 >= 0) {\n nums1[p--] = nums1[p1] > nums2[p2] ? nums1[p1--] : nums2[p2--];\n }\n while (p2 >= 0) nums1[p--] = nums2[p2--];\n}", "solution_cpp": "void merge(vector& nums1, int m, vector& nums2, int n) {\n int p1 = m-1, p2 = n-1, p = m+n-1;\n while (p1 >= 0 && p2 >= 0) nums1[p--] = nums1[p1] > nums2[p2] ? nums1[p1--] : nums2[p2--];\n while (p2 >= 0) nums1[p--] = nums2[p2--];\n}", "test_cases": ["nums1=[1,2,3], m=3, nums2=[2,5,6], n=3 -> [1,2,2,3,5,6]", "nums1=[], m=0, nums2=[1], n=1 -> [1]"], "key_points": ["从后往前合并", "三指针技巧"], "tags": ["array", "easy", "Microsoft", "Uber"]} {"problem_id": "algo_01963", "original_id": "max-subarray", "title": "最大子数组和", "category": "array", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "给你一个整数数组 nums ,请你找出一个具有最大和的连续子数组,返回其最大和。", "solution_python": "def maxSubArray(nums):\n max_sum = current = nums[0]\n for num in nums[1:]:\n current = max(num, current + num)\n max_sum = max(max_sum, current)\n return max_sum", "solution_java": "public int maxSubArray(int[] nums) {\n int maxSum = nums[0], curr = nums[0];\n for (int i = 1; i < nums.length; i++) {\n curr = Math.max(nums[i], curr + nums[i]);\n maxSum = Math.max(maxSum, curr);\n }\n return maxSum;\n}", "solution_cpp": "int maxSubArray(vector& nums) {\n int maxSum = nums[0], curr = nums[0];\n for (int i = 1; i < nums.size(); i++) {\n curr = max(nums[i], curr + nums[i]);\n maxSum = max(maxSum, curr);\n }\n return maxSum;\n}", "test_cases": ["nums=[-2,1,-3,4,-1,2,1,-5,4] -> 6", "nums=[1] -> 1"], "key_points": ["Kadane算法", "动态规划基础题"], "tags": ["array", "medium", "Google", "Microsoft"]} {"problem_id": "algo_01964", "original_id": "valid-parentheses", "title": "有效的括号", "category": "string", "difficulty": "easy", "companies": ["Google", "Uber"], "description": "给定一个只包括 '(',')','{','}','[',']' 的字符串 s,判断字符串是否有效。", "solution_python": "def isValid(s):\n stack = []\n mapping = {')': '(', ']': '[', '}': '{'}\n for c in s:\n if c in mapping:\n if not stack or stack[-1] != mapping[c]: return False\n stack.pop()\n else: stack.append(c)\n return not stack", "solution_java": "public boolean isValid(String s) {\n Stack stack = new Stack<>();\n Map map = Map.of(')', '(', ']', '[', '}', '{');\n for (char c : s.toCharArray()) {\n if (map.containsValue(c)) stack.push(c);\n else if (!stack.isEmpty() && stack.pop() != map.get(c)) return false;\n }\n return stack.isEmpty();\n}", "solution_cpp": "bool isValid(string s) {\n stack st;\n unordered_map m = {{')','('},{']','['},{'}','{'}};\n for (char c : s) {\n if (m.find(c) == m.end()) st.push(c);\n else if (st.empty() || st.top() != m[c]) return false;\n else st.pop();\n }\n return st.empty();\n}", "test_cases": ["s=\"()\" -> true", "s=\"()[]{}\" -> true", "s=\"(]\" -> false"], "key_points": ["栈匹配法", "注意空栈边界"], "tags": ["string", "easy", "Google", "Uber"]} {"problem_id": "algo_01965", "original_id": "longest-palindrome", "title": "最长回文子串", "category": "string", "difficulty": "medium", "companies": ["Google", "Amazon"], "description": "给你一个字符串 s,找到 s 中最长的回文子串。", "solution_python": "def longestPalindrome(s):\n def expand(l, r):\n while l >= 0 and r < len(s) and s[l] == s[r]: l -= 1; r += 1\n return l + 1, r - 1\n start = end = 0\n for i in range(len(s)):\n l1, r1 = expand(i, i)\n l2, r2 = expand(i, i + 1)\n if r1 - l1 > end - start: start, end = l1, r1\n if r2 - l2 > end - start: start, end = l2, r2\n return s[start:end+1]", "solution_java": "public String longestPalindrome(String s) {\n int start = 0, end = 0;\n for (int i = 0; i < s.length(); i++) {\n int len1 = expand(s, i, i), len2 = expand(s, i, i+1);\n int len = Math.max(len1, len2);\n if (len > end - start) { start = i - (len-1)/2; end = i + len/2; }\n }\n return s.substring(start, end + 1);\n}\nprivate int expand(String s, int l, int r) {\n while (l >= 0 && r < s.length() && s.charAt(l) == s.charAt(r)) { l--; r++; }\n return r - l - 1;\n}", "solution_cpp": "string longestPalindrome(string s) {\n int start = 0, end = 0;\n for (int i = 0; i < s.size(); i++) {\n int len1 = expand(s, i, i), len2 = expand(s, i, i+1);\n if (max(len1, len2) > end - start) { start = i - (max(len1,len2)-1)/2; end = i + max(len1,len2)/2; }\n }\n return s.substr(start, end - start + 1);\n}", "test_cases": ["s=\"babad\" -> bab或aba", "s=\"cbbd\" -> bb"], "key_points": ["中心扩展法", "处理奇偶长度"], "tags": ["string", "medium", "Google", "Amazon"]} {"problem_id": "algo_01966", "original_id": "reverse-list", "title": "反转链表", "category": "linkedlist", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "给你单链表的头节点 head,请你反转链表,并返回反转后的链表。", "solution_python": "def reverseList(head):\n prev = None\n curr = head\n while curr:\n nxt = curr.next\n curr.next = prev\n prev = curr\n curr = nxt\n return prev", "solution_java": "public ListNode reverseList(ListNode head) {\n ListNode prev = null, curr = head;\n while (curr != null) {\n ListNode next = curr.next;\n curr.next = prev;\n prev = curr;\n curr = next;\n }\n return prev;\n}", "solution_cpp": "ListNode* reverseList(ListNode* head) {\n ListNode* prev = nullptr, *curr = head;\n while (curr) {\n ListNode* next = curr->next;\n curr->next = prev;\n prev = curr;\n curr = next;\n }\n return prev;\n}", "test_cases": ["head=[1,2,3,4,5] -> [5,4,3,2,1]", "head=[1,2] -> [2,1]"], "key_points": ["迭代法 O(1)空间", "递归法 O(n)空间"], "tags": ["linkedlist", "medium", "Google", "Microsoft"]} {"problem_id": "algo_01967", "original_id": "middle-node", "title": "链表的中间结点", "category": "linkedlist", "difficulty": "easy", "companies": ["Amazon", "Facebook"], "description": "给你单链表的头节点 head,请你找出并返回链表的中间结点。如果有两个中间结点,则返回第二个中间结点。", "solution_python": "def middleNode(head):\n slow = fast = head\n while fast and fast.next:\n slow = slow.next\n fast = fast.next.next\n return slow", "solution_java": "public ListNode middleNode(ListNode head) {\n ListNode slow = head, fast = head;\n while (fast != null && fast.next != null) {\n slow = slow.next;\n fast = fast.next.next;\n }\n return slow;\n}", "solution_cpp": "ListNode* middleNode(ListNode* head) {\n ListNode* slow = head, *fast = head;\n while (fast && fast->next) { slow = slow->next; fast = fast->next->next; }\n return slow;\n}", "test_cases": ["head=[1,2,3,4,5] -> 3", "head=[1,2,3,4,5,6] -> 4"], "key_points": ["快慢指针", "O(n)时间O(1)空间"], "tags": ["linkedlist", "easy", "Amazon", "Facebook"]} {"problem_id": "algo_01968", "original_id": "max-depth", "title": "二叉树的最大深度", "category": "tree", "difficulty": "easy", "companies": ["Microsoft", "Apple"], "description": "给定一个二叉树 root,返回其最大深度。", "solution_python": "def maxDepth(root):\n if not root: return 0\n return max(maxDepth(root.left), maxDepth(root.right)) + 1", "solution_java": "public int maxDepth(TreeNode root) {\n if (root == null) return 0;\n return Math.max(maxDepth(root.left), maxDepth(root.right)) + 1;\n}", "solution_cpp": "int maxDepth(TreeNode* root) {\n if (!root) return 0;\n return max(maxDepth(root->left), maxDepth(root->right)) + 1;\n}", "test_cases": ["root=[3,9,20,null,null,15,7] -> 3", "root=[1,null,2] -> 2"], "key_points": ["DFS递归", "层序遍历也可"], "tags": ["tree", "easy", "Microsoft", "Apple"]} {"problem_id": "algo_01969", "original_id": "inorder-traversal", "title": "二叉树的中序遍历", "category": "tree", "difficulty": "easy", "companies": ["Google", "Microsoft"], "description": "给定一个二叉树的根节点 root,返回它的中序遍历结果。", "solution_python": "def inorderTraversal(root):\n result = []\n def dfs(node):\n if node:\n dfs(node.left)\n result.append(node.val)\n dfs(node.right)\n dfs(root)\n return result", "solution_java": "public List inorderTraversal(TreeNode root) {\n List res = new ArrayList<>();\n dfs(root, res);\n return res;\n}\nprivate void dfs(TreeNode node, List res) {\n if (node == null) return;\n dfs(node.left, res); res.add(node.val); dfs(node.right, res);\n}", "solution_cpp": "vector inorderTraversal(TreeNode* root) {\n vector res;\n dfs(root, res);\n return res;\n}\nvoid dfs(TreeNode* node, vector& res) {\n if (!node) return;\n dfs(node->left, res); res.push_back(node->val); dfs(node->right, res);\n}", "test_cases": ["root=[1,null,2,3] -> [1,3,2]", "root=[] -> []"], "key_points": ["左-根-右顺序", "递归最简洁"], "tags": ["tree", "easy", "Google", "Microsoft"]} {"problem_id": "algo_01970", "original_id": "binary-search", "title": "二分查找", "category": "binarysearch", "difficulty": "easy", "companies": ["Google", "Amazon"], "description": "给定一个 n 个元素有序的(升序)整型数组 nums 和一个目标值 target,写一个函数搜索 nums 中的 target,如果目标值存在返回下标,否则返回 -1。", "solution_python": "def search(nums, target):\n left, right = 0, len(nums) - 1\n while left <= right:\n mid = (left + right) // 2\n if nums[mid] == target: return mid\n elif nums[mid] < target: left = mid + 1\n else: right = mid - 1\n return -1", "solution_java": "public int search(int[] nums, int target) {\n int left = 0, right = nums.length - 1;\n while (left <= right) {\n int mid = left + (right - left) / 2;\n if (nums[mid] == target) return mid;\n else if (nums[mid] < target) left = mid + 1;\n else right = mid - 1;\n }\n return -1;\n}", "solution_cpp": "int search(vector& nums, int target) {\n int left = 0, right = nums.size() - 1;\n while (left <= right) {\n int mid = left + (right - left) / 2;\n if (nums[mid] == target) return mid;\n else if (nums[mid] < target) left = mid + 1;\n else right = mid - 1;\n }\n return -1;\n}", "test_cases": ["nums=[-1,0,3,5,9,12], target=9 -> 4", "nums=[-1,0,3,5,9,12], target=2 -> -1"], "key_points": ["标准模板", "注意防溢出写法"], "tags": ["binarysearch", "easy", "Google", "Amazon"]} {"problem_id": "algo_01971", "original_id": "climbing-stairs", "title": "爬楼梯", "category": "dp", "difficulty": "easy", "companies": ["Amazon", "Google"], "description": "假设你正在爬楼梯。需要 n 阶你才能到达楼顶。每次你可以爬 1 或 2 个台阶。你有多少种不同的方法可以爬到楼顶?", "solution_python": "def climbStairs(n):\n if n <= 2: return n\n a, b = 1, 2\n for _ in range(3, n+1):\n a, b = b, a + b\n return b", "solution_java": "public int climbStairs(int n) {\n if (n <= 2) return n;\n int a = 1, b = 2;\n for (int i = 3; i <= n; i++) { int temp = a + b; a = b; b = temp; }\n return b;\n}", "solution_cpp": "int climbStairs(int n) {\n if (n <= 2) return n;\n int a = 1, b = 2;\n for (int i = 3; i <= n; i++) { int temp = a + b; a = b; b = temp; }\n return b;\n}", "test_cases": ["n=2 -> 2", "n=3 -> 3", "n=5 -> 8"], "key_points": ["斐波那契数列", "滚动数组优化空间"], "tags": ["dp", "easy", "Amazon", "Google"]} {"problem_id": "algo_01972", "original_id": "coin-change", "title": "零钱兑换", "category": "dp", "difficulty": "medium", "companies": ["Google", "Amazon"], "description": "给你一个整数数组 coins 表示不同面额的硬币,以及一个整数 amount 表示总金额。计算并返回可以凑成总金额所需的最少的硬币个数。如果没有任何一种硬币组合能组成总金额,返回 -1。", "solution_python": "def coinChange(coins, amount):\n dp = [float('inf')] * (amount + 1)\n dp[0] = 0\n for coin in coins:\n for x in range(coin, amount + 1):\n dp[x] = min(dp[x], dp[x - coin] + 1)\n return dp[amount] if dp[amount] != float('inf') else -1", "solution_java": "public int coinChange(int[] coins, int amount) {\n int[] dp = new int[amount + 1];\n Arrays.fill(dp, amount + 1);\n dp[0] = 0;\n for (int coin : coins) {\n for (int x = coin; x <= amount; x++) {\n dp[x] = Math.min(dp[x], dp[x - coin] + 1);\n }\n }\n return dp[amount] > amount ? -1 : dp[amount];\n}", "solution_cpp": "int coinChange(vector& coins, int amount) {\n vector dp(amount + 1, amount + 1);\n dp[0] = 0;\n for (int coin : coins) {\n for (int x = coin; x <= amount; x++) {\n dp[x] = min(dp[x], dp[x - coin] + 1);\n }\n }\n return dp[amount] > amount ? -1 : dp[amount];\n}", "test_cases": ["coins=[1,2,5], amount=11 -> 3", "coins=[2], amount=3 -> -1"], "key_points": ["完全背包问题", "dp[x] = min(dp[x-coin]+1)"], "tags": ["dp", "medium", "Google", "Amazon"]} {"problem_id": "algo_01973", "original_id": "subsets", "title": "子集", "category": "backtracking", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "给你一个整数数组 nums ,数组中的元素 互不相同 。返回该数组所有可能的子集(幂集)。", "solution_python": "def subsets(nums):\n result = []\n def backtrack(start, path):\n result.append(path[:])\n for i in range(start, len(nums)):\n path.append(nums[i])\n backtrack(i + 1, path)\n path.pop()\n backtrack(0, [])\n return result", "solution_java": "public List> subsets(int[] nums) {\n List> result = new ArrayList<>();\n backtrack(nums, 0, new ArrayList<>(), result);\n return result;\n}\nprivate void backtrack(int[] nums, int start, List path, List> result) {\n result.add(new ArrayList<>(path));\n for (int i = start; i < nums.length; i++) {\n path.add(nums[i]);\n backtrack(nums, i + 1, path, result);\n path.remove(path.size() - 1);\n }\n}", "solution_cpp": "vector> subsets(vector& nums) {\n vector> result;\n vector path;\n backtrack(nums, 0, path, result);\n return result;\n}\nvoid backtrack(vector& nums, int start, vector& path, vector>& result) {\n result.push_back(path);\n for (int i = start; i < nums.size(); i++) {\n path.push_back(nums[i]);\n backtrack(nums, i + 1, path, result);\n path.pop_back();\n }\n}", "test_cases": ["nums=[1,2,3] -> [[],[1],[2],[1,2],[3],[1,3],[2,3],[1,2,3]]"], "key_points": ["选或不选", "DFS遍历子集树"], "tags": ["backtracking", "medium", "Google", "Microsoft"]} {"problem_id": "algo_01974", "original_id": "permutations", "title": "全排列", "category": "backtracking", "difficulty": "medium", "companies": ["Google", "Facebook"], "description": "给定一个不含重复数字的数组 nums,返回其所有可能的全排列。", "solution_python": "def permute(nums):\n result = []\n def backtrack(path, used):\n if len(path) == len(nums):\n result.append(path[:])\n return\n for i in range(len(nums)):\n if used[i]: continue\n used[i] = True\n path.append(nums[i])\n backtrack(path, used)\n path.pop()\n used[i] = False\n backtrack([], [False]*len(nums))\n return result", "solution_java": "public List> permute(int[] nums) {\n List> result = new ArrayList<>();\n boolean[] used = new boolean[nums.length];\n backtrack(nums, used, new ArrayList<>(), result);\n return result;\n}\nprivate void backtrack(int[] nums, boolean[] used, List path, List> result) {\n if (path.size() == nums.length) { result.add(new ArrayList<>(path)); return; }\n for (int i = 0; i < nums.length; i++) {\n if (used[i]) continue;\n used[i] = true;\n path.add(nums[i]);\n backtrack(nums, used, path, result);\n path.remove(path.size() - 1);\n used[i] = false;\n }\n}", "solution_cpp": "vector> permute(vector& nums) {\n vector> result;\n vector used(nums.size(), false);\n vector path;\n backtrack(nums, used, path, result);\n return result;\n}\nvoid backtrack(vector& nums, vector& used, vector& path, vector>& result) {\n if (path.size() == nums.size()) { result.push_back(path); return; }\n for (int i = 0; i < nums.size(); i++) {\n if (used[i]) continue;\n used[i] = true;\n path.push_back(nums[i]);\n backtrack(nums, used, path, result);\n path.pop_back();\n used[i] = false;\n }\n}", "test_cases": ["nums=[1,2,3] -> [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]"], "key_points": ["标记已使用元素", "回溯经典模板"], "tags": ["backtracking", "medium", "Google", "Facebook"]} {"problem_id": "algo_01975", "original_id": "top-k-frequent", "title": "前K个高频元素", "category": "heap", "difficulty": "medium", "companies": ["Amazon", "Facebook"], "description": "给你一个整数数组 nums 和一个整数 k,请你返回其中出现频率前 k 高的元素。", "solution_python": "import heapq\nfrom collections import Counter\ndef topKFrequent(nums, k):\n count = Counter(nums)\n heap = []\n for num, freq in count.items():\n heapq.heappush(heap, (freq, num))\n if len(heap) > k: heapq.heappop(heap)\n return [num for freq, num in heap]", "solution_java": "public int[] topKFrequent(int[] nums, int k) {\n Map count = new HashMap<>();\n for (int n : nums) count.put(n, count.getOrDefault(n, 0) + 1);\n PriorityQueue> heap = \n new PriorityQueue<>((a, b) -> a.getValue() - b.getValue());\n for (Map.Entry e : count.entrySet()) {\n heap.offer(e);\n if (heap.size() > k) heap.poll();\n }\n int[] res = new int[k];\n for (int i = k - 1; i >= 0; i--) res[i] = heap.poll().getKey();\n return res;\n}", "solution_cpp": "vector topKFrequent(vector& nums, int k) {\n unordered_map count;\n for (int n : nums) count[n]++;\n priority_queue, vector>, greater>> heap;\n for (auto& [num, freq] : count) {\n heap.push({freq, num});\n if (heap.size() > k) heap.pop();\n }\n vector res;\n while (!heap.empty()) { res.push_back(heap.top().second); heap.pop(); }\n reverse(res.begin(), res.end());\n return res;\n}", "test_cases": ["nums=[1,1,1,2,2,3], k=2 -> [1,2]", "nums=[1], k=1 -> [1]"], "key_points": ["小顶堆保持大小k", "时间复杂度O(nlogk)"], "tags": ["heap", "medium", "Amazon", "Facebook"]} {"problem_id": "algo_01976", "original_id": "3sum", "title": "三数之和", "category": "two-pointers", "difficulty": "medium", "companies": ["Google", "Amazon"], "description": "给你一个整数数组 nums,判断是否存在三元组满足和为0,返回所有不重复的三元组。", "solution_python": "def threeSum(nums):\n nums.sort()\n result = []\n for i in range(len(nums) - 2):\n if i > 0 and nums[i] == nums[i-1]: continue\n left, right = i + 1, len(nums) - 1\n while left < right:\n total = nums[i] + nums[left] + nums[right]\n if total < 0: left += 1\n elif total > 0: right -= 1\n else:\n result.append([nums[i], nums[left], nums[right]])\n while left < right and nums[left] == nums[left+1]: left += 1\n while left < right and nums[right] == nums[right-1]: right -= 1\n left += 1; right -= 1\n return result", "solution_java": "public List> threeSum(int[] nums) {\n Arrays.sort(nums);\n List> result = new ArrayList<>();\n for (int i = 0; i < nums.length - 2; i++) {\n if (i > 0 && nums[i] == nums[i-1]) continue;\n int left = i + 1, right = nums.length - 1;\n while (left < right) {\n int total = nums[i] + nums[left] + nums[right];\n if (total < 0) left++;\n else if (total > 0) right--;\n else {\n result.add(Arrays.asList(nums[i], nums[left], nums[right]));\n while (left < right && nums[left] == nums[left+1]) left++;\n while (left < right && nums[right] == nums[right-1]) right--;\n left++; right--;\n }\n }\n }\n return result;\n}", "solution_cpp": "vector> threeSum(vector& nums) {\n sort(nums.begin(), nums.end());\n vector> result;\n for (int i = 0; i < nums.size() - 2; i++) {\n if (i > 0 && nums[i] == nums[i-1]) continue;\n int left = i + 1, right = nums.size() - 1;\n while (left < right) {\n int total = nums[i] + nums[left] + nums[right];\n if (total < 0) left++;\n else if (total > 0) right--;\n else {\n result.push_back({nums[i], nums[left], nums[right]});\n while (left < right && nums[left] == nums[left+1]) left++;\n while (left < right && nums[right] == nums[right-1]) right--;\n left++; right--;\n }\n }\n }\n return result;\n}", "test_cases": ["nums=[-1,0,1,2,-1,-4] -> [[-1,-1,2],[-1,0,1]]"], "key_points": ["排序+双指针", "去重是关键"], "tags": ["two-pointers", "medium", "Google", "Amazon"]} {"problem_id": "algo_01977", "original_id": "container-water", "title": "盛最多水的容器", "category": "two-pointers", "difficulty": "medium", "companies": ["Google", "Uber"], "description": "给定一个长度为 n 的整数数组 height,找出其中的两条线,使得它们与 x 轴共同构成的容器可以容纳最多的水。", "solution_python": "def maxArea(height):\n left, right = 0, len(height) - 1\n max_area = 0\n while left < right:\n h = min(height[left], height[right])\n max_area = max(max_area, h * (right - left))\n if height[left] < height[right]: left += 1\n else: right -= 1\n return max_area", "solution_java": "public int maxArea(int[] height) {\n int left = 0, right = height.length - 1, maxArea = 0;\n while (left < right) {\n int h = Math.min(height[left], height[right]);\n maxArea = Math.max(maxArea, h * (right - left));\n if (height[left] < height[right]) left++;\n else right--;\n }\n return maxArea;\n}", "solution_cpp": "int maxArea(vector& height) {\n int left = 0, right = height.size() - 1, maxArea = 0;\n while (left < right) {\n int h = min(height[left], height[right]);\n maxArea = max(maxArea, h * (right - left));\n if (height[left] < height[right]) left++;\n else right--;\n }\n return maxArea;\n}", "test_cases": ["height=[1,8,6,2,5,4,8,3,7] -> 49"], "key_points": ["移动短边指针", "面积=min(h1,h2)*width"], "tags": ["two-pointers", "medium", "Google", "Uber"]} {"problem_id": "algo_01978", "original_id": "min-stack", "title": "最小栈", "category": "stack", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "设计一个支持 push,pop,top 操作,并能在常数时间内检索到最小元素的栈。", "solution_python": "class MinStack:\n def __init__(self):\n self.stack = []\n self.min_stack = []\n def push(self, val):\n self.stack.append(val)\n self.min_stack.append(min(val, self.min_stack[-1] if self.min_stack else val))\n def pop(self):\n self.stack.pop(); self.min_stack.pop()\n def top(self): return self.stack[-1]\n def getMin(self): return self.min_stack[-1]", "solution_java": "class MinStack {\n Stack stack = new Stack<>();\n Stack minStack = new Stack<>();\n public void push(int val) { stack.push(val); minStack.push(Math.min(val, minStack.isEmpty() ? val : minStack.peek())); }\n public void pop() { stack.pop(); minStack.pop(); }\n public int top() { return stack.peek(); }\n public int getMin() { return minStack.peek(); }\n}", "solution_cpp": "class MinStack {\n stack st, minSt;\npublic:\n void push(int val) { st.push(val); minSt.push(min(val, minSt.empty() ? val : minSt.top())); }\n void pop() { st.pop(); minSt.pop(); }\n int top() { return st.top(); }\n int getMin() { return minSt.top(); }\n};", "test_cases": ["push(-2), push(0), push(-3) -> getMin() returns -3"], "key_points": ["辅助栈记录最小值", "O(1)时间获取最小值"], "tags": ["stack", "medium", "Google", "Microsoft"]} {"problem_id": "algo_01979", "original_id": "lru-cache", "title": "LRU缓存", "category": "design", "difficulty": "hard", "companies": ["Google", "Amazon"], "description": "设计和实现一个 LRU(最近最少使用)缓存机制。", "solution_python": "class LRUCache:\n def __init__(self, capacity):\n self.capacity = capacity\n self.cache = {}\n self.order = []\n def get(self, key):\n if key not in self.cache: return -1\n self.order.remove(key); self.order.append(key)\n return self.cache[key]\n def put(self, key, value):\n if key in self.cache:\n self.order.remove(key)\n elif len(self.cache) >= self.capacity:\n del self.cache[self.order.pop(0)]\n self.cache[key] = value; self.order.append(key)", "solution_java": "class LRUCache {\n int capacity;\n LinkedHashMap cache = new LinkedHashMap<>();\n public LRUCache(int cap) { capacity = cap; }\n public int get(int key) { return cache.containsKey(key) ? cache.remove(key) : -1; }\n public void put(int key, int val) {\n if (cache.containsKey(key)) cache.remove(key);\n else if (cache.size() >= capacity) cache.remove(cache.keySet().iterator().next());\n cache.put(key, val);\n }\n}", "solution_cpp": "class LRUCache {\n int cap;\n list> dll;\n unordered_map>::iterator> cache;\npublic:\n LRUCache(int capacity) : cap(capacity) {}\n int get(int key) {\n auto it = cache.find(key);\n if (it == cache.end()) return -1;\n dll.splice(dll.end(), dll, it->second);\n return it->second->second;\n }\n void put(int key, int value) {\n auto it = cache.find(key);\n if (it != cache.end()) dll.erase(it->second);\n else if (cache.size() >= cap) { cache.erase(dll.front().first); dll.pop_front(); }\n dll.push_back({key, value});\n cache[key] = --dll.end();\n }\n};", "test_cases": ["put(1,1), put(2,2), get(1) -> 1"], "key_points": ["HashMap + 双向链表", "O(1)时间操作"], "tags": ["design", "hard", "Google", "Amazon"]} {"problem_id": "algo_01980", "original_id": "num-islands", "title": "岛屿数量", "category": "graph", "difficulty": "medium", "companies": ["Google", "Facebook"], "description": "给你一个由 '1'(陆地)和 '0'(水)组成的二维网格,请你计算网格中岛屿的数量。岛屿总是被水包围,且只能由水平或垂直方向相邻的陆地连接形成。", "solution_python": "def numIslands(grid):\n if not grid: return 0\n rows, cols = len(grid), len(grid[0])\n count = 0\n def dfs(r, c):\n if r < 0 or r >= rows or c < 0 or c >= cols or grid[r][c] != '1': return\n grid[r][c] = '0'\n dfs(r+1, c); dfs(r-1, c); dfs(r, c+1); dfs(r, c-1)\n for r in range(rows):\n for c in range(cols):\n if grid[r][c] == '1': count += 1; dfs(r, c)\n return count", "solution_java": "public int numIslands(char[][] grid) {\n if (grid.length == 0) return 0;\n int count = 0;\n for (int i = 0; i < grid.length; i++)\n for (int j = 0; j < grid[0].length; j++)\n if (grid[i][j] == '1') { count++; dfs(grid, i, j); }\n return count;\n}\nprivate void dfs(char[][] grid, int r, int c) {\n if (r < 0 || r >= grid.length || c < 0 || c >= grid[0].length || grid[r][c] != '1') return;\n grid[r][c] = '0';\n dfs(grid, r+1, c); dfs(grid, r-1, c); dfs(grid, r, c+1); dfs(grid, r, c-1);\n}", "solution_cpp": "int numIslands(vector>& grid) {\n if (grid.empty()) return 0;\n int count = 0;\n for (int i = 0; i < grid.size(); i++)\n for (int j = 0; j < grid[0].size(); j++)\n if (grid[i][j] == '1') { count++; dfs(grid, i, j); }\n return count;\n}\nvoid dfs(vector>& grid, int r, int c) {\n if (r < 0 || r >= grid.size() || c < 0 || c >= grid[0].size() || grid[r][c] != '1') return;\n grid[r][c] = '0';\n dfs(grid, r+1, c); dfs(grid, r-1, c); dfs(grid, r, c+1); dfs(grid, r, c-1);\n}", "test_cases": ["grid=[[1,1,1,1,0],[1,1,0,1,0],[1,1,0,0,0],[0,0,0,0,0]] -> 1"], "key_points": ["DFS/BFS遍历", "访问后标记为0避免重复"], "tags": ["graph", "medium", "Google", "Facebook"]} {"problem_id": "algo_01981", "original_id": "two-sum", "title": "两数之和", "category": "array", "difficulty": "easy", "companies": ["Amazon", "Google"], "description": "给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那两个整数,并返回他们的数组下标。", "solution_python": "def twoSum(nums, target):\n hashmap = {}\n for i, num in enumerate(nums):\n complement = target - num\n if complement in hashmap:\n return [hashmap[complement], i]\n hashmap[num] = i\n return []", "solution_java": "public int[] twoSum(int[] nums, int target) {\n Map map = new HashMap<>();\n for (int i = 0; i < nums.length; i++) {\n int complement = target - nums[i];\n if (map.containsKey(complement)) return new int[]{map.get(complement), i};\n map.put(nums[i], i);\n }\n return new int[]{};\n}", "solution_cpp": "vector twoSum(vector& nums, int target) {\n unordered_map m;\n for (int i = 0; i < nums.size(); i++) {\n if (m.count(target - nums[i])) return {m[target - nums[i]], i};\n m[nums[i]] = i;\n }\n return {};\n}", "test_cases": ["nums=[2,7,11,15], target=9 -> [0,1]", "nums=[3,2,4], target=6 -> [1,2]"], "key_points": ["哈希表一次遍历", "空间换时间"], "tags": ["array", "easy", "Amazon", "Google"]} {"problem_id": "algo_01982", "original_id": "merge-sorted", "title": "合并两个有序数组", "category": "array", "difficulty": "easy", "companies": ["Microsoft", "Uber"], "description": "给你两个按非递减顺序排列的整数数组 nums1 和 nums2,另有两个整数 m 和 n,分别表示 nums1 和 nums2 中的元素数目。请你合并 nums2 到 nums1 中。", "solution_python": "def merge(nums1, m, nums2, n):\n p1, p2, p = m-1, n-1, m+n-1\n while p1 >= 0 and p2 >= 0:\n if nums1[p1] > nums2[p2]: nums1[p] = nums1[p1]; p1 -= 1\n else: nums1[p] = nums2[p2]; p2 -= 1\n p -= 1\n while p2 >= 0: nums1[p] = nums2[p2]; p2 -= 1; p -= 1", "solution_java": "public void merge(int[] nums1, int m, int[] nums2, int n) {\n int p1 = m-1, p2 = n-1, p = m+n-1;\n while (p1 >= 0 && p2 >= 0) {\n nums1[p--] = nums1[p1] > nums2[p2] ? nums1[p1--] : nums2[p2--];\n }\n while (p2 >= 0) nums1[p--] = nums2[p2--];\n}", "solution_cpp": "void merge(vector& nums1, int m, vector& nums2, int n) {\n int p1 = m-1, p2 = n-1, p = m+n-1;\n while (p1 >= 0 && p2 >= 0) nums1[p--] = nums1[p1] > nums2[p2] ? nums1[p1--] : nums2[p2--];\n while (p2 >= 0) nums1[p--] = nums2[p2--];\n}", "test_cases": ["nums1=[1,2,3], m=3, nums2=[2,5,6], n=3 -> [1,2,2,3,5,6]", "nums1=[], m=0, nums2=[1], n=1 -> [1]"], "key_points": ["从后往前合并", "三指针技巧"], "tags": ["array", "easy", "Microsoft", "Uber"]} {"problem_id": "algo_01983", "original_id": "max-subarray", "title": "最大子数组和", "category": "array", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "给你一个整数数组 nums ,请你找出一个具有最大和的连续子数组,返回其最大和。", "solution_python": "def maxSubArray(nums):\n max_sum = current = nums[0]\n for num in nums[1:]:\n current = max(num, current + num)\n max_sum = max(max_sum, current)\n return max_sum", "solution_java": "public int maxSubArray(int[] nums) {\n int maxSum = nums[0], curr = nums[0];\n for (int i = 1; i < nums.length; i++) {\n curr = Math.max(nums[i], curr + nums[i]);\n maxSum = Math.max(maxSum, curr);\n }\n return maxSum;\n}", "solution_cpp": "int maxSubArray(vector& nums) {\n int maxSum = nums[0], curr = nums[0];\n for (int i = 1; i < nums.size(); i++) {\n curr = max(nums[i], curr + nums[i]);\n maxSum = max(maxSum, curr);\n }\n return maxSum;\n}", "test_cases": ["nums=[-2,1,-3,4,-1,2,1,-5,4] -> 6", "nums=[1] -> 1"], "key_points": ["Kadane算法", "动态规划基础题"], "tags": ["array", "medium", "Google", "Microsoft"]} {"problem_id": "algo_01984", "original_id": "valid-parentheses", "title": "有效的括号", "category": "string", "difficulty": "easy", "companies": ["Google", "Uber"], "description": "给定一个只包括 '(',')','{','}','[',']' 的字符串 s,判断字符串是否有效。", "solution_python": "def isValid(s):\n stack = []\n mapping = {')': '(', ']': '[', '}': '{'}\n for c in s:\n if c in mapping:\n if not stack or stack[-1] != mapping[c]: return False\n stack.pop()\n else: stack.append(c)\n return not stack", "solution_java": "public boolean isValid(String s) {\n Stack stack = new Stack<>();\n Map map = Map.of(')', '(', ']', '[', '}', '{');\n for (char c : s.toCharArray()) {\n if (map.containsValue(c)) stack.push(c);\n else if (!stack.isEmpty() && stack.pop() != map.get(c)) return false;\n }\n return stack.isEmpty();\n}", "solution_cpp": "bool isValid(string s) {\n stack st;\n unordered_map m = {{')','('},{']','['},{'}','{'}};\n for (char c : s) {\n if (m.find(c) == m.end()) st.push(c);\n else if (st.empty() || st.top() != m[c]) return false;\n else st.pop();\n }\n return st.empty();\n}", "test_cases": ["s=\"()\" -> true", "s=\"()[]{}\" -> true", "s=\"(]\" -> false"], "key_points": ["栈匹配法", "注意空栈边界"], "tags": ["string", "easy", "Google", "Uber"]} {"problem_id": "algo_01985", "original_id": "longest-palindrome", "title": "最长回文子串", "category": "string", "difficulty": "medium", "companies": ["Google", "Amazon"], "description": "给你一个字符串 s,找到 s 中最长的回文子串。", "solution_python": "def longestPalindrome(s):\n def expand(l, r):\n while l >= 0 and r < len(s) and s[l] == s[r]: l -= 1; r += 1\n return l + 1, r - 1\n start = end = 0\n for i in range(len(s)):\n l1, r1 = expand(i, i)\n l2, r2 = expand(i, i + 1)\n if r1 - l1 > end - start: start, end = l1, r1\n if r2 - l2 > end - start: start, end = l2, r2\n return s[start:end+1]", "solution_java": "public String longestPalindrome(String s) {\n int start = 0, end = 0;\n for (int i = 0; i < s.length(); i++) {\n int len1 = expand(s, i, i), len2 = expand(s, i, i+1);\n int len = Math.max(len1, len2);\n if (len > end - start) { start = i - (len-1)/2; end = i + len/2; }\n }\n return s.substring(start, end + 1);\n}\nprivate int expand(String s, int l, int r) {\n while (l >= 0 && r < s.length() && s.charAt(l) == s.charAt(r)) { l--; r++; }\n return r - l - 1;\n}", "solution_cpp": "string longestPalindrome(string s) {\n int start = 0, end = 0;\n for (int i = 0; i < s.size(); i++) {\n int len1 = expand(s, i, i), len2 = expand(s, i, i+1);\n if (max(len1, len2) > end - start) { start = i - (max(len1,len2)-1)/2; end = i + max(len1,len2)/2; }\n }\n return s.substr(start, end - start + 1);\n}", "test_cases": ["s=\"babad\" -> bab或aba", "s=\"cbbd\" -> bb"], "key_points": ["中心扩展法", "处理奇偶长度"], "tags": ["string", "medium", "Google", "Amazon"]} {"problem_id": "algo_01986", "original_id": "reverse-list", "title": "反转链表", "category": "linkedlist", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "给你单链表的头节点 head,请你反转链表,并返回反转后的链表。", "solution_python": "def reverseList(head):\n prev = None\n curr = head\n while curr:\n nxt = curr.next\n curr.next = prev\n prev = curr\n curr = nxt\n return prev", "solution_java": "public ListNode reverseList(ListNode head) {\n ListNode prev = null, curr = head;\n while (curr != null) {\n ListNode next = curr.next;\n curr.next = prev;\n prev = curr;\n curr = next;\n }\n return prev;\n}", "solution_cpp": "ListNode* reverseList(ListNode* head) {\n ListNode* prev = nullptr, *curr = head;\n while (curr) {\n ListNode* next = curr->next;\n curr->next = prev;\n prev = curr;\n curr = next;\n }\n return prev;\n}", "test_cases": ["head=[1,2,3,4,5] -> [5,4,3,2,1]", "head=[1,2] -> [2,1]"], "key_points": ["迭代法 O(1)空间", "递归法 O(n)空间"], "tags": ["linkedlist", "medium", "Google", "Microsoft"]} {"problem_id": "algo_01987", "original_id": "middle-node", "title": "链表的中间结点", "category": "linkedlist", "difficulty": "easy", "companies": ["Amazon", "Facebook"], "description": "给你单链表的头节点 head,请你找出并返回链表的中间结点。如果有两个中间结点,则返回第二个中间结点。", "solution_python": "def middleNode(head):\n slow = fast = head\n while fast and fast.next:\n slow = slow.next\n fast = fast.next.next\n return slow", "solution_java": "public ListNode middleNode(ListNode head) {\n ListNode slow = head, fast = head;\n while (fast != null && fast.next != null) {\n slow = slow.next;\n fast = fast.next.next;\n }\n return slow;\n}", "solution_cpp": "ListNode* middleNode(ListNode* head) {\n ListNode* slow = head, *fast = head;\n while (fast && fast->next) { slow = slow->next; fast = fast->next->next; }\n return slow;\n}", "test_cases": ["head=[1,2,3,4,5] -> 3", "head=[1,2,3,4,5,6] -> 4"], "key_points": ["快慢指针", "O(n)时间O(1)空间"], "tags": ["linkedlist", "easy", "Amazon", "Facebook"]} {"problem_id": "algo_01988", "original_id": "max-depth", "title": "二叉树的最大深度", "category": "tree", "difficulty": "easy", "companies": ["Microsoft", "Apple"], "description": "给定一个二叉树 root,返回其最大深度。", "solution_python": "def maxDepth(root):\n if not root: return 0\n return max(maxDepth(root.left), maxDepth(root.right)) + 1", "solution_java": "public int maxDepth(TreeNode root) {\n if (root == null) return 0;\n return Math.max(maxDepth(root.left), maxDepth(root.right)) + 1;\n}", "solution_cpp": "int maxDepth(TreeNode* root) {\n if (!root) return 0;\n return max(maxDepth(root->left), maxDepth(root->right)) + 1;\n}", "test_cases": ["root=[3,9,20,null,null,15,7] -> 3", "root=[1,null,2] -> 2"], "key_points": ["DFS递归", "层序遍历也可"], "tags": ["tree", "easy", "Microsoft", "Apple"]} {"problem_id": "algo_01989", "original_id": "inorder-traversal", "title": "二叉树的中序遍历", "category": "tree", "difficulty": "easy", "companies": ["Google", "Microsoft"], "description": "给定一个二叉树的根节点 root,返回它的中序遍历结果。", "solution_python": "def inorderTraversal(root):\n result = []\n def dfs(node):\n if node:\n dfs(node.left)\n result.append(node.val)\n dfs(node.right)\n dfs(root)\n return result", "solution_java": "public List inorderTraversal(TreeNode root) {\n List res = new ArrayList<>();\n dfs(root, res);\n return res;\n}\nprivate void dfs(TreeNode node, List res) {\n if (node == null) return;\n dfs(node.left, res); res.add(node.val); dfs(node.right, res);\n}", "solution_cpp": "vector inorderTraversal(TreeNode* root) {\n vector res;\n dfs(root, res);\n return res;\n}\nvoid dfs(TreeNode* node, vector& res) {\n if (!node) return;\n dfs(node->left, res); res.push_back(node->val); dfs(node->right, res);\n}", "test_cases": ["root=[1,null,2,3] -> [1,3,2]", "root=[] -> []"], "key_points": ["左-根-右顺序", "递归最简洁"], "tags": ["tree", "easy", "Google", "Microsoft"]} {"problem_id": "algo_01990", "original_id": "binary-search", "title": "二分查找", "category": "binarysearch", "difficulty": "easy", "companies": ["Google", "Amazon"], "description": "给定一个 n 个元素有序的(升序)整型数组 nums 和一个目标值 target,写一个函数搜索 nums 中的 target,如果目标值存在返回下标,否则返回 -1。", "solution_python": "def search(nums, target):\n left, right = 0, len(nums) - 1\n while left <= right:\n mid = (left + right) // 2\n if nums[mid] == target: return mid\n elif nums[mid] < target: left = mid + 1\n else: right = mid - 1\n return -1", "solution_java": "public int search(int[] nums, int target) {\n int left = 0, right = nums.length - 1;\n while (left <= right) {\n int mid = left + (right - left) / 2;\n if (nums[mid] == target) return mid;\n else if (nums[mid] < target) left = mid + 1;\n else right = mid - 1;\n }\n return -1;\n}", "solution_cpp": "int search(vector& nums, int target) {\n int left = 0, right = nums.size() - 1;\n while (left <= right) {\n int mid = left + (right - left) / 2;\n if (nums[mid] == target) return mid;\n else if (nums[mid] < target) left = mid + 1;\n else right = mid - 1;\n }\n return -1;\n}", "test_cases": ["nums=[-1,0,3,5,9,12], target=9 -> 4", "nums=[-1,0,3,5,9,12], target=2 -> -1"], "key_points": ["标准模板", "注意防溢出写法"], "tags": ["binarysearch", "easy", "Google", "Amazon"]} {"problem_id": "algo_01991", "original_id": "climbing-stairs", "title": "爬楼梯", "category": "dp", "difficulty": "easy", "companies": ["Amazon", "Google"], "description": "假设你正在爬楼梯。需要 n 阶你才能到达楼顶。每次你可以爬 1 或 2 个台阶。你有多少种不同的方法可以爬到楼顶?", "solution_python": "def climbStairs(n):\n if n <= 2: return n\n a, b = 1, 2\n for _ in range(3, n+1):\n a, b = b, a + b\n return b", "solution_java": "public int climbStairs(int n) {\n if (n <= 2) return n;\n int a = 1, b = 2;\n for (int i = 3; i <= n; i++) { int temp = a + b; a = b; b = temp; }\n return b;\n}", "solution_cpp": "int climbStairs(int n) {\n if (n <= 2) return n;\n int a = 1, b = 2;\n for (int i = 3; i <= n; i++) { int temp = a + b; a = b; b = temp; }\n return b;\n}", "test_cases": ["n=2 -> 2", "n=3 -> 3", "n=5 -> 8"], "key_points": ["斐波那契数列", "滚动数组优化空间"], "tags": ["dp", "easy", "Amazon", "Google"]} {"problem_id": "algo_01992", "original_id": "coin-change", "title": "零钱兑换", "category": "dp", "difficulty": "medium", "companies": ["Google", "Amazon"], "description": "给你一个整数数组 coins 表示不同面额的硬币,以及一个整数 amount 表示总金额。计算并返回可以凑成总金额所需的最少的硬币个数。如果没有任何一种硬币组合能组成总金额,返回 -1。", "solution_python": "def coinChange(coins, amount):\n dp = [float('inf')] * (amount + 1)\n dp[0] = 0\n for coin in coins:\n for x in range(coin, amount + 1):\n dp[x] = min(dp[x], dp[x - coin] + 1)\n return dp[amount] if dp[amount] != float('inf') else -1", "solution_java": "public int coinChange(int[] coins, int amount) {\n int[] dp = new int[amount + 1];\n Arrays.fill(dp, amount + 1);\n dp[0] = 0;\n for (int coin : coins) {\n for (int x = coin; x <= amount; x++) {\n dp[x] = Math.min(dp[x], dp[x - coin] + 1);\n }\n }\n return dp[amount] > amount ? -1 : dp[amount];\n}", "solution_cpp": "int coinChange(vector& coins, int amount) {\n vector dp(amount + 1, amount + 1);\n dp[0] = 0;\n for (int coin : coins) {\n for (int x = coin; x <= amount; x++) {\n dp[x] = min(dp[x], dp[x - coin] + 1);\n }\n }\n return dp[amount] > amount ? -1 : dp[amount];\n}", "test_cases": ["coins=[1,2,5], amount=11 -> 3", "coins=[2], amount=3 -> -1"], "key_points": ["完全背包问题", "dp[x] = min(dp[x-coin]+1)"], "tags": ["dp", "medium", "Google", "Amazon"]} {"problem_id": "algo_01993", "original_id": "subsets", "title": "子集", "category": "backtracking", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "给你一个整数数组 nums ,数组中的元素 互不相同 。返回该数组所有可能的子集(幂集)。", "solution_python": "def subsets(nums):\n result = []\n def backtrack(start, path):\n result.append(path[:])\n for i in range(start, len(nums)):\n path.append(nums[i])\n backtrack(i + 1, path)\n path.pop()\n backtrack(0, [])\n return result", "solution_java": "public List> subsets(int[] nums) {\n List> result = new ArrayList<>();\n backtrack(nums, 0, new ArrayList<>(), result);\n return result;\n}\nprivate void backtrack(int[] nums, int start, List path, List> result) {\n result.add(new ArrayList<>(path));\n for (int i = start; i < nums.length; i++) {\n path.add(nums[i]);\n backtrack(nums, i + 1, path, result);\n path.remove(path.size() - 1);\n }\n}", "solution_cpp": "vector> subsets(vector& nums) {\n vector> result;\n vector path;\n backtrack(nums, 0, path, result);\n return result;\n}\nvoid backtrack(vector& nums, int start, vector& path, vector>& result) {\n result.push_back(path);\n for (int i = start; i < nums.size(); i++) {\n path.push_back(nums[i]);\n backtrack(nums, i + 1, path, result);\n path.pop_back();\n }\n}", "test_cases": ["nums=[1,2,3] -> [[],[1],[2],[1,2],[3],[1,3],[2,3],[1,2,3]]"], "key_points": ["选或不选", "DFS遍历子集树"], "tags": ["backtracking", "medium", "Google", "Microsoft"]} {"problem_id": "algo_01994", "original_id": "permutations", "title": "全排列", "category": "backtracking", "difficulty": "medium", "companies": ["Google", "Facebook"], "description": "给定一个不含重复数字的数组 nums,返回其所有可能的全排列。", "solution_python": "def permute(nums):\n result = []\n def backtrack(path, used):\n if len(path) == len(nums):\n result.append(path[:])\n return\n for i in range(len(nums)):\n if used[i]: continue\n used[i] = True\n path.append(nums[i])\n backtrack(path, used)\n path.pop()\n used[i] = False\n backtrack([], [False]*len(nums))\n return result", "solution_java": "public List> permute(int[] nums) {\n List> result = new ArrayList<>();\n boolean[] used = new boolean[nums.length];\n backtrack(nums, used, new ArrayList<>(), result);\n return result;\n}\nprivate void backtrack(int[] nums, boolean[] used, List path, List> result) {\n if (path.size() == nums.length) { result.add(new ArrayList<>(path)); return; }\n for (int i = 0; i < nums.length; i++) {\n if (used[i]) continue;\n used[i] = true;\n path.add(nums[i]);\n backtrack(nums, used, path, result);\n path.remove(path.size() - 1);\n used[i] = false;\n }\n}", "solution_cpp": "vector> permute(vector& nums) {\n vector> result;\n vector used(nums.size(), false);\n vector path;\n backtrack(nums, used, path, result);\n return result;\n}\nvoid backtrack(vector& nums, vector& used, vector& path, vector>& result) {\n if (path.size() == nums.size()) { result.push_back(path); return; }\n for (int i = 0; i < nums.size(); i++) {\n if (used[i]) continue;\n used[i] = true;\n path.push_back(nums[i]);\n backtrack(nums, used, path, result);\n path.pop_back();\n used[i] = false;\n }\n}", "test_cases": ["nums=[1,2,3] -> [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]"], "key_points": ["标记已使用元素", "回溯经典模板"], "tags": ["backtracking", "medium", "Google", "Facebook"]} {"problem_id": "algo_01995", "original_id": "top-k-frequent", "title": "前K个高频元素", "category": "heap", "difficulty": "medium", "companies": ["Amazon", "Facebook"], "description": "给你一个整数数组 nums 和一个整数 k,请你返回其中出现频率前 k 高的元素。", "solution_python": "import heapq\nfrom collections import Counter\ndef topKFrequent(nums, k):\n count = Counter(nums)\n heap = []\n for num, freq in count.items():\n heapq.heappush(heap, (freq, num))\n if len(heap) > k: heapq.heappop(heap)\n return [num for freq, num in heap]", "solution_java": "public int[] topKFrequent(int[] nums, int k) {\n Map count = new HashMap<>();\n for (int n : nums) count.put(n, count.getOrDefault(n, 0) + 1);\n PriorityQueue> heap = \n new PriorityQueue<>((a, b) -> a.getValue() - b.getValue());\n for (Map.Entry e : count.entrySet()) {\n heap.offer(e);\n if (heap.size() > k) heap.poll();\n }\n int[] res = new int[k];\n for (int i = k - 1; i >= 0; i--) res[i] = heap.poll().getKey();\n return res;\n}", "solution_cpp": "vector topKFrequent(vector& nums, int k) {\n unordered_map count;\n for (int n : nums) count[n]++;\n priority_queue, vector>, greater>> heap;\n for (auto& [num, freq] : count) {\n heap.push({freq, num});\n if (heap.size() > k) heap.pop();\n }\n vector res;\n while (!heap.empty()) { res.push_back(heap.top().second); heap.pop(); }\n reverse(res.begin(), res.end());\n return res;\n}", "test_cases": ["nums=[1,1,1,2,2,3], k=2 -> [1,2]", "nums=[1], k=1 -> [1]"], "key_points": ["小顶堆保持大小k", "时间复杂度O(nlogk)"], "tags": ["heap", "medium", "Amazon", "Facebook"]} {"problem_id": "algo_01996", "original_id": "3sum", "title": "三数之和", "category": "two-pointers", "difficulty": "medium", "companies": ["Google", "Amazon"], "description": "给你一个整数数组 nums,判断是否存在三元组满足和为0,返回所有不重复的三元组。", "solution_python": "def threeSum(nums):\n nums.sort()\n result = []\n for i in range(len(nums) - 2):\n if i > 0 and nums[i] == nums[i-1]: continue\n left, right = i + 1, len(nums) - 1\n while left < right:\n total = nums[i] + nums[left] + nums[right]\n if total < 0: left += 1\n elif total > 0: right -= 1\n else:\n result.append([nums[i], nums[left], nums[right]])\n while left < right and nums[left] == nums[left+1]: left += 1\n while left < right and nums[right] == nums[right-1]: right -= 1\n left += 1; right -= 1\n return result", "solution_java": "public List> threeSum(int[] nums) {\n Arrays.sort(nums);\n List> result = new ArrayList<>();\n for (int i = 0; i < nums.length - 2; i++) {\n if (i > 0 && nums[i] == nums[i-1]) continue;\n int left = i + 1, right = nums.length - 1;\n while (left < right) {\n int total = nums[i] + nums[left] + nums[right];\n if (total < 0) left++;\n else if (total > 0) right--;\n else {\n result.add(Arrays.asList(nums[i], nums[left], nums[right]));\n while (left < right && nums[left] == nums[left+1]) left++;\n while (left < right && nums[right] == nums[right-1]) right--;\n left++; right--;\n }\n }\n }\n return result;\n}", "solution_cpp": "vector> threeSum(vector& nums) {\n sort(nums.begin(), nums.end());\n vector> result;\n for (int i = 0; i < nums.size() - 2; i++) {\n if (i > 0 && nums[i] == nums[i-1]) continue;\n int left = i + 1, right = nums.size() - 1;\n while (left < right) {\n int total = nums[i] + nums[left] + nums[right];\n if (total < 0) left++;\n else if (total > 0) right--;\n else {\n result.push_back({nums[i], nums[left], nums[right]});\n while (left < right && nums[left] == nums[left+1]) left++;\n while (left < right && nums[right] == nums[right-1]) right--;\n left++; right--;\n }\n }\n }\n return result;\n}", "test_cases": ["nums=[-1,0,1,2,-1,-4] -> [[-1,-1,2],[-1,0,1]]"], "key_points": ["排序+双指针", "去重是关键"], "tags": ["two-pointers", "medium", "Google", "Amazon"]} {"problem_id": "algo_01997", "original_id": "container-water", "title": "盛最多水的容器", "category": "two-pointers", "difficulty": "medium", "companies": ["Google", "Uber"], "description": "给定一个长度为 n 的整数数组 height,找出其中的两条线,使得它们与 x 轴共同构成的容器可以容纳最多的水。", "solution_python": "def maxArea(height):\n left, right = 0, len(height) - 1\n max_area = 0\n while left < right:\n h = min(height[left], height[right])\n max_area = max(max_area, h * (right - left))\n if height[left] < height[right]: left += 1\n else: right -= 1\n return max_area", "solution_java": "public int maxArea(int[] height) {\n int left = 0, right = height.length - 1, maxArea = 0;\n while (left < right) {\n int h = Math.min(height[left], height[right]);\n maxArea = Math.max(maxArea, h * (right - left));\n if (height[left] < height[right]) left++;\n else right--;\n }\n return maxArea;\n}", "solution_cpp": "int maxArea(vector& height) {\n int left = 0, right = height.size() - 1, maxArea = 0;\n while (left < right) {\n int h = min(height[left], height[right]);\n maxArea = max(maxArea, h * (right - left));\n if (height[left] < height[right]) left++;\n else right--;\n }\n return maxArea;\n}", "test_cases": ["height=[1,8,6,2,5,4,8,3,7] -> 49"], "key_points": ["移动短边指针", "面积=min(h1,h2)*width"], "tags": ["two-pointers", "medium", "Google", "Uber"]} {"problem_id": "algo_01998", "original_id": "min-stack", "title": "最小栈", "category": "stack", "difficulty": "medium", "companies": ["Google", "Microsoft"], "description": "设计一个支持 push,pop,top 操作,并能在常数时间内检索到最小元素的栈。", "solution_python": "class MinStack:\n def __init__(self):\n self.stack = []\n self.min_stack = []\n def push(self, val):\n self.stack.append(val)\n self.min_stack.append(min(val, self.min_stack[-1] if self.min_stack else val))\n def pop(self):\n self.stack.pop(); self.min_stack.pop()\n def top(self): return self.stack[-1]\n def getMin(self): return self.min_stack[-1]", "solution_java": "class MinStack {\n Stack stack = new Stack<>();\n Stack minStack = new Stack<>();\n public void push(int val) { stack.push(val); minStack.push(Math.min(val, minStack.isEmpty() ? val : minStack.peek())); }\n public void pop() { stack.pop(); minStack.pop(); }\n public int top() { return stack.peek(); }\n public int getMin() { return minStack.peek(); }\n}", "solution_cpp": "class MinStack {\n stack st, minSt;\npublic:\n void push(int val) { st.push(val); minSt.push(min(val, minSt.empty() ? val : minSt.top())); }\n void pop() { st.pop(); minSt.pop(); }\n int top() { return st.top(); }\n int getMin() { return minSt.top(); }\n};", "test_cases": ["push(-2), push(0), push(-3) -> getMin() returns -3"], "key_points": ["辅助栈记录最小值", "O(1)时间获取最小值"], "tags": ["stack", "medium", "Google", "Microsoft"]} {"problem_id": "algo_01999", "original_id": "lru-cache", "title": "LRU缓存", "category": "design", "difficulty": "hard", "companies": ["Google", "Amazon"], "description": "设计和实现一个 LRU(最近最少使用)缓存机制。", "solution_python": "class LRUCache:\n def __init__(self, capacity):\n self.capacity = capacity\n self.cache = {}\n self.order = []\n def get(self, key):\n if key not in self.cache: return -1\n self.order.remove(key); self.order.append(key)\n return self.cache[key]\n def put(self, key, value):\n if key in self.cache:\n self.order.remove(key)\n elif len(self.cache) >= self.capacity:\n del self.cache[self.order.pop(0)]\n self.cache[key] = value; self.order.append(key)", "solution_java": "class LRUCache {\n int capacity;\n LinkedHashMap cache = new LinkedHashMap<>();\n public LRUCache(int cap) { capacity = cap; }\n public int get(int key) { return cache.containsKey(key) ? cache.remove(key) : -1; }\n public void put(int key, int val) {\n if (cache.containsKey(key)) cache.remove(key);\n else if (cache.size() >= capacity) cache.remove(cache.keySet().iterator().next());\n cache.put(key, val);\n }\n}", "solution_cpp": "class LRUCache {\n int cap;\n list> dll;\n unordered_map>::iterator> cache;\npublic:\n LRUCache(int capacity) : cap(capacity) {}\n int get(int key) {\n auto it = cache.find(key);\n if (it == cache.end()) return -1;\n dll.splice(dll.end(), dll, it->second);\n return it->second->second;\n }\n void put(int key, int value) {\n auto it = cache.find(key);\n if (it != cache.end()) dll.erase(it->second);\n else if (cache.size() >= cap) { cache.erase(dll.front().first); dll.pop_front(); }\n dll.push_back({key, value});\n cache[key] = --dll.end();\n }\n};", "test_cases": ["put(1,1), put(2,2), get(1) -> 1"], "key_points": ["HashMap + 双向链表", "O(1)时间操作"], "tags": ["design", "hard", "Google", "Amazon"]} {"problem_id": "algo_02000", "original_id": "num-islands", "title": "岛屿数量", "category": "graph", "difficulty": "medium", "companies": ["Google", "Facebook"], "description": "给你一个由 '1'(陆地)和 '0'(水)组成的二维网格,请你计算网格中岛屿的数量。岛屿总是被水包围,且只能由水平或垂直方向相邻的陆地连接形成。", "solution_python": "def numIslands(grid):\n if not grid: return 0\n rows, cols = len(grid), len(grid[0])\n count = 0\n def dfs(r, c):\n if r < 0 or r >= rows or c < 0 or c >= cols or grid[r][c] != '1': return\n grid[r][c] = '0'\n dfs(r+1, c); dfs(r-1, c); dfs(r, c+1); dfs(r, c-1)\n for r in range(rows):\n for c in range(cols):\n if grid[r][c] == '1': count += 1; dfs(r, c)\n return count", "solution_java": "public int numIslands(char[][] grid) {\n if (grid.length == 0) return 0;\n int count = 0;\n for (int i = 0; i < grid.length; i++)\n for (int j = 0; j < grid[0].length; j++)\n if (grid[i][j] == '1') { count++; dfs(grid, i, j); }\n return count;\n}\nprivate void dfs(char[][] grid, int r, int c) {\n if (r < 0 || r >= grid.length || c < 0 || c >= grid[0].length || grid[r][c] != '1') return;\n grid[r][c] = '0';\n dfs(grid, r+1, c); dfs(grid, r-1, c); dfs(grid, r, c+1); dfs(grid, r, c-1);\n}", "solution_cpp": "int numIslands(vector>& grid) {\n if (grid.empty()) return 0;\n int count = 0;\n for (int i = 0; i < grid.size(); i++)\n for (int j = 0; j < grid[0].size(); j++)\n if (grid[i][j] == '1') { count++; dfs(grid, i, j); }\n return count;\n}\nvoid dfs(vector>& grid, int r, int c) {\n if (r < 0 || r >= grid.size() || c < 0 || c >= grid[0].size() || grid[r][c] != '1') return;\n grid[r][c] = '0';\n dfs(grid, r+1, c); dfs(grid, r-1, c); dfs(grid, r, c+1); dfs(grid, r, c-1);\n}", "test_cases": ["grid=[[1,1,1,1,0],[1,1,0,1,0],[1,1,0,0,0],[0,0,0,0,0]] -> 1"], "key_points": ["DFS/BFS遍历", "访问后标记为0避免重复"], "tags": ["graph", "medium", "Google", "Facebook"]}