怎么做企业官方网站/长沙网站搭建关键词排名
以下是 LeetCode Top 100 面试必备题目及其解决方案示例。这些题目涵盖了数据结构、算法、动态规划、回溯等多种重要的面试话题。希望各位同学有所收货,早日脱离底层到达彼岸!
1. Two Sum
- 题目: 给定一个整数数组
nums
和一个目标值target
,找出数组中两个数的和等于目标值的索引。 - 解决方案:
public int[] TwoSum(int[] nums, int target) {var map = new Dictionary<int, int>();for (int i = 0; i < nums.Length; i++) {int complement = target - nums[i];if (map.ContainsKey(complement)) {return new int[] { map[complement], i };}map[nums[i]] = i;}throw new ArgumentException("No two sum solution"); }
2. Add Two Numbers
- 题目: 给定两个非空链表,表示两个非负整数,每个节点表示一个数字,返回它们的和。
- 解决方案:
public ListNode AddTwoNumbers(ListNode l1, ListNode l2) {var dummy = new ListNode(0);var p = l1;var q = l2;var current = dummy;int carry = 0;while (p != null || q != null) {int x = (p != null) ? p.val : 0;int y = (q != null) ? q.val : 0;int sum = carry + x + y;carry = sum / 10;current.next = new ListNode(sum % 10);current = current.next;if (p != null) p = p.next;if (q != null) q = q.next;}if (carry > 0) {current.next = new ListNode(carry);}return dummy.next; }
3. Longest Substring Without Repeating Characters
- 题目: 给定一个字符串,找出其中最长的没有重复字符的子串的长度。
- 解决方案:
public int LengthOfLongestSubstring(string s) {var map = new Dictionary<char, int>();int left = 0;int maxLength = 0;for (int right = 0; right < s.Length; right++) {if (map.ContainsKey(s[right])) {left = Math.Max(map[s[right]] + 1, left);}map[s[right]] = right;maxLength = Math.Max(maxLength, right - left + 1);}return maxLength; }
4. Median of Two Sorted Arrays
- 题目: 给定两个排序数组,找出它们的中位数。
- 解决方案:
public double FindMedianSortedArrays(int[] nums1, int[] nums2) {int m = nums1.Length, n = nums2.Length;int i = 0, j = 0;int mid1 = (m + n + 1) / 2;int mid2 = (m + n + 2) / 2;int num1 = 0, num2 = 0;while (i < m || j < n) {if (i < m && (j >= n || nums1[i] < nums2[j])) {num1 = nums1[i++];} else {num1 = nums2[j++];}if (i + j == mid1) {num1 = num2;}if (i + j == mid2) {num2 = num1;break;}}return (m + n) % 2 == 0 ? (num1 + num2) / 2.0 : num2; }
5. Longest Palindromic Substring
- 题目: 找出给定字符串中的最长回文子串。
- 解决方案:
public string LongestPalindrome(string s) {if (s.Length == 0) return "";string longest = "";for (int i = 0; i < s.Length; i++) {string odd = ExpandAroundCenter(s, i, i);string even = ExpandAroundCenter(s, i, i + 1);string longer = odd.Length > even.Length ? odd : even;if (longer.Length > longest.Length) {longest = longer;}}return longest; }private string ExpandAroundCenter(string s, int left, int right) {while (left >= 0 && right < s.Length && s[left] == s[right]) {left--;right++;}return s.Substring(left + 1, right - left - 1); }
6. Zigzag Conversion
- 题目: 将一个字符串按照指定的行数进行 Zigzag 转换。
- 解决方案:
public string Convert(string s, int numRows) {if (numRows == 1) return s;var rows = new char[Math.Min(numRows, s.Length)][];for (int i = 0; i < rows.Length; i++) rows[i] = new char[s.Length];int curRow = 0;bool goingDown = false;foreach (char c in s) {rows[curRow][0] = c;if (curRow == 0 || curRow == numRows - 1) goingDown = !goingDown;curRow += goingDown ? 1 : -1;}var result = new StringBuilder();foreach (var row in rows) {foreach (var ch in row) {if (ch != '\0') result.Append(ch);}}return result.ToString(); }
7. Reverse Integer
- 题目: 反转一个整数。
- 解决方案:
public int Reverse(int x) {int rev = 0;while (x != 0) {int pop = x % 10;x /= 10;if (rev > Int32.MaxValue / 10 || (rev == Int32.MaxValue / 10 && pop > 7)) return 0;if (rev < Int32.MinValue / 10 || (rev == Int32.MinValue / 10 && pop < -8)) return 0;rev = rev * 10 + pop;}return rev; }
8. String to Integer (atoi)
- 题目: 将字符串转换为整数。
- 解决方案:
public int MyAtoi(string s) {int i = 0, sign = 1, result = 0;while (i < s.Length && s[i] == ' ') i++;if (i < s.Length && (s[i] == '+' || s[i] == '-')) {sign = s[i] == '-' ? -1 : 1;i++;}while (i < s.Length && Char.IsDigit(s[i])) {int digit = s[i] - '0';if (result > Int32.MaxValue / 10 || (result == Int32.MaxValue / 10 && digit > 7)) return sign == 1 ? Int32.MaxValue : Int32.MinValue;result = result * 10 + digit;i++;}return result * sign; }
9. Palindrome Number
- 题目: 判断一个整数是否是回文数。
- 解决方案:
public bool IsPalindrome(int x) {if (x < 0 || (x % 10 == 0 && x != 0)) return false;int reversed = 0, original = x;while (x > 0) {reversed = reversed * 10 + x % 10;x /= 10;}return original == reversed; }
10. Regular Expression Matching
- 题目: 实现正则表达式匹配。
- 解决方案:
public bool IsMatch(string s, string p) {bool[,] dp = new bool[s.Length + 1, p.Length + 1];dp[0, 0] = true;for (int j = 1; j <= p.Length; j++) {if (p[j - 1] == '*') {dp[0, j] = dp[0, j - 2];}}for (int i = 1; i <= s.Length; i++) {for (int j = 1; j <= p.Length; j++) {if (p[j - 1] == s[i - 1] || p[j - 1] == '.') {dp[i, j] = dp[i - 1, j - 1];} else if (p[j - 1] == '*') {dp[i, j] = dp[i, j - 2] || (dp[i - 1, j] && (s[i - 1] == p[j - 2] || p[j - 2] == '.'));}}}return dp[s.Length, p.Length];
}
11. Container With Most Water
- 题目: 找出容器中可以容纳最多水的两条线。
- 解决方案:
public int MaxArea(int[] height) {int left = 0, right = height.Length - 1;int maxArea = 0;while (left < right) {int width = right - left;int minHeight = Math.Min(height[left], height[right]);maxArea = Math.Max(maxArea, width * minHeight);if (height[left] < height[right]) {left++;} else {right--;}}return maxArea;}
12. Integer to Roman
- 题目: 将整数转换为罗马数字。
- 解决方案:
public string IntToRoman(int num) {var values = new int[] { 1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1 };var symbols = new string[] { "M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I" };var sb = new StringBuilder();for (int i = 0; i < values.Length; i++) {while (num >= values[i]) {sb.Append(symbols[i]);num -= values[i];}}return sb.ToString(); }
13. Roman to Integer
- 题目: 将罗马数字转换为整数。
- 解决方案:
public int RomanToInt(string s) {var map = new Dictionary<char, int> {{'I', 1}, {'V', 5}, {'X', 10}, {'L', 50}, {'C', 100}, {'D', 500}, {'M', 1000}};int total = 0;for (int i = 0; i < s.Length; i++) {int value = map[s[i]];if (i < s.Length - 1 && value < map[s[i + 1]]) {total -= value;} else {total += value;}}return total; }
14. Longest Common Prefix
- 题目: 找出一组字符串的最长公共前缀。
- 解决方案:
public string LongestCommonPrefix(string[] strs) {if (strs.Length == 0) return "";string prefix = strs[0];for (int i = 1; i < strs.Length; i++) {while (strs[i].IndexOf(prefix) != 0) {prefix = prefix.Substring(0, prefix.Length - 1);if (prefix.Length == 0) return "";}}return prefix; }
15. 3Sum
- 题目: 给定一个整数数组,找出所有和为零的三元组。
- 解决方案:
public IList<IList<int>> ThreeSum(int[] nums) {var result = new List<IList<int>>();Array.Sort(nums);for (int i = 0; i < nums.Length - 2; i++) {if (i > 0 && nums[i] == nums[i - 1]) continue;int left = i + 1, right = nums.Length - 1;while (left < right) {int sum = nums[i] + nums[left] + nums[right];if (sum < 0) {left++;} else if (sum > 0) {right--;} else {result.Add(new List<int> { nums[i], nums[left], nums[right] });while (left < right && nums[left] == nums[left + 1]) left++;while (left < right && nums[right] == nums[right - 1]) right--;left++;right--;}}}return result; }
16. 4Sum
- 题目: 给定一个整数数组,找出所有和为目标值的四元组。
- 解决方案:
public IList<IList<int>> FourSum(int[] nums, int target) {var result = new List<IList<int>>();Array.Sort(nums);for (int i = 0; i < nums.Length - 3; i++) {if (i > 0 && nums[i] == nums[i - 1]) continue;for (int j = i + 1; j < nums.Length - 2; j++) {if (j > i + 1 && nums[j] == nums[j - 1]) continue;int left = j + 1, right = nums.Length - 1;while (left < right) {int sum = nums[i] + nums[j] + nums[left] + nums[right];if (sum < target) {left++;} else if (sum > target) {right--;} else {result.Add(new List<int> { nums[i], nums[j], nums[left], nums[right] });while (left < right && nums[left] == nums[left + 1]) left++;while (left < right && nums[right] == nums[right - 1]) right--;left++;right--;}}}}return result; }
17. Remove Nth Node From End of List
- 题目: 从链表中删除倒数第 N 个节点。
- 解决方案:
public ListNode RemoveNthFromEnd(ListNode head, int n) {var dummy = new ListNode(0) { next = head };var first = dummy;var second = dummy;for (int i = 1; i <= n + 1; i++) {first = first.next;}while (first != null) {first = first.next;second = second.next;}second.next = second.next.next;return dummy.next; }
18. Valid Parentheses
- 题目: 判断括号字符串是否有效。
- 解决方案:
public bool IsValid(string s) {var stack = new Stack<char>();foreach (char c in s) {if (c == '(' || c == '{' || c == '[') {stack.Push(c);} else {if (stack.Count == 0) return false;char top = stack.Pop();if (c == ')' && top != '(') return false;if (c == '}' && top != '{') return false;if (c == ']' && top != '[') return false;}}return stack.Count == 0; }
19. Merge Two Sorted Lists
- 题目: 合并两个已排序的链表。
- 解决方案:
public ListNode MergeTwoLists(ListNode l1, ListNode l2) {var dummy = new ListNode(0);var current = dummy;while (l1 != null && l2 != null) {if (l1.val < l2.val) {current.next = l1;l1 = l1.next;} else {current.next = l2;l2 = l2.next;}current = current.next;}if (l1 != null) current.next = l1;if (l2 != null) current.next = l2;return dummy.next; }
20. Generate Parentheses
- 题目: 生成所有合法的括号组合。
- 解决方案:
public IList<string> GenerateParenthesis(int n) {var result = new List<string>();Generate(result, "", 0, 0, n);return result; }private void Generate(IList<string> result, string s, int left, int right, int n) {if (s.Length == 2 * n) {result.Add(s);return;}if (left < n) Generate(result, s + "(", left + 1, right, n);if (right < left) Generate(result, s + ")", left, right + 1, n); }
21. Swap Nodes in Pairs
- 题目: 交换链表中相邻的节点。
- 解决方案:
public ListNode SwapPairs(ListNode head) {var dummy = new ListNode(0) { next = head };var current = dummy;while (current.next != null && current.next.next != null) {var first = current.next;var second = current.next.next;first.next = second.next;second.next = first;current.next = second;current = first;}return dummy.next;}
22. Remove Duplicates from Sorted Array
- 题目: 从已排序数组中删除重复项。
- 解决方案:
public int RemoveDuplicates(int[] nums) {if (nums.Length == 0) return 0;int j = 0;for (int i = 1; i < nums.Length; i++) {if (nums[i] != nums[j]) {j++;nums[j] = nums[i];}}return j + 1;}
23. Search Insert Position
- 题目: 查找给定值在已排序数组中的插入位置。
- 解决方案:
public int SearchInsert(int[] nums, int target) {int left = 0, right = nums.Length - 1;while (left <= right) {int mid = left + (right - left) / 2;if (nums[mid] == target) return mid;if (nums[mid] < target) left = mid + 1;else right = mid - 1;}return left; }
24. Count and Say
- 题目: 输出第 n 项 “Count and Say” 序列。
- 解决方案:
public string CountAndSay(int n) {if (n == 1) return "1";var previous = CountAndSay(n - 1);var sb = new StringBuilder();int count = 1;for (int i = 1; i < previous.Length; i++) {if (previous[i] == previous[i - 1]) {count++;} else {sb.Append(count).Append(previous[i - 1]);count = 1;}}sb.Append(count).Append(previous[previous.Length - 1]);return sb.ToString(); }
25. Valid Sudoku
- 题目: 判断给定的 9x9 数独是否有效。
- 解决方案:
public bool IsValidSudoku(char[][] board) {var rows = new HashSet<string>[9];var cols = new HashSet<string>[9];var boxes = new HashSet<string>[9];for (int i = 0; i < 9; i++) {rows[i] = new HashSet<string>();cols[i] = new HashSet<string>();boxes[i] = new HashSet<string>();}for (int i = 0; i < 9; i++) {for (int j = 0; j < 9; j++) {char c = board[i][j];if (c == '.') continue;if (!rows[i].Add(c + "row" + i) ||!cols[j].Add(c + "col" + j) ||!boxes[(i / 3) * 3 + j / 3].Add(c + "box" + (i / 3) * 3 + j / 3)) {return false;}}}return true; }
26. Sudoku Solver
- 题目: 解一个数独问题。
- 解决方案:
public void SolveSudoku(char[][] board) {Solve(board); }private bool Solve(char[][] board) {for (int i = 0; i < 9; i++) {for (int j = 0; j < 9; j++) {if (board[i][j] == '.') {for (char c = '1'; c <= '9'; c++) {if (IsValid(board, i, j, c)) {board[i][j] = c;if (Solve(board)) return true;board[i][j] = '.';}}return false;}}}return true; }private bool IsValid(char[][] board, int row, int col, char c) {for (int i = 0; i < 9; i++) {if (board[row][i] == c || board[i][col] == c ||board[3 * (row / 3) + i / 3][3 * (col / 3) + i % 3] == c) {return false;}}return true; }
27. Word Search
- 题目: 给定一个二维网格和一个单词,判断网格中是否存在这个单词。
- 解决方案:
public bool Exist(char[][] board, string word) {for (int i = 0; i < board.Length; i++) {for (int j = 0; j < board[0].Length; j++) {if (Backtrack(board, word, i, j, 0)) return true;}}return false; }private bool Backtrack(char[][] board, string word, int i, int j, int k) {if (k == word.Length) return true;if (i < 0 || i >= board.Length || j < 0 || j >= board[0].Length ||board[i][j] != word[k]) return false;char temp = board[i][j];board[i][j] = '#'; // mark as visitedbool found = Backtrack(board, word, i + 1, j, k + 1) ||Backtrack(board, word, i - 1, j, k + 1) ||Backtrack(board, word, i, j + 1, k + 1) ||Backtrack(board, word, i, j - 1, k + 1);board[i][j] = temp; // unmarkreturn found; }
28. Combination Sum
- 题目: 给定一个数组和一个目标值,找出所有可能的组合,使得它们的和等于目标值。
- 解决方案:
public IList<IList<int>> CombinationSum(int[] candidates, int target) {var result = new List<IList<int>>();var combination = new List<int>();Backtrack(candidates, target, 0, combination, result);return result; }private void Backtrack(int[] candidates, int target, int start, IList<int> combination, IList<IList<int>> result) {if (target == 0) {result.Add(new List<int>(combination));return;}if (target < 0) return;for (int i = start; i < candidates.Length; i++) {combination.Add(candidates[i]);Backtrack(candidates, target - candidates[i], i, combination, result);combination.RemoveAt(combination.Count - 1);} }
29. Combination Sum II
- 题目: 给定一个数组和一个目标值,找出所有可能的组合,使得它们的和等于目标值,并且每个数字只能使用一次。
- 解决方案:
public IList<IList<int>> CombinationSum2(int[] candidates, int target) {var result = new List<IList<int>>();Array.Sort(candidates);var combination = new List<int>();Backtrack(candidates, target, 0, combination, result);return result; }private void Backtrack(int[] candidates, int target, int start, IList<int> combination, IList<IList<int>> result) {if (target == 0) {result.Add(new List<int>(combination));return;}if (target < 0) return;for (int i = start; i < candidates.Length; i++) {if (i > start && candidates[i] == candidates[i - 1]) continue;combination.Add(candidates[i]);Backtrack(candidates, target - candidates[i], i + 1, combination, result);combination.RemoveAt(combination.Count - 1);} }
30. Permutations
- 题目: 给定一个不含重复数字的数组,返回它们的所有排列。
- 解决方案:
public IList<IList<int>> Permute(int[] nums) {var result = new List<IList<int>>();var permutation = new List<int>();var used = new bool[nums.Length];Backtrack(nums, used, permutation, result);return result;}private void Backtrack(int[] nums, bool[] used, IList<int> permutation, IList<IList<int>> result) {if (permutation.Count == nums.Length) {result.Add(new List<int>(permutation));return;}for (int i = 0; i < nums.Length; i++) {if (used[i]) continue;used[i] = true;permutation.Add(nums[i]);Backtrack(nums, used, permutation, result);permutation.RemoveAt(permutation.Count - 1);used[i] = false;}}
31. Permutations II
- 题目: 给定一个可能包含重复数字的数组,返回它们的所有唯一排列。
- 解决方案:
public IList<IList<int>> PermuteUnique(int[] nums) {var result = new List<IList<int>>();var permutation = new List<int>();Array.Sort(nums);var used = new bool[nums.Length];Backtrack(nums, used, permutation, result);return result;}private void Backtrack(int[] nums, bool[] used, IList<int> permutation, IList<IList<int>> result) {if (permutation.Count == nums.Length) {result.Add(new List<int>(permutation));return;}for (int i = 0; i < nums.Length; i++) {if (used[i] || (i > 0 && nums[i] == nums[i - 1] && !used[i - 1])) continue;used[i] = true;permutation.Add(nums[i]);Backtrack(nums, used, permutation, result);permutation.RemoveAt(permutation.Count - 1);used[i] = false;}}
32. Generate Parentheses
- 题目: 生成所有合法的括号组合。
- 解决方案:
public IList<string> GenerateParenthesis(int n) {var result = new List<string>();Generate(result, "", 0, 0, n);return result; }private void Generate(IList<string> result, string s, int left, int right, int n) {if (s.Length == 2 * n) {result.Add(s);return;}if (left < n) Generate(result, s + "(", left + 1, right, n);if (right < left) Generate(result, s + ")", left, right + 1, n); }
33. Spiral Matrix
- 题目: 给定一个 m x n 的矩阵,返回它的螺旋顺序。
- 解决方案:
public IList<int> SpiralOrder(int[][] matrix) {var result = new List<int>();if (matrix.Length == 0) return result;int top = 0, bottom = matrix.Length - 1;int left = 0, right = matrix[0].Length - 1;while (top <= bottom && left <= right) {for (int i = left; i <= right; i++) result.Add(matrix[top][i]);top++;for (int i = top; i <= bottom; i++) result.Add(matrix[i][right]);right--;if (top <= bottom) {for (int i = right; i >= left; i--) result.Add(matrix[bottom][i]);bottom--;}if (left <= right) {for (int i = bottom; i >= top; i--) result.Add(matrix[i][left]);left++;}}return result; }
34. Rotate Image
- 题目: 旋转一个 n x n 的矩阵 90 度。
- 解决方案:
public void Rotate(int[][] matrix) {int n = matrix.Length;// Transpose the matrixfor (int i = 0; i < n; i++) {for (int j = i; j < n; j++) {int temp = matrix[i][j];matrix[i][j] = matrix[j][i];matrix[j][i] = temp;}}// Reverse each rowfor (int i = 0; i < n; i++) {for (int j = 0; j < n / 2; j++) {int temp = matrix[i][j];matrix[i][j] = matrix[i][n - 1 - j];matrix[i][n - 1 - j] = temp;}} }
35. Set Matrix Zeroes
- 题目: 如果矩阵中的某个元素为零,则将该元素所在行和列的所有元素都置零。
- 解决方案:
public void SetZeroes(int[][] matrix) {bool firstRowZero = false, firstColZero = false;int m = matrix.Length, n = matrix[0].Length;for (int i = 0; i < m; i++) {if (matrix[i][0] == 0) firstColZero = true;}for (int j = 0; j < n; j++) {if (matrix[0][j] == 0) firstRowZero = true;}for (int i = 1; i < m; i++) {for (int j = 1; j < n; j++) {if (matrix[i][j] == 0) {matrix[i][0] = 0;matrix[0][j] = 0;}}}for (int i = 1; i < m; i++) {for (int j = 1; j < n; j++) {if (matrix[i][0] == 0 || matrix[0][j] == 0) {matrix[i][j] = 0;}}}if (firstRowZero) {for (int j = 0; j < n; j++) matrix[0][j] = 0;}if (firstColZero) {for (int i = 0; i < m; i++) matrix[i][0] = 0;} }
36. Sort Colors
- 题目: 对包含红色、白色和蓝色的数组进行排序,使得所有红色排在前面,白色排在中间,蓝色排在最后面。
- 解决方案:
public void SortColors(int[] nums) {int red = 0, white = 0, blue = nums.Length - 1;while (white <= blue) {if (nums[white] == 0) {Swap(nums, red++, white++);} else if (nums[white] == 1) {white++;} else {Swap(nums, white, blue--);}} }private void Swap(int[] nums, int i, int j) {int temp = nums[i];nums[i] = nums[j];nums[j] = temp; }
37. Search in Rotated Sorted Array
- 题目: 在旋转排序数组中查找目标值。
- 解决方案:
public int Search(int[] nums, int target) {int left = 0, right = nums.Length - 1;while (left <= right) {int mid = left + (right - left) / 2;if (nums[mid] == target) return mid;if (nums[left] <= nums[mid]) {if (nums[left] <= target && target < nums[mid]) {right = mid - 1;} else {left = mid + 1;}} else {if (nums[mid] < target && target <= nums[right]) {left = mid + 1;} else {right = mid - 1;}}}return -1; }
38. Search Insert Position
- 题目: 查找给定值在已排序数组中的插入位置。
- 解决方案:
public int SearchInsert(int[] nums, int target) {int left = 0, right = nums.Length - 1;while (left <= right) {int mid = left + (right - left) / 2;if (nums[mid] == target) return mid;if (nums[mid] < target) left = mid + 1;else right = mid - 1;}return left; }
39. Two Sum II - Input Array Is Sorted
- 题目: 给定一个已排序的数组和一个目标值,找出两个数之和为目标值的索引。
- 解决方案:
public int[] TwoSum(int[] numbers, int target) {int left = 0, right = numbers.Length - 1;while (left < right) {int sum = numbers[left] + numbers[right];if (sum == target) return new int[] { left + 1, right + 1 };if (sum < target) left++;else right--;}return new int[] { -1, -1};
}
40. Majority Element
- 题目: 找出数组中出现次数超过 n/2 次的元素。
- 解决方案:
public int MajorityElement(int[] nums) {int count = 0, candidate = 0;foreach (int num in nums) {if (count == 0) candidate = num;count += (num == candidate) ? 1 : -1;}return candidate; }
好的,我们继续。
41. Combination Sum III
- 题目: 找出所有的 k 个数,使它们的和等于 n。
- 解决方案:
public IList<IList<int>> CombinationSum3(int k, int n) {var result = new List<IList<int>>();var combination = new List<int>();Backtrack(k, n, 1, combination, result);return result; }private void Backtrack(int k, int n, int start, IList<int> combination, IList<IList<int>> result) {if (combination.Count == k && n == 0) {result.Add(new List<int>(combination));return;}for (int i = start; i <= 9; i++) {combination.Add(i);Backtrack(k, n - i, i + 1, combination, result);combination.RemoveAt(combination.Count - 1);} }
42. Subsets
- 题目: 给定一个不含重复数字的数组,返回所有可能的子集。
- 解决方案:
public IList<IList<int>> Subsets(int[] nums) {var result = new List<IList<int>>();var subset = new List<int>();Backtrack(nums, 0, subset, result);return result; }private void Backtrack(int[] nums, int start, IList<int> subset, IList<IList<int>> result) {result.Add(new List<int>(subset));for (int i = start; i < nums.Length; i++) {subset.Add(nums[i]);Backtrack(nums, i + 1, subset, result);subset.RemoveAt(subset.Count - 1);} }
43. Subsets II
- 题目: 给定一个可能包含重复数字的数组,返回所有可能的子集。
- 解决方案:
public IList<IList<int>> SubsetsWithDup(int[] nums) {var result = new List<IList<int>>();var subset = new List<int>();Array.Sort(nums);Backtrack(nums, 0, subset, result);return result; }private void Backtrack(int[] nums, int start, IList<int> subset, IList<IList<int>> result) {result.Add(new List<int>(subset));for (int i = start; i < nums.Length; i++) {if (i > start && nums[i] == nums[i - 1]) continue;subset.Add(nums[i]);Backtrack(nums, i + 1, subset, result);subset.RemoveAt(subset.Count - 1);} }
44. Reverse Bits
- 题目: 反转给定的 32 位无符号整数的二进制位。
- 解决方案:
public uint ReverseBits(uint n) {uint result = 0;for (int i = 0; i < 32; i++) {result = (result << 1) | (n & 1);n >>= 1;}return result; }
45. Hamming Distance
- 题目: 计算两个整数之间的汉明距离。
- 解决方案:
public int HammingDistance(int x, int y) {return CountBits(x ^ y); }private int CountBits(int n) {int count = 0;while (n > 0) {count += n & 1;n >>= 1;}return count; }
46. Single Number
- 题目: 给定一个非空整数数组,其中每个元素都出现两次,除了一个元素只出现了一次,找出那个只出现一次的元素。
- 解决方案:
public int SingleNumber(int[] nums) {int result = 0;foreach (int num in nums) {result ^= num;}return result; }
47. Missing Number
- 题目: 给定一个包含 0 到 n 的所有整数的数组,除了其中一个整数缺失,找出缺失的那个整数。
- 解决方案:
public int MissingNumber(int[] nums) {int n = nums.Length;int total = n * (n + 1) / 2;int sum = 0;foreach (int num in nums) {sum += num;}return total - sum; }
48. Find the Duplicate Number
- 题目: 给定一个包含 n + 1 个整数的数组,其中每个整数都在 1 到 n 之间,找出重复的那个数字。
- 解决方案:
public int FindDuplicate(int[] nums) {int slow = nums[0];int fast = nums[0];do {slow = nums[slow];fast = nums[nums[fast]];} while (slow != fast);fast = nums[0];while (slow != fast) {slow = nums[slow];fast = nums[fast];}return slow; }
49. Linked List Cycle
- 题目: 判断一个链表是否有环。
- 解决方案:
public bool HasCycle(ListNode head) {var slow = head;var fast = head;while (fast != null && fast.next != null) {slow = slow.next;fast = fast.next.next;if (slow == fast) return true;}return false; }
50. Merge Intervals
- 题目: 合并重叠的区间。
- 解决方案:
public int[][] Merge(int[][] intervals) {if (intervals.Length == 0) return new int[0][];Array.Sort(intervals, (a, b) => a[0].CompareTo(b[0]));var result = new List<int[]>();var current = intervals[0];result.Add(current);for (int i = 1; i < intervals.Length; i++) {if (intervals[i][0] <= current[1]) {current[1] = Math.Max(current[1], intervals[i][1]);} else {current = intervals[i];result.Add(current);}}return result.ToArray(); }
51. Insert Interval
- 题目: 在一个已排序的区间列表中插入一个新的区间并合并所有重叠的区间。
- 解决方案:
public int[][] Insert(int[][] intervals, int[] newInterval) {var result = new List<int[]>();int i = 0, n = intervals.Length;// Add all intervals ending before newInterval startswhile (i < n && intervals[i][1] < newInterval[0]) {result.Add(intervals[i++]);}// Merge all overlapping intervals to one considering newIntervalwhile (i < n && intervals[i][0] <= newInterval[1]) {newInterval[0] = Math.Min(newInterval[0], intervals[i][0]);newInterval[1] = Math.Max(newInterval[1], intervals[i][1]);i++;}result.Add(newInterval);// Add all the restwhile (i < n) {result.Add(intervals[i++]);}return result.ToArray(); }
52. Intervals Intersection
- 题目: 找出两个区间列表的交集。
- 解决方案:
public int[][] IntervalIntersection(int[][] A, int[][] B) {var result = new List<int[]>();int i = 0, j = 0;while (i < A.Length && j < B.Length) {int start = Math.Max(A[i][0], B[j][0]);int end = Math.Min(A[i][1], B[j][1]);if (start <= end) {result.Add(new[] { start, end });}if (A[i][1] < B[j][1]) {i++;} else {j++;}}return result.ToArray(); }
53. Course Schedule
- 题目: 判断是否可以完成所有课程,课程之间的先修关系由一个二维数组表示。
- 解决方案:
public bool CanFinish(int numCourses, int[][] prerequisites) {var graph = new List<int>[numCourses];var inDegree = new int[numCourses];for (int i = 0; i < numCourses; i++) {graph[i] = new List<int>();}foreach (var pre in prerequisites) {graph[pre[1]].Add(pre[0]);inDegree[pre[0]]++;}var queue = new Queue<int>();for (int i = 0; i < numCourses; i++) {if (inDegree[i] == 0) queue.Enqueue(i);}int count = 0;while (queue.Count > 0) {var node = queue.Dequeue();count++;foreach (var neighbor in graph[node]) {inDegree[neighbor]--;if (inDegree[neighbor] == 0) queue.Enqueue(neighbor);}}return count == numCourses;
}
54. Top K Frequent Elements
- 题目: 给定一个非空的整数数组,返回出现频率前 k 高的元素。
- 解决方案:
public IList<int> TopKFrequent(int[] nums, int k) {var frequency = new Dictionary<int, int>();foreach (var num in nums) {if (frequency.ContainsKey(num)) {frequency[num]++;} else {frequency[num] = 1;}}var sorted = frequency.OrderByDescending(pair => pair.Value).Take(k).Select(pair => pair.Key).ToList();return sorted;}
55. Kth Largest Element in an Array
- 题目: 找出数组中第 k 个最大的元素。
- 解决方案:
public int FindKthLargest(int[] nums, int k) {Array.Sort(nums);return nums[nums.Length - k]; }
56. Valid Parentheses
- 题目: 判断字符串中的括号是否有效。
- 解决方案:
public bool IsValid(string s) {var stack = new Stack<char>();var map = new Dictionary<char, char> {{ ')', '(' },{ ']', '[' },{ '}', '{' }};foreach (var ch in s) {if (map.ContainsKey(ch)) {if (stack.Count == 0 || stack.Pop() != map[ch]) return false;} else {stack.Push(ch);}}return stack.Count == 0; }
57. Generate Parentheses
- 题目: 生成所有合法的括号组合。
- 解决方案:
public IList<string> GenerateParenthesis(int n) {var result = new List<string>();Generate(result, "", 0, 0, n);return result; }private void Generate(IList<string> result, string s, int left, int right, int n) {if (s.Length == 2 * n) {result.Add(s);return;}if (left < n) Generate(result, s + "(", left + 1, right, n);if (right < left) Generate(result, s + ")", left, right + 1, n); }
58. String to Integer (atoi)
- 题目: 实现
atoi
函数,将字符串转换为整数。 - 解决方案:
public int MyAtoi(string s) {if (string.IsNullOrWhiteSpace(s)) return 0;int index = 0, sign = 1, result = 0;while (index < s.Length && s[index] == ' ') index++;if (index < s.Length && (s[index] == '+' || s[index] == '-')) {sign = s[index] == '+' ? 1 : -1;index++;}while (index < s.Length && char.IsDigit(s[index])) {int digit = s[index] - '0';if (result > (int.MaxValue - digit) / 10) {return sign == 1 ? int.MaxValue : int.MinValue;}result = result * 10 + digit;index++;}return result * sign; }
59. Longest Substring Without Repeating Characters
- 题目: 找出一个字符串中最长的不包含重复字符的子串的长度。
- 解决方案:
public int LengthOfLongestSubstring(string s) {var map = new Dictionary<char, int>();int left = 0, maxLength = 0;for (int right = 0; right < s.Length; right++) {if (map.ContainsKey(s[right])) {left = Math.Max(map[s[right]] + 1, left);}map[s[right]] = right;maxLength = Math.Max(maxLength, right - left + 1);}return maxLength; }
60. Median of Two Sorted Arrays
- 题目: 查找两个排序数组的中位数。
- 解决方案:
public double FindMedianSortedArrays(int[] nums1, int[] nums2) {int m = nums1.Length, n = nums2.Length;if (m > n) {return FindMedianSortedArrays(nums2, nums1);}int imin = 0, imax = m, halfLen = (m + n + 1) / 2;while (imin <= imax) {int i = (imin + imax) / 2;int j = halfLen - i;if (i < m && nums2[j - 1] > nums1[i]) {imin = i + 1;} else if (i > 0 && nums1[i - 1] > nums2[j]) {imax = i - 1;} else {int maxLeft = 0;if (i == 0) maxLeft = nums2[j - 1];else if (j == 0) maxLeft = nums1[i - 1];else maxLeft = Math.Max(nums1[i - 1], nums2[j - 1]);if ((m + n) % 2 == 1) return maxLeft;int minRight = 0;if (i == m) minRight = nums2[j];else if (j == n) minRight = nums1[i];else minRight = Math.Min(nums1[i], nums2[j]);return (maxLeft + minRight) / 2.0;}}throw new ArgumentException("Input arrays are not sorted."); }
61. Search a 2D Matrix
- 题目: 在一个 m x n 矩阵中查找目标值。
- 解决方案:
public bool SearchMatrix(int[][] matrix, int target) {if (matrix.Length == 0 || matrix[0].Length == 0) return false;int m = matrix.Length, n = matrix[0].Length;int row = 0, col = n - 1;while (row < m && col >= 0) {if (matrix[row][col] == target) return true;if (matrix[row][col] > target) col--;else row++;}return false; }
62. Word Ladder
- 题目: 变换一个单词到另一个单词,每次只改变一个字母,找出最短的变换序列长度。
- 解决方案:
public int LadderLength(string beginWord, string endWord, IList<string> wordList) {var wordSet = new HashSet<string>(wordList);if (!wordSet.Contains(endWord)) return 0;var queue = new Queue<string>();queue.Enqueue(beginWord);int length = 1;while (queue.Count > 0) {int levelSize = queue.Count;for (int i = 0; i < levelSize; i++) {var word = queue.Dequeue();if (word == endWord) return length;var chars = word.ToCharArray();for (int j = 0; j < chars.Length; j++) {char originalChar = chars[j];for (char c = 'a'; c <= 'z'; c++) {if (c == originalChar) continue;chars[j] = c;var newWord = new string(chars);if (wordSet.Contains(newWord)) {queue.Enqueue(newWord);wordSet.Remove(newWord);}}chars[j] = originalChar;}}length++;}return 0; }
63. Number of Islands
- 题目: 给定一个 2D 网格,其中 1 代表陆地,0 代表水,计算岛屿的数量。
- 解决方案:
public int NumIslands(char[][] grid) {if (grid.Length == 0) return 0;int m = grid.Length, n = grid[0].Length;int count = 0;for (int i = 0; i < m; i++) {for (int j = 0; j < n; j++) {if (grid[i][j] == '1') {DFS(grid, i, j);count++;}}}return count;
}private void DFS(char[][] grid, int i, int j) {if (i < 0 || i >= grid.Length || j < 0 || j >= grid[0].Length || grid[i][j] == '0') return;grid[i][j] = '0';DFS(grid, i + 1, j);DFS(grid, i - 1, j);DFS(grid, i, j + 1);DFS(grid, i, j - 1);
}
64. Clone Graph
- 题目: 克隆一个无向图。
- 解决方案:
public Node CloneGraph(Node node) {if (node == null) return null;var map = new Dictionary<Node, Node>();var queue = new Queue<Node>();queue.Enqueue(node);map[node] = new Node(node.val);while (queue.Count > 0) {var curr = queue.Dequeue();foreach (var neighbor in curr.neighbors) {if (!map.ContainsKey(neighbor)) {map[neighbor] = new Node(neighbor.val);queue.Enqueue(neighbor);}map[curr].neighbors.Add(map[neighbor]);}}return map[node]; }
65. Serialize and Deserialize Binary Tree
- 题目: 实现二叉树的序列化和反序列化。
- 解决方案:
public class Codec {public string Serialize(TreeNode root) {var sb = new StringBuilder();Serialize(root, sb);return sb.ToString();}private void Serialize(TreeNode root, StringBuilder sb) {if (root == null) {sb.Append("null,");return;}sb.Append(root.val + ",");Serialize(root.left, sb);Serialize(root.right, sb);}public TreeNode Deserialize(string data) {var nodes = data.Split(',');var queue = new Queue<string>(nodes);return Deserialize(queue);}private TreeNode Deserialize(Queue<string> queue) {var val = queue.Dequeue();if (val == "null") return null;var node = new TreeNode(int.Parse(val));node.left = Deserialize(queue);node.right = Deserialize(queue);return node;} }
66. Add Two Numbers
- 题目: 给定两个非空链表表示两个非负整数,按位相加它们的值,并返回一个新的链表。
- 解决方案:
public ListNode AddTwoNumbers(ListNode l1, ListNode l2) {var dummy = new ListNode(0);var p = dummy;var carry = 0;while (l1 != null || l2 != null || carry != 0) {var x = (l1 != null) ? l1.val : 0;var y = (l2 != null) ? l2.val : 0;var sum = carry + x + y;carry = sum / 10;p.next = new ListNode(sum % 10);p = p.next;if (l1 != null) l1 = l1.next;if (l2 != null) l2 = l2.next;}return dummy.next; }
67. Add Two Numbers II
- 题目: 给定两个链表表示两个非负整数,按位相加它们的值,并返回一个新的链表,链表的数值是反向的。
- 解决方案:
public ListNode AddTwoNumbers(ListNode l1, ListNode l2) {var stack1 = new Stack<int>();var stack2 = new Stack<int>();while (l1 != null) {stack1.Push(l1.val);l1 = l1.next;}while (l2 != null) {stack2.Push(l2.val);l2 = l2.next;}var dummy = new ListNode(0);var carry = 0;while (stack1.Count > 0 || stack2.Count > 0 || carry > 0) {var x = (stack1.Count > 0) ? stack1.Pop() : 0;var y = (stack2.Count > 0) ? stack2.Pop() : 0;var sum = x + y + carry;carry = sum / 10;var node = new ListNode(sum % 10);node.next = dummy.next;dummy.next = node;}return dummy.next; }
68. Palindrome Linked List
- 题目: 判断链表是否为回文。
- 解决方案:
public bool IsPalindrome(ListNode head) {if (head == null) return true;var slow = head;var fast = head;var stack = new Stack<int>();while (fast != null && fast.next != null) {stack.Push(slow.val);slow = slow.next;fast = fast.next.next;}if (fast != null) slow = slow.next;while (slow != null) {if (stack.Pop() != slow.val) return false;slow = slow.next;}return true; }
69. Reverse Linked List
- 题目: 反转一个单链表。
- 解决方案:
public ListNode ReverseList(ListNode head) {ListNode prev = null;ListNode curr = head;while (curr != null) {var next = curr.next;curr.next = prev;prev = curr;curr = next;}return prev; }
70. Merge Two Sorted Lists
- 题目: 合并两个排序的链表,并返回合并后的链表。
- 解决方案:
public ListNode MergeTwoLists(ListNode l1, ListNode l2) {var dummy = new ListNode(0);var p = dummy;while (l1 != null && l2 != null) {if (l1.val < l2.val) {p.next = l1;l1 = l1.next;} else {p.next = l2;l2 = l2.next;}p = p.next;}p.next = (l1 != null) ? l1 : l2;return dummy.next; }
71. Convert Sorted List to Binary Search Tree
- 题目: 将一个排序的链表转换为平衡的二叉搜索树。
- 解决方案:
public TreeNode SortedListToBST(ListNode head) {if (head == null) return null;return ConvertToBST(ref head, 0, GetLength(head)); }private TreeNode ConvertToBST(ref ListNode head, int start, int end) {if (start > end) return null;int mid = (start + end) / 2;TreeNode left = ConvertToBST(ref head, start, mid - 1);TreeNode root = new TreeNode(head.val);root.left = left;head = head.next;root.right = ConvertToBST(ref head, mid + 1, end);return root; }private int GetLength(ListNode head) {int length = 0;while (head != null) {length++;head = head.next;}return length; }
72. Delete Node in a Linked List
- 题目: 删除链表中给定的节点。
- 解决方案:
public void DeleteNode(ListNode node) {if (node == null || node.next == null) return;node.val = node.next.val;node.next = node.next.next; }
73. Find Minimum in Rotated Sorted Array
- 题目: 找出旋转排序数组中的最小值。
- 解决方案:
public int FindMin(int[] nums) {int left = 0, right = nums.Length - 1;while (left < right) {int mid = left + (right - left) / 2;if (nums[mid] > nums[right]) {left = mid + 1;} else {right = mid;}}return nums[left]; }
74. Find Peak Element
- 题目: 找到数组中的峰值元素。
- 解决方案:
public int FindPeakElement(int[] nums) {int left = 0, right = nums.Length - 1;while (left < right) {int mid = left + (right - left) / 2;if (nums[mid] > nums[mid + 1]) {right = mid;} else {left = mid + 1;}}return left; }
75. Product of Array Except Self
- 题目: 给定一个整数数组 nums,返回一个数组 output,output[i] 是
nums
中除了nums[i]
外的所有元素的乘积。 - 解决方案:
public int[] ProductExceptSelf(int[] nums) {int n = nums.Length;var output = new int[n];var left = new int[n];var right = new int[n];left[0] = 1;for (int i = 1; i < n; i++) {left[i] = left[i - 1] * nums[i - 1];}right[n - 1] = 1;for (int i = n - 2; i >= 0; i--) {right[i] = right[i + 1] * nums[i + 1];}for (int i = 0; i < n; i++) {output[i] = left[i] * right[i];}return output; }
76. 3Sum
- 题目: 给定一个整数数组,找出所有和为零的三元组。
- 解决方案:
public IList<IList<int>> ThreeSum(int[] nums) {var result = new List<IList<int>>();Array.Sort(nums);for (int i = 0; i < nums.Length - 2; i++) {if (i > 0 && nums[i] == nums[i - 1]) continue;int left = i + 1, right = nums.Length - 1;while (left < right) {int sum = nums[i] + nums[left] + nums[right];if (sum < 0) left++;else if (sum > 0) right--;else {result.Add(new List<int> { nums[i], nums[left], nums[right] });while (left < right && nums[left] == nums[left + 1]) left++;while (left < right && nums[right] == nums[right - 1]) right--;left++;right--;}}}return result; }
77. Group Anagrams
- 题目: 将一组字符串按字母异位词分组。
- 解决方案:
public IList<IList<string>> GroupAnagrams(string[] strs) {var map = new Dictionary<string, IList<string>>();foreach (var str in strs) {var chars = str.ToCharArray();Array.Sort(chars);var key = new string(chars);if (!map.ContainsKey(key)) {map[key] = new List<string>();}map[key].Add(str);}return new List<IList<string>>(map.Values); }
78. Letter Combinations of a Phone Number
- 题目: 给定一个数字字符串,返回所有可能的字母组合。
- 解决方案:
public IList<string> LetterCombinations(string digits) {var result = new List<string>();if (string.IsNullOrEmpty(digits)) return result;var phoneMap = new Dictionary<char, string> {{ '2', "abc" }, { '3', "def" }, { '4', "ghi" },{ '5', "jkl" }, { '6', "mno" }, { '7', "pqrs" },{ '8', "tuv" }, { '9', "wxyz" }};GenerateCombinations(phoneMap, digits, 0, new StringBuilder(), result);return result; }private void GenerateCombinations(Dictionary<char, string> phoneMap, string digits, int index, StringBuilder combination, IList<string> result) {if (index == digits.Length) {result.Add(combination.ToString());return;}var digit = digits[index];var letters = phoneMap[digit];for (int i = 0; i < letters.Length; i++) {combination.Append(letters[i]);GenerateCombinations(phoneMap, digits, index + 1, combination, result);combination.Length--;} }
79. Remove Duplicates from Sorted Array
- 题目: 从排序数组中移除重复项,使每个元素只出现一次,并返回新的长度。
- 解决方案:
public int RemoveDuplicates(int[] nums) {if (nums.Length == 0) return 0;int index = 1;for (int i = 1; i < nums.Length; i++) {if (nums[i] != nums[i - 1]) {nums[index++] = nums[i];}}return index; }
80. Move Zeroes
- 题目: 移动数组中的零,使所有非零元素都在前面,并保持相对顺序。
- 解决方案:
public void MoveZeroes(int[] nums) {int lastNonZeroFoundAt = 0;for (int i = 0; i < nums.Length; i++) {if (nums[i] != 0) {Swap(nums, i, lastNonZeroFoundAt);lastNonZeroFoundAt++;}} }private void Swap(int[] nums, int i, int j) {int temp = nums[i];nums[i] = nums[j];nums[j] = temp; }
81. Longest Common Prefix
- 题目: 找到字符串数组的最长公共前缀。
- 解决方案:
public string LongestCommonPrefix(string[] strs) {if (strs.Length == 0) return "";var prefix = strs[0];for (int i = 1; i < strs.Length; i++) {while (strs[i].IndexOf(prefix) != 0) {prefix = prefix.Substring(0, prefix.Length - 1);if (prefix == "") return "";}}return prefix; }
82. Reverse Integer
- 题目: 反转一个 32 位的整数。
- 解决方案:
public int Reverse(int x) {long result = 0;while (x != 0) {result = result * 10 + x % 10;x /= 10;}if (result > int.MaxValue || result < int.MinValue) return 0;return (int)result; }
83. String Compression
- 题目: 压缩字符串,只保留字符和它们的出现次数。
- 解决方案:
public int Compress(char[] chars) {int write = 0, read = 0;while (read < chars.Length) {char currentChar = chars[read];int count = 0;while (read < chars.Length && chars[read] == currentChar) {read++;count++;}chars[write++] = currentChar;if (count > 1) {foreach (var digit in count.ToString()) {chars[write++] = digit;}}}return write; }
84. Find Minimum in Rotated Sorted Array II
- 题目: 在可能包含重复元素的旋转排序数组中找到最小值。
- 解决方案:
public int FindMin(int[] nums) {int left = 0, right = nums.Length - 1;while (left < right) {int mid = left + (right - left) / 2;if (nums[mid] < nums[right]) {right = mid;} else if (nums[mid] > nums[right]) {left = mid + 1;} else {right--;}}return nums[left]; }
85. Search Insert Position
- 题目: 给定一个排序数组和一个目标值,返回目标值应该插入的位置。
- 解决方案:
public int SearchInsert(int[] nums, int target) {int left = 0, right = nums.Length - 1;while (left <= right) {int mid = left + (right - left) / 2;if (nums[mid] == target) return mid;if (nums[mid] < target) left = mid + 1;else right = mid - 1;}return left; }
86. Two Sum
- 题目: 给定一个整数数组和一个目标值,找出数组中和为目标值的两个数字。
- 解决方案:
public int[] TwoSum(int[] nums, int target) {var map = new Dictionary<int, int>();for (int i = 0; i < nums.Length; i++) {int complement = target -nums[i];if (map.ContainsKey(complement)) {return new[] { map[complement], i };}map[nums[i]] = i;}return null;}
87. Longest Substring Without Repeating Characters
- 题目: 给定一个字符串,找出最长的无重复字符子串。
- 解决方案:
public int LengthOfLongestSubstring(string s) {var map = new Dictionary<char, int>();int left = 0, maxLength = 0;for (int right = 0; right < s.Length; right++) {if (map.ContainsKey(s[right])) {left = Math.Max(map[s[right]] + 1, left);}map[s[right]] = right;maxLength = Math.Max(maxLength, right - left + 1);}return maxLength;}
88. Longest Palindromic Substring
- 题目: 给定一个字符串,找到最长的回文子串。
- 解决方案:
public string LongestPalindrome(string s) {if (s.Length == 0) return "";string longest = "";for (int i = 0; i < s.Length; i++) {string odd = ExpandAroundCenter(s, i, i);string even = ExpandAroundCenter(s, i, i + 1);string currentLongest = odd.Length > even.Length ? odd : even;if (currentLongest.Length > longest.Length) {longest = currentLongest;}}return longest; }private string ExpandAroundCenter(string s, int left, int right) {while (left >= 0 && right < s.Length && s[left] == s[right]) {left--;right++;}return s.Substring(left + 1, right - left - 1); }
89. Remove Duplicates from Sorted Array II
- 题目: 从排序数组中删除重复项,使每个元素最多出现两次。
- 解决方案:
public int RemoveDuplicates(int[] nums) {int index = 0, count = 0;for (int i = 0; i < nums.Length; i++) {if (i < 2 || nums[i] != nums[index - 2]) {nums[index++] = nums[i];}}return index; }
90. Valid Parentheses
- 题目: 给定一个字符串,判断括号是否有效。
- 解决方案:
public bool IsValid(string s) {var stack = new Stack<char>();foreach (var c in s) {if (c == '(' || c == '[' || c == '{') {stack.Push(c);} else {if (stack.Count == 0) return false;char top = stack.Pop();if ((c == ')' && top != '(') ||(c == ']' && top != '[') ||(c == '}' && top != '{')) {return false;}}}return stack.Count == 0; }
91. Generate Parentheses
- 题目: 生成所有有效的括号组合。
- 解决方案:
public IList<string> GenerateParenthesis(int n) {var result = new List<string>();Generate(result, "", 0, 0, n);return result; }private void Generate(IList<string> result, string current, int open, int close, int max) {if (current.Length == max * 2) {result.Add(current);return;}if (open < max) {Generate(result, current + "(", open + 1, close, max);}if (close < open) {Generate(result, current + ")", open, close + 1, max);} }
92. Unique Paths
- 题目: 计算从左上角到右下角的所有不同路径数。
- 解决方案:
public int UniquePaths(int m, int n) {var dp = new int[m, n];for (int i = 0; i < m; i++) {dp[i, 0] = 1;}for (int j = 0; j < n; j++) {dp[0, j] = 1;}for (int i = 1; i < m; i++) {for (int j = 1; j < n; j++) {dp[i, j] = dp[i - 1, j] + dp[i, j - 1];}}return dp[m - 1, n - 1]; }
93. Maximum Subarray
- 题目: 找到一个数组的最大子数组和。
- 解决方案:
public int MaxSubArray(int[] nums) {int maxSoFar = nums[0];int maxEndingHere = nums[0];for (int i = 1; i < nums.Length; i++) {maxEndingHere = Math.Max(nums[i], maxEndingHere + nums[i]);maxSoFar = Math.Max(maxSoFar, maxEndingHere);}return maxSoFar; }
94. Climbing Stairs
- 题目: 给定楼梯的阶数,计算到达顶部的方法数。
- 解决方案:
public int ClimbStairs(int n) {if (n <= 1) return 1;int[] dp = new int[n + 1];dp[1] = 1;dp[2] = 2;for (int i = 3; i <= n; i++) {dp[i] = dp[i - 1] + dp[i - 2];}return dp[n]; }
95. Maximum Product Subarray
- 题目: 找到一个数组的最大乘积子数组。
- 解决方案:
public int MaxProduct(int[] nums) {int maxSoFar = nums[0];int minEndingHere = nums[0];int maxEndingHere = nums[0];for (int i = 1; i < nums.Length; i++) {int tempMax = maxEndingHere;maxEndingHere = Math.Max(nums[i], Math.Max(maxEndingHere * nums[i], minEndingHere * nums[i]));minEndingHere = Math.Min(nums[i], Math.Min(tempMax * nums[i], minEndingHere * nums[i]));maxSoFar = Math.Max(maxSoFar, maxEndingHere);}return maxSoFar; }
96. Word Break
- 题目: 判断一个字符串是否可以被分割成字典中的单词。
- 解决方案:
public bool WordBreak(string s, IList<string> wordDict) {var wordSet = new HashSet<string>(wordDict);var dp = new bool[s.Length + 1];dp[0] = true;for (int i = 1; i <= s.Length; i++) {for (int j = 0; j < i; j++) {if (dp[j] && wordSet.Contains(s.Substring(j, i - j))) {dp[i] = true;break;}}}return dp[s.Length]; }
97. Edit Distance
- 题目: 计算将一个字符串转换成另一个字符串所需的最少操作数。
- 解决方案:
public int MinDistance(string word1, string word2) {int m = word1.Length;int n = word2.Length;var dp = new int[m + 1, n + 1];for (int i = 0; i <= m; i++) dp[i, 0] = i;for (int j = 0; j <= n; j++) dp[0, j] = j;for (int i = 1; i <= m; i++) {for (int j = 1; j <= n; j++) {if (word1[i - 1] == word2[j - 1]) {dp[i, j] = dp[i - 1, j - 1];} else {dp[i, j] = 1 + Math.Min(dp[i - 1, j], Math.Min(dp[i, j - 1], dp[i - 1, j - 1]));}}}return dp[m, n]; }
98. Search in Rotated Sorted Array
- 题目: 在旋转排序数组中查找目标值。
- 解决方案:
public int Search(int[] nums, int target) {int left = 0, right = nums.Length - 1;while (left <= right) {int mid = left + (right - left) / 2;if (nums[mid] == target) return mid;if (nums[left] <= nums[mid]) {if (nums[left] <= target && target < nums[mid]) {right = mid - 1;} else {left = mid + 1;}} else {if (nums[mid] < target && target <= nums[right]) {left = mid + 1;} else {right = mid - 1;}}}return -1;}
99. Best Time to Buy and Sell Stock
- 题目: 给定一个数组,找出最大利润。
- 解决方案:
public int MaxProfit(int[] prices) {int minPrice = int.MaxValue;int maxProfit = 0;foreach (var price in prices) {minPrice = Math.Min(minPrice, price);maxProfit = Math.Max(maxProfit, price - minPrice);}return maxProfit; }
100. Longest Substring with At Most Two Distinct Characters
- 题目: 找到包含至多两个不同字符的最长子串。
- 解决方案:
public int LengthOfLongestSubstringTwoDistinct(string s) {var map = new Dictionary<char, int>();int left = 0, maxLength = 0;for (int right = 0; right < s.Length; right++) {map[s[right]] = right;if (map.Count > 2) {var minIndex = int.MaxValue;foreach (var index in map.Values) {minIndex = Math.Min(minIndex, index);}map.Remove(s[minIndex]);left = minIndex + 1;}maxLength = Math.Max(maxLength, right - left + 1);}return maxLength; }
相关文章:

如何提高编程面试成功率:LeetCode Top 100 问题及解答解析(详细面试宝典)
以下是 LeetCode Top 100 面试必备题目及其解决方案示例。这些题目涵盖了数据结构、算法、动态规划、回溯等多种重要的面试话题。希望各位同学有所收货,早日脱离底层到达彼岸! 1. Two Sum 题目: 给定一个整数数组 nums 和一个目标值 target,…...

K-近邻和神经网络
K-近邻(K-NN, K-Nearest Neighbors) 原理 K-近邻(K-NN)是一种非参数分类和回归算法。K-NN 的主要思想是根据距离度量(如欧氏距离)找到训练数据集中与待预测样本最近的 K 个样本,并根据这 K 个…...

用EasyV全景图低成本重现真实场景,360°感受数字孪生
全景图,即借助绘画、相片、视频、三维模型等形式,通过广角的表现手段,尽可能多表现出周围的环境。避免了一般平面效果图视角单一,不能带来全方位视角的缺陷,能够全方位的展示360度球型范围内的所有景致,最大…...

【Golang 面试 - 进阶题】每日 3 题(九)
✍个人博客:Pandaconda-CSDN博客 📣专栏地址:http://t.csdnimg.cn/UWz06 📚专栏简介:在这个专栏中,我将会分享 Golang 面试中常见的面试题给大家~ ❤️如果有收获的话,欢迎点赞👍收藏…...

孟德尔随机化、R语言,报错,如何解决?
🏆本文收录于《CSDN问答解惑-专业版》专栏,主要记录项目实战过程中的Bug之前因后果及提供真实有效的解决方案,希望能够助你一臂之力,帮你早日登顶实现财富自由🚀;同时,欢迎大家关注&&收…...

一文剖析高可用向量数据库的本质
面对因电力故障、网络问题或人为操作失误等导致的服务中断,数据库系统高可用能够保证系统在这些情况下仍然不间断地提供服务。如果数据库系统不具备高可用性,那么系统就需要承担停机和数据丢失等重大风险,而这些风险极有可能造成用户流失&…...

JavaScript青少年简明教程:异常处理
JavaScript青少年简明教程:异常处理 在 JavaScript 中,异常指的是程序执行过程中出现的错误或异常情况。这些错误可能导致程序无法正常执行,甚至崩溃。ECMA-262规范了多种JavaScript错误类型,这些类型都继承自Error基类。主要的错…...

科普文:Lombok使用及工作原理详解
1. 概叙 Lombok是什么? Project Lombok 是一个 JAVA 库,它可以自动插入编辑器和构建工具,为您的 JAVA 锦上添花。再也不要写另一个 getter/setter 或 equals 等方法,只要有一个注注解,你的类就有一个功能齐全的生成器…...

飞致云开源社区月度动态报告(2024年7月)
自2023年6月起,中国领先的开源软件公司FIT2CLOUD飞致云以月度为单位发布《飞致云开源社区月度动态报告》,旨在向广大社区用户同步飞致云旗下系列开源软件的发展情况,以及当月主要的产品新版本发布、社区运营成果等相关信息。 飞致云开源大屏…...

mybatis-plus——实现动态字段排序,根据实体获取字段映射数据库的具体字段
前言 前端需要根据表头的点击控件可以排序,虽然前端能根据当前页的数据进行对应字段的排序,但也仅局限于实现当前页的排序,无法满足全部数据的排序,所以需要走接口的查询进行排序,获取最全的排序数据 实现方案 前端…...

redis:Linux安装redis,redis常用的数据类型及相关命令
1. 什么是NoSQL nosql[not only sql]不仅仅是sql。所有非关系型数据库的统称。除去关系型数据库之外的都是非关系数据库。 1.1为什么使用NoSQL NoSQL数据库相较于传统关系型数据库具有灵活性、可扩展性和高性能等优势,适合处理非结构化和半结构化数据,…...

JavaScript 和 HTML5 Canvas实现图像绘制与处理
前言 JavaScript 和 HTML5 的 canvas 元素提供了强大的图形和图像处理功能,使得开发者能够在网页上创建动态和交互式的视觉体验。这里我们将探讨如何使用 canvas 和 JavaScript 来处理图像加载,并在其上进行图像绘制。我们将实现一个简单的示例…...

Java之Java基础二十(集合[上])
Java 集合框架可以分为两条大的支线: ①、Collection,主要由 List、Set、Queue 组成: List 代表有序、可重复的集合,典型代表就是封装了动态数组的 ArrayList 和封装了链表的 LinkedList;Set 代表无序、不可重复的集…...

【C++BFS】1162. 地图分析
本文涉及知识点 CBFS算法 LeetCode1162. 地图分析 你现在手里有一份大小为 n x n 的 网格 grid,上面的每个 单元格 都用 0 和 1 标记好了。其中 0 代表海洋,1 代表陆地。 请你找出一个海洋单元格,这个海洋单元格到离它最近的陆地单元格的距…...

实战:安装ElasticSearch 和常用操作命令
概叙 科普文:深入理解ElasticSearch体系结构-CSDN博客 Elasticsearch各版本比较 ElasticSearch 单点安装 1 创建普通用户 #1 创建普通用户名,密码 [roothlink1 lyz]# useradd lyz [roothlink1 lyz]# passwd lyz#2 然后 关闭xshell 重新登录 ip 地址…...

React-Native 宝藏库大揭秘:精选开源项目与实战代码解析
1. 引言 1.1 React-Native 简介 React-Native 是由 Facebook 开发的一个开源框架,它允许开发者使用 JavaScript 和 React 的编程模型来构建跨平台的移动应用。React-Native 的核心理念是“Learn Once, Write Anywhere”,即学习一次 React 的编程模型&am…...

数据结构:二叉树(链式结构)
文章目录 1. 二叉树的链式结构2. 二叉树的创建和实现相关功能2.1 创建二叉树2.2 二叉树的前,中,后序遍历2.2.1 前序遍历2.2.2 中序遍历2.2.3 后序遍历 2.3 二叉树节点个数2.4 二叉树叶子结点个数2.5 二叉树第k层结点个数2.6 二叉树的深度/高度2.7 二叉树…...

召唤生命,阻止轻生——《生命门外》
本书的目的,就是阻止自杀!拉回那些深陷在这样的思维当中正在挣扎犹豫的人,提醒他们珍爱生命,让更多的人,尤其是年轻人从执迷不悟的犹豫徘徊中幡然醒悟,回归正常的生活。 网络上抱孩子跳桥轻生的母亲&#…...

JVM:栈上的数据存储
文章目录 一、Java虚拟机中的基本数据类型 一、Java虚拟机中的基本数据类型 在Java中有8大基本数据类型: 这里的内存占用,指的是堆上或者数组中内存分配的空间大小,栈上的实现更加复杂。 Java中的8大数据类型在虚拟机中的实现:…...

C#实战 - C#实现发送邮件的三种方法
作者:逍遥Sean 简介:一个主修Java的Web网站\游戏服务器后端开发者 主页:https://blog.csdn.net/Ureliable 觉得博主文章不错的话,可以三连支持一下~ 如有疑问和建议,请私信或评论留言! 前言 当使用 C# 编程…...

数模原理精解【5】
文章目录 二元分布满足要求边际分布条件概率例子1例子2 损失函数概率分布期望值例 参考文献 二元分布 满足要求 连续情况下, φ ( x , y ) \varphi (x,y) φ(x,y)为随机变量 X 、 Y X、Y X、Y的联合概率分布(二元分布),如果以下条件满足: …...

C语言篇——使用运算符将16进制数据反转
比如:将一个16进制0xFD,即11111101,反向,输出10111111,即0xBF。 #include <stdio.h>unsigned char reverseBits(unsigned char num) {unsigned char reverse_num 0;int i;for (i 0; i < 8; i) {if ((num &…...

2025年和2024CFA一级SchweserKaplan Notes 全集 (内附分享链接)
CFA一级notes百度网盘下载 2024年和2025年 CFA一级考纲已经正式发布,相比与老考纲,新考纲变化实在不算小。 2024年和2025年 CFA一级notes完整版全 https://drive.uc.cn/s/6394c0b6b1a54?public1 2024年和2025年 cfa二级notes完整版全 https://driv…...

B树的实现:代码示例与解析
B树的实现:代码示例与解析 引言 B树是一种自平衡的树数据结构,广泛应用于文件系统和数据库系统中。它是一种多路搜索树,旨在保持数据有序并允许高效的查找、插入和删除操作。本文将深入探讨B树的实现,提供完整的代码示例和详细的…...

HCIA总结
一、情景再现:ISP网络为学校提供了DNS服务,所以,DNS服务器驻留在ISP网络内,而不再学校网络内。DHCP服务器运行在学校网络的路由器上 小明拿了一台电脑,通过网线,接入到校园网内部。其目的是为了访问谷歌网站…...

软件测试_接口测试面试题
接口测试是软件测试中的重要环节,它主要验证系统不同模块之间的通信和数据交互是否正常。在软件开发过程中,各个模块之间的接口是实现功能的关键要素,因此对接口进行全面而准确的测试是确保系统稳定性和可靠性的关键步骤。 接口测试的核心目…...

C++初阶学习第五弹——类与对象(下)
类与对象(上):C初阶学习第三弹——类与对象(上)-CSDN博客 类和对象(中):C初阶学习第四弹——类与对象(中)-CSDN博客 一.赋值运算符重载 1.1 运算符重载 C为…...

最低工资标准数据(2001-2023年不等)、省市县,整理好的面板数据(excel格式)
时间范围:2001-2022年 具体内容:一:最低工资数据标准时间:2012-2021包含指标: 省份城市/区县小时最低工资标准(非全日制)月最低工资标准实施日期 样例数据: 二:各省最低…...

计算机毕业设计选题推荐-戏曲文化体验系统-Java/Python项目实战
✨作者主页:IT毕设梦工厂✨ 个人简介:曾从事计算机专业培训教学,擅长Java、Python、微信小程序、Golang、安卓Android等项目实战。接项目定制开发、代码讲解、答辩教学、文档编写、降重等。 ☑文末获取源码☑ 精彩专栏推荐⬇⬇⬇ Java项目 Py…...

【深度学习】CosyVoice,论文
CosyVoice_v1.pdf 文章目录 CosyVoice: A Scalable Multilingual Zero-shot Text-to-speech Synthesizer based on Supervised Semantic Tokens摘要1 引言2 CosyVoice: 使用监督语义标记的可扩展TTS模型2.1 用于语音的监督语义标记2.2 用于TTS的大型语言模型2.3 最优传输条件流…...