当前位置:   article > 正文

如何提高编程面试成功率:LeetCode Top 100 问题及解答解析(详细面试宝典)_程序面试 排行榜问题

程序面试 排行榜问题

以下是 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");
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11

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;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22

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;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14

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;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23

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);
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21

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();
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19

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;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11

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;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15

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;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9

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];
}

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22

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;
  }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16

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();
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13

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;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16

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;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12

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;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25

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;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29

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;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17

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;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15

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;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20

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);
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15

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;
  }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17

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;
  }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12

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;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11

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();
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19

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;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25

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;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31

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 visited
        bool 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;  // unmark
        return found;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23

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);
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20

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);
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22

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;
      }
  }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25

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;
      }
  }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24

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);
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15

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;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27

34. Rotate Image

  • 题目: 旋转一个 n x n 的矩阵 90 度。
  • 解决方案:
    public void Rotate(int[][] matrix) {
        int n = matrix.Length;
    
        // Transpose the matrix
        for (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 row
        for (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;
            }
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21

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;
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37

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;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19

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;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24

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;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11

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
   }; 
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12

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;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9

好的,我们继续。

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);
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19

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);
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15

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);
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17

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;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8

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;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12

46. Single Number

  • 题目: 给定一个非空整数数组,其中每个元素都出现两次,除了一个元素只出现了一次,找出那个只出现一次的元素。
  • 解决方案:
    public int SingleNumber(int[] nums) {
        int result = 0;
        foreach (int num in nums) {
            result ^= num;
        }
        return result;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7

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;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9

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;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17

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;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13

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();
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20

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 starts
        while (i < n && intervals[i][1] < newInterval[0]) {
            result.Add(intervals[i++]);
        }
    
        // Merge all overlapping intervals to one considering newInterval
        while (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 rest
        while (i < n) {
            result.Add(intervals[i++]);
        }
    
        return result.ToArray();
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24

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();
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21

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;
}

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32

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;
  }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13

55. Kth Largest Element in an Array

  • 题目: 找出数组中第 k 个最大的元素。
  • 解决方案:
    public int FindKthLargest(int[] nums, int k) {
        Array.Sort(nums);
        return nums[nums.Length - k];
    }
    
    • 1
    • 2
    • 3
    • 4

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;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18

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);
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15

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;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22

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;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14

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.");
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33

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;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14

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;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34

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);
}

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28

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];
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21

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;
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33

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;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19

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;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29

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;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22

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;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13

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;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18

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;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29

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;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

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];
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14

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;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16

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;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22

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;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24

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);
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16

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--;
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28

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;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12

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;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15

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;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13

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;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10

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;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20

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];
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16

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;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12

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;
  }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15

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;
  }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14

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);
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23

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;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11

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;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19

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);
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20

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];
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15

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;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11

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];
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13

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;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14

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];
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16

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];
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20

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;
  }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25

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;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11

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;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
声明:本文内容由网友自发贡献,转载请注明出处:【wpsshop博客】
推荐阅读
相关标签
  

闽ICP备14008679号