├── LeetCodeInCSharp ├── 292_NimGame.cs ├── 268_MissingNumber.cs ├── 96_UniqueBinarySearchTrees.cs ├── 168_ExcelSheetColumnTitle.cs ├── 171_ExcelSheetColumnNumber.cs ├── 226_InvertBinaryTree.cs ├── 136_SingleNumber.cs ├── 283_MoveZeroes.cs ├── 137_SingleNumberII.cs ├── 104_MaximumDepthOfABinaryTree.cs ├── 217_ContainsDuplicate.cs ├── 260_SingleNumberIII.cs ├── 53_MaximumSubarray.cs ├── 66_PlusOne.cs ├── 83_RemoveDuplicatesFromSortedList.cs ├── 238_ProductofArrayExceptSelf.cs ├── 191_NumberOf1Bits.cs ├── 141_LinkedListCycle.cs ├── 100_SameTree.cs ├── 237_DeleteNodeInALinkedList.cs ├── 169_MajorityElement.cs ├── 70_ClimbingStairs.cs ├── 235_LowestCommonAncestorOfABinarySearchTree.cs ├── 122_BestTimeToBuyAndSellStockII.cs ├── 258_AddDigits.cs ├── 242_ValidAnagram.cs ├── 35_SearchInsertPosition.cs ├── Properties │ └── AssemblyInfo.cs ├── 144_BinaryTreePreOrderTraversal.cs ├── 12_IntegerToRoman.cs ├── 94_BinaryTreeInOrderTraversal.cs ├── 107_LevelOrderBinaryTreeTraversalII.cs ├── 116_PopulatingNextRightPointersInEachNode.cs ├── 13_RomanToInteger.cs ├── 28_ImplementStrStr.cs └── LeetCodeInCSharp.csproj ├── .gitattributes ├── LeetCodeInCSharpUnitTest ├── UnitTest137_SingleNumberII.cs ├── UnitTest136_SingleNumber.cs ├── UnitTest122_BestTimeToBuyAndSellStockII.cs ├── UnitTest283_MoveZeroes.cs ├── UnitTest96_UniqueBinarySearchTrees.cs ├── UnitTest168_ExcelSheetColumnTitle.cs ├── UnitTest260_SingleNumberIII.cs ├── UnitTest12_IntegerToRoman.cs ├── UnitTest292_NimGame.cs ├── UnitTest217_ContainsDuplicate.cs ├── UnitTest171_ExcelSheetColumnNumber.cs ├── UnitTest268_MissingNumber.cs ├── UnitTest66_PlusOne.cs ├── UnitTest242_ValidAnagram.cs ├── UnitTest53_MaximumSubarray.cs ├── UnitTest191_NumberOf1Bits.cs ├── UnitTest104_MaximumDepthOfABinaryTree.cs ├── UnitTest169_MajorityElement.cs ├── UnitTest83_RemoveDuplicatesFromSortedList.cs ├── UnitTest141_LinkedListCycle.cs ├── UnitTest238_ProductofArrayExceptSelf.cs ├── UnitTest107_LevelOrderBinaryTreeTraversalII.cs ├── UnitTest226_InverBinaryTree.cs ├── UnitTest258_AddDigits.cs ├── UnitTest235_LowestCommonAncestorOfABinarySearchTree.cs ├── UnitTest237_DeleteNodeInALinkedList.cs ├── UnitTest94_BinaryTreeInOrderTraversal.cs ├── UnitTest144_BinaryTreePreOrderTraversal.cs ├── UnitTest13_RomanToInteger.cs ├── UnitTest100_SameTree.cs ├── UnitTest35_SearchInsertPosition.cs ├── UnitTest116_PopulatingNextRightPointersInEachNode.cs ├── Properties │ └── AssemblyInfo.cs ├── UnitTest70_ClimbingStairs.cs ├── UnitTest28_ImplementStrStr.cs └── LeetCodeInCSharpUnitTest.csproj ├── LeetCodeInCSharp.sln ├── .gitignore └── README.md /LeetCodeInCSharp/292_NimGame.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Threading.Tasks; 6 | 7 | namespace LeetCodeInCSharp 8 | { 9 | public class NimGameSolution 10 | { 11 | public static bool CanWinNim(int n) 12 | { 13 | return n % 4 != 0; 14 | } 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /.gitattributes: -------------------------------------------------------------------------------- 1 | # Auto detect text files and perform LF normalization 2 | * text=auto 3 | 4 | # Custom for Visual Studio 5 | *.cs diff=csharp 6 | 7 | # Standard to msysgit 8 | *.doc diff=astextplain 9 | *.DOC diff=astextplain 10 | *.docx diff=astextplain 11 | *.DOCX diff=astextplain 12 | *.dot diff=astextplain 13 | *.DOT diff=astextplain 14 | *.pdf diff=astextplain 15 | *.PDF diff=astextplain 16 | *.rtf diff=astextplain 17 | *.RTF diff=astextplain 18 | -------------------------------------------------------------------------------- /LeetCodeInCSharpUnitTest/UnitTest137_SingleNumberII.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using Microsoft.VisualStudio.TestTools.UnitTesting; 3 | using LeetCodeInCSharp; 4 | 5 | namespace LeetCodeInCSharpUnitTest 6 | { 7 | [TestClass] 8 | public class UnitTest137_SingleNumberII 9 | { 10 | [TestMethod] 11 | public void TestMethodSingleNumber() 12 | { 13 | int[] nums = new int[] { 1, 1, 1, 2, 2, 2, 3, 4, 4, 4, 5, 5, 5 }; 14 | Assert.AreEqual(3, SingleNumberIISolution.SingleNumber(nums)); 15 | } 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /LeetCodeInCSharp/268_MissingNumber.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Threading.Tasks; 6 | 7 | namespace LeetCodeInCSharp 8 | { 9 | public class MissingNumberSolution 10 | { 11 | public static int MissingNumber(int[] nums) 12 | { 13 | int sum = nums.Length * (nums.Length + 1) / 2; 14 | foreach (var num in nums) 15 | { 16 | sum -= num; 17 | } 18 | return sum; 19 | } 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /LeetCodeInCSharpUnitTest/UnitTest136_SingleNumber.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using Microsoft.VisualStudio.TestTools.UnitTesting; 3 | using LeetCodeInCSharp; 4 | 5 | namespace LeetCodeInCSharpUnitTest 6 | { 7 | [TestClass] 8 | public class UnitTest136_SingleNumber 9 | { 10 | [TestMethod] 11 | public void TestMethodSingleNumber() 12 | { 13 | 14 | int[] nums = new int[]{1, 3, 9, 5, 4, 6, 5, 3, 1, 9, 4}; 15 | int singleNumber = SingleNumberClass.SingleNumber(nums); 16 | Assert.AreEqual(6, singleNumber); 17 | } 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /LeetCodeInCSharpUnitTest/UnitTest122_BestTimeToBuyAndSellStockII.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using Microsoft.VisualStudio.TestTools.UnitTesting; 3 | using LeetCodeInCSharp; 4 | 5 | namespace LeetCodeInCSharpUnitTest 6 | { 7 | [TestClass] 8 | public class UnitTest1 9 | { 10 | [TestMethod] 11 | public void TestMethodMaxProfit() 12 | { 13 | int[] prices = new int[20] { 1, 3, 9, 5, 3, 1, 3, 5, 3, 9, 7, 9, 3, 7, 5, 1, 3, 9, 9, 7 }; 14 | int maxProfit = StockTradeII.MaxProfit(prices); 15 | Assert.AreEqual(32, maxProfit); 16 | } 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /LeetCodeInCSharp/96_UniqueBinarySearchTrees.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Threading.Tasks; 6 | 7 | namespace LeetCodeInCSharp 8 | { 9 | public class UniqueBinarySearchTreesSolution 10 | { 11 | public static int NumTrees(int n) 12 | { 13 | int[] c = new int[n + 1]; 14 | c[0] = 1; 15 | for (int i = 1; i <= n; i++) 16 | for (int j = 0; j < i; j++) 17 | c[i] += c[j] * c[i - j - 1]; 18 | return c[n]; 19 | } 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /LeetCodeInCSharpUnitTest/UnitTest283_MoveZeroes.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using Microsoft.VisualStudio.TestTools.UnitTesting; 3 | using LeetCodeInCSharp; 4 | 5 | namespace LeetCodeInCSharpUnitTest 6 | { 7 | [TestClass] 8 | public class UnitTest283_MoveZeroes 9 | { 10 | [TestMethod] 11 | public void TestMethodMoveZeroes() 12 | { 13 | var array = new int[] { 0, 1, 0, 2, 0, 3, 0, 4, 0, 5, 0, 6, 0 }; 14 | MoveZeroesSolution.MoveZeroes(array); 15 | CollectionAssert.AreEqual(new int[] { 1, 2, 3, 4, 5, 6, 0, 0, 0, 0, 0, 0, 0 }, array); 16 | } 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /LeetCodeInCSharpUnitTest/UnitTest96_UniqueBinarySearchTrees.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using Microsoft.VisualStudio.TestTools.UnitTesting; 3 | using LeetCodeInCSharp; 4 | 5 | namespace LeetCodeInCSharpUnitTest 6 | { 7 | [TestClass] 8 | public class UnitTest96_UniqueBinarySearchTrees 9 | { 10 | [TestMethod] 11 | public void TestMethodNumTrees() 12 | { 13 | Assert.AreEqual(1, UniqueBinarySearchTreesSolution.NumTrees(1)); 14 | Assert.AreEqual(2, UniqueBinarySearchTreesSolution.NumTrees(2)); 15 | Assert.AreEqual(5, UniqueBinarySearchTreesSolution.NumTrees(3)); 16 | } 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /LeetCodeInCSharpUnitTest/UnitTest168_ExcelSheetColumnTitle.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using Microsoft.VisualStudio.TestTools.UnitTesting; 3 | using LeetCodeInCSharp; 4 | 5 | namespace LeetCodeInCSharpUnitTest 6 | { 7 | [TestClass] 8 | public class UnitTest168_ExcelSheetColumnTitle 9 | { 10 | [TestMethod] 11 | public void TestMethodConvertToTitle() 12 | { 13 | Assert.AreEqual("A", ConvertToTitleSolution.ConvertToTitle(1)); 14 | Assert.AreEqual("Z", ConvertToTitleSolution.ConvertToTitle(26)); 15 | Assert.AreEqual("AA", ConvertToTitleSolution.ConvertToTitle(27)); 16 | } 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /LeetCodeInCSharpUnitTest/UnitTest260_SingleNumberIII.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using Microsoft.VisualStudio.TestTools.UnitTesting; 3 | using LeetCodeInCSharp; 4 | 5 | namespace LeetCodeInCSharpUnitTest 6 | { 7 | [TestClass] 8 | public class UnitTest260_SingleNumberIII 9 | { 10 | [TestMethod] 11 | public void TestMethodSingleNumber() 12 | { 13 | var array = new int[] { 1, 2, 3, 4, 6, 1, 2, 3 }; 14 | var result = SingleNumberIIISolution.SingleNumber(array); 15 | foreach (int i in result) 16 | { 17 | Console.Write(i + ","); 18 | } 19 | } 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /LeetCodeInCSharpUnitTest/UnitTest12_IntegerToRoman.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using Microsoft.VisualStudio.TestTools.UnitTesting; 3 | using LeetCodeInCSharp; 4 | 5 | namespace LeetCodeInCSharpUnitTest 6 | { 7 | [TestClass] 8 | public class UnitTest12_IntegerToRoman 9 | { 10 | [TestMethod] 11 | public void TestMethodIntToRoman() 12 | { 13 | Assert.AreEqual("MMMCMXCIX", IntToRomanSolution.IntToRoman(3999)); 14 | } 15 | 16 | [TestMethod] 17 | public void TestMethodIntToRoman2() 18 | { 19 | Assert.AreEqual("MMMCMXCIX", IntToRomanSolution.IntToRoman2(3999)); 20 | } 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /LeetCodeInCSharp/168_ExcelSheetColumnTitle.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Threading.Tasks; 6 | 7 | namespace LeetCodeInCSharp 8 | { 9 | public class ConvertToTitleSolution 10 | { 11 | public static string ConvertToTitle(int n) 12 | { 13 | string title = ""; 14 | while (n > 0) 15 | { 16 | n--; 17 | title = System.Text.Encoding.ASCII.GetString(new byte[] { (byte)((n) % 26 + 65) }) + title; 18 | n = n / 26; 19 | } 20 | return title; 21 | } 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /LeetCodeInCSharpUnitTest/UnitTest292_NimGame.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using Microsoft.VisualStudio.TestTools.UnitTesting; 3 | using LeetCodeInCSharp; 4 | 5 | namespace LeetCodeInCSharpUnitTest 6 | { 7 | [TestClass] 8 | public class UnitTest292_NimGame 9 | { 10 | [TestMethod] 11 | public void TestMethod1CanWinNim() 12 | { 13 | int g1 = 10; 14 | int g2 = 1; 15 | int g3 = 4; 16 | Assert.AreEqual(true, NimGameSolution.CanWinNim(g1)); 17 | Assert.AreEqual(true, NimGameSolution.CanWinNim(g2)); 18 | Assert.AreEqual(false, NimGameSolution.CanWinNim(g3)); 19 | } 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /LeetCodeInCSharp/171_ExcelSheetColumnNumber.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Threading.Tasks; 6 | 7 | namespace LeetCodeInCSharp 8 | { 9 | public class TitleToNumberSolution 10 | { 11 | public static int TitleToNumber(string s) 12 | { 13 | char[] array = s.ToCharArray(); 14 | int sum = 0; 15 | for (int i = array.Length - 1; i >= 0; i--) 16 | { 17 | sum += ((int)(Convert.ToByte(array[i])) - 64) * (int)(Math.Pow(26, array.Length - 1 - i)); 18 | } 19 | return sum; 20 | } 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /LeetCodeInCSharp/226_InvertBinaryTree.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Threading.Tasks; 6 | 7 | //Problem description: 8 | //Invert a binary tree 9 | 10 | namespace LeetCodeInCSharp 11 | { 12 | public class InvertBinaryTreeSolution 13 | { 14 | public static TreeNode InvertTree(TreeNode root) 15 | { 16 | if (root == null) return null; 17 | var buffer = root.left; 18 | root.left = root.right; 19 | root.right = buffer; 20 | InvertTree(root.left); 21 | InvertTree(root.right); 22 | return root; 23 | } 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /LeetCodeInCSharpUnitTest/UnitTest217_ContainsDuplicate.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using Microsoft.VisualStudio.TestTools.UnitTesting; 3 | using LeetCodeInCSharp; 4 | 5 | namespace LeetCodeInCSharpUnitTest 6 | { 7 | [TestClass] 8 | public class UnitTest217_ContainsDuplicate 9 | { 10 | [TestMethod] 11 | public void TestMethodContainsDuplicate() 12 | { 13 | var test1 = new int[] { 1, 2, 3, 4, 5, 6, 7 }; 14 | var test2 = new int[] { 1, 2, 3, 3, 4, 5, 6, 7 }; 15 | Assert.AreEqual(false, ContainsDuplicateSolution.ContainsDuplicate(test1)); 16 | Assert.AreEqual(true, ContainsDuplicateSolution.ContainsDuplicate(test2)); 17 | } 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /LeetCodeInCSharp/136_SingleNumber.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Threading.Tasks; 6 | 7 | //Problem description: 8 | //Given an array of integers, every element appears 9 | //twice except for one. Find that single one. 10 | 11 | namespace LeetCodeInCSharp 12 | { 13 | public class SingleNumberClass 14 | { 15 | public static int SingleNumber(int[] nums) 16 | { 17 | var answer = nums[0]; 18 | //use bitwise XOR to filter out the ones in pair 19 | for (int i = 1; i < nums.Length; i++) 20 | answer ^= nums[i]; 21 | return answer; 22 | } 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /LeetCodeInCSharp/283_MoveZeroes.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Threading.Tasks; 6 | 7 | namespace LeetCodeInCSharp 8 | { 9 | public class MoveZeroesSolution 10 | { 11 | public static void MoveZeroes(int[] nums) 12 | { 13 | int toBeSwapped = 0; 14 | for (int i = 0; i < nums.Length; i++) 15 | if (nums[i] != 0) 16 | Swap(ref nums[i], ref nums[toBeSwapped++]); 17 | } 18 | public static void Swap(ref int left, ref int right) 19 | { 20 | int temp = left; 21 | left = right; 22 | right = temp; 23 | } 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /LeetCodeInCSharpUnitTest/UnitTest171_ExcelSheetColumnNumber.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using Microsoft.VisualStudio.TestTools.UnitTesting; 3 | using LeetCodeInCSharp; 4 | 5 | namespace LeetCodeInCSharpUnitTest 6 | { 7 | [TestClass] 8 | public class UnitTest171_ExcelSheetColumnNumber 9 | { 10 | [TestMethod] 11 | public void TestMethodTitleToNumber() 12 | { 13 | string title1 = "A"; 14 | string title2 = "Z"; 15 | string title3 = "AA"; 16 | 17 | Assert.AreEqual(1, TitleToNumberSolution.TitleToNumber(title1)); 18 | Assert.AreEqual(26, TitleToNumberSolution.TitleToNumber(title2)); 19 | Assert.AreEqual(27, TitleToNumberSolution.TitleToNumber(title3)); 20 | } 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /LeetCodeInCSharpUnitTest/UnitTest268_MissingNumber.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using Microsoft.VisualStudio.TestTools.UnitTesting; 3 | using LeetCodeInCSharp; 4 | 5 | namespace LeetCodeInCSharpUnitTest 6 | { 7 | [TestClass] 8 | public class UnitTest268_MissingNumber 9 | { 10 | [TestMethod] 11 | public void TestMethodMissingNumber() 12 | { 13 | int[] nums1 = new int[] { 1 }; 14 | var nums2 = new int[] { 1, 0 }; 15 | var nums3 = new int[] { 0, 2 }; 16 | Assert.AreEqual(0, MissingNumberSolution.MissingNumber(nums1)); 17 | Assert.AreEqual(2, MissingNumberSolution.MissingNumber(nums2)); 18 | Assert.AreEqual(1, MissingNumberSolution.MissingNumber(nums3)); 19 | } 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /LeetCodeInCSharp/137_SingleNumberII.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Threading.Tasks; 6 | 7 | namespace LeetCodeInCSharp 8 | { 9 | public class SingleNumberIISolution 10 | { 11 | public static int SingleNumber(int[] nums) 12 | { 13 | var dic = new Dictionary(); 14 | foreach (var num in nums) 15 | { 16 | if (dic.ContainsKey(num)) dic[num]++; 17 | else dic.Add(num, 1); 18 | } 19 | foreach (KeyValuePair entry in dic) 20 | { 21 | if (entry.Value == 1) return entry.Key; 22 | } 23 | return 0; 24 | } 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /LeetCodeInCSharpUnitTest/UnitTest66_PlusOne.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using Microsoft.VisualStudio.TestTools.UnitTesting; 3 | using LeetCodeInCSharp; 4 | 5 | namespace LeetCodeInCSharpUnitTest 6 | { 7 | [TestClass] 8 | public class UnitTest66_PlusOne 9 | { 10 | [TestMethod] 11 | public void TestMethodPlusOne() 12 | { 13 | int[] test1 = new int[]{9,9,9}; 14 | int[] test2 = new int[] { 1,0,2,3,4,8,9,9,9 }; 15 | var result1 = PlusOneSolution.PlusOne(test1); 16 | var result2 = PlusOneSolution.PlusOne(test2); 17 | 18 | CollectionAssert.AreEqual(new int[] { 1, 0, 0, 0 }, result1); 19 | CollectionAssert.AreEqual(new int[] { 1, 0, 2, 3, 4, 9, 0, 0, 0 }, result2); 20 | } 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /LeetCodeInCSharp/104_MaximumDepthOfABinaryTree.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Threading.Tasks; 6 | 7 | //Problem description: 8 | //Given a binary tree, find its maximum depth. 9 | 10 | namespace LeetCodeInCSharp 11 | { 12 | public class TreeNode 13 | { 14 | public int val; 15 | public TreeNode left; 16 | public TreeNode right; 17 | public TreeNode(int x) { val = x; } 18 | } 19 | public class MaximumDepthOfABinaryTree 20 | { 21 | //The recursive solution 22 | public static int MaxDepth(TreeNode root) 23 | { 24 | return root == null ? 0 : 1 + Math.Max(MaxDepth(root.left), MaxDepth(root.right)); 25 | } 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /LeetCodeInCSharpUnitTest/UnitTest242_ValidAnagram.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using Microsoft.VisualStudio.TestTools.UnitTesting; 3 | using LeetCodeInCSharp; 4 | 5 | namespace LeetCodeInCSharpUnitTest 6 | { 7 | [TestClass] 8 | public class UnitTest242_ValidAnagram 9 | { 10 | [TestMethod] 11 | public void TestMethodIsAnagram() 12 | { 13 | string s1 = "aacc"; 14 | string t1 = "ccac"; 15 | Assert.AreEqual(false, ValidAnagramSolution.IsAnagram(s1, t1)); 16 | } 17 | 18 | [TestMethod] 19 | public void TestMethodIsAnagram2() 20 | { 21 | string s1 = "aacc"; 22 | string t1 = "ccac"; 23 | Assert.AreEqual(false, ValidAnagramSolution.IsAnagram2(s1, t1)); 24 | } 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /LeetCodeInCSharp/217_ContainsDuplicate.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Threading.Tasks; 6 | 7 | namespace LeetCodeInCSharp 8 | { 9 | public class ContainsDuplicateSolution 10 | { 11 | public static bool ContainsDuplicate(int[] nums) 12 | { 13 | //Alan Wang's one line solution ------- 14 | //return nums.Count() != (new HashSet(nums)).Count(); 15 | //------------------------------------- 16 | var hashSet = new HashSet(); 17 | foreach (var num in nums) 18 | { 19 | if (hashSet.Add(num) == false) 20 | return true; 21 | } 22 | return false; 23 | } 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /LeetCodeInCSharp/260_SingleNumberIII.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Threading.Tasks; 6 | 7 | namespace LeetCodeInCSharp 8 | { 9 | public class SingleNumberIIISolution 10 | { 11 | public static int[] SingleNumber(int[] nums) 12 | { 13 | int aXORb = 0; 14 | foreach (int i in nums) 15 | aXORb ^= i; 16 | int lastSetBit = aXORb & (-aXORb); 17 | int[] singleNumber = new int[] { 0, 0 }; 18 | foreach (int i in nums) 19 | { 20 | if ((i & lastSetBit) == 0) singleNumber[0] ^= i; 21 | else singleNumber[1] ^= i; 22 | } 23 | return singleNumber; 24 | } 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /LeetCodeInCSharpUnitTest/UnitTest53_MaximumSubarray.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using Microsoft.VisualStudio.TestTools.UnitTesting; 3 | using LeetCodeInCSharp; 4 | 5 | namespace LeetCodeInCSharpUnitTest 6 | { 7 | [TestClass] 8 | public class UnitTest53_MaximumSubarray 9 | { 10 | [TestMethod] 11 | public void TestMethodMaxSubArray() 12 | { 13 | var nums1 = new int[] { 1, -1, 1, -1, 1, -1 }; 14 | var nums2 = new int[] { 1, -2, 3, -4, 5 }; 15 | var nums3 = new int[] { 1, 2, 2 , 2 , -5, 4, -7, 6}; 16 | Assert.AreEqual(1, MaxSubArraySolution.MaxSubArray(nums1)); 17 | Assert.AreEqual(5, MaxSubArraySolution.MaxSubArray(nums2)); 18 | Assert.AreEqual(7, MaxSubArraySolution.MaxSubArray(nums3)); 19 | } 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /LeetCodeInCSharp/53_MaximumSubarray.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Threading.Tasks; 6 | 7 | namespace LeetCodeInCSharp 8 | { 9 | public class MaxSubArraySolution 10 | { 11 | public static int MaxSubArray(int[] nums) 12 | { 13 | if (nums.Length == 0) return 0; 14 | 15 | int prev = nums[0]; 16 | int cur = prev; 17 | int max = cur; 18 | 19 | for (int i = 1; i < nums.Length; i++ ) 20 | { 21 | if (prev > 0) cur = prev + nums[i]; 22 | else cur = nums[i]; 23 | max = Math.Max(max, cur); 24 | prev = cur; 25 | } 26 | 27 | return max; 28 | } 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /LeetCodeInCSharpUnitTest/UnitTest191_NumberOf1Bits.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using Microsoft.VisualStudio.TestTools.UnitTesting; 3 | using LeetCodeInCSharp; 4 | 5 | namespace LeetCodeInCSharpUnitTest 6 | { 7 | [TestClass] 8 | public class UnitTest191_NumberOf1Bits 9 | { 10 | [TestMethod] 11 | public void TestMethodHammingWeight() 12 | { 13 | uint a = 0; 14 | uint b = 1; 15 | uint c = 2; 16 | uint d = 100; 17 | 18 | Assert.AreEqual(0, HammingWeightSolution.HammingWeight(a)); 19 | Assert.AreEqual(1, HammingWeightSolution.HammingWeight(b)); 20 | Assert.AreEqual(1, HammingWeightSolution.HammingWeight(c)); 21 | Assert.AreEqual(3, HammingWeightSolution.HammingWeight(d)); 22 | } 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /LeetCodeInCSharpUnitTest/UnitTest104_MaximumDepthOfABinaryTree.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using Microsoft.VisualStudio.TestTools.UnitTesting; 3 | using LeetCodeInCSharp; 4 | 5 | namespace LeetCodeInCSharpUnitTest 6 | { 7 | [TestClass] 8 | public class UnitTest104_MaximumDepthOfABinaryTree 9 | { 10 | [TestMethod] 11 | public void TestMethodMaxDepth() 12 | { 13 | var tree = new TreeNode(0); 14 | tree.left = new TreeNode(1); 15 | tree.right = new TreeNode(1); 16 | tree.left.left = new TreeNode(2); 17 | tree.left.left.left = new TreeNode(3); 18 | tree.left.right = new TreeNode(2); 19 | 20 | int depth = MaximumDepthOfABinaryTree.MaxDepth(tree); 21 | Assert.AreEqual(4, depth); 22 | } 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /LeetCodeInCSharpUnitTest/UnitTest169_MajorityElement.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using Microsoft.VisualStudio.TestTools.UnitTesting; 3 | using LeetCodeInCSharp; 4 | 5 | namespace LeetCodeInCSharpUnitTest 6 | { 7 | [TestClass] 8 | public class UnitTest169_MajorityElement 9 | { 10 | [TestMethod] 11 | public void TestMethodMajorityElement() 12 | { 13 | int[] list = new int[] { 1, 2, 1, 3, 1, 4, 1, 5, 1, 6, 1, 1, 1 }; 14 | Assert.AreEqual(1, MajorityElementSolution.MajoirityElement(list)); 15 | } 16 | 17 | [TestMethod] 18 | public void TestMethodMajorityElement2() 19 | { 20 | int[] list = new int[] { 1, 2, 1, 3, 1, 4, 1, 5, 1, 6, 1, 1, 1 }; 21 | Assert.AreEqual(1, MajorityElementSolution.MajoirityElement2(list)); 22 | } 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /LeetCodeInCSharp/66_PlusOne.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Threading.Tasks; 6 | 7 | namespace LeetCodeInCSharp 8 | { 9 | public class PlusOneSolution 10 | { 11 | public static int[] PlusOne(int[] digits) 12 | { 13 | for (int i = digits.Length - 1; i >= 0; i--) 14 | { 15 | if (digits[i] == 9) 16 | { 17 | digits[i] = 0; 18 | } 19 | else 20 | { 21 | digits[i]++; 22 | return digits; 23 | } 24 | } 25 | 26 | var newDigits = new int[digits.Length + 1]; 27 | newDigits[0] = 1; 28 | return newDigits; 29 | } 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /LeetCodeInCSharp/83_RemoveDuplicatesFromSortedList.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Threading.Tasks; 6 | 7 | namespace LeetCodeInCSharp 8 | { 9 | public class DeleteDuplicatesSolution 10 | { 11 | public static ListNode DeleteDuplicates(ListNode head) 12 | { 13 | if (head == null) return null; 14 | var pointer = head; 15 | while (pointer.next != null) 16 | { 17 | while (pointer.val == pointer.next.val) 18 | { 19 | pointer.next = pointer.next.next; 20 | if (pointer.next == null) return head; 21 | } 22 | pointer = pointer.next; 23 | } 24 | return head; 25 | } 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /LeetCodeInCSharp/238_ProductofArrayExceptSelf.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Threading.Tasks; 6 | 7 | namespace LeetCodeInCSharp 8 | { 9 | public class ProductExceptSelfSolution 10 | { 11 | public static int[] ProductExceptSelf(int[] nums) 12 | { 13 | var result = new int[nums.Length]; 14 | int pre = 1; 15 | int post = 1; 16 | for (int i = 0; i < nums.Length; i++) 17 | { 18 | result[i] = pre; 19 | pre *= nums[i]; 20 | } 21 | for (int i = nums.Length - 1; i >= 0; i--) 22 | { 23 | result[i] *= post; 24 | post *= nums[i]; 25 | } 26 | return result; 27 | } 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /LeetCodeInCSharpUnitTest/UnitTest83_RemoveDuplicatesFromSortedList.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using Microsoft.VisualStudio.TestTools.UnitTesting; 3 | using LeetCodeInCSharp; 4 | 5 | namespace LeetCodeInCSharpUnitTest 6 | { 7 | [TestClass] 8 | public class UnitTest83_RemoveDuplicatesFromSortedList 9 | { 10 | [TestMethod] 11 | public void TestMethodDeleteDuplicates() 12 | { 13 | var list = new ListNode(0); 14 | list.next = new ListNode(1); 15 | list.next.next = new ListNode(1); 16 | list.next.next.next = new ListNode(2); 17 | list.next.next.next.next = new ListNode(2); 18 | 19 | list = DeleteDuplicatesSolution.DeleteDuplicates(list); 20 | Assert.AreEqual(2, list.next.next.val); 21 | Assert.AreEqual(null, list.next.next.next); 22 | } 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /LeetCodeInCSharp/191_NumberOf1Bits.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Threading.Tasks; 6 | 7 | //Problem description: 8 | //Write a function that takes an unsigned integer 9 | //and returns the number of ’1' bits it has (also 10 | //known as the Hamming weight). 11 | //For example, the 32-bit integer ’11' has binary 12 | //representation 00000000000000000000000000001011, 13 | //so the function should return 3. 14 | 15 | namespace LeetCodeInCSharp 16 | { 17 | public class HammingWeightSolution 18 | { 19 | public static int HammingWeight(uint n) { 20 | int result = 0; 21 | while (n > 0) 22 | { 23 | result += (int)(n % 2); 24 | n = n >> 1; 25 | } 26 | return result; 27 | } 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /LeetCodeInCSharpUnitTest/UnitTest141_LinkedListCycle.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using Microsoft.VisualStudio.TestTools.UnitTesting; 3 | using LeetCodeInCSharp; 4 | 5 | namespace LeetCodeInCSharpUnitTest 6 | { 7 | [TestClass] 8 | public class UnitTest141_LinkedListCycle 9 | { 10 | [TestMethod] 11 | public void TestMethodHasCycle() 12 | { 13 | var list = new ListNode(1); 14 | list.next = new ListNode(2); 15 | list.next.next = new ListNode(3); 16 | var cycleNode = new ListNode(4); 17 | list.next.next.next = cycleNode; 18 | list.next.next.next.next = new ListNode(5); 19 | list.next.next.next.next.next = new ListNode(6); 20 | list.next.next.next.next.next.next = cycleNode; 21 | 22 | Assert.AreEqual(true, HasCycleSolution.HasCycle(list)); 23 | } 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /LeetCodeInCSharpUnitTest/UnitTest238_ProductofArrayExceptSelf.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using Microsoft.VisualStudio.TestTools.UnitTesting; 3 | using LeetCodeInCSharp; 4 | 5 | namespace LeetCodeInCSharpUnitTest 6 | { 7 | [TestClass] 8 | public class UnitTest238_ProductofArrayExceptSelf 9 | { 10 | [TestMethod] 11 | public void TestMethodProductExceptSelf() 12 | { 13 | var list1 = new int[] { 1, 2, 3, 4, 5, 6 }; 14 | var list2 = new int[] { 0, 0, 0 }; 15 | CollectionAssert.AreEqual( 16 | new int[] { 720, 360, 240, 180, 144, 120 }, 17 | ProductExceptSelfSolution.ProductExceptSelf(list1) 18 | ); 19 | CollectionAssert.AreEqual( 20 | new int[] { 0, 0, 0 }, 21 | ProductExceptSelfSolution.ProductExceptSelf(list2) 22 | ); 23 | } 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /LeetCodeInCSharp/141_LinkedListCycle.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Threading.Tasks; 6 | 7 | namespace LeetCodeInCSharp 8 | { 9 | public class HasCycleSolution 10 | { 11 | public static bool HasCycle(ListNode head) 12 | { 13 | var pre = head; 14 | var cur = head; 15 | while (cur != null && cur.next != null) 16 | { 17 | if (cur.next == head) return true; 18 | cur = cur.next; 19 | pre.next = head; 20 | pre = cur; 21 | } 22 | return false; 23 | } 24 | } 25 | 26 | 27 | public class ListNode 28 | { 29 | public int val; 30 | public ListNode next; 31 | public ListNode(int x) 32 | { 33 | val = x; 34 | next = null; 35 | } 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /LeetCodeInCSharpUnitTest/UnitTest107_LevelOrderBinaryTreeTraversalII.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using Microsoft.VisualStudio.TestTools.UnitTesting; 3 | using LeetCodeInCSharp; 4 | 5 | namespace LeetCodeInCSharpUnitTest 6 | { 7 | [TestClass] 8 | public class UnitTestLevelOrderBottom 9 | { 10 | [TestMethod] 11 | public void TestMethodLevelOrderBottom() 12 | { 13 | var tree = new TreeNode(3); 14 | tree.left = new TreeNode(9); 15 | tree.right = new TreeNode(20); 16 | tree.right.left = new TreeNode(15); 17 | tree.right.right = new TreeNode(7); 18 | 19 | var list = LevelOrderBTTII.LevelOrderBottom(tree); 20 | Assert.AreEqual(15, list[0][0]); 21 | Assert.AreEqual(7, list[0][1]); 22 | Assert.AreEqual(9, list[1][0]); 23 | Assert.AreEqual(20, list[1][1]); 24 | Assert.AreEqual(3, list[2][0]); 25 | } 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /LeetCodeInCSharp/100_SameTree.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Threading.Tasks; 6 | 7 | //Problem description: 8 | //Given two binary trees, write a function to check if they are equal or not. 9 | //Two binary trees are considered equal if they are structurally identical and the nodes have the same value. 10 | 11 | namespace LeetCodeInCSharp 12 | { 13 | public class SameTreeSolution 14 | { 15 | public static bool IsSameTree(TreeNode p, TreeNode q) 16 | { 17 | if (p == null && q == null) 18 | return true; 19 | else if ((p != null && q == null) || (p == null && q != null)) 20 | return false; 21 | else if (p.val != q.val) 22 | return false; 23 | else 24 | return IsSameTree(p.left, q.left) == true && IsSameTree(p.right, q.right) == true; 25 | } 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /LeetCodeInCSharpUnitTest/UnitTest226_InverBinaryTree.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using Microsoft.VisualStudio.TestTools.UnitTesting; 3 | using LeetCodeInCSharp; 4 | 5 | namespace LeetCodeInCSharpUnitTest 6 | { 7 | [TestClass] 8 | public class UnitTest226_InverBinaryTree 9 | { 10 | [TestMethod] 11 | public void TestMethodInvertTree() 12 | { 13 | var tree = new TreeNode(10); 14 | tree.left = new TreeNode(8); 15 | tree.right = new TreeNode(12); 16 | tree.left.left = new TreeNode(7); 17 | tree.left.right = new TreeNode(9); 18 | 19 | tree = InvertBinaryTreeSolution.InvertTree(tree); 20 | 21 | Assert.AreEqual(10, tree.val); 22 | Assert.AreEqual(8, tree.right.val); 23 | Assert.AreEqual(12, tree.left.val); 24 | Assert.AreEqual(7, tree.right.right.val); 25 | Assert.AreEqual(9, tree.right.left.val); 26 | } 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /LeetCodeInCSharp/237_DeleteNodeInALinkedList.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Threading.Tasks; 6 | 7 | //Problem description: 8 | //Write a function to delete a node (except the tail) 9 | //in a singly linked list, given only access to that node. 10 | //Supposed the linked list is 1 -> 2 -> 3 -> 4 and you 11 | //are given the third node with value 3, the linked list 12 | //should become 1 -> 2 -> 4 after calling your function. 13 | 14 | namespace LeetCodeSolutions 15 | { 16 | //Definition for singly-linked list. 17 | public class ListNode { 18 | public int val; 19 | public ListNode next; 20 | public ListNode(int x) { val = x; } 21 | } 22 | 23 | public class DeleteNodeInALinkedList 24 | { 25 | public static void DeleteNode(ListNode node) 26 | { 27 | node.val = node.next.val; 28 | node.next = node.next.next; 29 | } 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /LeetCodeInCSharp/169_MajorityElement.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Threading.Tasks; 6 | 7 | namespace LeetCodeInCSharp 8 | { 9 | public class MajorityElementSolution 10 | { 11 | //O(nlogn) 12 | public static int MajoirityElement(int[] nums) 13 | { 14 | Array.Sort(nums); 15 | return nums[nums.Length / 2]; 16 | } 17 | 18 | //O(n) 19 | public static int MajoirityElement2(int[] nums) 20 | { 21 | int max = 0; 22 | int count = 0; 23 | for (int i = 0; i < nums.Length; i++) 24 | { 25 | if (count == 0) 26 | { 27 | max = nums[i]; 28 | count++; 29 | } 30 | else if(max == nums[i]) count++; 31 | else count--; 32 | } 33 | return max; 34 | } 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /LeetCodeInCSharp/70_ClimbingStairs.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Threading.Tasks; 6 | 7 | namespace LeetCodeInCSharp 8 | { 9 | public class ClimbStairsSolution 10 | { 11 | public static int ClimbStairs(int n) 12 | { 13 | return Climb(n); 14 | } 15 | 16 | public static int Climb(int count) 17 | { 18 | if (count <= 0) return 1; 19 | if (count == 1) return 1; 20 | int a = Climb(count - 2); 21 | int b = Climb(count - 1); 22 | return a + b; 23 | } 24 | 25 | public static int ClimbStairsNoRecursive(int n) 26 | { 27 | var list = new List(); 28 | list.Add(1); 29 | list.Add(2); 30 | for (int i = 2; i < n; i++) 31 | { 32 | list.Add(list[i - 2] + list[i - 1]); 33 | } 34 | return list[n - 1]; 35 | } 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /LeetCodeInCSharp/235_LowestCommonAncestorOfABinarySearchTree.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Threading.Tasks; 6 | 7 | namespace LeetCodeInCSharp 8 | { 9 | public class LCASolution 10 | { 11 | public static TreeNode LowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) 12 | { 13 | TreeNode small, large; 14 | if (p.val < q.val) 15 | { 16 | small = p; 17 | large = q; 18 | } 19 | else 20 | { 21 | small = q; 22 | large = p; 23 | } 24 | 25 | var temp = root; 26 | while (!(temp.val >= small.val && temp.val <= large.val)) 27 | { 28 | if (temp.val < small.val) 29 | temp = temp.right; 30 | else 31 | temp = temp.left; 32 | } 33 | return temp; 34 | } 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /LeetCodeInCSharpUnitTest/UnitTest258_AddDigits.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using Microsoft.VisualStudio.TestTools.UnitTesting; 3 | using LeetCodeInCSharp; 4 | 5 | namespace LeetCodeInCSharpUnitTest 6 | { 7 | [TestClass] 8 | public class UnitTest258_AddDigits 9 | { 10 | [TestMethod] 11 | public void TestMethodAddDigits() 12 | { 13 | Assert.AreEqual(6, AddDigitsSolution.AddDigits(12345)); 14 | Assert.AreEqual(0, AddDigitsSolution.AddDigits(0)); 15 | Assert.AreEqual(9, AddDigitsSolution.AddDigits(999999)); 16 | Assert.AreEqual(2, AddDigitsSolution.AddDigits(11)); 17 | } 18 | 19 | [TestMethod] 20 | public void TestMethodAddDigitsRec() 21 | { 22 | Assert.AreEqual(6, AddDigitsSolution.AddDigitsRec(12345)); 23 | Assert.AreEqual(0, AddDigitsSolution.AddDigitsRec(0)); 24 | Assert.AreEqual(9, AddDigitsSolution.AddDigitsRec(999999)); 25 | Assert.AreEqual(2, AddDigitsSolution.AddDigitsRec(11)); 26 | } 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /LeetCodeInCSharpUnitTest/UnitTest235_LowestCommonAncestorOfABinarySearchTree.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using Microsoft.VisualStudio.TestTools.UnitTesting; 3 | using LeetCodeInCSharp; 4 | 5 | namespace LeetCodeInCSharpUnitTest 6 | { 7 | [TestClass] 8 | public class UnitTest235_LowestCommonAncestorOfABinarySearchTree 9 | { 10 | [TestMethod] 11 | public void TestMethodLowestCommonAncestor() 12 | { 13 | var tree0 = new TreeNode(20); 14 | tree0.left = new TreeNode(10); 15 | tree0.right = new TreeNode(30); 16 | tree0.left.left = new TreeNode(5); 17 | tree0.left.right = new TreeNode(15); 18 | tree0.right.left = new TreeNode(25); 19 | tree0.right.right = new TreeNode(35); 20 | tree0.left.left.left = new TreeNode(2); 21 | 22 | Assert.AreEqual(20, LCASolution.LowestCommonAncestor(tree0, tree0.left.left.left, tree0.right.right).val); 23 | Assert.AreEqual(5, LCASolution.LowestCommonAncestor(tree0, tree0.left.left.left, tree0.left.left).val); 24 | } 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /LeetCodeInCSharp/122_BestTimeToBuyAndSellStockII.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Threading.Tasks; 6 | 7 | //Problem description: 8 | //Say you have an array for which the ith element 9 | //is the price of a given stock on day i. 10 | //Design an algorithm to find the maximum profit. 11 | //You may complete as many transactions as you like 12 | //(ie, buy one and sell one share of the stock multiple times). 13 | //However, you may not engage in multiple transactions at the 14 | //same time (ie, you must sell the stock before you buy again). 15 | 16 | namespace LeetCodeInCSharp 17 | { 18 | public class StockTradeII 19 | { 20 | public static int MaxProfit(int[] prices) 21 | { 22 | int maxProfit = 0; 23 | for (int i = 1; i < prices.Length; i++) 24 | { 25 | if (prices[i] > prices[i - 1]) 26 | { 27 | maxProfit += prices[i] - prices[i - 1]; 28 | } 29 | } 30 | return maxProfit; 31 | } 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /LeetCodeInCSharp/258_AddDigits.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Threading.Tasks; 6 | 7 | //Problem descriptiton: 8 | //Given a non-negative integer num, repeatedly add all its digits until the result has only one digit. 9 | //For example: 10 | //Given num = 38, the process is like: 3 + 8 = 11, 1 + 1 = 2. Since 2 has only one digit, return it. 11 | 12 | namespace LeetCodeInCSharp 13 | { 14 | public class AddDigitsSolution 15 | { 16 | //O(1) way 17 | public static int AddDigits(int num) 18 | { 19 | return num - (int)((num - 1) / 9) * 9; 20 | //an alternative to write it 21 | //return num == 0 ? 0 : (num % 9 == 0 ? 9 : num % 9); 22 | } 23 | 24 | //recursive way 25 | public static int AddDigitsRec(int num) 26 | { 27 | if (num < 10) return num; 28 | int sum = 0; 29 | while (num != 0) 30 | { 31 | sum += num % 10; 32 | num /= 10; 33 | } 34 | return AddDigitsRec(sum); 35 | } 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /LeetCodeInCSharpUnitTest/UnitTest237_DeleteNodeInALinkedList.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using Microsoft.VisualStudio.TestTools.UnitTesting; 3 | using LeetCodeSolutions; 4 | 5 | namespace LeetCodeTests 6 | { 7 | [TestClass] 8 | public class UnitTest237_DeleteNodeInALinkedList 9 | { 10 | [TestMethod] 11 | public void TestMethodDeleteNode() 12 | { 13 | //generate a linkedList 1 -> 2 -> 3 -> 4 14 | var linkedList = new ListNode(1); 15 | var buffer = linkedList; 16 | for (int i = 2; i < 5; i++) 17 | { 18 | buffer.next = new ListNode(i); 19 | buffer = buffer.next; 20 | } 21 | 22 | //select the node with value 3 23 | buffer = linkedList.next.next; 24 | Console.WriteLine(buffer.val); 25 | DeleteNodeInALinkedList.DeleteNode(buffer); 26 | 27 | //s 28 | Assert.AreEqual(1, linkedList.val); 29 | Assert.AreEqual(2, linkedList.next.val); 30 | Assert.AreEqual(4, linkedList.next.next.val); 31 | Assert.AreEqual(null, linkedList.next.next.next); 32 | } 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /LeetCodeInCSharp/242_ValidAnagram.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Threading.Tasks; 6 | 7 | namespace LeetCodeInCSharp 8 | { 9 | public class ValidAnagramSolution 10 | { 11 | public static bool IsAnagram(string s, string t) 12 | { 13 | char[] sArr = s.ToCharArray(); 14 | char[] tArr = t.ToCharArray(); 15 | Array.Sort(sArr); 16 | Array.Sort(tArr); 17 | var newS = new string(sArr); 18 | var newT = new string(tArr); 19 | return newS == newT; 20 | } 21 | 22 | public static bool IsAnagram2(string s, string t) 23 | { 24 | int[] alphabet = new int[26]; 25 | foreach (var byt in Encoding.ASCII.GetBytes(s)) 26 | { 27 | alphabet[byt - 97]++; 28 | } 29 | foreach (var byt in Encoding.ASCII.GetBytes(t)) 30 | { 31 | alphabet[byt - 97]--; 32 | } 33 | foreach (var count in alphabet) 34 | if (count != 0) return false; 35 | return true; 36 | } 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /LeetCodeInCSharpUnitTest/UnitTest94_BinaryTreeInOrderTraversal.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using Microsoft.VisualStudio.TestTools.UnitTesting; 4 | using LeetCodeInCSharp; 5 | 6 | namespace LeetCodeInCSharpUnitTest 7 | { 8 | [TestClass] 9 | public class UnitTest94_BinaryTreeInOrderTraversal 10 | { 11 | [TestMethod] 12 | public void TestMethodInorderTraversal() 13 | { 14 | var tree = new TreeNode(1); 15 | tree.left = new TreeNode(2); 16 | tree.right = new TreeNode(3); 17 | tree.right.left = new TreeNode(4); 18 | tree.right.right = new TreeNode(5); 19 | 20 | IList list = new List { 2, 1, 4, 3, 5 }; 21 | for (int i = 0; i < InOrderTraversalSolution.InorderTraversal(tree).Count; i++) 22 | { 23 | Assert.AreEqual(list[i], InOrderTraversalSolution.InorderTraversal(tree)[i]); 24 | } 25 | for (int i = 0; i < InOrderTraversalSolution.StackInorderTraversal(tree).Count; i++) 26 | { 27 | Assert.AreEqual(list[i], InOrderTraversalSolution.StackInorderTraversal(tree)[i]); 28 | } 29 | } 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /LeetCodeInCSharpUnitTest/UnitTest144_BinaryTreePreOrderTraversal.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using Microsoft.VisualStudio.TestTools.UnitTesting; 4 | using LeetCodeInCSharp; 5 | 6 | namespace LeetCodeInCSharpUnitTest 7 | { 8 | [TestClass] 9 | public class UnitTest144_BinaryTreePreOrderTraversal 10 | { 11 | [TestMethod] 12 | public void TestMethodPreOrderTraversal() 13 | { 14 | var tree = new TreeNode(1); 15 | tree.left = new TreeNode(2); 16 | tree.right = new TreeNode(3); 17 | tree.right.left = new TreeNode(4); 18 | tree.right.right = new TreeNode(5); 19 | 20 | IList list = new List { 1, 2, 3, 4, 5 }; 21 | 22 | for (int i = 0; i < PreOrderTraversalSolution.PreorderTraversal(tree).Count; i++) 23 | { 24 | Assert.AreEqual(i + 1, PreOrderTraversalSolution.PreorderTraversal(tree)[i]); 25 | } 26 | 27 | for (int i = 0; i < PreOrderTraversalSolution.StackPreorderTraversal(tree).Count; i++) 28 | { 29 | Assert.AreEqual(i + 1, PreOrderTraversalSolution.StackPreorderTraversal(tree)[i]); 30 | } 31 | } 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /LeetCodeInCSharp/35_SearchInsertPosition.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Threading.Tasks; 6 | 7 | namespace LeetCodeInCSharp 8 | { 9 | public class SearchInsertSolution 10 | { 11 | //linear search 168ms 12 | public static int SearchInsert(int[] nums, int target) 13 | { 14 | for (int i = 0; i < nums.Length; i++) 15 | if (target <= nums[i]) return i; 16 | return nums.Length; 17 | } 18 | 19 | //binary search 156ms 20 | public static int SearchInsertBinary(int[] nums, int target) 21 | { 22 | int low = 0; 23 | int high = nums.Length - 1; 24 | int mid = high / 2; 25 | while (high != low) 26 | { 27 | if (target == nums[mid]) return mid; 28 | else if (target < nums[mid]) 29 | { 30 | high = mid; 31 | mid = (high - low) / 2 + low; 32 | } 33 | else 34 | { 35 | low = mid + 1; 36 | mid = (high - low) / 2 + low; 37 | } 38 | } 39 | return target > nums[high] ? high + 1 : high; 40 | } 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /LeetCodeInCSharpUnitTest/UnitTest13_RomanToInteger.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using Microsoft.VisualStudio.TestTools.UnitTesting; 4 | using LeetCodeInCSharp; 5 | 6 | namespace LeetCodeInCSharpUnitTest 7 | { 8 | [TestClass] 9 | public class UnitTest13_RomanToInteger 10 | { 11 | [TestMethod] 12 | public void TestMethodRomanToInt() 13 | { 14 | var list = new Dictionary(); 15 | list[1] = "I"; 16 | list[2] = "II"; 17 | list[3] = "III"; 18 | list[4] = "IV"; 19 | list[5] = "V"; 20 | list[6] = "VI"; 21 | list[7] = "VII"; 22 | list[8] = "VIII"; 23 | list[9] = "IX"; 24 | list[10] = "X"; 25 | list[14] = "XIV"; 26 | list[19] = "XIX"; 27 | list[20] = "XX"; 28 | list[49] = "XLIX"; 29 | list[50] = "L"; 30 | list[99] = "XCIX"; 31 | list[100] = "C"; 32 | list[499] = "CDXCIX"; 33 | list[500] = "D"; 34 | list[999] = "CMXCIX"; 35 | list[1000] = "M"; 36 | list[3999] = "MMMCMXCIX"; 37 | foreach (var pair in list) 38 | Assert.AreEqual(pair.Key, RomanToIntSolution.RomanToInt(pair.Value)); 39 | } 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /LeetCodeInCSharpUnitTest/UnitTest100_SameTree.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using Microsoft.VisualStudio.TestTools.UnitTesting; 3 | using LeetCodeInCSharp; 4 | 5 | namespace LeetCodeInCSharpUnitTest 6 | { 7 | [TestClass] 8 | public class UnitTest100_SameTree 9 | { 10 | [TestMethod] 11 | public void TestMethodIsSameTree() 12 | { 13 | var tree1 = new TreeNode(0); 14 | var tree2 = new TreeNode(0); 15 | var tree3 = new TreeNode(0); 16 | var tree4 = new TreeNode(1); 17 | 18 | tree1.left = new TreeNode(1); 19 | tree1.right = new TreeNode(1); 20 | tree1.left.left = new TreeNode(2); 21 | 22 | tree2.left = new TreeNode(1); 23 | tree2.right = new TreeNode(1); 24 | tree2.left.left = new TreeNode(2); 25 | 26 | tree3.left = new TreeNode(1); 27 | tree3.right = new TreeNode(1); 28 | tree3.left.right = new TreeNode(2); 29 | 30 | tree1.left = new TreeNode(1); 31 | tree1.right = new TreeNode(1); 32 | tree1.left.left = new TreeNode(2); 33 | 34 | Assert.AreEqual(true, SameTreeSolution.IsSameTree(tree1, tree2)); 35 | Assert.AreEqual(false, SameTreeSolution.IsSameTree(tree1, tree3)); 36 | Assert.AreEqual(false, SameTreeSolution.IsSameTree(tree1, tree4)); 37 | 38 | } 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /LeetCodeInCSharpUnitTest/UnitTest35_SearchInsertPosition.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using Microsoft.VisualStudio.TestTools.UnitTesting; 3 | using LeetCodeInCSharp; 4 | 5 | namespace LeetCodeInCSharpUnitTest 6 | { 7 | [TestClass] 8 | public class UnitTest35_SearchInsertPosition 9 | { 10 | [TestMethod] 11 | public void TestMethodSearchInsert() 12 | { 13 | var arr1 = new int[] { 1 }; 14 | var res = SearchInsertSolution.SearchInsert(arr1, 0); 15 | Assert.AreEqual(0, res); 16 | } 17 | 18 | [TestMethod] 19 | public void TestMethodSearchInseartBinary() 20 | { 21 | var arr1 = new int[] { 1 }; 22 | var res1 = SearchInsertSolution.SearchInsertBinary(arr1, 0); 23 | var res2 = SearchInsertSolution.SearchInsertBinary(arr1, 2); 24 | Assert.AreEqual(0, res1); 25 | Assert.AreEqual(1, res2); 26 | var arr2 = new int[] { 1, 3, 5, 7 }; 27 | var res3 = SearchInsertSolution.SearchInsertBinary(arr2, 0); 28 | Assert.AreEqual(0, res3); 29 | var res4 = SearchInsertSolution.SearchInsertBinary(arr2, 3); 30 | Assert.AreEqual(1, res4); 31 | var res5 = SearchInsertSolution.SearchInsertBinary(arr2, 4); 32 | Assert.AreEqual(2, res5); 33 | var res6 = SearchInsertSolution.SearchInsertBinary(arr2, 8); 34 | Assert.AreEqual(4, res6); 35 | } 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /LeetCodeInCSharpUnitTest/UnitTest116_PopulatingNextRightPointersInEachNode.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using Microsoft.VisualStudio.TestTools.UnitTesting; 3 | using LeetCodeInCSharp; 4 | 5 | namespace LeetCodeInCSharpUnitTest 6 | { 7 | [TestClass] 8 | public class UnitTest116_PopulatingNextRightPointersInEachNode 9 | { 10 | [TestMethod] 11 | public void TestMethodConnectQueue() 12 | { 13 | var tree = new TreeLinkNode(0); 14 | tree.left = new TreeLinkNode(1); 15 | tree.right = new TreeLinkNode(2); 16 | tree.left.left = new TreeLinkNode(3); 17 | tree.left.right = new TreeLinkNode(4); 18 | tree.right.left = new TreeLinkNode(5); 19 | tree.right.right = new TreeLinkNode(6); 20 | 21 | ConnectSolution.ConnectQueue(tree); 22 | Assert.AreEqual("[0,#,1,2,#,3,4,5,6,#]", tree.ToString()); 23 | } 24 | 25 | [TestMethod] 26 | public void TestMethodConnectRecursive() 27 | { 28 | var tree = new TreeLinkNode(0); 29 | tree.left = new TreeLinkNode(1); 30 | tree.right = new TreeLinkNode(2); 31 | tree.left.left = new TreeLinkNode(3); 32 | tree.left.right = new TreeLinkNode(4); 33 | tree.right.left = new TreeLinkNode(5); 34 | tree.right.right = new TreeLinkNode(6); 35 | 36 | ConnectSolution.ConnectRecursive(tree); 37 | Assert.AreEqual("[0,#,1,2,#,3,4,5,6,#]", tree.ToString()); 38 | } 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /LeetCodeInCSharp/Properties/AssemblyInfo.cs: -------------------------------------------------------------------------------- 1 | using System.Reflection; 2 | using System.Runtime.CompilerServices; 3 | using System.Runtime.InteropServices; 4 | 5 | // General Information about an assembly is controlled through the following 6 | // set of attributes. Change these attribute values to modify the information 7 | // associated with an assembly. 8 | [assembly: AssemblyTitle("LeetCodeInCSharp")] 9 | [assembly: AssemblyDescription("")] 10 | [assembly: AssemblyConfiguration("")] 11 | [assembly: AssemblyCompany("")] 12 | [assembly: AssemblyProduct("LeetCodeInCSharp")] 13 | [assembly: AssemblyCopyright("Copyright © 2015")] 14 | [assembly: AssemblyTrademark("")] 15 | [assembly: AssemblyCulture("")] 16 | 17 | // Setting ComVisible to false makes the types in this assembly not visible 18 | // to COM components. If you need to access a type in this assembly from 19 | // COM, set the ComVisible attribute to true on that type. 20 | [assembly: ComVisible(false)] 21 | 22 | // The following GUID is for the ID of the typelib if this project is exposed to COM 23 | [assembly: Guid("9b48afe5-2d62-4eaa-a168-6c9878e9cd10")] 24 | 25 | // Version information for an assembly consists of the following four values: 26 | // 27 | // Major Version 28 | // Minor Version 29 | // Build Number 30 | // Revision 31 | // 32 | // You can specify all the values or you can default the Build and Revision Numbers 33 | // by using the '*' as shown below: 34 | // [assembly: AssemblyVersion("1.0.*")] 35 | [assembly: AssemblyVersion("1.0.0.0")] 36 | [assembly: AssemblyFileVersion("1.0.0.0")] 37 | -------------------------------------------------------------------------------- /LeetCodeInCSharpUnitTest/Properties/AssemblyInfo.cs: -------------------------------------------------------------------------------- 1 | using System.Reflection; 2 | using System.Runtime.CompilerServices; 3 | using System.Runtime.InteropServices; 4 | 5 | // General Information about an assembly is controlled through the following 6 | // set of attributes. Change these attribute values to modify the information 7 | // associated with an assembly. 8 | [assembly: AssemblyTitle("LeetCodeInCSharpUnitTest")] 9 | [assembly: AssemblyDescription("")] 10 | [assembly: AssemblyConfiguration("")] 11 | [assembly: AssemblyCompany("")] 12 | [assembly: AssemblyProduct("LeetCodeInCSharpUnitTest")] 13 | [assembly: AssemblyCopyright("Copyright © 2015")] 14 | [assembly: AssemblyTrademark("")] 15 | [assembly: AssemblyCulture("")] 16 | 17 | // Setting ComVisible to false makes the types in this assembly not visible 18 | // to COM components. If you need to access a type in this assembly from 19 | // COM, set the ComVisible attribute to true on that type. 20 | [assembly: ComVisible(false)] 21 | 22 | // The following GUID is for the ID of the typelib if this project is exposed to COM 23 | [assembly: Guid("b047126d-918a-46be-b3a2-887e3333f4d3")] 24 | 25 | // Version information for an assembly consists of the following four values: 26 | // 27 | // Major Version 28 | // Minor Version 29 | // Build Number 30 | // Revision 31 | // 32 | // You can specify all the values or you can default the Build and Revision Numbers 33 | // by using the '*' as shown below: 34 | // [assembly: AssemblyVersion("1.0.*")] 35 | [assembly: AssemblyVersion("1.0.0.0")] 36 | [assembly: AssemblyFileVersion("1.0.0.0")] 37 | -------------------------------------------------------------------------------- /LeetCodeInCSharp.sln: -------------------------------------------------------------------------------- 1 | 2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio 2013 4 | VisualStudioVersion = 12.0.31101.0 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "LeetCodeInCSharp", "LeetCodeInCSharp\LeetCodeInCSharp.csproj", "{F6FE01ED-E37B-4CEA-9EAE-85F1653E5382}" 7 | EndProject 8 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "LeetCodeInCSharpUnitTest", "LeetCodeInCSharpUnitTest\LeetCodeInCSharpUnitTest.csproj", "{DD67833C-BC32-40D8-9041-71CA292394FE}" 9 | EndProject 10 | Global 11 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 12 | Debug|Any CPU = Debug|Any CPU 13 | Release|Any CPU = Release|Any CPU 14 | EndGlobalSection 15 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 16 | {F6FE01ED-E37B-4CEA-9EAE-85F1653E5382}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 17 | {F6FE01ED-E37B-4CEA-9EAE-85F1653E5382}.Debug|Any CPU.Build.0 = Debug|Any CPU 18 | {F6FE01ED-E37B-4CEA-9EAE-85F1653E5382}.Release|Any CPU.ActiveCfg = Release|Any CPU 19 | {F6FE01ED-E37B-4CEA-9EAE-85F1653E5382}.Release|Any CPU.Build.0 = Release|Any CPU 20 | {DD67833C-BC32-40D8-9041-71CA292394FE}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 21 | {DD67833C-BC32-40D8-9041-71CA292394FE}.Debug|Any CPU.Build.0 = Debug|Any CPU 22 | {DD67833C-BC32-40D8-9041-71CA292394FE}.Release|Any CPU.ActiveCfg = Release|Any CPU 23 | {DD67833C-BC32-40D8-9041-71CA292394FE}.Release|Any CPU.Build.0 = Release|Any CPU 24 | EndGlobalSection 25 | GlobalSection(SolutionProperties) = preSolution 26 | HideSolutionNode = FALSE 27 | EndGlobalSection 28 | EndGlobal 29 | -------------------------------------------------------------------------------- /LeetCodeInCSharp/144_BinaryTreePreOrderTraversal.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Threading.Tasks; 6 | 7 | namespace LeetCodeInCSharp 8 | { 9 | public class PreOrderTraversalSolution 10 | { 11 | /// 12 | /// The recursive way 13 | /// 14 | /// 15 | /// 16 | public static IList PreorderTraversal(TreeNode root) 17 | { 18 | if (root == null) return new List(); 19 | else return new List() { root.val } 20 | .Concat(PreorderTraversal(root.left)) 21 | .Concat(PreorderTraversal(root.right)) 22 | .ToList(); 23 | } 24 | 25 | /// 26 | /// The stack solution 27 | /// 28 | /// Root node of the tree 29 | /// A list of PreOrderTraversal of the tree 30 | public static IList StackPreorderTraversal(TreeNode root) 31 | { 32 | var list = new List(); 33 | var stack = new Stack(); 34 | TreeNode temp; 35 | if (root != null) stack.Push(root); 36 | while (stack.Count != 0) 37 | { 38 | temp = stack.Pop(); 39 | list.Add(temp.val); 40 | if(temp.right != null) stack.Push(temp.right); 41 | if(temp.left != null) stack.Push(temp.left); 42 | } 43 | return list; 44 | } 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /LeetCodeInCSharp/12_IntegerToRoman.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Threading.Tasks; 6 | 7 | namespace LeetCodeInCSharp 8 | { 9 | public class IntToRomanSolution 10 | { 11 | //my way 12 | public static string IntToRoman(int num) 13 | { 14 | var dic1 = new Dictionary { { 1, "I" }, { 2, "II" }, { 3, "III" }, { 4, "IV" }, { 5, "V" }, { 6, "VI" }, { 7, "VII" }, { 8, "VIII" }, { 9, "IX" }, { 0, "" } }; 15 | var dic10 = new Dictionary { { 1, "X" }, { 2, "XX" }, { 3, "XXX" }, { 4, "XL" }, { 5, "L" }, { 6, "LX" }, { 7, "LXX" }, { 8, "LXXX" }, { 9, "XC" }, { 0, "" } }; 16 | var dic100 = new Dictionary { { 1, "C" }, { 2, "CC" }, { 3, "CCC" }, { 4, "CD" }, { 5, "D" }, { 6, "DC" }, { 7, "DCC" }, { 8, "DCCC" }, { 9, "CM" }, { 0, "" } }; 17 | var dic1000 = new Dictionary { { 1, "M" }, { 2, "MM" }, { 3, "MMM" }, { 0, "" } }; 18 | 19 | return dic1000[num / 1000 % 10] + dic100[num / 100 % 10] + dic10[num / 10 % 10] + dic1[num % 10]; 20 | } 21 | 22 | //the smart way 23 | public static string IntToRoman2(int num) 24 | { 25 | int[] values = { 1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1 }; 26 | string[] strs = { "M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I" }; 27 | string roman = ""; 28 | for (int i = 0; i < values.Length; i++) 29 | { 30 | while (num >= values[i]) 31 | { 32 | num -= values[i]; 33 | roman += strs[i]; 34 | } 35 | } 36 | return roman; 37 | } 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /LeetCodeInCSharp/94_BinaryTreeInOrderTraversal.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Threading.Tasks; 6 | 7 | namespace LeetCodeInCSharp 8 | { 9 | public class InOrderTraversalSolution 10 | { 11 | //recursive solution 12 | public static IList InorderTraversal(TreeNode root) 13 | { 14 | var list = new List(); 15 | if (root == null) return list; 16 | list.AddRange(InorderTraversal(root.left)); 17 | list.Add(root.val); 18 | list.AddRange(InorderTraversal(root.right)); 19 | return list; 20 | } 21 | 22 | //stack iteration solution 23 | public static IList StackInorderTraversal(TreeNode root) 24 | { 25 | var list = new List(); 26 | if (root == null) return list; 27 | var stack = new Stack(); 28 | var temp = root; 29 | while (temp != null) 30 | { 31 | while (temp != null) 32 | { 33 | if (temp.right != null) 34 | stack.Push(temp.right); 35 | stack.Push(temp); 36 | temp = temp.left; 37 | } 38 | 39 | temp = stack.Pop(); 40 | 41 | while (stack.Count != 0 && temp.right == null) 42 | { 43 | list.Add(temp.val); 44 | temp = stack.Pop(); 45 | } 46 | 47 | list.Add(temp.val); 48 | 49 | if (stack.Count != 0) 50 | temp = stack.Pop(); 51 | else 52 | temp = null; 53 | } 54 | return list; 55 | } 56 | } 57 | } 58 | -------------------------------------------------------------------------------- /LeetCodeInCSharpUnitTest/UnitTest70_ClimbingStairs.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using Microsoft.VisualStudio.TestTools.UnitTesting; 3 | using LeetCodeInCSharp; 4 | 5 | namespace LeetCodeInCSharpUnitTest 6 | { 7 | [TestClass] 8 | public class UnitTest70_ClimbingStairs 9 | { 10 | [TestMethod] 11 | public void TestMethodClimbStairs() 12 | { 13 | Assert.AreEqual(1, ClimbStairsSolution.ClimbStairs(1)); 14 | Assert.AreEqual(2, ClimbStairsSolution.ClimbStairs(2)); 15 | Assert.AreEqual(3, ClimbStairsSolution.ClimbStairs(3)); 16 | Assert.AreEqual(5, ClimbStairsSolution.ClimbStairs(4)); 17 | Assert.AreEqual(8, ClimbStairsSolution.ClimbStairs(5)); 18 | Assert.AreEqual(13, ClimbStairsSolution.ClimbStairs(6)); 19 | Assert.AreEqual(21, ClimbStairsSolution.ClimbStairs(7)); 20 | Assert.AreEqual(34, ClimbStairsSolution.ClimbStairs(8)); 21 | Assert.AreEqual(55, ClimbStairsSolution.ClimbStairs(9)); 22 | } 23 | 24 | [TestMethod] 25 | public void TestMethodClimbStairsNoRecursive() 26 | { 27 | Assert.AreEqual(1, ClimbStairsSolution.ClimbStairsNoRecursive(1)); 28 | Assert.AreEqual(2, ClimbStairsSolution.ClimbStairsNoRecursive(2)); 29 | Assert.AreEqual(3, ClimbStairsSolution.ClimbStairsNoRecursive(3)); 30 | Assert.AreEqual(5, ClimbStairsSolution.ClimbStairsNoRecursive(4)); 31 | Assert.AreEqual(8, ClimbStairsSolution.ClimbStairsNoRecursive(5)); 32 | Assert.AreEqual(13, ClimbStairsSolution.ClimbStairsNoRecursive(6)); 33 | Assert.AreEqual(21, ClimbStairsSolution.ClimbStairsNoRecursive(7)); 34 | Assert.AreEqual(34, ClimbStairsSolution.ClimbStairsNoRecursive(8)); 35 | Assert.AreEqual(55, ClimbStairsSolution.ClimbStairsNoRecursive(9)); 36 | } 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /LeetCodeInCSharp/107_LevelOrderBinaryTreeTraversalII.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Threading.Tasks; 6 | 7 | namespace LeetCodeInCSharp 8 | { 9 | public class LevelOrderBTTII 10 | { 11 | public static IList> LevelOrderBottom(TreeNode root) 12 | { 13 | if(root == null) return new List>(); 14 | 15 | List> result = new List>(); 16 | List level = new List(); 17 | var queue = new Queue(); 18 | int height = 0; 19 | var temp = new NodeWithHeight(root,height); 20 | queue.Enqueue(temp); 21 | while(queue.Count != 0){ 22 | temp = queue.Dequeue(); 23 | if (temp.Height > height) 24 | { 25 | result.Insert(0, level); 26 | height = temp.Height; 27 | level = new List(); 28 | level.Add(temp.Node.val); 29 | } 30 | else 31 | level.Add(temp.Node.val); 32 | if (temp.Node.left != null) 33 | queue.Enqueue(new NodeWithHeight(temp.Node.left, temp.Height + 1)); 34 | if (temp.Node.right != null) 35 | queue.Enqueue(new NodeWithHeight(temp.Node.right, temp.Height + 1)); 36 | } 37 | if (level.Count != 0) 38 | result.Insert(0, level); 39 | return result; 40 | } 41 | } 42 | 43 | public class NodeWithHeight 44 | { 45 | public TreeNode Node{get; private set;} 46 | public int Height { get; private set;} 47 | public NodeWithHeight(TreeNode node, int height) 48 | { 49 | Node = node; 50 | Height = height; 51 | } 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /LeetCodeInCSharp/116_PopulatingNextRightPointersInEachNode.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Threading.Tasks; 6 | 7 | namespace LeetCodeInCSharp 8 | { 9 | public class TreeLinkNode 10 | { 11 | public int val; 12 | public TreeLinkNode left; 13 | public TreeLinkNode right; 14 | public TreeLinkNode next; 15 | public TreeLinkNode(int val) 16 | { 17 | this.val = val; 18 | left = right = next = null; 19 | } 20 | 21 | public override string ToString() 22 | { 23 | var list = new List(); 24 | var queue = new Queue(); 25 | var temp = this; 26 | queue.Enqueue(temp); 27 | while (queue.Count != 0) 28 | { 29 | temp = queue.Dequeue(); 30 | list.Add(temp.val.ToString()); 31 | if (temp.next == null) list.Add("#"); 32 | if (temp.left != null) queue.Enqueue(temp.left); 33 | if (temp.right != null) queue.Enqueue(temp.right); 34 | } 35 | return "[" + String.Join(",", list) + "]"; 36 | } 37 | } 38 | public class ConnectSolution 39 | { 40 | //BFS using queue 41 | public static void ConnectQueue(TreeLinkNode root) 42 | { 43 | if (root == null) return; 44 | var queue = new Queue(); 45 | var temp = root; 46 | queue.Enqueue(temp); 47 | while (queue.Count != 0) 48 | { 49 | temp = queue.Dequeue(); 50 | if (temp.left != null) 51 | { 52 | temp.left.next = temp.right; 53 | queue.Enqueue(temp.left); 54 | queue.Enqueue(temp.right); 55 | if (temp.next != null) temp.right.next = temp.next.left; 56 | } 57 | } 58 | } 59 | 60 | //DFS recursive 61 | public static void ConnectRecursive(TreeLinkNode root) 62 | { 63 | if (root == null) return; 64 | if (root.left != null) 65 | { 66 | root.left.next = root.right; 67 | if (root.next != null) root.right.next = root.next.left; 68 | } 69 | ConnectRecursive(root.left); 70 | ConnectRecursive(root.right); 71 | } 72 | } 73 | } 74 | -------------------------------------------------------------------------------- /LeetCodeInCSharp/13_RomanToInteger.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Threading.Tasks; 6 | 7 | namespace LeetCodeInCSharp 8 | { 9 | public class RomanToIntSolution 10 | { 11 | //O(n) solution 12 | public static int RomanToInt(string s) 13 | { 14 | var charArray = s.ToCharArray(); 15 | var sum = 0; 16 | for (int i = 0; i < charArray.Length; i++) 17 | { 18 | if (charArray[i] == 'M') 19 | sum += 1000; 20 | else if (charArray[i] == 'D') 21 | sum += 500; 22 | else if (charArray[i] == 'C') 23 | { 24 | if (i < charArray.Length - 1 && charArray[i + 1] == 'M') 25 | { 26 | sum += 900; 27 | i++; 28 | } 29 | else if (i < charArray.Length - 1 && charArray[i + 1] == 'D') 30 | { 31 | sum += 400; 32 | i++; 33 | } 34 | else sum += 100; 35 | } 36 | else if (charArray[i] == 'L') 37 | sum += 50; 38 | else if (charArray[i] == 'X') 39 | { 40 | if (i < charArray.Length - 1 && charArray[i + 1] == 'C') 41 | { 42 | sum += 90; 43 | i++; 44 | } 45 | else if (i < charArray.Length - 1 && charArray[i + 1] == 'L') 46 | { 47 | sum += 40; 48 | i++; 49 | } 50 | else sum += 10; 51 | } 52 | else if (charArray[i] == 'V') 53 | sum += 5; 54 | else if (charArray[i] == 'I') 55 | { 56 | if (i < charArray.Length - 1 && charArray[i + 1] == 'X') 57 | { 58 | sum += 9; 59 | i++; 60 | } 61 | else if (i < charArray.Length - 1 && charArray[i + 1] == 'V') 62 | { 63 | sum += 4; 64 | i++; 65 | } 66 | else sum += 1; 67 | } 68 | } 69 | return sum; 70 | } 71 | } 72 | } 73 | -------------------------------------------------------------------------------- /LeetCodeInCSharpUnitTest/UnitTest28_ImplementStrStr.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using Microsoft.VisualStudio.TestTools.UnitTesting; 3 | using LeetCodeSolutions; 4 | 5 | namespace LeetCodeTests 6 | { 7 | [TestClass] 8 | public class UnitTest28_ImplementStrStr 9 | { 10 | [TestMethod] 11 | public void TestMethodStrStrNaive() 12 | { 13 | string haystack = "This is an interesting problem."; 14 | string needle1 = ""; 15 | string needle2 = " int"; 16 | string needle3 = "probleem"; 17 | 18 | Assert.AreEqual(0, ImplementStrStr.StrStrNaive(haystack, needle1)); 19 | Assert.AreEqual(10, ImplementStrStr.StrStrNaive(haystack, needle2)); 20 | Assert.AreEqual(-1, ImplementStrStr.StrStrNaive(haystack, needle3)); 21 | } 22 | 23 | [TestMethod] 24 | public void TestMethodStrStrRabinKarp() 25 | { 26 | string haystack = "abc def"; 27 | string needle = "abc"; 28 | Assert.AreEqual(0, ImplementStrStr.StrStrRabinKarp(haystack, needle)); 29 | 30 | haystack = "abcdef"; 31 | needle = "cd"; 32 | Assert.AreEqual(2, ImplementStrStr.StrStrRabinKarp(haystack, needle)); 33 | 34 | haystack = "abcd"; 35 | needle = ""; 36 | Assert.AreEqual(0, ImplementStrStr.StrStrRabinKarp(haystack, needle)); 37 | 38 | haystack = "ab"; 39 | needle = "abc"; 40 | Assert.AreEqual(-1, ImplementStrStr.StrStrRabinKarp(haystack, needle)); 41 | 42 | haystack = "abcd efg"; 43 | needle = "hij"; 44 | Assert.AreEqual(-1, ImplementStrStr.StrStrRabinKarp(haystack, needle)); 45 | 46 | //leetcode test case 65/72 I did not pass in the first time 47 | haystack = "aaaabaaabbabbaaaaaabbabbbaaabababaaaaabbbbbbbbbbbbbbbaabbbbabbaababbbababababaaaabbbbaaabababbbaaabbaabbabbbbbababbabbaabbbabaabaaaaabbbaaaaaabaaaabababababbaabaabbaaaaaaaababbabaa"; 48 | needle = "aabbaaaabbbbaabaaabaabbaaababbabbbbbaba"; 49 | //Assert.AreEqual(-1, ImplementStrStr.StrStrRabinKarp(haystack, needle)); 50 | 51 | haystack = "baabbaaaaaaabbaaaaabbabbababaabbabbbbbabbabbbbbbabababaabbbbbaaabbbbabaababababbbaabbbbaaabbaababbbaabaabbabbaaaabababaaabbabbababbabbaaabbbbabbbbabbabbaabbbaa"; 52 | needle = "bbaaaababa"; 53 | Assert.AreEqual(107, ImplementStrStr.StrStrRabinKarp(haystack, needle)); 54 | 55 | //var token1 = haystack.Substring(107, 10); 56 | //Console.WriteLine(token1); 57 | 58 | } 59 | 60 | 61 | } 62 | } 63 | -------------------------------------------------------------------------------- /LeetCodeInCSharp/28_ImplementStrStr.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Threading.Tasks; 6 | 7 | //Problem description: 8 | //Implement strStr(). 9 | //Returns the index of the first occurrence of needle 10 | //in haystack, or -1 if needle is not part of haystack. 11 | 12 | namespace LeetCodeSolutions 13 | { 14 | public class ImplementStrStr 15 | { 16 | //The Naive String Match algorithm 17 | public static int StrStrNaive(string haystack, string needle) 18 | { 19 | if (needle.Length == 0) 20 | return 0; 21 | for (int i = 0; i < haystack.Length - needle.Length + 1; i++) 22 | { 23 | if (haystack[i] == needle[0]) 24 | { 25 | bool equal = true; 26 | for (int j = 0; j < needle.Length; j++) 27 | { 28 | if (needle[j] != haystack[i + j]) 29 | { 30 | equal = false; 31 | break; 32 | } 33 | } 34 | if (equal == true) return i; 35 | } 36 | } 37 | return -1; 38 | } 39 | 40 | public static int StrStrRabinKarp(string haystack, string needle) 41 | { 42 | int len = needle.Length; 43 | //2 special case 44 | if (haystack.Length < len) return -1; 45 | if (needle == "") return 0; 46 | 47 | //base prime number used for rabin-karp's hash function 48 | int basement = 256; 49 | //prime number used to scale down the hash value 50 | int prime = 31; 51 | //the factor used to multiply with the character to be removed from the hash 52 | int factor = (int)((Math.Pow(basement, needle.Length - 1)) % prime); 53 | 54 | //get ascii value of the needle and the initial window 55 | int needleHash = 0; 56 | int windowHash = 0; 57 | byte[] needleBytes = Encoding.ASCII.GetBytes(needle); 58 | byte[] windowBytes = Encoding.ASCII.GetBytes(haystack.Substring(0, len)); 59 | 60 | //generate hash value for both 61 | for (int i = 0; i < needle.Length; i++) 62 | { 63 | needleHash = (needleHash * basement + needleBytes[i]) % prime; 64 | windowHash = (windowHash * basement + windowBytes[i]) % prime; 65 | } 66 | 67 | //loop to find match 68 | bool findMatch = true; 69 | for (int i = 0; i < haystack.Length - len + 1; i++) 70 | { 71 | //if hash value matches, incase the hash value are not uniq, iterate through needle and window 72 | if (needleHash == windowHash) 73 | { 74 | findMatch = true; 75 | for (int j = 0; j < len; j++) 76 | { 77 | if (needle[j] != haystack[i + j]) 78 | { 79 | findMatch = false; 80 | break; 81 | } 82 | } 83 | if (findMatch == true) return i; 84 | } 85 | //move the sliding window and find the hash value for new window 86 | if (i < haystack.Length - len) 87 | { 88 | byte removeByte = Encoding.ASCII.GetBytes(haystack.Substring(i, 1))[0]; 89 | byte addByte = Encoding.ASCII.GetBytes(haystack.Substring(i + len, 1))[0]; 90 | //function of rolling hash 91 | windowHash = ((windowHash - removeByte * factor) * basement + addByte) % prime; 92 | //ensure the window hash to be positive 93 | if (windowHash < 0) windowHash += prime; 94 | } 95 | } 96 | return -1; 97 | } 98 | } 99 | } 100 | -------------------------------------------------------------------------------- /LeetCodeInCSharp/LeetCodeInCSharp.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | Debug 6 | AnyCPU 7 | {F6FE01ED-E37B-4CEA-9EAE-85F1653E5382} 8 | Library 9 | Properties 10 | LeetCodeInCSharp 11 | LeetCodeInCSharp 12 | v4.5 13 | 512 14 | 15 | 16 | true 17 | full 18 | false 19 | bin\Debug\ 20 | DEBUG;TRACE 21 | prompt 22 | 4 23 | 24 | 25 | pdbonly 26 | true 27 | bin\Release\ 28 | TRACE 29 | prompt 30 | 4 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 | 78 | 79 | 86 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | ## Ignore Visual Studio temporary files, build results, and 2 | ## files generated by popular Visual Studio add-ons. 3 | 4 | # User-specific files 5 | *.suo 6 | *.user 7 | *.userosscache 8 | *.sln.docstates 9 | 10 | # Build results 11 | [Dd]ebug/ 12 | [Dd]ebugPublic/ 13 | [Rr]elease/ 14 | [Rr]eleases/ 15 | x64/ 16 | x86/ 17 | build/ 18 | bld/ 19 | [Bb]in/ 20 | [Oo]bj/ 21 | 22 | # Roslyn cache directories 23 | *.ide/ 24 | 25 | # MSTest test Results 26 | [Tt]est[Rr]esult*/ 27 | [Bb]uild[Ll]og.* 28 | 29 | #NUNIT 30 | *.VisualState.xml 31 | TestResult.xml 32 | 33 | # Build Results of an ATL Project 34 | [Dd]ebugPS/ 35 | [Rr]eleasePS/ 36 | dlldata.c 37 | 38 | *_i.c 39 | *_p.c 40 | *_i.h 41 | *.ilk 42 | *.meta 43 | *.obj 44 | *.pch 45 | *.pdb 46 | *.pgc 47 | *.pgd 48 | *.rsp 49 | *.sbr 50 | *.tlb 51 | *.tli 52 | *.tlh 53 | *.tmp 54 | *.tmp_proj 55 | *.log 56 | *.vspscc 57 | *.vssscc 58 | .builds 59 | *.pidb 60 | *.svclog 61 | *.scc 62 | 63 | # Chutzpah Test files 64 | _Chutzpah* 65 | 66 | # Visual C++ cache files 67 | ipch/ 68 | *.aps 69 | *.ncb 70 | *.opensdf 71 | *.sdf 72 | *.cachefile 73 | 74 | # Visual Studio profiler 75 | *.psess 76 | *.vsp 77 | *.vspx 78 | 79 | # TFS 2012 Local Workspace 80 | $tf/ 81 | 82 | # Guidance Automation Toolkit 83 | *.gpState 84 | 85 | # ReSharper is a .NET coding add-in 86 | _ReSharper*/ 87 | *.[Rr]e[Ss]harper 88 | *.DotSettings.user 89 | 90 | # JustCode is a .NET coding addin-in 91 | .JustCode 92 | 93 | # TeamCity is a build add-in 94 | _TeamCity* 95 | 96 | # DotCover is a Code Coverage Tool 97 | *.dotCover 98 | 99 | # NCrunch 100 | _NCrunch_* 101 | .*crunch*.local.xml 102 | 103 | # MightyMoose 104 | *.mm.* 105 | AutoTest.Net/ 106 | 107 | # Web workbench (sass) 108 | .sass-cache/ 109 | 110 | # Installshield output folder 111 | [Ee]xpress/ 112 | 113 | # DocProject is a documentation generator add-in 114 | DocProject/buildhelp/ 115 | DocProject/Help/*.HxT 116 | DocProject/Help/*.HxC 117 | DocProject/Help/*.hhc 118 | DocProject/Help/*.hhk 119 | DocProject/Help/*.hhp 120 | DocProject/Help/Html2 121 | DocProject/Help/html 122 | 123 | # Click-Once directory 124 | publish/ 125 | 126 | # Publish Web Output 127 | *.[Pp]ublish.xml 128 | *.azurePubxml 129 | # TODO: Comment the next line if you want to checkin your web deploy settings 130 | # but database connection strings (with potential passwords) will be unencrypted 131 | *.pubxml 132 | *.publishproj 133 | 134 | # NuGet Packages 135 | *.nupkg 136 | # The packages folder can be ignored because of Package Restore 137 | **/packages/* 138 | # except build/, which is used as an MSBuild target. 139 | !**/packages/build/ 140 | # If using the old MSBuild-Integrated Package Restore, uncomment this: 141 | #!**/packages/repositories.config 142 | 143 | # Windows Azure Build Output 144 | csx/ 145 | *.build.csdef 146 | 147 | # Windows Store app package directory 148 | AppPackages/ 149 | 150 | # Others 151 | sql/ 152 | *.Cache 153 | ClientBin/ 154 | [Ss]tyle[Cc]op.* 155 | ~$* 156 | *~ 157 | *.dbmdl 158 | *.dbproj.schemaview 159 | *.pfx 160 | *.publishsettings 161 | node_modules/ 162 | 163 | # RIA/Silverlight projects 164 | Generated_Code/ 165 | 166 | # Backup & report files from converting an old project file 167 | # to a newer Visual Studio version. Backup files are not needed, 168 | # because we have git ;-) 169 | _UpgradeReport_Files/ 170 | Backup*/ 171 | UpgradeLog*.XML 172 | UpgradeLog*.htm 173 | 174 | # SQL Server files 175 | *.mdf 176 | *.ldf 177 | 178 | # Business Intelligence projects 179 | *.rdl.data 180 | *.bim.layout 181 | *.bim_*.settings 182 | 183 | # Microsoft Fakes 184 | FakesAssemblies/ 185 | 186 | # ========================= 187 | # Operating System Files 188 | # ========================= 189 | 190 | # OSX 191 | # ========================= 192 | 193 | .DS_Store 194 | .AppleDouble 195 | .LSOverride 196 | 197 | # Thumbnails 198 | ._* 199 | 200 | # Files that might appear on external disk 201 | .Spotlight-V100 202 | .Trashes 203 | 204 | # Directories potentially created on remote AFP share 205 | .AppleDB 206 | .AppleDesktop 207 | Network Trash Folder 208 | Temporary Items 209 | .apdisk 210 | 211 | # Windows 212 | # ========================= 213 | 214 | # Windows image file caches 215 | Thumbs.db 216 | ehthumbs.db 217 | 218 | # Folder config file 219 | Desktop.ini 220 | 221 | # Recycle Bin used on file shares 222 | $RECYCLE.BIN/ 223 | 224 | # Windows Installer files 225 | *.cab 226 | *.msi 227 | *.msm 228 | *.msp 229 | 230 | # Windows shortcuts 231 | *.lnk 232 | -------------------------------------------------------------------------------- /LeetCodeInCSharpUnitTest/LeetCodeInCSharpUnitTest.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Debug 5 | AnyCPU 6 | {DD67833C-BC32-40D8-9041-71CA292394FE} 7 | Library 8 | Properties 9 | LeetCodeInCSharpUnitTest 10 | LeetCodeInCSharpUnitTest 11 | v4.5 12 | 512 13 | {3AC096D0-A1C2-E12C-1390-A8335801FDAB};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} 14 | 10.0 15 | $(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion) 16 | $(ProgramFiles)\Common Files\microsoft shared\VSTT\$(VisualStudioVersion)\UITestExtensionPackages 17 | False 18 | UnitTest 19 | 20 | 21 | true 22 | full 23 | false 24 | bin\Debug\ 25 | DEBUG;TRACE 26 | prompt 27 | 4 28 | 29 | 30 | pdbonly 31 | true 32 | bin\Release\ 33 | TRACE 34 | prompt 35 | 4 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 | 78 | 79 | 80 | 81 | 82 | 83 | 84 | 85 | 86 | 87 | 88 | 89 | 90 | 91 | {f6fe01ed-e37b-4cea-9eae-85f1653e5382} 92 | LeetCodeInCSharp 93 | 94 | 95 | 96 | 97 | 98 | 99 | False 100 | 101 | 102 | False 103 | 104 | 105 | False 106 | 107 | 108 | False 109 | 110 | 111 | 112 | 113 | 114 | 115 | 122 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # LeetCodeInCSharp 2 | 3 | # List 4 | + #12 Integer to roman 5 | + #13 Roman To Integer 6 | + #28 Implement strStr() 7 | + #35 Search insert position 8 | + #53 Maximun Subarray 9 | + #66 Plus One 10 | + #70 Climbing stairs 11 | + #83 Remove duplicates from sorted list 12 | + #94 Binary tree in-order traversal 13 | + #96 Unique binary search trees 14 | + #100 Same tree 15 | + #104 Maximum depth of a binary tree 16 | + #107 Level order binary tree traversal II 17 | + #116 Populating next right pointers in each node 18 | + #122 Best Time to Buy and Sell Stock II 19 | + #136 Single number 20 | + #137 Single number II 21 | + #141 Linked list cycle 22 | + #144 Binary tree pre-order traversal 23 | + #168 ExcelSheetColumnTitle 24 | + #169 Majority element 25 | + #191 Number of 1 bits 26 | + #217 Contains duplicate 27 | + #226 Invert binary tree 28 | + #235 Lowest Common Ancestor of a Binary Search Tree 29 | + #237 Delete node in a linked list 30 | + #238 Product of array except self 31 | + #242 Valid anagram 32 | + #258 Add digits 33 | + #260 Single number III 34 | + #268 Missing number 35 | + #283 Move Zeroes 36 | + #292 Nim Game 37 | 38 | # Detail 39 | ## #12 Integer to roman 40 | **LeetCode Link**: 41 | [https://leetcode.com/problems/integer-to-roman/](https://leetcode.com/problems/integer-to-roman/) 42 | **Problem description**: 43 | Given an integer, convert it to a roman numeral. Input is guaranteed to be within the range from 1 to 3999. 44 | **Source code**: 45 | [https://github.com/scottszb1987/LeetCodeInCSharp/blob/master/LeetCodeInCSharp/12_IntegerToRoman.cs](https://github.com/scottszb1987/LeetCodeInCSharp/blob/master/LeetCodeInCSharp/12_IntegerToRoman.cs) 46 | **Detail**: 47 | -my solution: 48 | Very straight forward solution. 49 | ``` 50 | var dic1 = new Dictionary { { 1, "I" }, { 2, "II" }, { 3, "III" }, { 4, "IV" }, { 5, "V" }, { 6, "VI" }, { 7, "VII" }, { 8, "VIII" }, { 9, "IX" }, { 0, "" } }; 51 | var dic10 = new Dictionary { { 1, "X" }, { 2, "XX" }, { 3, "XXX" }, { 4, "XL" }, { 5, "L" }, { 6, "LX" }, { 7, "LXX" }, { 8, "LXXX" }, { 9, "XC" }, { 0, "" } }; 52 | var dic100 = new Dictionary { { 1, "C" }, { 2, "CC" }, { 3, "CCC" }, { 4, "CD" }, { 5, "D" }, { 6, "DC" }, { 7, "DCC" }, { 8, "DCCC" }, { 9, "CM" }, { 0, "" } }; 53 | var dic1000 = new Dictionary { { 1, "M" }, { 2, "MM" }, { 3, "MMM" }, { 0, "" } }; 54 | return dic1000[num / 1000 % 10] + dic100[num / 100 % 10] + dic10[num / 10 % 10] + dic1[num % 10]; 55 | ``` 56 | -the smarter solution, [refer to lucifer27's solution](https://leetcode.com/discuss/49870/my-java-solution-easy-to-understand): This is slower (O(N) or O(1)???since num has a upper limit???) 57 | ``` 58 | int[] values = { 1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1 }; 59 | string[] strs = { "M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I" }; 60 | string roman = ""; 61 | for (int i = 0; i < values.Length; i++) 62 | { 63 | while (num >= values[i]) 64 | { 65 | num -= values[i]; 66 | roman += strs[i]; 67 | } 68 | } 69 | return roman; 70 | ``` 71 | 72 | ## #13 Roman To Integer 73 | **LeetCode Link**: 74 | [https://leetcode.com/problems/roman-to-integer/](https://leetcode.com/problems/roman-to-integer/) 75 | **Problem description**: 76 | Given a roman numeral, convert it to an integer. Input is guaranteed to be within the range from 1 to 3999. 77 | **Source code**: 78 | [https://github.com/scottszb1987/LeetCodeInCSharp/blob/master/LeetCodeInCSharp/13_RomanToInteger.cs](https://github.com/scottszb1987/LeetCodeInCSharp/blob/master/LeetCodeInCSharp/13_RomanToInteger.cs) 79 | **Detail**: 80 | -O(N) solution: 81 | The special notation combinations in Roman numerals are ```4:IV, 9:IX, 40:XL, 90:XC, 400:CD, 900:CM```, other than that, all notations are just added together. For this solution, iterate through the whole string, once meet a specific combination list above, move the iterator forward once more. Although this method takes to many lines, its worst case time complexity is only O(N), and it does not need extra space. 82 | 83 | ## #28 Implement strStr() 84 | **LeetCode Link**: 85 | [https://leetcode.com/problems/implement-strstr/](https://leetcode.com/problems/implement-strstr/) 86 | **Problem description**: 87 | Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack. 88 | **Source code**: 89 | [https://github.com/scottszb1987/LeetCodeInCSharp/blob/master/LeetCodeInCSharp/28_ImplementStrStr.cs](https://github.com/scottszb1987/LeetCodeInCSharp/blob/master/LeetCodeInCSharp/28_ImplementStrStr.cs) 90 | **Explanation**: 91 | - Naive string search (136ms): 92 | Iterate through the ```haystack``` char by char, if the char matches the first char in ```needle```, iterate through the following chars in the ```haystack``` with the length of ```needle``` to check match. This brute force search has time complexity of O(MN). 93 | - Rabin-karp algorithm (132ms): 94 | (To be solved!!)Solution passed LeetCode test, but still confusing about the 'base' choice. Has asked on StackOverFlow. 95 | [[StackOverFlowLink]](http://stackoverflow.com/questions/32576677/issue-with-implementing-rabin-karp-algorithm-to-search-string-in-leetcode-28-im) 96 | - KMP algorithm: 97 | ...to be implemented... 98 | - Boyer- Moore algorithm: 99 | ...to be implemented... 100 | 101 | ## #35 Search insert position 102 | **LeetCode Link**: 103 | [https://leetcode.com/problems/search-insert-position/](https://leetcode.com/problems/search-insert-position/) 104 | **Problem description**: 105 | Given a sorted array and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order. You may assume no duplicates in the array. Here are few examples. 106 | ``` 107 | [1,3,5,6], 5 → 2 108 | [1,3,5,6], 2 → 1 109 | [1,3,5,6], 7 → 4 110 | [1,3,5,6], 0 → 0 111 | ``` 112 | **Source code**: 113 | [https://github.com/scottszb1987/LeetCodeInCSharp/blob/master/LeetCodeInCSharp/35_SearchInsertPosition.cs](https://github.com/scottszb1987/LeetCodeInCSharp/blob/master/LeetCodeInCSharp/35_SearchInsertPosition.cs) 114 | **Explanation**: 115 | - Linear search solution (Time: O(n), 164ms): 116 | ``` 117 | for (int i = 0; i < nums.Length; i++) 118 | if (target <= nums[i]) return i; 119 | return nums.Length; 120 | ``` 121 | - Binary search solution (Time: O(log(n)), 156ms): 122 | Loop until ```low == high```(return exact match if there is), if```target > nums[high]```, return ```high + 1```, else return ```high```. 123 | 124 | ## #53 Maximun Subarray 125 | **LeetCode Link**: 126 | [https://leetcode.com/problems/maximum-subarray/](https://leetcode.com/problems/maximum-subarray/) 127 | **Problem description**: 128 | Find the contiguous subarray within an array (containing at least one number) which has the largest sum. For example, given the array [−2,1,−3,4,−1,2,1,−5,4], the contiguous subarray [4,−1,2,1] has the largest sum = 6. 129 | **Source code**: 130 | [https://github.com/scottszb1987/LeetCodeInCSharp/blob/master/LeetCodeInCSharp/53_MaximumSubarray.cs](https://github.com/scottszb1987/LeetCodeInCSharp/blob/master/LeetCodeInCSharp/53_MaximumSubarray.cs) 131 | **Detail**: 132 | -O(n) solution (156ms), refer to [xi11's solution](https://leetcode.com/discuss/38913/o-n-time-o-1-space-dp-solution-java) 133 | Assuming we have a abstract dynamic window, this window start from 0th item with 1 length. Declare a ```max``` to store current maximum sum, a ```prev``` to store latest iterated window's sum, a ```cur``` to store current window's sum, they are all initialized to ```nums[0]```. Iterate through nums, if ```prev``` is positive, previous window is worth adding to current item, thus the window expand to current item, the current sum ```cur``` equal to previous sum + current item ```cur = prev + nums[i]```; if prev is negative, it is not worth adding to current item, the life of old window ends, start a new window begin from current item, update current sum ```cur``` to current item ```nums[i]```'s value. ```max``` is independent with this windowing process, only that every time current sum ```cur``` changes, compare with old ```max``` and update ```max``` to ```Math.Max(max,cur)```. 134 | 135 | ## #66 Plus One 136 | **LeetCode Link**: 137 | [https://leetcode.com/problems/plus-one/](https://leetcode.com/problems/plus-one/) 138 | **Problem description**: 139 | Given a non-negative number represented as an array of digits, plus one to the number. 140 | The digits are stored such that the most significant digit is at the head of the list. 141 | **Source code**: 142 | [https://github.com/scottszb1987/LeetCodeInCSharp/blob/master/LeetCodeInCSharp/66_PlusOne.cs](https://github.com/scottszb1987/LeetCodeInCSharp/blob/master/LeetCodeInCSharp/66_PlusOne.cs) 143 | **Explanation**: 144 | - Simple iteration solution(500ms): 145 | Iterate through ```digits```, from ```digits[digits.Length - 1]``` to ```digits[0]```. If current number is not 9, the loop is not worth continueing, thus just add ```1``` to it and break the loop, and return ```digits```; otherwise make current number ```0``` and continue. If nothing's returned after the loop, it means all digits are ```9```, thus create a new int array ```newDigits``` with ```Length = digits.Length + 1```, set ```newDigits[0]``` to ```1```, and return ```newDigits```. 146 | 147 | ## #70 Climbing stairs 148 | **LeetCode Link**: 149 | [https://leetcode.com/problems/climbing-stairs/](https://leetcode.com/problems/climbing-stairs/) 150 | **Problem description**: 151 | You are climbing a stair case. It takes n steps to reach to the top. 152 | Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top? 153 | **Source code**: 154 | [https://github.com/scottszb1987/LeetCodeInCSharp/blob/master/LeetCodeInCSharp/70_ClimbingStairs.cs](https://github.com/scottszb1987/LeetCodeInCSharp/blob/master/LeetCodeInCSharp/70_ClimbingStairs.cs) 155 | **Explanation**: 156 | - Fabonacci solution: 157 | for ```n = 1 : ...```, the result would be ```1, 2, 3, 5, 8, 13, 21, 34, 55```, thus you can see it is a Fabonacci sequence. Except the first 2 numbers, every number equal to: ```number[i] = number[i-2] + number[i-1]```. 158 | 159 | ## #83 remove duplicates from sorted list 160 | **LeetCode Link**: 161 | [https://leetcode.com/problems/remove-duplicates-from-sorted-list/](https://leetcode.com/problems/remove-duplicates-from-sorted-list/) 162 | **Problem description**: 163 | Given a sorted linked list, delete all duplicates such that each element appear only once. 164 | For example, 165 | Given 1->1->2, return 1->2. 166 | Given 1->1->2->3->3, return 1->2->3. 167 | **Source code**: 168 | [https://github.com/scottszb1987/LeetCodeInCSharp/blob/master/LeetCodeInCSharp/83_RemoveDuplicatesFromSortedList.cs](https://github.com/scottszb1987/LeetCodeInCSharp/blob/master/LeetCodeInCSharp/83_RemoveDuplicatesFromSortedList.cs) 169 | **Explanation**: 170 | - common solution: 171 | if ```current.val == current.next.val```, ```current.next = current.next.next```. 172 | 173 | ## #94 Binary tree in-order traversal 174 | **LeetCode Link**: 175 | [https://leetcode.com/problems/binary-tree-inorder-traversal/](https://leetcode.com/problems/binary-tree-inorder-traversal/) 176 | **Problem description**: 177 | Given a binary tree, return the inorder traversal of its nodes' values. Note: Recursive solution is trivial, could you do it iteratively? 178 | **Source code**: 179 | [https://github.com/scottszb1987/LeetCodeInCSharp/blob/master/LeetCodeInCSharp/94_BinaryTreeInOrderTraversal.cs](https://github.com/scottszb1987/LeetCodeInCSharp/blob/master/LeetCodeInCSharp/94_BinaryTreeInOrderTraversal.cs) 180 | **Explanation**: 181 | - Recursive way (524ms): 182 | ``` 183 | method inorder(root){ 184 | inorder(root.left); 185 | store root; 186 | inorder(root.right); 187 | } 188 | ``` 189 | - Stack solution: 190 | This is an iteration solution via stack. 191 | ``` 192 | root 193 | /\ 194 | /\ 195 | /\ 196 | subtree1 197 | / 198 | /\ 199 | subtree2 200 | / 201 | / 202 | ``` 203 | It treats every right child as a start of a subtree. It stores a subtree in stack, deals with it, and then track back to the latest node with right node, and goes into this subtree and deal with it. Well this is hard to explain clearly :(. 204 | - Morris traversal 205 | Seems to be the best iteration solution, to be implemented. 206 | 207 | ## #96 Unique binary search trees 208 | **LeetCode Link**: 209 | [https://leetcode.com/problems/unique-binary-search-trees/](https://leetcode.com/problems/unique-binary-search-trees/) 210 | **Problem description**: 211 | Given n, how many structurally unique BST's (binary search trees) that store values 1...n? 212 | For example, Given n = 3, there are a total of 5 unique BST's. 213 | ``` 214 | 1 3 3 2 1 215 | \ / / / \ \ 216 | 3 2 1 1 3 2 217 | / / \ \ 218 | 2 1 2 3 219 | ``` 220 | **Source code**: 221 | [https://github.com/scottszb1987/LeetCodeInCSharp/blob/master/LeetCodeInCSharp/96_UniqueBinarySearchTrees.cs](https://github.com/scottszb1987/LeetCodeInCSharp/blob/master/LeetCodeInCSharp/96_UniqueBinarySearchTrees.cs) 222 | **Detail**: 223 | - Iteration way(52ms), refer to [rain4's solution](https://leetcode.com/discuss/55761/c%23-accepted-52ms-based-on-the-quora-answer) and [Mohit modi's explanation](https://www.quora.com/Given-n-how-many-structurally-unique-BSTs-binary-search-trees-that-store-values-1-to-n-are-there): 224 | + For different root choice, you can always devide the BST into left-sub-BST and right-sub-BST. Recursively for each sub-BST we can devide it into 2 sub-BSTs. 225 | + For different root choice: 226 | 1. root == 1, 0 element on the left, n - 1 element on the right 227 | 2. root == 2, 1 element on the left, n - 2 element on the right 228 | 3. root == 3, 2 element on the left, n - 3 element on the right 229 | 4. ... 230 | 5. root == i, i - 1 element on the left, n - i element on the right 231 | 6. ... 232 | 7. root == n, n - 1 element on the left, 0 element on the right 233 | + For a BST of n nodes, we want to count all the possible root choices, thus let sum(n) represent the result, we have: 234 | ```sum(n) = sum(0)sum(n - 1) + sum(1)sum(n - 2) + sum(2)sum(n - 3) + ... + sum(i - 1)sum(n - i) + ... + sum(n - 1)sum(0)``` 235 | + Declare an array to store sum(1) to sum(n), although what we want is just sum(n), we still need to find out and store sum(1) to sum(n), because each sum is used by the next sum. To visualize each turn: 236 | 1. ```sum(1) = 1``` for a BST with only 1 node, there is only 1 possible outcome. 237 | 2. ```sum(2) = sum(0)sum(1) + sum(1)sum(0) = 1 + 1 = 2``` sum(1) is acquired from above. 238 | 3. ```sum(3) = sum(0)sum(2) + sum(1)sum(1) + sum(2)sum(0) = 2 + 1 + 2 = 5``` 239 | 4. ... 240 | At the end, we will get sum(n). 241 | 242 | ## #100 Same tree 243 | **LeetCode Link**: 244 | [https://leetcode.com/problems/same-tree/](https://leetcode.com/problems/same-tree/) 245 | **Problem description**: 246 | Given two binary trees, write a function to check if they are equal or not. 247 | Two binary trees are considered equal if they are structurally identical and the nodes have the same value. 248 | **Source code**: 249 | [https://github.com/scottszb1987/LeetCodeInCSharp/blob/master/LeetCodeInCSharp/100_SameTree.cs](https://github.com/scottszb1987/LeetCodeInCSharp/blob/master/LeetCodeInCSharp/100_SameTree.cs) 250 | **Explanation**: 251 | - Recursive way (160ms): 252 | A very straightforward one line recursive solution. 4 cases: 253 | both null -> true; 254 | one is null but the other is not -> false; 255 | both not null but value not equal -> false; 256 | else -> check children; 257 | 258 | ## #104 Maximum depth of a binary tree 259 | **LeetCode Link**: 260 | [https://leetcode.com/problems/maximum-depth-of-binary-tree/](https://leetcode.com/problems/maximum-depth-of-binary-tree/) 261 | **Problem description**: 262 | Given a binary tree, find its maximum depth. 263 | **Source code**: [https://github.com/scottszb1987/LeetCodeInCSharp/blob/master/LeetCodeInCSharp/104_MaximumDepthOfABinaryTree.cs](https://github.com/scottszb1987/LeetCodeInCSharp/blob/master/LeetCodeInCSharp/104_MaximumDepthOfABinaryTree.cs) 264 | **Explanation**: 265 | - Recursive way (164ms): 266 | A very straightforward one line recursive solution. 267 | 268 | ## #107 Level order binary tree traversal II 269 | **LeetCode Link**: 270 | [https://leetcode.com/problems/binary-tree-level-order-traversal-ii/](https://leetcode.com/problems/binary-tree-level-order-traversal-ii/) 271 | **Problem description**: 272 | Given a binary tree, return the bottom-up level order traversal of its nodes' values. (ie, from left to right, level by level from leaf to root). 273 | **Source code**: 274 | [https://github.com/scottszb1987/LeetCodeInCSharp/blob/master/LeetCodeInCSharp/107_LevelOrderBinaryTreeTraversalII.cs](https://github.com/scottszb1987/LeetCodeInCSharp/blob/master/LeetCodeInCSharp/107_LevelOrderBinaryTreeTraversalII.cs) 275 | **Explanation**: 276 | - BFS solution (502ms): 277 | Use a queue to do Breadth First Search. The way I did to check the level is creating a class called NodeWithHeight to wrap the TreeNode and a Height property. So every time instead of enqueueing a node into the queue, I wrap it and its height in a NodeWithHeight object, and enqueue this object to the queue. 278 | 279 | ## #116 Populating next right pointers in each node 280 | **LeetCode Link**: 281 | [https://leetcode.com/problems/populating-next-right-pointers-in-each-node/](https://leetcode.com/problems/populating-next-right-pointers-in-each-node/) 282 | **Problem description**: 283 | Given a binary tree: 284 | ``` 285 | struct TreeLinkNode { 286 | TreeLinkNode *left; 287 | TreeLinkNode *right; 288 | TreeLinkNode *next; 289 | } 290 | ``` 291 | Populate each next pointer to point to its next right node. If there is no next right node, the next pointer should be set to NULL. Initially, all next pointers are set to NULL. Note: You may only use constant extra space; You may assume that it is a perfect binary tree (ie, all leaves are at the same level, and every parent has two children). 292 | **Source code**: 293 | [https://github.com/scottszb1987/LeetCodeInCSharp/blob/master/LeetCodeInCSharp/116_PopulatingNextRightPointersInEachNode.cs](https://github.com/scottszb1987/LeetCodeInCSharp/blob/master/LeetCodeInCSharp/116_PopulatingNextRightPointersInEachNode.cs) 294 | **Explanation**: 295 | - BFS queue solution and DFS recursive solution (200ms): 296 | Both ways are straight forward. The simple logic they both use are: 297 | ``` 298 | if(root.left != null) root.left.next = root.right; 299 | if(root.right != null && root.next != null) root.right.next = root.next.left; 300 | ``` 301 | 302 | ## #122 Best time to buy and sell stack II 303 | **LeetCode Link**: 304 | [https://leetcode.com/problems/best-time-to-buy-and-sell-stock-ii/](https://leetcode.com/problems/best-time-to-buy-and-sell-stock-ii/) 305 | **Problem description**: 306 | Say you have an array for which the ith element is the price of a given stock on day i. 307 | Design an algorithm to find the maximum profit. You may complete as many transactions as you like (ie, buy one and sell one share of the stock multiple times). However, you may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again). 308 | **Source code**: 309 | [https://github.com/scottszb1987/LeetCodeInCSharp/blob/master/LeetCodeInCSharp/122_BestTimeToBuyAndSellStockII.cs](https://github.com/scottszb1987/LeetCodeInCSharp/blob/master/LeetCodeInCSharp/122_BestTimeToBuyAndSellStockII.cs) 310 | **Explanation**: 311 | - Iteration way (148ms): 312 | The problem description is confusing. Actually what it says is to find the maximum profit per share of a stock. Just buy at low price day (compare to day + 1) and sell at (day + 1); 313 | 314 | ## #136 Single number 315 | **LeetCode Link**: 316 | [https://leetcode.com/problems/single-number/](https://leetcode.com/problems/single-number/) 317 | **Problem description**: 318 | Given an array of integers, every element appears 319 | twice except for one. Find that single one. 320 | **Source code**: 321 | [https://github.com/scottszb1987/LeetCodeInCSharp/blob/master/LeetCodeInCSharp/136_SingleNumber.cs](https://github.com/scottszb1987/LeetCodeInCSharp/blob/master/LeetCodeInCSharp/136_SingleNumber.cs) 322 | **Detail**: 323 | - Bitwise XOR (156ms, O(n)): 324 | This solution uses 'bitwise XOR' to quickly solve the problem, each element in the array only needs to be checked once. 325 | ```^``` is the bitwise XOR in C#. For bitwise XOR: (0 XOR 0 = 0, 0 XOR 1 = 1, 1 XOR 0 = 1, 1 XOR 1 = 0). Thus the ones are not single will offset each other, only the single number will live to the end. 326 | 327 | ## #137 Single number II 328 | **LeetCode Link**: 329 | [https://leetcode.com/problems/single-number-ii/](https://leetcode.com/problems/single-number-ii/) 330 | **Problem description**: 331 | Given an array of integers, every element appears three times except for one. Find that single one. 332 | **Source code**: 333 | [https://github.com/scottszb1987/LeetCodeInCSharp/blob/master/LeetCodeInCSharp/137_SingleNumberII.cs](https://github.com/scottszb1987/LeetCodeInCSharp/blob/master/LeetCodeInCSharp/137_SingleNumberII.cs) 334 | **Explanation**: 335 | - Dictionary solution (152ms): 336 | Declare a ```Dictionary```, iterate through ```nums```, add a new ```KeyValuePair``` which ```key``` is current ```num``` and ```value``` is ```1``` to it if the number is met in the first time, or ```value ++``` if the key already exists. Then iterate through the dictionary to find the one with ```value == 1```. 337 | 338 | ## #141 Linked list cycle 339 | **LeetCode Link**: 340 | [https://leetcode.com/problems/linked-list-cycle/](https://leetcode.com/problems/linked-list-cycle/) 341 | **Problem description**: 342 | Given a linked list, determine if it has a cycle in it. Follow up: Can you solve it without using extra space? 343 | **Source code**: 344 | [https://github.com/scottszb1987/LeetCodeInCSharp/blob/master/LeetCodeInCSharp/141_LinkedListCycle.cs](https://github.com/scottszb1987/LeetCodeInCSharp/blob/master/LeetCodeInCSharp/141_LinkedListCycle.cs) 345 | **Explanation**: 346 | - Best way so far (156mms), refer to [[huxijiuhao's solution]](https://leetcode.com/discuss/54343/simple-and-easy-understanding-java-solution-time-n-space-o-1): 347 | The key to solve this problem is to find a way to track all visited nodes. Recording them causes extra space, the simpler way is to give all visited nodes an uniform feature. "huxijiuhao"'s solution modify all visited nodes' ```next``` pointer points to the ```head```, so during the traversal once you have node points to any of the nodes you visited, it will point to the ```head```. The time complexity is O(n), and space is O(1). (This solution breaks the linked list, but the question does not have any consideration on this, so this is all good) 348 | 349 | ## #144 Binary tree pre-order traversal 350 | **LeetCode Link**: 351 | [https://leetcode.com/problems/binary-tree-preorder-traversal/](https://leetcode.com/problems/binary-tree-preorder-traversal/) 352 | **Problem description**: 353 | Given a binary tree, return the preorder traversal of its nodes' values. Note: Recursive solution is trivial, could you do it iteratively? 354 | **Source code**: 355 | [https://github.com/scottszb1987/LeetCodeInCSharp/blob/master/LeetCodeInCSharp/144_BinaryTreePreOrderTraversal.cs](https://github.com/scottszb1987/LeetCodeInCSharp/blob/master/LeetCodeInCSharp/144_BinaryTreePreOrderTraversal.cs) 356 | **Explanation**: 357 | - Recursion way (508ms): 358 | ``` 359 | method preorder(root){ 360 | store root; 361 | preorder(root.left); 362 | preorder(root.right); 363 | } 364 | ``` 365 | - Stack solution (520ms): 366 | ``` 367 | method preorder(root){ 368 | stack.push(root); 369 | while(stack not empty){ 370 | temp = stack.pop; 371 | list.add(temp); 372 | stack.push(temp.right); 373 | stack.push(temp.left); 374 | } 375 | return list; 376 | } 377 | ``` 378 | 379 | ## #168 Excel sheet column title 380 | **LeetCode Link**: 381 | [https://leetcode.com/problems/excel-sheet-column-title/](https://leetcode.com/problems/excel-sheet-column-title/) 382 | **Problem description**: 383 | Given a positive integer, return its corresponding column title as appear in an Excel sheet. 384 | ``` 385 | A -> 1 386 | B -> 2 387 | C -> 3 388 | ... 389 | Z -> 26 390 | AA -> 27 391 | AB -> 28 392 | ``` 393 | **Source code**: 394 | [https://github.com/scottszb1987/LeetCodeInCSharp/blob/master/LeetCodeInCSharp/168_ExcelSheetColumnTitle.cs](https://github.com/scottszb1987/LeetCodeInCSharp/blob/master/LeetCodeInCSharp/168_ExcelSheetColumnTitle.cs) 395 | **Explanation**: 396 | - Modulo solution (48ms): 397 | This problemm is actually converting a ```0``` started 10-scale system to a ```1``` started 26-scale system. 398 | ```number % 26``` gives a remainder to map character. ```'A'``` is #65 in the ASCII table. Thus use ```remainder + 65``` to map character in the ASCII table. 399 | Because ```26 % 26``` leads to 0 which cannot used to map ```'Z'```, I used '0 - 25' instead of '1 - 26' to map 'A - Z'. 400 | Thus in every execution in the loop, do ```n--;``` at the begining. 401 | 402 | ## #169 Majority element 403 | **LeetCode Link**: 404 | [https://leetcode.com/problems/majority-element/](https://leetcode.com/problems/majority-element/) 405 | **Problem description**: 406 | Given an array of size n, find the majority element. The majority element is the element that appears more than ⌊ n/2 ⌋ times. You may assume that the array is non-empty and the majority element always exist in the array. 407 | **Source code**: 408 | [https://github.com/scottszb1987/LeetCodeInCSharp/blob/master/LeetCodeInCSharp/169_MajorityElement.cs](https://github.com/scottszb1987/LeetCodeInCSharp/blob/master/LeetCodeInCSharp/169_MajorityElement.cs) 409 | **Explanation**: 410 | - Sorting 2-line solution (152ms): 411 | Sort the array first, no matter if the majority items are larger or small, simply pick the item in the middle ((n/2 + 1)th item if even numbers). Since the C# ```Array.Sort()``` uses quicksort algorithm, the time complexity would be O(nlogn). 412 | - Iteration solution (152ms), refer to [[andy-sheng's solution]](https://leetcode.com/discuss/45660/my-o-n-time-and-o-1-space-solution-in-c) 413 | This method provides O(n) time complexity. 414 | 415 | ## #171 Excel sheet column number 416 | **LeetCode Link**: 417 | [https://leetcode.com/problems/excel-sheet-column-number/](https://leetcode.com/problems/excel-sheet-column-number/) 418 | **Problem description**: 419 | Given a column title as appear in an Excel sheet, return its corresponding column number. 420 | ``` 421 | A -> 1 422 | B -> 2 423 | C -> 3 424 | ... 425 | Z -> 26 426 | AA -> 27 427 | AB -> 28 428 | ``` 429 | **Source code**: 430 | [https://github.com/scottszb1987/LeetCodeInCSharp/blob/master/LeetCodeInCSharp/171_ExcelSheetColumnNumber.cs](https://github.com/scottszb1987/LeetCodeInCSharp/blob/master/LeetCodeInCSharp/171_ExcelSheetColumnNumber.cs) 431 | **Explanation**: 432 | - Common way (164ms): 433 | Split string into charArray, iterate through, each item times corresbonding 26's power and add to the sum. 434 | 435 | ## #191 Number of 1 bits 436 | **LeetCode Link**: 437 | [https://leetcode.com/problems/number-of-1-bits/](https://leetcode.com/problems/number-of-1-bits/) 438 | **Problem description**: 439 | Write a function that takes an unsigned integer and returns the number of '1' bits it has (also known as the Hamming weight). 440 | For example, the 32-bit integer '11' has binary representation 00000000000000000000000000001011, so the function should return 3. 441 | **Source code**: 442 | [https://github.com/scottszb1987/LeetCodeInCSharp/blob/master/LeetCodeInCSharp/191_NumberOf1Bits.cs](https://github.com/scottszb1987/LeetCodeInCSharp/blob/master/LeetCodeInCSharp/191_NumberOf1Bits.cs) 443 | **Explanation**: 444 | - Bitwise shift and modulo (56ms): 445 | do ```n % 2```, will actually return the LSB of n in binary. Add this value to the result, and shift ```n``` 1 bit to the right. Loop until ```n``` equals 0. 446 | 447 | ## #217 Contains duplicate 448 | **LeetCode Link**: 449 | [https://leetcode.com/problems/contains-duplicate/](https://leetcode.com/problems/contains-duplicate/) 450 | **Problem description**: 451 | Given an array of integers, find if the array contains any duplicates. Your function should return true if any value appears at least twice in the array, and it should return false if every element is distinct. 452 | **Source code**: 453 | [https://github.com/scottszb1987/LeetCodeInCSharp/blob/master/LeetCodeInCSharp/217_ContainsDuplicate.cs](https://github.com/scottszb1987/LeetCodeInCSharp/blob/master/LeetCodeInCSharp/217_ContainsDuplicate.cs) 454 | **Explanation**: 455 | - Via hashset solution (O(n), 176ms): 456 | In C# .NET, 2 features of Hashset are used this problem. 1st, each element in a hashset is unique, duplicate adding will return false; 2nd, the searching time complexity is O(1), thus the adding time complexity is O(1). To solve this problem, declare a ```Hashset hashset```, iterate through the given ```nums``` and add each item to ```hashset```, return true if ```hashset.Add()``` returns false. 457 | 458 | ## #226 Invert binary tree 459 | **LeetCode Link**: 460 | [https://leetcode.com/problems/invert-binary-tree/](https://leetcode.com/problems/invert-binary-tree/) 461 | **Problem description**: 462 | Invert a binary tree. 463 | **Source code**: 464 | [https://github.com/scottszb1987/LeetCodeInCSharp/blob/master/LeetCodeInCSharp/226_InvertBinaryTree.cs](https://github.com/scottszb1987/LeetCodeInCSharp/blob/master/LeetCodeInCSharp/226_InvertBinaryTree.cs) 465 | **Explanation**: 466 | - Recursive way (160ms): 467 | Feel sorry for Max Howell. I might get nervous too. 468 | 469 | ## #235 Lowest Common Ancestor of a Binary Search Tree 470 | **LeetCode Link**: 471 | [https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-search-tree/](https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-search-tree/) 472 | **Problem description**: 473 | Given a binary search tree (BST), find the lowest common ancestor (LCA) of two given nodes in the BST. 474 | **Source code**: 475 | [https://github.com/scottszb1987/LeetCodeInCSharp/blob/master/LeetCodeInCSharp/235_LowestCommonAncestorOfABinarySearchTree.cs](https://github.com/scottszb1987/LeetCodeInCSharp/blob/master/LeetCodeInCSharp/235_LowestCommonAncestorOfABinarySearchTree.cs) 476 | **Explanation**: 477 | - traversal solution(188ms): 478 | To find the lowest common ancestor, it is actually looking for the first node that match the conditions that both (<=) than the small node and (>=) than the large node at the same time. 479 | 480 | ## #237 Delete node in a linked list 481 | **LeetCode Link**: 482 | [https://leetcode.com/problems/delete-node-in-a-linked-list/](https://leetcode.com/problems/delete-node-in-a-linked-list/) 483 | **Problem description**: 484 | Write a function to delete a node (except the tail) 485 | in a singly linked list, given only access to that node. 486 | Supposed the linked list is 1 -> 2 -> 3 -> 4 and you 487 | are given the third node with value 3, the linked list 488 | should become 1 -> 2 -> 4 after calling your function. 489 | **Source code**: 490 | [https://github.com/scottszb1987/LeetCodeInCSharp/blob/master/LeetCodeInCSharp/237_DeleteNodeInALinkedList.cs](https://github.com/scottszb1987/LeetCodeInCSharp/blob/master/LeetCodeInCSharp/237_DeleteNodeInALinkedList.cs) 491 | **Explanation**: 492 | - 2 line solution(172ms): 493 | The list pointer is not provided, thus you cannot iterate through the list, and you are not given the previous ```next``` pointer. This problem needs an alternative way to delete the node. 494 | ```... ---> currentNodeToBeDeleted(node 0) ---> node1 ---> node2 ---> ...``` 495 | To delete node0, copy the value of node1 to node0, change node0's ```next``` to point to node2. 496 | Thus node0 now holds the properties of node1, and the node actually being discarded on the memory is node1. 497 | 498 | ## #238 Product of array except self 499 | **LeetCode Link**: 500 | [https://leetcode.com/problems/product-of-array-except-self/](https://leetcode.com/problems/product-of-array-except-self/) 501 | **Problem description**: 502 | Given an array of n integers where n > 1, nums, return an array output such that output[i] is equal to the product of all the elements of nums except nums[i]. Solve it without division and in O(n). For example, given [1,2,3,4], return [24,12,8,6]. Follow up: Could you solve it with constant space complexity? (Note: The output array does not count as extra space for the purpose of space complexity analysis.) 503 | **Source code**: 504 | [https://github.com/scottszb1987/LeetCodeInCSharp/blob/master/LeetCodeInCSharp/238_ProductofArrayExceptSelf.cs](https://github.com/scottszb1987/LeetCodeInCSharp/blob/master/LeetCodeInCSharp/238_ProductofArrayExceptSelf.cs) 505 | **Explanation**: 506 | - The best solution so far (512ms), refer to [[areshead's solution]](https://leetcode.com/discuss/53781/my-solution-beats-100%25-java-solutions) : 507 | What it does is to iterate through the ```nums``` array twice. Firstly set ```pre``` and ```post``` to 1, they are the product before ```(i)th``` item and product after ```(i)th``` item. In the first loop, iterate through ```nums``` incrementally, set ```result[i]``` to ```pre``` and then update the ```pre``` by ```pre *= nums[i]```. In the second loop, iterate through ```nums``` decrementally, update ```result[i]``` by ```result[i] *= post``` and then update ```post``` by ```post *= nums[i]```. 508 | 509 | ## #242 Valid anagram 510 | **LeekCode Link**: 511 | [https://leetcode.com/problems/valid-anagram/](https://leetcode.com/problems/valid-anagram/) 512 | **Problem description**: 513 | Given two strings s and t, write a function to determine if t is an anagram of s. 514 | For example, 515 | s = "anagram", t = "nagaram", return true. 516 | s = "rat", t = "car", return false. 517 | **Source code**: 518 | [https://github.com/scottszb1987/LeetCodeInCSharp/blob/master/LeetCodeInCSharp/242_ValidAnagram.cs](https://github.com/scottszb1987/LeetCodeInCSharp/blob/master/LeetCodeInCSharp/242_ValidAnagram.cs) 519 | **Detail**: 520 | - sorting solution: 521 | Alphabetically sort each string, and commpare them. This method is relatively slow, each sorting (quick sort) has O(nlogn) time complexity.To sort a string: 522 | ``` 523 | char[] a = s.ToCharArray(); 524 | Array.Sort(a); 525 | return new string(a); 526 | ``` 527 | 528 | - an O(n) solution (132ms), refer to [零一's solution](https://leetcode.com/discuss/57355/0ms-c-solution-o-n-time): 529 | Declare an int array ```alphabet``` with 26 Length, that each one related to an character in the alphabet table. Iterate through the 1st string, ++ the value at the corresbonding slot in ```alphabet```, then iterate through the 2nd string, -- the value at the corresbonding slot in ```alphabet```, after this, if the value of each slot in ```alphabet``` is 0, then return true, otherwise return false. 530 | 531 | 532 | ## #258 Add digits 533 | **LeekCode Link**: 534 | [https://leetcode.com/problems/add-digits/](https://leetcode.com/problems/add-digits/) 535 | **Problem description**: 536 | Given a non-negative integer num, repeatedly add all its digits until the result has only one digit. 537 | For example: given num = 38, the process is like: 3 + 8 = 11, 1 + 1 = 2. Since 2 has only one digit, return it. 538 | **Source code**: 539 | [https://github.com/scottszb1987/LeetCodeInCSharp/blob/master/LeetCodeInCSharp/258_AddDigits.cs](https://github.com/scottszb1987/LeetCodeInCSharp/blob/master/LeetCodeInCSharp/258_AddDigits.cs) 540 | **Explanation**: 541 | - The best solution with O(1) time complexity: 542 | [[Wikipedia reference]](https://en.wikipedia.org/wiki/Digital_root) 543 | In short words, "If a number produces a digital root of exactly 9, then the number is a multiple of 9." 544 | ```result = num - root((num - 1) / 9) * 9;``` 545 | - Recursive way(68ms): 546 | Return the num if num < 10, else just calculate the sum and pass as parameter to itself. 547 | Notice that you do not have to convert ```num``` to string, there is a simpler way: [[reference]](http://stackoverflow.com/questions/478968/sum-of-digits-in-c-sharp) 548 | ```sum = 0; 549 | while (n != 0) { 550 | sum += n % 10; 551 | n /= 10; 552 | }``` 553 | 554 | ## #260 Single number III 555 | **LeetCode Link**: 556 | [https://leetcode.com/problems/single-number-iii/](https://leetcode.com/problems/single-number-iii/) 557 | **Problem description**: 558 | Given an array of numbers nums, in which exactly two elements appear only once and all the other elements appear exactly twice. Find the two elements that appear only once. 559 | For example: Given nums = [1, 2, 1, 3, 2, 5], return [3, 5]. 560 | **Source code**: 561 | [https://github.com/scottszb1987/LeetCodeInCSharp/blob/master/LeetCodeInCSharp/260_SingleNumberIII.cs](https://github.com/scottszb1987/LeetCodeInCSharp/blob/master/LeetCodeInCSharp/260_SingleNumberIII.cs) 562 | **Explanation**: 563 | - Bitwise way (564ms): 564 | 1. Get the bitwise XOR result of the array. 565 | For the numbers in pair, the XOR result will be 0. Thus after doing XOR one by one for the whole array, the result will be the XOR of the 2 single numbers, assume it's called ```aXORb```. 566 | 2. Get the last set bit of the ```aXORb```. 567 | Because a and b are distinct, ```aXORb``` will have at least 1 bit is set (is 1). We need to find one of the set bit. 568 | Why? Because at this specific bit, one of ```a``` and ```b``` would be 1 (let's say ```a```), and the other must be 0 (let's say ```b```), and use this feature we could group up all the numbers in the array into 2 groups. 569 | One of this group will all have this bit set to 1 (let's say group ```a```), and the other group will all have this bit set to 0 (let's say group ```b```). The number of numbers in each group does not matter, because we will do XOR for each group, and the ones in pairs will all end up to 0, the only one left of group a will be a, and the only one left of group b will be b. 570 | How? ```int lastSetBit = aXORb & (-aXORb)``` can be used to find the last set bit. In C# ```int``` uses 2's complment (I suppose so, correct me if wrong) for negative number. For example, ```3``` would be ```0011``` in binary, and ```-3``` would be ```1101```, that ```0011 XOR 1101``` leads to ```0001```, which is the last set bit. 571 | 3. Group numbers into 2 groups. 572 | Iterate through the array, check condition ```(number & lastSetBit) == 0``` to group up, and XOR through each group, you will finally get a and b. 573 | 574 | ## #268 Missing number 575 | **LeetCode Link**: 576 | [https://leetcode.com/problems/missing-number/](https://leetcode.com/problems/missing-number/) 577 | **Problem description**: 578 | Given an array containing n distinct numbers taken from 0, 1, 2, ..., n, find the one that is missing from the array. 579 | For example, Given nums = [0, 1, 3] return 2. Requires O(n) time complexity and O(1) space complexity. 580 | **Source code**: 581 | [https://github.com/scottszb1987/LeetCodeInCSharp/blob/master/LeetCodeInCSharp/268_MissingNumber.cs](https://github.com/scottszb1987/LeetCodeInCSharp/blob/master/LeetCodeInCSharp/268_MissingNumber.cs) 582 | **Explanation**: 583 | - sum solution: 584 | ```nums``` is not sorted, we cannot sort it because the sorting time complexity would be O(nlogn). ```nums``` has at most 1 missing number, thus the basic strategy to solve this question is to fined expected sum and actual sum of ```nums```, and ```expectedSum - actualSum``` will be the missing number we want. However, there are several corner cases we need to consider:```1. missing 0 (should return 0);2. missing nothing (should return max of nums + 1)``` 585 | To cover these corner cases, we calculate the sum: ```sum = nums.Length * (nums.Length + 1) / 2```, and iterate through ```nums``` to do ```sum -= nums[i]```. So if 0 is missing, it returns 0; if number is missing in between, it will return the number; if no number is missing, it will return ```nums.Length```. 586 | 587 | ## #283 Move Zeroes 588 | **LeetCode Link**: 589 | [https://leetcode.com/problems/move-zeroes/](https://leetcode.com/problems/move-zeroes/) 590 | **Problem description**: 591 | Given an array nums, write a function to move all 0's to the end of it while maintaining the relative order of the non-zero elements. For example, given nums = [0, 1, 0, 3, 12], after calling your function, nums should be [1, 3, 12, 0, 0]. 592 | **Source code**: 593 | [https://github.com/scottszb1987/LeetCodeInCSharp/blob/master/LeetCodeInCSharp/283_MoveZeroes.cs](https://github.com/scottszb1987/LeetCodeInCSharp/blob/master/LeetCodeInCSharp/283_MoveZeroes.cs) 594 | **Explanation**: 595 | - Iteration way (492ms), refer to [[fetoyal's solution]](https://leetcode.com/discuss/59355/3-lines-o-1-space-o-n-time-c): 596 | Iterate through to find none-zero number and move to the front. Thanks to fetoyal's brillient solution. 597 | 598 | ## #292 Nim Game 599 | **LeetCode Link**: 600 | [https://leetcode.com/problems/nim-game/](https://leetcode.com/problems/nim-game/) 601 | **Problem description**: 602 | You are playing the following Nim Game with your friend: There is a heap of stones on the table, each time one of you take turns to remove 1 to 3 stones. The one who removes the last stone will be the winner. You will take the first turn to remove the stones. 603 | 604 | Both of you are very clever and have optimal strategies for the game. Write a function to determine whether you can win the game given the number of stones in the heap. 605 | 606 | For example, if there are 4 stones in the heap, then you will never win the game: no matter 1, 2, or 3 stones you remove, the last stone will always be removed by your friend. 607 | **Source code**: 608 | [https://github.com/scottszb1987/LeetCodeInCSharp/blob/master/LeetCodeInCSharp/292_NimGame.cs](https://github.com/scottszb1987/LeetCodeInCSharp/blob/master/LeetCodeInCSharp/292_NimGame.cs) 609 | **Explanation**: 610 | - 1 line solution: 611 | Counting backwards, for the first 3, you win any way; if you are at 4th, you lose anyway; if 5,6,7, you can put your oppenent to 4 to win the game; if 8, your oppenent will end up 5 or 6 or 7, you lose ... so you see the pattern 612 | --------------------------------------------------------------------------------