赞
踩
以下是 LeetCode Top 100 面试必备题目及其解决方案示例。这些题目涵盖了数据结构、算法、动态规划、回溯等多种重要的面试话题。希望各位同学有所收货,早日脱离底层到达彼岸!
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");
}
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; }
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;
}
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; }
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); }
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(); }
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;
}
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;
}
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;
}
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]; }
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; }
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();
}
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; }
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;
}
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; }
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; }
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; }
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;
}
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; }
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);
}
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; }
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;
}
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;
}
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(); }
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; }
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; }
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; }
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); } }
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); } }
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; } }
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; } }
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);
}
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; }
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; } } }
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; } }
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; }
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; }
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;
}
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
};
}
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;
}
好的,我们继续。
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); } }
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);
}
}
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); } }
public uint ReverseBits(uint n) {
uint result = 0;
for (int i = 0; i < 32; i++) {
result = (result << 1) | (n & 1);
n >>= 1;
}
return result;
}
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;
}
public int SingleNumber(int[] nums) {
int result = 0;
foreach (int num in nums) {
result ^= num;
}
return result;
}
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;
}
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; }
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;
}
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(); }
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(); }
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(); }
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; }
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;
}
public int FindKthLargest(int[] nums, int k) {
Array.Sort(nums);
return nums[nums.Length - k];
}
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; }
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);
}
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; }
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;
}
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."); }
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;
}
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; }
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); }
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]; }
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; } }
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; }
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; }
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; }
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;
}
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; }
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; }
public void DeleteNode(ListNode node) {
if (node == null || node.next == null) return;
node.val = node.next.val;
node.next = node.next.next;
}
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];
}
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; }
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; }
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; }
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); }
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--; } }
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;
}
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;
}
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;
}
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;
}
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; }
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]; }
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;
}
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;
}
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;
}
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); }
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;
}
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; }
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); } }
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];
}
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;
}
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];
}
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;
}
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]; }
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]; }
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; }
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;
}
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; }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。