diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..5b0a56e --- /dev/null +++ b/.gitattributes @@ -0,0 +1,6 @@ +*.rb linguist-language=C +ChenXiaoxu/* linguist-vendored +CuiGuangfan/* linguist-vendored +SheYi/* linguist-vendored +JiQiang/* linguist-vendored +XuPershing/* linguist-vendored diff --git a/ALeetcode/week-10/137-SingleNumber2.md b/ALeetcode/week-10/137-SingleNumber2.md new file mode 100644 index 0000000..030138b --- /dev/null +++ b/ALeetcode/week-10/137-SingleNumber2.md @@ -0,0 +1,70 @@ +Single Number II +---------------- +* Author: LHearen +* E-mail: LHearen@126.com +* Time : Tue May 31 09:20:30 CST 2016 +* Description: Given an array of integers, every element appears three times except for one. Find that single one. +Note: +Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory? +* Source: https://leetcode.com/problems/single-number-ii/ + +### Solution +Along with detailed comments in the code, no further comments will be added here. + +``` +//AC - 8ms; +//direct method - calculate each bit and find the single one; +int singleNumber0(int* nums, int size) +{ + int b, ret = 0; + int len = sizeof(int)*8; + for(int i = 0; i < len; i++) + { + b = 1 << i; + int count = 0; + for(int j = 0; j < size; j++) + if(b & nums[j]) + count++; + if(count%3) + ret |= b; + + } + return ret; + +} +``` + + +``` +//AC - 4ms; +//inspired by logical circuit design and boolean algebra; +//counter - unit of 3; +//current incoming next +//a b c a b +//0 0 0 0 0 +//0 1 0 0 1 +//1 0 0 1 0 +//0 0 1 0 1 +//0 1 1 1 0 +//1 0 1 0 0 +//a = a&~b&~c + ~a&b&c; +//b = ~a&b&~c + ~a&~b&c; +//return a|b since the single number can appear once or twice; +int singleNumber(int* nums, int size) +{ + int a=0, b=0; + for(int i = 0; i < size; i++) + { + int t = (~a&b&nums[i])|(a&~b&~nums[i]); + b = (~a&~b&nums[i])|(~a&b&~nums[i]); + a = t; + + } + return a|b; + +} +``` + +### Feedback +There must be some better solutions to this problem, if you've got one, please never hesitate to inform me of that, so many thanks in advance! + diff --git a/ALeetcode/week-12/324-WiggleSort2.md b/ALeetcode/week-12/324-WiggleSort2.md new file mode 100644 index 0000000..ac7c8f4 --- /dev/null +++ b/ALeetcode/week-12/324-WiggleSort2.md @@ -0,0 +1,89 @@ +WiggleSortII +------------ +* Author: LHearen +* E-mail: LHearen@126.com +* Time : Tue May 31 09:20:30 CST 2016 +* Description: Given an unsorted array nums, reorder it such that nums[0] < nums[1] > nums[2] < nums[3].... +Example: +(1) Given nums = [1, 5, 1, 1, 6, 4], one possible answer is [1, 4, 1, 5, 1, 6]. +(2) Given nums = [1, 3, 2, 2, 3, 1], one possible answer is [2, 3, 1, 3, 1, 2]. +Note: +You may assume all input has valid answer. +Follow Up: +Can you do it in O(n) time and/or in-place with O(1) extra space? +* Source: https://leetcode.com/problems/wiggle-sort-ii/ + +### Solution + +Can there any true O(n) solution of this problem? +I solved this by sorting and using another O(n) space to store the sorted elements and then rearranging them into the original array. + +There are several things we should clearly find out: + +in the result array, the even index position will contain smaller elements while the odd index position bigger ones; +to avoid the middle part of the sorted array meet each other too quick (for example if we rearrange them like this: the smaller in ascending order, the bigger in descending order -> in different order but filling the result array in the same direction); so we have to rearrange them in the same order to the result array; +but soon we will tumble into a dilemma by this test case [4, 5, 5, 6] in which if we rearrange them as the rules mentioned above it can be wrong; +how about starting to place them from the end of the result array? then -> 5, 6, 4, 5 should be the result (the smaller: 4, 5; the bigger: 5, 6 and place the bigger first 5 since the last index is 3, an odd index then the first 4 of the smaller and then the second of the bigger 6, and then the second of the smaller 5). Quite right! the odd and even position rule -> big : odd, small : even +Bang! End of Story! + +space cost O(n) +time cost O(nlogn) + + +### Details in C + +``` +void swap(int* p, int* q) +{ + int t=*p; *p=*q; *q=t; + +} + +void sort(int* nums, int begin, int end) +{ + int l=begin, r=end; + int v = nums[l+(r-l)/2]; + while(l <= r) + { + while(nums[l] < v) l++; + while(nums[r] > v) r--; + if(l <= r) + { + swap(nums+l, nums+r); + l++; r--; + + } + + } + if(begin < r) + sort(nums, begin, r); + if(l < end) + sort(nums, l, end); + +} + +//AC - 40ms; +void wiggleSort(int* nums, int size) +{ + sort(nums, 0, size-1); //using quick sort to sort the array first; + int *arr = (int*)malloc(sizeof(int)*size); + for(int i = 0; i < size; i++) + arr[i] = nums[i]; + int small= 0; //the first of smallers; + int big = (size-1)/2+1; //the first of biggers; + int index = size-1; //start to fill in reverse direction: from right to left; + if(size%2 == 0) //if the size is even then the last should be indexed by odd size-1, so place the bigger one in odd position size-1; + nums[index--] = arr[big++]; + while(index > -1) + { + nums[index--] = arr[small++]; + if(index > -1) //in case of "underflow"; + nums[index--] = arr[big++]; + + } + +} +``` + +### Feedback +There must be some better solutions to this problem, if you've got one, please never hesitate to inform me of that, so many thanks in advance! diff --git a/ALeetcode/week-8/63-UniquePaths2.md b/ALeetcode/week-8/63-UniquePaths2.md new file mode 100644 index 0000000..cc3baf1 --- /dev/null +++ b/ALeetcode/week-8/63-UniquePaths2.md @@ -0,0 +1,101 @@ +--- +author: LHearen +time: Sat Jan 23 20:20:36 CST 2016 +categories: +-week8 +tags: +-DP +--- + +#### Unique Paths II + +*Author : LHearen* + +*E-mail : LHearen@126.com* + +*Time : Sat Jan 23 20:53:00 CST 2016* + +*Description : Follow up for Unique Paths: Now consider if some obstacles are added to the grids. How many unique paths would there be? An obstacle and empty space is marked as 1 and 0 respectively in the grid.* + +*Source : https://leetcode.com/problems/unique-paths-ii/* + +#### Specification +There is a direct way as UniquePaths, but that will definitely make the solution hard to realize and the complexity in space and time cost is rather high. At this very moment, we can spot one special feature in this problem, over-lapping sub-problems and the direct way will take lots of time to do the same sub-problems and that is why it will cost so much. So to improve the performance, we should try to store the handled sub-problems for later use and as a result we can try *Memoization* to hack it first; since *Memoization* can be simply used, then the *Dynamic Programming* might be helpful, so we will have the second solution. + +Both of them will cost O(row*column) in space and time complexity. + +#### Solution 1 - Memoization +To fully make use of the outstanding features of DP, we have to allocate an array to store the states for each position and initialize them to -1 for checking whether it is handled already or not, and when it is handled, we can then directly use it to further decrease time cost. As we can easily understand, when there is a block in the **position** the path will be set as 0 and all others will be determined by the left and upper position and before we continue we will record the current result to the array for re-use. + + +##### Code in C - 4ms; +``` +int traverse(int** grid, int row, int col, int** arrs) +{ + if(row < 0 || col < 0) + return 0; + if(arrs[row][col] != -1) + return arrs[row][col]; + int count = 0; + if(grid[row][col] == 1) + count = 0; + else if(row == 0 && col == 0) + count = 1; + else + count = traverse(grid, row-1, col, arrs) + traverse(grid, row, col-1, arrs); + arrs[row][col] = count; + return count; +} + +//AC - 4ms; +int uniquePathsWithObstacles1(int** grid, int rSize, int cSize) +{ + int **arrs = (int**)malloc(sizeof(int*)*rSize); + for(int i = 0; i < rSize; i++) + { + arrs[i] = (int*)malloc(sizeof(int)*cSize); + for(int j = 0; j < cSize; j++) + arrs[i][j] = -1; + } + traverse(grid, rSize-1, cSize-1, arrs); + return arrs[rSize-1][cSize-1]; +} +``` + +#### Solution 2 - Dynamic Programming +As we can see, the previous solution will demand initialization before traversal and then in each recursion there will also require further function invoking, to further improve the performance and save time cost, we can have a try at Dynamic Programming which is a bottom-up method and the major clues are quite the same as the previous one. + +##### Code in C - 0ms; +``` +//AC - 0ms; +int uniquePathsWithObstacles0(int** grid, int rSize, int cSize) +{ + int** arrs = (int**)malloc(sizeof(int*)*rSize); + for(int i = 0; i < rSize; i++) + arrs[i] = (int*)malloc(sizeof(int)*cSize); + for(int i = 0; i < rSize; i++) + for(int j = 0; j < cSize; j++) + { + if(i==0 && j==0 && grid[i][j]==0) + { + arrs[i][j] = 1; + continue; + } + if(grid[i][j] == 1) + { + arrs[i][j] = 0; + continue; + } + int count = 0; + if(j-1 > -1) + count += arrs[i][j-1]; + if(i-1 > -1) + count += arrs[i-1][j]; + arrs[i][j] = count; + } + return arrs[rSize-1][cSize-1]; +} +``` + +##### Additional +There must be some better solutions to this problem, if you've got one, please never hesitate to inform me of that, so many thanks in advance! diff --git a/ChenXiaoxu/1. Two Sum.md b/ChenXiaoxu/1. Two Sum.md new file mode 100644 index 0000000..624595c --- /dev/null +++ b/ChenXiaoxu/1. Two Sum.md @@ -0,0 +1,52 @@ +# 1. Two Sum + + +## Problem +Given an array of integers, return indices of the two numbers such that they add up to a specific target. + +You may assume that each input would have exactly one solution. + +Example: +``` +Given nums = [2, 7, 11, 15], target = 9, + +Because nums[0] + nums[1] = 2 + 7 = 9, +return [0, 1]. +``` +tag: + +## Solution + +方法一:暴力破解 + +时间复杂度O(N2) + +竟然**Accepted** :) + +方法二:哈希表 + +时间复杂度O(N), 空间复杂度O(N); + +**java** +```java + public int[] twoSum(int[] nums, int target) { + Map map = new HashMap(); + for(int i=0; i< nums.length; i++) { + if(map.containsKey(target-nums[i])) { + return new int[]{map.get(target-nums[i]), i}; + } else { + map.put(nums[i], i); + } + } + return null; + } +``` + +**go** +```go + +``` + +方法三:排序,逼近 + +时间复杂度O(NLogN) \ No newline at end of file diff --git a/ChenXiaoxu/101. Symmetric Tree.md b/ChenXiaoxu/101. Symmetric Tree.md new file mode 100644 index 0000000..3dacee0 --- /dev/null +++ b/ChenXiaoxu/101. Symmetric Tree.md @@ -0,0 +1,96 @@ +# 101. Symmetric Tree + +## Problem + +Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center). + +For example, this binary tree is symmetric: +``` + 1 + / \ + 2 2 + / \ / \ +3 4 4 3 +But the following is not: + 1 + / \ + 2 2 + \ \ + 3 3 +``` +Note: +Bonus points if you could solve it both recursively and iteratively. + +tag: + +## Solution + +### 递归 + +树中两个点对称(n1,n2), 递归判断n1的左子树与n2的右子树,n2的右子树与n2的左子树是否对称 + +**java** +```java + public boolean isSymmetric(TreeNode root) { + return root==null || helper(root.left, root.right); + } + + boolean helper(TreeNode n1, TreeNode n1) { + if(n1==null || n2==null) return n1==n2; + if(n1.val != n2.val) return false; + return helper(n1.left, n2.right)&&helper(n1.right, n2.left); + } +``` + +**go** +```go + +``` + +### 迭代 + +**模拟递归工作栈** + +```java + public boolean isSymmetric(TreeNode root) { + if(root==null) return true; + + Stack s = new Stack(); + + if(root.left!=null && root.right!=null) { + s.push(root.left); + s.push(root.right); + } else if(root.left==null && root.right==null) { + return true; + } else { + return false; + } + + TreeNode left, right; + + while(!s.isEmpty()) { + // if(s.size()%2!=0) return false; + right = s.pop(); + left = s.pop(); + if(right.val!=left.val) return false; + + if(left.left!=null && right.right!=null) { + s.push(left.left); + s.push(right.right); + } else if(!(left.left==null&&right.right==null)) { + return false; + } + + if(left.right!=null && right.left!=null) { + s.push(left.right); + s.push(right.left); + } else if(!(left.right==null && right.left==null)) { + return false; + } + } + + return true; + } +``` + +**层次遍历,判断每层是否对称** \ No newline at end of file diff --git a/ChenXiaoxu/102. Binary Tree Level Order Traversal.md b/ChenXiaoxu/102. Binary Tree Level Order Traversal.md new file mode 100644 index 0000000..4364568 --- /dev/null +++ b/ChenXiaoxu/102. Binary Tree Level Order Traversal.md @@ -0,0 +1,57 @@ +# [107. Binary Tree Level Order Traversal II](https://leetcode.com/problems/binary-tree-level-order-traversal-ii/) + +## Problem + +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). + +For example: +Given binary tree {3,9,20,#,#,15,7}, +``` + 3 + / \ + 9 20 + / \ + 15 7 +``` +return its level order traversal as: +``` +[ + [15,7], + [9,20], + [3] +] +``` + +tag: +- tree +- bfs + +## Solution + +类似于[Binary Tree Level Order Traversal I](https://leetcode.com/problems/binary-tree-level-order-traversal/) 对二叉树宽度优先搜索,并记录每层的节点数,遍历完一层后,把结果**插入到链表头部**,再进行下一层遍历 + +**java** +```java + public List> levelOrderBottom(TreeNode root) { + List> res = new LinkedList>(); + if (root==null) return res; + Queue q = new LinkedList(); + q.offer(root); + while(!q.isEmpty()) { + int levelNum = q.size(); + List subList = new LinkedList(); + for(int i=0; i> zigzagLevelOrder(TreeNode root) { + List> res = new LinkedList>(); + if(root==null) return res; + Queue q = new LinkedList(); + q.offer(root); + boolean level = false; + while(!q.isEmpty()) { + int levelNum = q.size(); + List subList = new LinkedList(); + for(int i=0; i> levelOrder(TreeNode root) { + Queue q = new LinkedList(); + List> res = new LinkedList>(); + + if(root==null) return res; + + q.offer(root); + while(!q.isEmpty()) { + int levelNum = q.size(); + List subList = new LinkedList(); + for(int i=0; iHere is the proof. Proved by contradiction: + +>Suppose the returned result is not the optimal solution. Then there must exist an optimal solution, say a container with aol and aor (left and right respectively), such that it has a greater volume than the one we got. Since our algorithm stops only if the two pointers meet. So, we must have visited one of them but not the other. WLOG, let's say we visited aol but not aor. When a pointer stops at a_ol, it won't move until + +>The other pointer also points to aol. In this case, iteration ends. But the other pointer must have visited aor on its way from right end to aol. Contradiction to our assumption that we didn't visit aor. + +>The other pointer arrives at a value, say arr, that is greater than aol before it reaches aor. In this case, we does move aol. But notice that the volume of aol and arr is already greater than aol and aor (as it is wider and heigher), which means that aol and aor is not the optimal solution -- Contradiction! + +**java** +```java + public int maxArea(int[] height) { + int i=0, j=height.length-1; + int res = 0; + while(i - 左右子树高度之差不大于1 +> - 左右子树也是平衡二叉树 + +**java** +```java + public boolean isBalanced(TreeNode root) { + if(root==null) return true; + return Math.abs(depth(root.left)-depth(root.right))<=1 && isBalanced(root.left) && isBalanced(root.right); + } + + int depth(TreeNode root) { + if(root==null) return 0; + return Math.max(depth(root.left),depth(root.right))+1; + } +``` + +**go** +```go + +``` \ No newline at end of file diff --git a/ChenXiaoxu/111. Minimum Depth of Binary Tree.md b/ChenXiaoxu/111. Minimum Depth of Binary Tree.md new file mode 100644 index 0000000..17951bb --- /dev/null +++ b/ChenXiaoxu/111. Minimum Depth of Binary Tree.md @@ -0,0 +1,29 @@ +# 111. Minimum Depth of Binary Tree + +## Problem + +Given a binary tree, find its minimum depth. + +tag: + +## Solution + +当前树最小高度等于: +- 若左子树为空, 右子树高度+1 +- 若有子树为空, 左子树高度+1 +- 左右子树种最小高度+1 + +**java** +```java + public int minDepth(TreeNode root) { + if(root==null) return 0; + if(root.left==null) return minDepth(root.right)+1; + if(root.right==null) return minDepth(root.left)+1; + return Math.min(minDepth(root.left), minDepth(root.right))+1; + } +``` + +**go** +```go + +``` \ No newline at end of file diff --git a/ChenXiaoxu/121. Best Time to Buy and Sell Stock.md b/ChenXiaoxu/121. Best Time to Buy and Sell Stock.md new file mode 100644 index 0000000..113528d --- /dev/null +++ b/ChenXiaoxu/121. Best Time to Buy and Sell Stock.md @@ -0,0 +1,37 @@ +# 121. Best Time to Buy and Sell Stock + +## Problem + +Say you have an array for which the ith element is the price of a given stock on day i. + +If you were only permitted to complete at most one transaction (ie, buy one and sell one share of the stock), design an algorithm to find the maximum profit. + +tag: +- dp + +## Solution +动态规划: +``` +profit[i] = profit[i-1] if price[i]-min <= profit[i-1] + = price[i] if price[i]-min > profit[i-1] + +min = min price[j] (j<=i) +``` +**java** +```java + public int maxProfit(int[] prices) { + int min = Integer.MAX_VALUE, profit = 0; + for(int i=0; i profit) + profit = prices[i]-min; + } + return profit; + } +``` + +**go** +```go + +``` \ No newline at end of file diff --git a/ChenXiaoxu/125 Valid Palindrome.md b/ChenXiaoxu/125 Valid Palindrome.md new file mode 100644 index 0000000..210d8ec --- /dev/null +++ b/ChenXiaoxu/125 Valid Palindrome.md @@ -0,0 +1,46 @@ +# 125. Valid Palindrome + +## Problem + +Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases. + +For example, +"A man, a plan, a canal: Panama" is a palindrome. +"race a car" is not a palindrome. + +Note: +Have you consider that the string might be empty? This is a good question to ask during an interview. + +For the purpose of this problem, we define empty string as valid palindrome. + +tag: +- two pointers +- string + +## Solution + +**java** +```java + public boolean isPalindrome(String s) { + if (s == null || s.isEmpty()) + return true; + int l = 0, r = s.length() - 1; + while (l < r) { + if (!Character.isLetterOrDigit(s.charAt(l))) { + l++; + continue; + } + if (!Character.isLetterOrDigit(s.charAt(r))) { + r--; + continue; + } + if (Character.toLowerCase(s.charAt(l)) == Character.toLowerCase(s.charAt(r))) { + l++; + r--; + } else { + return false; + } + } + return true; + } +``` \ No newline at end of file diff --git a/ChenXiaoxu/136. Single Number.md b/ChenXiaoxu/136. Single Number.md new file mode 100644 index 0000000..7cbf461 --- /dev/null +++ b/ChenXiaoxu/136. Single Number.md @@ -0,0 +1,25 @@ +# 136. Single Number + +## Problem +Given an array of integers, every element appears twice except for one. Find that single one. + +tag: +- 位运算 + +## Solution + +**java** +```java + public int singleNumber(int[] nums) { + int res = nums[0]; + for(int i=1; i>i)&1; + } + res |= ((c[i]%3)< 1, 00 => 0. + return a|b; + + } +``` \ No newline at end of file diff --git a/ChenXiaoxu/139. Word Break.md b/ChenXiaoxu/139. Word Break.md new file mode 100644 index 0000000..2927e99 --- /dev/null +++ b/ChenXiaoxu/139. Word Break.md @@ -0,0 +1,61 @@ +# 139. Word Break + +## Problem +Given a string s and a dictionary of words dict, determine if s can be segmented into a space-separated sequence of one or more dictionary words. + +For example, given +s = "leetcode", +dict = ["leet", "code"]. + +Return true because "leetcode" can be segmented as "leet code". +tag: + +## Solution + +方法一: 分支限界法(记忆化搜索) + +**java** +```java + public boolean wordBreak(String s, Set wordDict) { + return helper(s, wordDict, new HashMap()); + } + + boolean helper(String s, Set wordDict, Map map) { + if(map.containsKey(s)) return map.get(s); + if(s.length()==0) return true; + boolean res = false; + for(String word : wordDict) { + if(s.startsWith(word)) { + res |= helper(s.substring(word.length()), wordDict, map); + } + } + map.put(s, res); + return res; + } +``` + +**go** +```go + +``` + +方法二: 动态规划(效果不太好,可能与数据集有关) + +设dp[i]表示长度i的字串是否能够划分, 则: + +dp[i] = dp[i-j] 如果字串ij在词典中(0= wordDict) { + boolean[] dp = new boolean[s.length()+1]; + dp[0] = true; + for(int i=1; i=0&&!dp[i]; j--){ + if(wordDict.contains(s.substring(i-j,i))) dp[i] = dp[i-j]; + } + } + return dp[dp.length-1]; +} +``` \ No newline at end of file diff --git a/ChenXiaoxu/140. Word Break II.md b/ChenXiaoxu/140. Word Break II.md new file mode 100644 index 0000000..45d78e8 --- /dev/null +++ b/ChenXiaoxu/140. Word Break II.md @@ -0,0 +1,54 @@ +# 140. Word Break II + +## Problem +Given a string s and a dictionary of words dict, add spaces in s to construct a sentence where each word is a valid dictionary word. + +Return all such possible sentences. + +For example, given +s = "catsanddog", +dict = ["cat", "cats", "and", "sand", "dog"]. + +A solution is ["cats and dog", "cat sand dog"]. + +tag: +- backtracking +- dp +- 记忆化搜索 + +## Solution + +直接DFS, 会TLE :( + +采用记忆化搜索进行剪枝:在搜索的过程中,用map纪录已经搜索过的结果 + +**java** +```java + public List wordBreak(String s, Set wordDict) { + return memSearch(s, wordDict, new HashMap>()); + } + + List memSearch(String s, Set dict, HashMap> map) { + if (map.containsKey(s)) + return map.get(s); + LinkedList res = new LinkedList(); + if (s.length() == 0) { + res.add(""); + return res; + } + for (String word : dict) { + if (s.startsWith(word)) { + List subList = memSearch(s.substring(word.length()), dict, map); + for (String sub : subList) + res.add(word + (sub.isEmpty() ? "" : " ") + sub); + } + } + map.put(s, res); + return res; + } +``` + +**go** +```go + +``` \ No newline at end of file diff --git a/ChenXiaoxu/141. Linked List Cycle.md b/ChenXiaoxu/141. Linked List Cycle.md new file mode 100644 index 0000000..014926e --- /dev/null +++ b/ChenXiaoxu/141. Linked List Cycle.md @@ -0,0 +1,53 @@ +# 141. Linked List Cycle + +## Problem + +Given a linked list, determine if it has a cycle in it. + +Follow up: +Can you solve it without using extra space? + +tag: + +## Solution + +快慢指针,slow一次移动一步,fast一次移动两步, 如果两个指针相遇,则存在环。 + +**证明:** +如图, 设交点为M,环的起点为E,|HE| = L1, |EM|=L2, 环的长度为 C, + +1. 第一个(速度慢的)指针在环里转满一圈之前,两个指针必然相遇 +设 slow第一次进入环时,fast在slow前方 a处, 经过x次移动后两指针相遇, 则```x = (2x+a)%L => x=L-a``` + +2. 相遇位置 +```2*(L1+L2) = L1+L2+nC => L1+L2=nC``` +即, 两指针相遇时,令fast指针重新从H点开始,一次移动一步,则fast, slow必定在环起点相遇 +![](http://img.blog.csdn.net/20151003220353630?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQv/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/Center) + + + +**java** + +```java + public ListNode detectCycle(ListNode head) { + if(head==null||head.next==null) return null; + ListNode f = head, s = head; + while(f!=null && f.next!=null) { + f = f.next.next; + s = s.next; + if(f==s) break; + } + if(f!=s) return null; + f = head; + while(f!=s) { + f = f.next; + s = s.next; + } + return f; + } +``` + +**go** +```go + +``` \ No newline at end of file diff --git a/ChenXiaoxu/142. Linked List Cycle II.md b/ChenXiaoxu/142. Linked List Cycle II.md new file mode 100644 index 0000000..658d685 --- /dev/null +++ b/ChenXiaoxu/142. Linked List Cycle II.md @@ -0,0 +1,36 @@ +# [142. Linked List Cycle II](https://leetcode.com/problems/linked-list-cycle-ii/) + +## Problem + +Given a linked list, return the node where the cycle begins. If there is no cycle, return null. + +Note: Do not modify the linked list. + +Follow up: +Can you solve it without using extra space? + +tag: + +## Solution + +参考,[141. Linked List Cycle]() 解题报告 + + +**java** + +```java + public boolean hasCycle(ListNode head) { + ListNode f = head, s = head; + while(s!=null&&s.next!=null) { + s = s.next.next; + f = f.next; + if(s==f) return true; + } + return false; + } +``` + +**go** +```go + +``` \ No newline at end of file diff --git a/ChenXiaoxu/15. 3Sum.md b/ChenXiaoxu/15. 3Sum.md new file mode 100644 index 0000000..2c9d4e1 --- /dev/null +++ b/ChenXiaoxu/15. 3Sum.md @@ -0,0 +1,51 @@ +# [15. 3Sum](https://leetcode.com/problems/3sum/) + +## Problem +Given an array S of n integers, are there elements a, b, c in S such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero. + +Note: +- Elements in a triplet (a,b,c) must be in non-descending order. (ie, a ≤ b ≤ c) +- The solution set must not contain duplicate triplets. + + For example, given array S = {-1 0 1 2 -1 -4}, + + A solution set is: + (-1, 0, 1) + (-1, -1, 2) + +tag: +- two pointers +- sort + +## Solution + +固定一个数,然后采用two sum方法求解, 注意去除重复元素。 + +```java + public List> threeSum(int[] nums) { + List> res = new ArrayList>(); + Arrays.sort(nums); + for (int i = 0; i < nums.length; i++) { + //skip duplicate elements + if (i - 1 >= 0 && nums[i] == nums[i - 1]) + continue; + int p1 = i + 1, p2 = nums.length - 1; + while (p1 < p2) { + if (nums[p1] + nums[p2] == 0 - nums[i]) { + res.add(Arrays.asList(nums[i], nums[p1], nums[p2])); + //skip duplicate elements + while (p1 + 1 < p2 && nums[p1] == nums[p1 + 1]) + p1++; + while (p2 - 1 > p1 && nums[p2] == nums[p2 - 1]) + p2--; + p1++; + p2--; + } else if (nums[p1] + nums[p2] < 0 - nums[i]) + p1++; + else + p2--; + } + } + return res; + } +``` \ No newline at end of file diff --git a/ChenXiaoxu/151. Reverse Words in a String.md b/ChenXiaoxu/151. Reverse Words in a String.md new file mode 100644 index 0000000..f3f99ae --- /dev/null +++ b/ChenXiaoxu/151. Reverse Words in a String.md @@ -0,0 +1,44 @@ +# 151. Reverse Words in a String + +## Problem +Given an input string, reverse the string word by word. + +For example, +Given s = "the sky is blue", +return "blue is sky the". + +tag: +- string +- StringBuffer, StringBuilder, String + +## Solution + +一种简单的方法是两边遍历, 第一遍遍历分离出字符串中的word, 保存在数组中, 第二遍遍历对字符串反转 + +从后向前迭代可以做到一次遍历, 纪录每个单词的起始位置,append到反转字符串 + +时间复杂度O(n), 空间负载都O(n) + +**java** +```java + public String reverseWords(String s) { + StringBuilder reversed = new StringBuilder(); + int j = s.length(); + for (int i = s.length() - 1; i >= 0; i--) { + if (s.charAt(i) == ' ') { + j = i; + } else if (i == 0 || s.charAt(i - 1) == ' ') { + if (reversed.length() != 0) { + reversed.append(' '); + } + reversed.append(s.substring(i, j)); + } + } + return reversed.toString(); + } +``` + +**go** +```go + +``` \ No newline at end of file diff --git a/ChenXiaoxu/165. Compare Version Numbers.md b/ChenXiaoxu/165. Compare Version Numbers.md new file mode 100644 index 0000000..7233ab6 --- /dev/null +++ b/ChenXiaoxu/165. Compare Version Numbers.md @@ -0,0 +1,43 @@ +# 165. Compare Version Numbers + + +## Problem + +Compare two version numbers version1 and version2. +If version1 > version2 return 1, if version1 < version2 return -1, otherwise return 0. + +You may assume that the version strings are non-empty and contain only digits and the . character. +The . character does not represent a decimal point and is used to separate number sequences. +For instance, 2.5 is not "two and a half" or "half way to version three", it is the fifth second-level revision of the second first-level revision. + +Here is an example of version numbers ordering: + +0.1 < 1.1 < 1.2 < 13.37 + +## Solution + +把字符串按点号拆分转换为整数,从高位到低位逐次比较,低位不存在补零比较。 + +**java** +```java + public int compareVersion(String version1, String version2) { + String[] v1 = version1.split("\\."), v2 = version2.split("\\."); + int maxLen = Math.max(v1.length, v2.length); + for (int i = 0; i < maxLen; i++) { + int n1 = i >= v1.length ? 0 : Integer.parseInt(v1[i]); + int n2 = i >= v2.length ? 0 : Integer.parseInt(v2[i]); + if (n1 > n2) + return 1; + else if (n1 < n2) + return -1; + else + continue; + } + return 0; + } +``` + +**go** +```go + +``` \ No newline at end of file diff --git a/ChenXiaoxu/166. Fraction to Recurring Decimal.md b/ChenXiaoxu/166. Fraction to Recurring Decimal.md new file mode 100644 index 0000000..f79584e --- /dev/null +++ b/ChenXiaoxu/166. Fraction to Recurring Decimal.md @@ -0,0 +1,48 @@ +# [166. Fraction to Recurring Decimal](https://leetcode.com/problems/fraction-to-recurring-decimal/) + +## Problem + +tag: + +## [Solution](https://leetcode.com/discuss/31521/short-java-solution) + +1. 判断符号,转化为正数处理 +分子、分母异号,为负,同号为正(**注意转换时,INT_MIN取反结果会超出范围,为了防止溢出,转换为long类型**) + +2. 分子除以分母 +- 如果恰好整除,返回结果 +- 如果不能整除,则商是最终结果的整数部分,小数部分由余数运算取得: + > 用哈希表纪录余数对应小数的位置,如果出现相同余数,则代表出现循环,在对应位置插入括号,计算结束 + > (余数*10)/分母, 对应小数的第一位 + >(余数*10)%分母,对应新的余数 + +3. 输出结果,去除末尾结果为零的情况 + +**java** +```java + public String fractionToDecimal(int numerator, int denominator) { + StringBuffer res = new StringBuffer(); + String sign = (numerator < 0 == denominator < 0 || numerator == 0) ? "" : "-"; + long num = Math.abs((long)numerator), den = Math.abs((long)denominator); + res.append(sign); + res.append(num / den); + long remainder = num % den; + if (remainder == 0) return res.toString(); + res.append("."); + HashMap map = new HashMap(); + while (!map.containsKey(remainder)) { + map.put(remainder, res.length()); + res.append(10 * remainder / den); + remainder = 10 * remainder % den; + } + int index = map.get(remainder); + res.insert(index, "("); + res.append(")"); + return res.toString().replace("(0)", ""); + } +``` + +**go** +```go + +``` \ No newline at end of file diff --git a/ChenXiaoxu/18. 4Sum.md b/ChenXiaoxu/18. 4Sum.md new file mode 100644 index 0000000..34437c0 --- /dev/null +++ b/ChenXiaoxu/18. 4Sum.md @@ -0,0 +1,50 @@ +# [18. 4Sum](https://leetcode.com/problems/4sum/) + +## Problem +Given an array S of n integers, are there elements a, b, c, and d in S such that a + b + c + d = target? Find all unique quadruplets in the array which gives the sum of target. + +Note: +Elements in a quadruplet (a,b,c,d) must be in non-descending order. (ie, a ≤ b ≤ c ≤ d) +The solution set must not contain duplicate quadruplets. + For example, given array S = {1 0 -1 0 -2 2}, and target = 0. + + A solution set is: + (-1, 0, 0, 1) + (-2, -1, 1, 2) + (-2, 0, 0, 2) + +tag: +- two pointers +- sort + +## Solution + +类似于3sum问题, 固定两个数,然后采用two sum方法求解, 注意去除重复元素。 + +```java +public List> fourSum(int[] nums, int target) { + List> res = new ArrayList>(); + Arrays.sort(nums); + for(int i=0; i0 && nums[i-1]==nums[i]) continue; + for(int j=i+1; jp1 && nums[p2]==nums[p2-1]) p2--; + p2--; + p1++; + } else if(nums[p1]+nums[p2] 4 -> 3) + (5 -> 6 -> 4) +Output: 7 -> 0 -> 8 + +tag: +- linked list + + +## Solution +链表模拟加法操作,高位补零简化代码 +**java** +```java + public ListNode addTwoNumbers(ListNode l1, ListNode l2) { + int carry = 0, res = 0; + ListNode dummy = new ListNode(0); + ListNode p = dummy; + while (l1 != null || l2 != null || carry!=0) { + res = ((l1==null)?0:l1.val) + ((l2==null)?0:l2.val) + carry; + carry = res / 10; + p.next = new ListNode(res % 10); + p = p.next; + l1 = (l1==null)?l1:l1.next; + l2 = (l2==null)?l2:l2.next; + } + return dummy.next; + } +``` + +**go** +```go + +``` \ No newline at end of file diff --git a/ChenXiaoxu/20. Valid Parentheses.md b/ChenXiaoxu/20. Valid Parentheses.md new file mode 100644 index 0000000..53ef4b1 --- /dev/null +++ b/ChenXiaoxu/20. Valid Parentheses.md @@ -0,0 +1,34 @@ +# 20. Valid Parentheses + +## Problem + +Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid. + +The brackets must close in the correct order, "()" and "()[]{}" are all valid but "(]" and "([)]" are not. + +tag: + +- String +- stack + +## Solution + +**java** +```java + public boolean isValid(String s) { + Stack stack = new Stack(); + String left = "([{", right = ")]}"; + for (int i = 0; i < s.length(); i++) { + if (s.charAt(i) == '(' || s.charAt(i) == '{' || s.charAt(i) == '[') { + stack.push(s.charAt(i)); + } else { + if (stack.isEmpty() || s.charAt(i) != right.charAt(left.indexOf(stack.peek()))) + return false; + stack.pop(); + } + } + if (!stack.isEmpty()) + return false; + return true; + } +``` \ No newline at end of file diff --git a/ChenXiaoxu/204. Count Primes.md b/ChenXiaoxu/204. Count Primes.md new file mode 100644 index 0000000..20d2052 --- /dev/null +++ b/ChenXiaoxu/204. Count Primes.md @@ -0,0 +1,34 @@ +# [204. Count Primes](https://leetcode.com/problems/count-primes/) + +## Problem +Count the number of prime numbers less than a non-negative number, n. + +tag: + +## Solution +参考该题的 [Hint](https://leetcode.com/problems/count-primes/) + +**java** +```java + public int countPrimes(int n) { + boolean[] isPrimes = new boolean[n]; + for (int i = 2; i < n; i++) isPrimes[i] = true; + for (int i = 2; i * i < n; i++) { + if (isPrimes[i]) { + for (int j = i * i; j < n; j += i) + isPrimes[j] = false; + } + } + int count = 0; + for (int i = 2; i < n; i++) { + if (isPrimes[i]) + count++; + } + return count; + } +``` + +**go** +```go + +``` \ No newline at end of file diff --git a/ChenXiaoxu/206. Reverse Linked List.md b/ChenXiaoxu/206. Reverse Linked List.md new file mode 100644 index 0000000..4acd8a3 --- /dev/null +++ b/ChenXiaoxu/206. Reverse Linked List.md @@ -0,0 +1,36 @@ +# 206. Reverse Linked List + +## Problem +Reverse a singly linked list. + +tag: + +## Solution +遍历链表,然后修改链表的指针,指向其前驱节点。注意当修改链表的next指针时,后继结点会丢失,因此需要保存后继结点。 +如图, 定义```pre, cur, next```分别指向当前,前驱,后继节点, 则: +``` +while(cur不为空) + 纪录后继节点: next = cur.next; + 修改当前结点指针: cur.next = pre; + 更新pre,cur节点位置: pre = cur; cur = next; +``` +![](http://i.imgur.com/ZjeZeco.jpg) + +**java** +```java + public ListNode reverseList(ListNode head) { + ListNode pre = null, next = null; + while(head!=null) { + next = head.next; + head.next = pre; + pre = head; + head = next; + } + return pre; + } +``` + +**go** +```go + +``` \ No newline at end of file diff --git a/ChenXiaoxu/LeetCode/src.main.java/linkedlist/merge/twolist/Solution.java b/ChenXiaoxu/21 Merge Two Sorted Lists.md similarity index 64% rename from ChenXiaoxu/LeetCode/src.main.java/linkedlist/merge/twolist/Solution.java rename to ChenXiaoxu/21 Merge Two Sorted Lists.md index fac9939..214cf6d 100644 --- a/ChenXiaoxu/LeetCode/src.main.java/linkedlist/merge/twolist/Solution.java +++ b/ChenXiaoxu/21 Merge Two Sorted Lists.md @@ -1,7 +1,17 @@ -package linkedlist.merge.twolist; +#69. Sqrt(x) -import linkedlist.ListNode; -public class Solution { +## Problem + +Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists. + +tag: +- linked list + +## Solution + +**java** + +```java public ListNode mergeTwoLists(ListNode l1, ListNode l2) { ListNode dummyHead = new ListNode(0); ListNode p = dummyHead; @@ -21,8 +31,4 @@ public ListNode mergeTwoLists(ListNode l1, ListNode l2) { p.next = l2; return dummyHead.next; } -} - - - - +``` diff --git a/ChenXiaoxu/217. Contains Duplicate.md b/ChenXiaoxu/217. Contains Duplicate.md new file mode 100644 index 0000000..70cc63b --- /dev/null +++ b/ChenXiaoxu/217. Contains Duplicate.md @@ -0,0 +1,24 @@ +# 217. Contains Duplicate + +## Problem +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. +tag: +- hash table + +## Solution + +**java** +```java + public boolean containsDuplicate(int[] nums) { + Set hashSet = new HashSet(); + for(int num: nums) { + if(!hashSet.add(num)) return true; + } + return false; + } +``` + +**go** +```go + +``` \ No newline at end of file diff --git a/ChenXiaoxu/219. Contains Duplicate II.md b/ChenXiaoxu/219. Contains Duplicate II.md new file mode 100644 index 0000000..991fcdd --- /dev/null +++ b/ChenXiaoxu/219. Contains Duplicate II.md @@ -0,0 +1,27 @@ +# 219. Contains Duplicate II + +## Problem +Given an array of integers and an integer k, find out whether there are two distinct indices i and j in the array such that nums[i] = nums[j] and the difference between i and j is at most k. + +tag: + +- hash table + +## Solution + +**java** +```java + public boolean containsNearbyDuplicate(int[] nums, int k) { + Map map = new HashMap(); + for(int i=0; i stack = new Stack(); + for (int i = 0; i < len; i++) { + if (Character.isDigit(s.charAt(i))) { + int sum = s.charAt(i) - '0'; + while (i + 1 < len && Character.isDigit(s.charAt(i + 1))) { + sum = sum * 10 + s.charAt(i + 1) - '0'; + i++; + } + res += sum*sign; + } else if (s.charAt(i) == '+') { + sign = 1; + } else if (s.charAt(i) == '-') { + sign = -1; + } else if (s.charAt(i) == '(') { + stack.push(res); + stack.push(sign); + res = 0; + sign = 1; + } else if (s.charAt(i) == ')') { + res = res * stack.pop() + stack.pop(); + } + } + return res; + } +``` + +**go** +```go + +``` \ No newline at end of file diff --git a/ChenXiaoxu/226. Invert Binary Tree.md b/ChenXiaoxu/226. Invert Binary Tree.md new file mode 100644 index 0000000..3d7d9d3 --- /dev/null +++ b/ChenXiaoxu/226. Invert Binary Tree.md @@ -0,0 +1,42 @@ +# 226. Invert Binary Tree + +## Problem +nvert a binary tree. + + 4 + / \ + 2 7 + / \ / \ +1 3 6 9 +to + 4 + / \ + 7 2 + / \ / \ +9 6 3 1 + +tag: + +## Solution + +>如果节点为空,返回 +>否则 +- 递归转换左子树 +- 递归转换右子树 +- 对换左右子树 + +**java** +```java + public TreeNode invertTree(TreeNode root) { + if(root==null) return root; + TreeNode tmp = root.left; + root.left = invertTree(root.right); + root.right = invertTree(tmp); + return root; + } +``` + +**go** +```go + +``` \ No newline at end of file diff --git a/ChenXiaoxu/LeetCode/src.main.java/linkedlist/merge/klist/Solution.java b/ChenXiaoxu/23 Merge k Sorted Lists.md similarity index 80% rename from ChenXiaoxu/LeetCode/src.main.java/linkedlist/merge/klist/Solution.java rename to ChenXiaoxu/23 Merge k Sorted Lists.md index 40e0207..b91b19f 100644 --- a/ChenXiaoxu/LeetCode/src.main.java/linkedlist/merge/klist/Solution.java +++ b/ChenXiaoxu/23 Merge k Sorted Lists.md @@ -1,9 +1,19 @@ -package linkedlist.merge.klist; +#69. Sqrt(x) -import java.util.List; +## Problem -import linkedlist.ListNode; +Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity. +tag: +- divide and conquer +- linked list +- heap + +## Solution + +**java** + +```java public class Solution { public ListNode mergeKLists(ListNode[] lists) { @@ -45,3 +55,4 @@ private ListNode mergeTwoLists(ListNode l1, ListNode l2) { return dummyHead.next; } } +``` diff --git a/ChenXiaoxu/234. Palindrome Linked List.md b/ChenXiaoxu/234. Palindrome Linked List.md new file mode 100644 index 0000000..c5330d3 --- /dev/null +++ b/ChenXiaoxu/234. Palindrome Linked List.md @@ -0,0 +1,47 @@ +# [234. Palindrome Linked List](https://leetcode.com/problems/palindrome-linked-list/) + +## Problem +Given a singly linked list, determine if it is a palindrome. + +Follow up: +Could you do it in O(n) time and O(1) space? + +tag: + +## Solution + +采用快慢指针找到中间节点,然后反转后半部分链表, 判断两部分链表是否相等,注意奇偶节点。 + +**java** +```java + public boolean isPalindrome(ListNode head) { + ListNode fast = head,slow = head; + while(fast!=null&&fast.next!=null) { + fast = fast.next.next; + slow = slow.next; + } + if(fast!=null) slow = slow.next; + slow = reverseList(slow); + while(slow!=null && slow.val==head.val) { + slow = slow.next; + head = head.next; + } + return slow==null; + } + + ListNode reverseList(ListNode head) { + ListNode pre = null, next = null; + while(head!=null) { + next = head.next; + head.next = pre; + pre = head; + head = next; + } + return pre; + } +``` + +**go** +```go + +``` \ No newline at end of file diff --git a/ChenXiaoxu/257. Binary Tree Paths.md b/ChenXiaoxu/257. Binary Tree Paths.md new file mode 100644 index 0000000..7b1a2df --- /dev/null +++ b/ChenXiaoxu/257. Binary Tree Paths.md @@ -0,0 +1,49 @@ +# 257. Binary Tree Paths + +## Problem + +Given a binary tree, return all root-to-leaf paths. + +For example, given the following binary tree: + + 1 + / \ +2 3 + \ + 5 +All root-to-leaf paths are: + +["1->2->5", "1->3"] + +tag: +- Tree + +## Solution + +**java** +```java + public List binaryTreePaths(TreeNode root) { + List res = new ArrayList(); + helper(res, new StringBuilder(), root); + return res; + } + + void helper(List res, StringBuilder str, TreeNode root) { + if(root==null) return; + int len = str.length(); + str.append(root.val); + if(root.left==null && root.right==null) { + res.add(str.toString()); + } else { + str.append("->"); + helper(res, str, root.left); + helper(res, str, root.right); + } + str.setLength(len); + } +``` + +**go** +```go + +``` \ No newline at end of file diff --git a/ChenXiaoxu/26 Remove Duplicates from Sorted Array.md b/ChenXiaoxu/26 Remove Duplicates from Sorted Array.md new file mode 100644 index 0000000..5bb1baf --- /dev/null +++ b/ChenXiaoxu/26 Remove Duplicates from Sorted Array.md @@ -0,0 +1,46 @@ +# 26. Remove Duplicates from Sorted Array + +## Problem + +Given a sorted array, remove the duplicates in place such that each element appear only once and return the new length. + +Do not allocate extra space for another array, you must do this in place with constant memory. + +For example, +Given input array nums = [1,1,2], + +Your function should return length = 2, with the first two elements of nums being 1 and 2 respectively. It doesn't matter what you leave beyond the new length. + + + +--- + +title: 26. Remove Duplicates from Sorted Array +description: "" +tags: +- Arrary +- Two Pointers + +categories: +- week7 + +--- + + +## Solution + +**java** + +```java + public int removeDuplicates(int[] nums) { + if (nums.length == 0 || nums.length == 1) + return nums.length; + int cur = 0; + for (int i = 1; i < nums.length; i++) { + if (nums[i] != nums[cur]) { + nums[++cur] = nums[i]; + } + } + return cur + 1; + } +``` \ No newline at end of file diff --git a/ChenXiaoxu/264. Ugly Number II.md b/ChenXiaoxu/264. Ugly Number II.md new file mode 100644 index 0000000..25bd4b7 --- /dev/null +++ b/ChenXiaoxu/264. Ugly Number II.md @@ -0,0 +1,51 @@ +# 264. Ugly Number II + +## Problem + +Write a program to find the n-th ugly number. + +Ugly numbers are positive numbers whose prime factors only include 2, 3, 5. For example, 1, 2, 3, 4, 5, 6, 8, 9, 10, 12 is the sequence of the first 10 ugly numbers. + +Note that 1 is typically treated as an ugly number. + +Hint: + +1. The naive approach is to call isUgly for every number until you reach the nth one. Most numbers are not ugly. Try to focus your effort on generating only the ugly ones. +2. An ugly number must be multiplied by either 2, 3, or 5 from a smaller ugly number. +3. The key is how to maintain the order of the ugly numbers. Try a similar approach of merging from three sorted lists: L1, L2, and L3. +4. Assume you have Uk, the kth ugly number. Then Uk+1 must be Min(L1 * 2, L2 * 3, L3 * 5). + +## Solution + +**暴力求解** + +直观的做法是对整数进行遍历,逐步判断每个数是否是丑数 + +**动态规划** + +丑数序列可以拆为以下子列表: +1x2,2x2,3x2,4x2...nextUgly*2... +1x3,2x3,3x3,4x3...nextUgly*3... +1x5,2x5,3x5,4x5...nextUgly*5... +采用合并有序链表的方法,从三个子列表中逐步获取最小的丑数。 +```java + public int nthUglyNumber(int n) { + List ugly = new ArrayList(n); + ugly.add(1); + int p2 = 0, p3=0, p5=0; + while (ugly.size()mid) right=mid; + else left = mid+1; + } + return left; + } +``` + +**go** +```go + +``` +### 方法二 + +参考 : https://leetcode.com/discuss/61086/java-time-and-space-solution-similar-find-loop-in-linkedlist \ No newline at end of file diff --git a/ChenXiaoxu/3. Longest Substring Without Repeating Characters.md b/ChenXiaoxu/3. Longest Substring Without Repeating Characters.md new file mode 100644 index 0000000..1b49482 --- /dev/null +++ b/ChenXiaoxu/3. Longest Substring Without Repeating Characters.md @@ -0,0 +1,76 @@ +# [3. Longest Substring Without Repeating Characters](https://leetcode.com/problems/longest-substring-without-repeating-characters/) + +## Problem +Given a string, find the length of the longest substring without repeating characters. For example, the longest substring without repeating letters for "abcabcbb" is "abc", which the length is 3. For "bbbbb" the longest substring is "b", with the length of 1. + +tag: + +## Solution + +最简单的方法是暴力破解,找出以每一个字母开头的最大字串, 时间复杂度为O(N2) + +假设,在一次计算的过程中,字串开始位置为p,在j位置遇到重复字母b, 重复的位置为i, i=i) { + i = charMap[s.charAt(j)]+1; + } + charMap[s.charAt(j)] = j; + maxLen = Math.max(j-i+1, maxLen); + } + return maxLen; + } +``` diff --git a/ChenXiaoxu/33 Search in Rotated Sorted Array.md b/ChenXiaoxu/33 Search in Rotated Sorted Array.md new file mode 100644 index 0000000..474e656 --- /dev/null +++ b/ChenXiaoxu/33 Search in Rotated Sorted Array.md @@ -0,0 +1,49 @@ +# 46. Permutations + +## Problem + +Suppose a sorted array is rotated at some pivot unknown to you beforehand. + +(i.e., 0 1 2 4 5 6 7 might become 4 5 6 7 0 1 2). + +You are given a target value to search. If found in the array return its index, otherwise return -1. + +You may assume no duplicate exists in the array. + +tags: +- array +- binary search + +similar problems: + +- (M) Search in Rotated Sorted Array II +- (M) Find Minimum in Rotated Sorted Array + + +## Solution + +```java +public int search(int[] nums, int target) { + if (nums == null || nums.length == 0) + return -1; + int left = 0, right = nums.length - 1; + while (left <= right) { + int mid = left + (right - left) / 2; + if (target == nums[mid]) + return mid; + + if (nums[mid] >= nums[left]) { + if (nums[left] <= target && target <= nums[mid]) + right = mid - 1; + else + left = mid + 1; + } else { + if (nums[mid] < target && target <= nums[right]) + left = mid + 1; + else + right = mid - 1; + } + } + return -1; +} +``` \ No newline at end of file diff --git a/ChenXiaoxu/LeetCode/src.main.java/bs/Solution.java b/ChenXiaoxu/34 Search for a Range.md similarity index 53% rename from ChenXiaoxu/LeetCode/src.main.java/bs/Solution.java rename to ChenXiaoxu/34 Search for a Range.md index 6b798b7..57de799 100644 --- a/ChenXiaoxu/LeetCode/src.main.java/bs/Solution.java +++ b/ChenXiaoxu/34 Search for a Range.md @@ -1,8 +1,26 @@ -package bs; +#34. Search for a Range -public class Solution { +## Problem - // 34 search for range +Given a sorted array of integers, find the starting and ending position of a given target value. + +Your algorithm's runtime complexity must be in the order of O(log n). + +If the target is not found in the array, return [-1, -1]. + +For example, +Given [5, 7, 7, 8, 8, 10] and target value 8, +return [3, 4]. + +tag: +- array +- binary search + +## Solution + +**java** + +```java public int[] searchRange(int[] nums, int target) { int l = 0, r = nums.length - 1; while (l <= r) { @@ -22,4 +40,4 @@ public int[] searchRange(int[] nums, int target) { } return new int[] { -1, -1 }; } -} +``` diff --git a/ChenXiaoxu/38. Count and Say.md b/ChenXiaoxu/38. Count and Say.md new file mode 100644 index 0000000..d824bd3 --- /dev/null +++ b/ChenXiaoxu/38. Count and Say.md @@ -0,0 +1,48 @@ +# 38. Count and Say + + +## Problem + +The count-and-say sequence is the sequence of integers beginning as follows: +1, 11, 21, 1211, 111221, ... + +1 is read off as "one 1" or 11. +11 is read off as "two 1s" or 21. +21 is read off as "one 2, then one 1" or 1211. +Given an integer n, generate the nth sequence. + +tag: +- string + +## Solution + +**java** +```java + public String countAndSay(int n) { + if (n <= 0) + return ""; + String pre = "1"; + for (int i = 2; i <= n; i++) { + StringBuffer next = new StringBuffer(); + int count = 1; + for (int j = 1; j < pre.length(); j++) { + if (pre.charAt(j) == pre.charAt(j - 1)) + count++; + else { + next.append(count); + next.append(pre.charAt(j - 1)); + count = 1; + } + } + next.append(count); + next.append(pre.charAt(pre.length() - 1)); + pre = next.toString(); + } + return pre; + } +``` + +**go** +```go + +``` \ No newline at end of file diff --git a/ChenXiaoxu/42. Trapping Rain Water.md b/ChenXiaoxu/42. Trapping Rain Water.md new file mode 100644 index 0000000..6ff7eff --- /dev/null +++ b/ChenXiaoxu/42. Trapping Rain Water.md @@ -0,0 +1,50 @@ +# 42. Trapping Rain Water + +## Problem + +Given n non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it is able to trap after raining. + +For example, +Given ```[0,1,0,2,1,0,1,3,2,1,2,1]```, return``` 6```. + +![](http://www.leetcode.com/wp-content/uploads/2012/08/rainwatertrap.png) + +The above elevation map is represented by array [0,1,0,2,1,0,1,3,2,1,2,1]. In this case, 6 units of rain water (blue section) are being trapped. + +tag: +- two pointers + +## Solution + +思路很简单,逐个分析每个槽能trap water的容量,然后进行累加即为总容量。关键在于算法的优化。 + +每个槽的容量为其左边最高与右边最高中较低的一个与该槽高度的差值。 + +常规的做法是进行遍历,对每个槽的容量计算,时间复杂度为O(N2). + +优化: 从左到右遍历纪录每个槽左边的最大值,从右到左遍历纪录每个槽最右边的最大值,时间复杂度O(2N) + + +**java** +```java + public int trap(int[] height) { + int[] mostHeight = new int[height.length]; + int max = 0, sum = 0; + for(int i=0; i=0; i--) { + mostHeight[i] = Math.min(max, mostHeight[i]); + if(max0 ? (mostHeight[i]-height[i]) :0 ; + } + return sum; + } +``` + +**go** +```go + +``` \ No newline at end of file diff --git a/ChenXiaoxu/43. Multiply Strings.md b/ChenXiaoxu/43. Multiply Strings.md new file mode 100644 index 0000000..35233a1 --- /dev/null +++ b/ChenXiaoxu/43. Multiply Strings.md @@ -0,0 +1,39 @@ +# [43. Multiply Strings](https://leetcode.com/problems/multiply-strings/) + +## Question +Given two numbers represented as strings, return multiplication of the numbers as a string. + +Note: The numbers can be arbitrarily large and are non-negative. +tag: +- 模拟 + +## [Solution](https://leetcode.com/discuss/71593/easiest-java-solution-with-graph-explanation) +从右到做扫描num1,num2, 对每一对数字执行乘法操作, 逐步累加。 处理过程如图所示, + + ```num1[i]*num2[j] 相乘结果的下标为[i+j, i+j+1]``` + +![](https://drscdn.500px.org/photo/130178585/m%3D2048/300d71f784f679d5e70fadda8ad7d68f) + + +**java** +```java + public String multiply(String num1, String num2) { + int len1 = num1.length(), len2 = num2.length(); + int[] res = new int[len1 + len2]; + for (int i = 0; i < len1; i++) + for (int j = 0; j < len2; j++) { + int mul = (num1.charAt(i) - '0') * (num2.charAt(j) - '0'); + int sum = mul + res[i + j + 1]; + res[i + j] += sum / 10; + res[i + j + 1] = sum % 10; + } + StringBuffer sb = new StringBuffer(); + for (int p : res) if (!(sb.length()==0 && p==0)) sb.append(p); + return sb.length() == 0 ? "0" : sb.toString(); + } +``` + +**go** +```go + +``` \ No newline at end of file diff --git a/ChenXiaoxu/46 Permutations.md b/ChenXiaoxu/46 Permutations.md new file mode 100644 index 0000000..4ccab50 --- /dev/null +++ b/ChenXiaoxu/46 Permutations.md @@ -0,0 +1,79 @@ +# 46. Permutations + +## Problem + +Given a collection of distinct numbers, return all possible permutations. + +For example, +[1,2,3] have the following permutations: +[1,2,3], [1,3,2], [2,1,3], [2,3,1], [3,1,2], and [3,2,1]. + +tags: +- backtracking +- 排列与组合 + + + +## Solution + +- 直接生成(递归/回溯) +- 邻位互换 +- 序数法 +- 字典序法 +- 轮转法 + +### 递归 +n个不重复数的全排列: +n=1 即为当前排列 +n>1 先排第一位 则Pn = iPn-1 (i=1,2,3,...n) + +**go** +```go +func Permtuate(res *[][]int, nums []int, begin int, end int) { + if begin == end { + *res = append(*res, nums) + } else { + for i := begin; i < end; i++ { + nums[begin], nums[i] = nums[i], nums[begin] + Permtuate(res, nums, begin+1, end) + nums[begin], nums[i] = nums[i], nums[begin] + } + } +} +``` +**java** +```java +public class Solution { + + //46. Permutations + public List> permute(int[] nums) { + List> res = new ArrayList>(); + recursive(res, nums, 0, nums.length); + return res; + } + + void recursive(List> res, int[] nums, int begin, int end) { + if (end == begin) { + List li = new ArrayList(nums.length); + for(Integer num:nums){ + li.add(num); + } + res.add(li); + } else { + for (int i = begin; i < end; i++) { + swap(nums, begin, i); + recursive(res, nums, begin + 1, end); + swap(nums, i, begin); + } + } + } + + void swap(int[] nums, int i, int j) { + int tmp = nums[i]; + nums[i] = nums[j]; + nums[j] = tmp; + } + + //47. Permutations II +} +``` \ No newline at end of file diff --git a/ChenXiaoxu/47 Permutations II.md b/ChenXiaoxu/47 Permutations II.md new file mode 100644 index 0000000..14156f0 --- /dev/null +++ b/ChenXiaoxu/47 Permutations II.md @@ -0,0 +1,91 @@ +# 47. Permutations II + +##Problem + +Given a collection of numbers that might contain duplicates, return all possible unique permutations. + +For example, +[1,1,2] have the following unique permutations: +[1,1,2], [1,2,1], and [2,1,1]. + +tags: +- backtracking +- 包含重复元素的全排列 + +## Solution + +参考:《组合数学》 + +- 直接生成(递归/回溯) +- 邻位互换 +- 序数法 +- 字典序法 +- 轮转法 + +### 递归 + +参考全排列的递归公式(46 Permutations.md),以重复元素作为前缀的均算作一个排列 +即: + +n=1 排列为自身 +n>1 Pn = iPi (i为序列中不重复的元素,Pi表示以i作为前缀的全排列) + +**java** +```java +public class Solution { + public List> permuteUnique(int[] nums) { + List> res = new ArrayList>(); + recur(res, nums, 0, nums.length); + return res; + } + + void recur(List> res, int[] nums, int begin, int end) { + if(begin==end) { + List li = new ArrayList(nums.length); + for(Integer num:nums) { + li.add(num); + } + res.add(li); + } else { + for(int i=begin;ibegin; i--) { + if(nums[end]==nums[i-1]) { + return false; + } + } + return true; + } +} +``` + +### 字典序法 + +**字典序:** +对于两个序列 a1...ak和b1...bk,若存在t,使得ai=bi,at < bt,则序列 +a1...ak < b1...bk + +**生成算法** + +设P是1...n的一个全排列,P = P1P2...Pj-1PjPj+1...Pk-1PkPk+1...Pn + +1. 找出j=max{i|Pi < Pi+1}, k=max{i|Pi <=> Pj} +2. 对换Pj,Pk +3. Pj+1...Pk-1PkPk+1...Pn + +**未完待续。。。** \ No newline at end of file diff --git a/ChenXiaoxu/49. Group Anagrams.md b/ChenXiaoxu/49. Group Anagrams.md new file mode 100644 index 0000000..422ef94 --- /dev/null +++ b/ChenXiaoxu/49. Group Anagrams.md @@ -0,0 +1,62 @@ +# 49. Group Anagrams + + +## Problem + +Given an array of strings, group anagrams together. + +For example, given: ["eat", "tea", "tan", "ate", "nat", "bat"], +Return: + +``` +[ + ["ate", "eat","tea"], + ["nat","tan"], + ["bat"] +] +``` + +Note: +For the return value, each inner list's elements must follow the lexicographic order. +All inputs will be in lower-case. + +tag: + +## Solution + +Anagram,回文构词法,指由颠倒字母顺序构成的单词,字母的种类和数目没有改变,只是改变了字母顺序,因此排序后相同。 + +用哈希表存储同构变形词的词根,对单词表进行遍历,在哈希表中查找同构的词根,并添到列表中。 + +注意结果按字母序输出,Java可采用Collections.sort实现。 + + +**java** +```java + public List> groupAnagrams(String[] strs) { + List> res = new ArrayList>(); + Map> map = new HashMap>(); + for (String str : strs) { + char[] tmp = str.toCharArray(); + Arrays.sort(tmp); + String key = new String(tmp); + List li = map.get(key); + if (li == null) { + li = new ArrayList(); + } + li.add(str); + map.put(key, li); + } + for (String key : map.keySet()) { + List value = map.get(key); + Collections.sort(value); + res.add(value); + } + return res; + } +``` + +**go** +```go + +``` \ No newline at end of file diff --git a/ChenXiaoxu/LeetCode/src.main.java/backtracking/nqueens_51/Solution.java b/ChenXiaoxu/51 N-Queens.md similarity index 65% rename from ChenXiaoxu/LeetCode/src.main.java/backtracking/nqueens_51/Solution.java rename to ChenXiaoxu/51 N-Queens.md index 88bc9a0..3aab5b1 100644 --- a/ChenXiaoxu/LeetCode/src.main.java/backtracking/nqueens_51/Solution.java +++ b/ChenXiaoxu/51 N-Queens.md @@ -1,8 +1,39 @@ -package backtracking.nqueens_51; +# 51. N-Queens -import java.util.ArrayList; -import java.util.List; +## Problem +The n-queens puzzle is the problem of placing n queens on an n×n chessboard such that no two queens attack each other. + + + +Given an integer n, return all distinct solutions to the n-queens puzzle. + +Each solution contains a distinct board configuration of the n-queens' placement, where 'Q' and '.' both indicate a queen and an empty space respectively. + +For example, +There exist two distinct solutions to the 4-queens puzzle: + +[ + [".Q..", // Solution 1 + "...Q", + "Q...", + "..Q."], + + ["..Q.", // Solution 2 + "Q...", + "...Q", + ".Q.."] +] + +tag: +- math +- binary search + +## Solution + +**java** + +```java public class Solution { public List> solveNQueens(int n) { @@ -53,4 +84,5 @@ public static void main(String[] args) { int n = 4; } -} \ No newline at end of file +} +``` diff --git a/ChenXiaoxu/6. ZigZag Conversion.md b/ChenXiaoxu/6. ZigZag Conversion.md new file mode 100644 index 0000000..4b7b98f --- /dev/null +++ b/ChenXiaoxu/6. ZigZag Conversion.md @@ -0,0 +1,63 @@ +# 6. ZigZag Conversion + +## Problem + +The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility) + +``` +P A H N +A P L S I I G +Y I R +``` +And then read line by line: "PAHNAPLSIIGYIR" +Write the code that will take a string and make this conversion given a number of rows: + +```string convert(string text, int nRows);``` + +convert("PAYPALISHIRING", 3) should return "PAHNAPLSIIGYIR". + +tag: +- String +- 归纳推理 + +## Solution + +我们用数字表示每一行字母的下标 + +``` + 0 2n-2 + 1 2n-3 2n-1 + 2 2n-4 2n-0 +... ... ... +n-3 n+1 +n-2 n +n-1 +``` +该排列具有周期性, 周期为```2n-2```, 设为```m```; +在每一个周期内,第一行和最后一行均有一个元素,其余每行有两个元素,具有以下规律: +第i行第一个元素为```j=km+i(k=0,1,2,3...)```, 第二个元素和第一个元素相差m-2i, 故第二个元素为j+m-2i。 + +具体实现如下: + +**java** +```java + public String convert(String s, int numRows) { + if (numRows <= 1) + return s; + int cycle = 2 * numRows - 2; + StringBuffer res = new StringBuffer(); + for (int i = 0; i < numRows; i++) { + for (int j = i; j < s.length(); j += cycle) { + if (j < s.length()) + res.append(s.charAt(j)); + if (i < numRows-1 && i > 0) { + int p = j + cycle - 2 * i; + if (p < s.length()) + res.append(s.charAt(p)); + } + } + } + return res.toString(); + } +``` + diff --git a/ChenXiaoxu/61. Rotate List.md b/ChenXiaoxu/61. Rotate List.md new file mode 100644 index 0000000..0bda297 --- /dev/null +++ b/ChenXiaoxu/61. Rotate List.md @@ -0,0 +1,70 @@ +# [61. Rotate List](https://leetcode.com/problems/rotate-list/) + +## Problem + +Given a list, rotate the list to the right by k places, where k is non-negative. + +For example: +Given ```1->2->3->4->5->NULL``` and ```k = 2```, +return``` 4->5->1->2->3->NULL```. + +tag: +- linkedlist +- two pointers + +## Solution + +把链表后K个节点旋转到前面; 研究了半天才搞懂题意 :( + +采用快慢指针 + +``` + +1. 定义两个指针p,q, 初始化分别指向dummyHead, 然后移动p,q开始旋转的位置和链表尾 +注意k可能超出链表长度, 因此要对链表长度取余, 即p移动```len-k%len```步, +dummyHead->1->2->3->4->5->null + ^ ^ + | | + p q + + +2. 对链表进行旋转操作 + +表尾指向表头: q-next = dummyHead->next; +表头指向新的表头: dummyHead->next = p->next; +新的表尾指向空: p-next = null + +dummyHead-4->5->1->2->3->null + ^ ^ + | | + q p +``` + + +**java** +```java + public ListNode rotateRight(ListNode head, int k) { + if(head==null) return head; + ListNode dummyHead = new ListNode(0); + dummyHead.next = head; + ListNode p=dummyHead,q=dummyHead; + + int len = 0; + while(q.next!=null) { + q = q.next; + len++; + } + for(int i=0; i1?1:0 +``` + +**java** +```java + public String addBinary(String a, String b) { + StringBuffer res = new StringBuffer(); + int carry = 0; + int i, j; + for (i = a.length() - 1, j = b.length() - 1; i >= 0 && j >= 0; i--, j--) { + int m = a.charAt(i) - '0', n = b.charAt(j) - '0'; + int r = m ^ n ^ carry; + carry = (m + n + carry) > 1 ? 1 : 0; + res.append(r); + } + if (i < 0 && j >= 0) { + while (j >= 0) { + res.append((b.charAt(j) - '0') ^ carry); + carry = (b.charAt(j) - '0') & carry; + j--; + } + if (carry == 1) + res.append(carry); + } else if (j < 0 && i >= 0) { + while (i >= 0) { + res.append((a.charAt(i) - '0') ^ carry); + carry = (a.charAt(i) - '0') & carry; + i--; + } + if (carry == 1) + res.append(carry); + } else { + if (carry > 0) + res.append(1); + } + return res.reverse().toString(); + } +``` \ No newline at end of file diff --git a/ChenXiaoxu/LeetCode/src.main.java/math/Solution.java b/ChenXiaoxu/69 Sqrt(x).md similarity index 57% rename from ChenXiaoxu/LeetCode/src.main.java/math/Solution.java rename to ChenXiaoxu/69 Sqrt(x).md index 7dde53b..a5872d2 100644 --- a/ChenXiaoxu/LeetCode/src.main.java/math/Solution.java +++ b/ChenXiaoxu/69 Sqrt(x).md @@ -1,6 +1,22 @@ -package math; +#69. Sqrt(x) -public class Solution { +## Problem + +Implement int sqrt(int x). + +Compute and return the square root of x. + +Subscribe to see which companies asked this question + +tag: +- math +- binary search + +## Solution + +**java** + +```java public int mySqrt(int x) { long l = 0, r = x / 2 + 1; @@ -15,4 +31,4 @@ else if (m * m > x) } return (int) r; } -} +``` diff --git a/ChenXiaoxu/75. Sort Colors.md b/ChenXiaoxu/75. Sort Colors.md new file mode 100644 index 0000000..aeee1ce --- /dev/null +++ b/ChenXiaoxu/75. Sort Colors.md @@ -0,0 +1,43 @@ +# [75. Sort Colors](https://leetcode.com/problems/sort-colors/) + +## Problem + +Given an array with n objects colored red, white or blue, sort them so that objects of the same color are adjacent, with the colors in the order red, white and blue. + +Here, we will use the integers 0, 1, and 2 to represent the color red, white, and blue respectively. + +tag: +- two pointers + +## Solution + +### 通用的解法 + +通用的解法是遍历一次数组,统计各种颜色的个数,然后重写数组。该方法需要遍历两边数组,但能决绝超过三种颜色问题。 + +### 一次遍历 + +定义两个指针,分隔三种颜色, 一次遍历, 把第一种颜色移到数组最前面, 把第三种颜色移到最后面。 + +**java** +```java + public void sortColors(int[] nums) { + int p1 = 0, p2 = nums.length-1; + for(int i=0; i<=p2; ) { + if(nums[i]==0) swap(nums, i++, p1++); + else if(nums[i]==2) swap(nums, i, p2--); + else i++; + } + } + + public void swap(int[] nums, int i, int j) { + int tmp = nums[i]; + nums[i] = nums[j]; + nums[j] = tmp; + } +``` + +**go** +```go + +``` \ No newline at end of file diff --git a/ChenXiaoxu/79 Word Search.md b/ChenXiaoxu/79 Word Search.md new file mode 100644 index 0000000..2884651 --- /dev/null +++ b/ChenXiaoxu/79 Word Search.md @@ -0,0 +1,26 @@ +# 79. Word Search + +## Probmel + +Given a 2D board and a word, find if the word exists in the grid. + +The word can be constructed from letters of sequentially adjacent cell, where "adjacent" cells are those horizontally or vertically neighboring. The same letter cell may not be used more than once. + +For example, +Given board = + + [ + ['A','B','C','E'], + ['S','F','C','S'], + ['A','D','E','E'] + ] + +word = "ABCCED", -> returns true, +word = "SEE", -> returns true, +word = "ABCB", -> returns false. + +tag: +- array +- backtracking + +## Solution \ No newline at end of file diff --git a/ChenXiaoxu/79. Word Search.md b/ChenXiaoxu/79. Word Search.md new file mode 100644 index 0000000..5db1de6 --- /dev/null +++ b/ChenXiaoxu/79. Word Search.md @@ -0,0 +1,59 @@ +# 79. Word Search + +## Problem + +Given a 2D board and a word, find if the word exists in the grid. + +The word can be constructed from letters of sequentially adjacent cell, where "adjacent" cells are those horizontally or vertically neighboring. The same letter cell may not be used more than once. + +For example, +Given board = +``` +[ + ['A','B','C','E'], + ['S','F','C','S'], + ['A','D','E','E'] +] +``` +word = "ABCCED", -> returns true, +word = "SEE", -> returns true, +word = "ABCB", -> returns false. + +tag: +- bfs + +## Solution + +以面板中的任一字符作为起始节点,进行深度优先搜索,如果匹配,返回True,如果所有节点的搜索结果均不匹配,返回false。 + +**java** +```java + public boolean exist(char[][] board, String word) { + boolean isVisit[][] = new boolean[board.length][board[0].length]; + for (int i = 0; i < board.length; i++) + for (int j = 0; j < board[0].length; j++) + if (search(board, isVisit, word, 0, i, j)) + return true; + return false; + } + + private boolean search(char[][] board, boolean[][] isVisit, String word, int index, int i, int j) { + if (index == word.length()) + return true; + if (i < 0 || j < 0 || i >= board.length || j >= board[0].length || isVisit[i][j] + || board[i][j] != word.charAt(index)) + return false; + isVisit[i][j] = true; + boolean result = search(board, isVisit, word, index + 1, i + 1, j) + || search(board, isVisit, word, index + 1, i - 1, j) + || search(board, isVisit, word, index + 1, i, j + 1) + || search(board, isVisit, word, index + 1, i, j - 1); + isVisit[i][j] = false; + return result; + } +``` + +**go** +```go + +``` \ No newline at end of file diff --git a/ChenXiaoxu/8 String to Integer (atoi).md b/ChenXiaoxu/8 String to Integer (atoi).md new file mode 100644 index 0000000..a70506f --- /dev/null +++ b/ChenXiaoxu/8 String to Integer (atoi).md @@ -0,0 +1,66 @@ +# 8. String to Integer (atoi) + +## Problem + +Implement atoi to convert a string to an integer. + +Hint: Carefully consider all possible input cases. If you want a challenge, please do not see below and ask yourself what are the possible input cases. + +Notes: It is intended for this problem to be specified vaguely (ie, no given input specs). You are responsible to gather all the input requirements up front. + +Update (2015-02-10): +The signature of the C++ function had been updated. If you still see your function signature accepts a const char * argument, please click the reload button to reset your code definition. + +spoilers alert... click to show requirements for atoi. + +Requirements for atoi: +The function first discards as many whitespace characters as necessary until the first non-whitespace character is found. Then, starting from this character, takes an optional initial plus or minus sign followed by as many numerical digits as possible, and interprets them as a numerical value. + +The string can contain additional characters after those that form the integral number, which are ignored and have no effect on the behavior of this function. + +If the first sequence of non-whitespace characters in str is not a valid integral number, or if no such sequence exists because either str is empty or it contains only whitespace characters, no conversion is performed. + +If no valid conversion could be performed, a zero value is returned. If the correct value is out of the range of representable values, INT_MAX (2147483647) or INT_MIN (-2147483648) is returned. + +tag: +- math +- string + + +## Solution + +**java** + +```java + public int myAtoi(String str) { + if (str == null || str.isEmpty()) + return 0; + + str = str.trim(); + + int index = 0; + int sign = 1; + long result = 0; + if (str.charAt(index) == '-') { + sign = -1; + index++; + } else if (str.charAt(index) == '+') { + index++; + } + for (; index < str.length(); index++) { + if (!Character.isDigit(str.charAt(index))) + break; + result = result * 10 + (str.charAt(index) - '0'); + if (result > Integer.MAX_VALUE) + break; + } + + result = sign * result; + if (result >= Integer.MAX_VALUE) + return Integer.MAX_VALUE; + if (result <= Integer.MIN_VALUE) + return Integer.MIN_VALUE; + + return (int) result; + } +``` \ No newline at end of file diff --git a/ChenXiaoxu/80 Remove Duplicates from Sorted Array II.md b/ChenXiaoxu/80 Remove Duplicates from Sorted Array II.md new file mode 100644 index 0000000..af2e6dc --- /dev/null +++ b/ChenXiaoxu/80 Remove Duplicates from Sorted Array II.md @@ -0,0 +1,35 @@ +# 80. Remove Duplicates from Sorted Array II + +## Problem + +Follow up for "Remove Duplicates": +What if duplicates are allowed at most twice? + +For example, +Given sorted array nums = [1,1,1,2,2,3], + +Your function should return length = 5, with the first five elements of nums being 1, 1, 2, 2 and 3. It doesn't matter what you leave beyond the new length. + + +tags: +- Array +- Two Pointers + +## Solution + +**java** + +```java + public int removeDuplicates(int[] nums) { + if (nums.length <= 2) + return nums.length; + int cur = 2, pre = 1; + while (cur < nums.length) { + if (nums[cur] == nums[pre] && nums[cur] == nums[pre - 1]) + cur++; + else + nums[++pre] = nums[cur++]; + } + return pre + 1; + } +``` \ No newline at end of file diff --git a/ChenXiaoxu/81 Search in Rotated Sorted Array II.md b/ChenXiaoxu/81 Search in Rotated Sorted Array II.md new file mode 100644 index 0000000..5dc7ef5 --- /dev/null +++ b/ChenXiaoxu/81 Search in Rotated Sorted Array II.md @@ -0,0 +1,47 @@ +# 46. Permutations + +## Problem + +Follow up for "Search in Rotated Sorted Array": +What if duplicates are allowed? + +Would this affect the run-time complexity? How and why? + +Write a function to determine if a given target is in the array. + +tags: +- array +- binary search + +similar problems: + +- (M) Search in Rotated Sorted Array + + +## Solution + +```java +public int search(int[] nums, int target) { + if (nums == null || nums.length == 0) + return -1; + int left = 0, right = nums.length - 1; + while (left <= right) { + int mid = left + (right - left) / 2; + if (target == nums[mid]) + return mid; + + if (nums[mid] >= nums[left]) { + if (nums[left] <= target && target <= nums[mid]) + right = mid - 1; + else + left = mid + 1; + } else { + if (nums[mid] < target && target <= nums[right]) + left = mid + 1; + else + right = mid - 1; + } + } + return -1; +} +``` \ No newline at end of file diff --git a/ChenXiaoxu/LeetCode/src.main.java/linkedlist/duplicates/II/Solution.java b/ChenXiaoxu/82 Remove Duplicates from Sorted List II.md similarity index 57% rename from ChenXiaoxu/LeetCode/src.main.java/linkedlist/duplicates/II/Solution.java rename to ChenXiaoxu/82 Remove Duplicates from Sorted List II.md index a89c787..9321419 100644 --- a/ChenXiaoxu/LeetCode/src.main.java/linkedlist/duplicates/II/Solution.java +++ b/ChenXiaoxu/82 Remove Duplicates from Sorted List II.md @@ -1,8 +1,21 @@ -package linkedlist.duplicates.II; +# 83. Remove Duplicates from Sorted List -import linkedlist.ListNode; +## Problem -public class Solution { +Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list. + +For example, +Given 1->2->3->3->4->4->5, return 1->2->5. +Given 1->1->1->2->3, return 2->3. + +tag: +- linked list + +## Solution + +**java** + +```java public ListNode deleteDuplicates(ListNode head) { if (head == null || head.next == null) return head; @@ -21,4 +34,4 @@ public ListNode deleteDuplicates(ListNode head) { } return dummyNode.next; } -} +``` diff --git a/ChenXiaoxu/83 Remove Duplicates from Sorted List.md b/ChenXiaoxu/83 Remove Duplicates from Sorted List.md new file mode 100644 index 0000000..f2a869e --- /dev/null +++ b/ChenXiaoxu/83 Remove Duplicates from Sorted List.md @@ -0,0 +1,31 @@ +# 83. Remove Duplicates from Sorted List + +## Problem + +Given a sorted linked list, delete all duplicates such that each element appear only once. + +For example, +Given 1->1->2, return 1->2. +Given 1->1->2->3->3, return 1->2->3. + +tag: +- linked list + +## Solution + +**java** + +```java + public ListNode deleteDuplicates(ListNode head) { + if (head==null||head.next==null) + return head; + ListNode p = head; + while (p.next != null) { + if (p.val == p.next.val) + p.next = p.next.next; + else + p = p.next; + } + return head; + } +``` diff --git a/ChenXiaoxu/86. Partition List.md b/ChenXiaoxu/86. Partition List.md new file mode 100644 index 0000000..444855c --- /dev/null +++ b/ChenXiaoxu/86. Partition List.md @@ -0,0 +1,44 @@ +# [86. Partition List](https://leetcode.com/problems/partition-list/) + +## Problem + +Given a linked list and a value x, partition it such that all nodes less than x come before nodes greater than or equal to x. + +You should preserve the original relative order of the nodes in each of the two partitions. + +For example, +Given 1->4->3->2->5->2 and x = 3, +return 1->2->2->4->3->5. + +tag: +- two pointers + +## Solution + +![](http://i.imgur.com/5i5vvk8.jpg) + +**java** +```java + public ListNode partition(ListNode head, int x) { + ListNode dummySmallHead = new ListNode(0), dummyBigHead = new ListNode(0); + ListNode p1 = dummySmallHead, p2 = dummyBigHead; + while(head!=null) { + if(head.val= 0){ + if(p2<0 || (p1>=0 && nums1[p1]>nums2[p2])) nums1[p--] = nums1[p1--];//注意p1>=0写在nums1[p1]>nums2[p2]之前 + else nums1[p--] = nums2[p2--]; + } + } +``` + +**go** +```go + +``` \ No newline at end of file diff --git a/ChenXiaoxu/91. Decode Ways.md b/ChenXiaoxu/91. Decode Ways.md new file mode 100644 index 0000000..a31c9af --- /dev/null +++ b/ChenXiaoxu/91. Decode Ways.md @@ -0,0 +1,56 @@ +# 91. Decode Ways + +## Problem + +A message containing letters from A-Z is being encoded to numbers using the following mapping: + +'A' -> 1 +'B' -> 2 +... +'Z' -> 26 +Given an encoded message containing digits, determine the total number of ways to decode it. + +For example, +Given encoded message "12", it could be decoded as "AB" (1 2) or "L" (12). + +The number of ways decoding "12" is 2. + +tag: + +- dp + +## Solution + +满足最优子结构和子问题重叠, 采用动态规划算法: + +设```f[i]```表示字串长度为i的解码方式数量,```f[0]=0```, 则: + +设```f[i]=0``` + +最后一位字符作为一个编码(```s.charAt(i-1)>'0'```): ```f[i] += f[i-1]``` +最后两位字符作为一个编码(```i>1 且 "10"= '0') + res[i] += res[i-1]; + if (i>1 && Integer.parseInt(s.substring(i - 2, i)) >= 10 && Integer.parseInt(s.substring(i - 2, i)) <= 26) + res[i] += res[i - 2]; + } + return res[length]; + } +``` + +**go** +```go + +``` \ No newline at end of file diff --git a/ChenXiaoxu/94. Binary Tree Inorder Traversal.md b/ChenXiaoxu/94. Binary Tree Inorder Traversal.md new file mode 100644 index 0000000..02288f9 --- /dev/null +++ b/ChenXiaoxu/94. Binary Tree Inorder Traversal.md @@ -0,0 +1,63 @@ +# 94. Binary Tree Inorder Traversal + +## Problem + +Given a binary tree, return the inorder traversal of its nodes' values. + +``` +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode(int x) { val = x; } + * } + */ +``` + +tag: + +## Solution + +### 递归 + +**java** +```java + public List inorderTraversal(TreeNode root, List res) { + if(root!=null) { + inorderTraversal(root.left, res); + res.add(root.val); + inorderTraversal(root.right, res); + } + return res; + } +``` + +**go** +```go + +``` + +### 迭代 + +``` java + public List inorderTraversal(TreeNode root) { + List res = new LinkedList(); + Stack s = new Stack(); + TreeNode p = root; + while(p!=null || !s.isEmpty()) { + //push root to stack, traverse left subtree + if(p!=null) { + s.push(p); + p=p.left; + } else { + //pop root, visit root node, and travese right subtree + p = s.pop(); + res.add(p.val); + p = p.right; + } + } + return res; + } +``` \ No newline at end of file diff --git a/ChenXiaoxu/96. Unique Binary Search Trees.md b/ChenXiaoxu/96. Unique Binary Search Trees.md new file mode 100644 index 0000000..f00256c --- /dev/null +++ b/ChenXiaoxu/96. Unique Binary Search Trees.md @@ -0,0 +1,43 @@ +# 96. Unique Binary Search Trees + +## Problem + +Given n, how many structurally unique BST's (binary search trees) that store values 1...n? + +For example, +Given n = 3, there are a total of 5 unique BST's. +``` + 1 3 3 2 1 + \ / / / \ \ + 3 2 1 1 3 2 + / / \ \ + 2 1 2 3 +``` + +tag: +- 组合问题 +- [卡特兰数](https://zh.wikipedia.org/wiki/%E5%8D%A1%E5%A1%94%E5%85%B0%E6%95%B0) +- dp + +## Solution + +该题即求解异构BST的个数: +有序数列1...n中以i为根的BST的左子树包含[1...i-1],用右子树包含[i+1...n],以i为根的异构BST个数为左子树与右子树的乘积,故异构BST总数为 +``` + f(n) = f(0)*f(n-1)+f(1)f(n-2)...f(n-1)*f(0) +``` + +**java** + +```java + public int numTrees(int n) { + int[] res = new int[n + 1]; + res[0] = res[1] = 1; + for (int i = 2; i <= n; i++) { + for (int k = 1; k <= i; k++) { + res[i] += res[k - 1] * res[i - k]; + } + } + return res[n]; + } +``` \ No newline at end of file diff --git a/ChenXiaoxu/98. Validate Binary Search Tree.md b/ChenXiaoxu/98. Validate Binary Search Tree.md new file mode 100644 index 0000000..16428b4 --- /dev/null +++ b/ChenXiaoxu/98. Validate Binary Search Tree.md @@ -0,0 +1,40 @@ +# 98. Validate Binary Search Tree + +## Problem +Given a binary tree, determine if it is a valid binary search tree (BST). + +Assume a BST is defined as follows: + +The left subtree of a node contains only nodes with keys less than the node's key. +The right subtree of a node contains only nodes with keys greater than the node's key. +Both the left and right subtrees must also be binary search trees. + +tag: + +## Solution +中序遍历,然后判断是否为升序 + +**java** +```java + public boolean isValidBST(TreeNode root) { + List res = new ArrayList(); + inOrderTraverse(root, res); + for(int i=1; i res) { + if(root!=null){ + inOrderTraverse(root.left, res); + res.add(root.val); + inOrderTraverse(root.right, res); + } + } +``` + +**go** +```go + +``` \ No newline at end of file diff --git a/ChenXiaoxu/LeetCode/.classpath b/ChenXiaoxu/LeetCode/.classpath deleted file mode 100644 index 0757c68..0000000 --- a/ChenXiaoxu/LeetCode/.classpath +++ /dev/null @@ -1,8 +0,0 @@ - - - - - - - - diff --git a/ChenXiaoxu/LeetCode/.project b/ChenXiaoxu/LeetCode/.project deleted file mode 100644 index 4fdb69a..0000000 --- a/ChenXiaoxu/LeetCode/.project +++ /dev/null @@ -1,17 +0,0 @@ - - - LeetCode - - - - - - org.eclipse.jdt.core.javabuilder - - - - - - org.eclipse.jdt.core.javanature - - diff --git a/ChenXiaoxu/LeetCode/.settings/org.eclipse.jdt.core.prefs b/ChenXiaoxu/LeetCode/.settings/org.eclipse.jdt.core.prefs deleted file mode 100644 index 3a21537..0000000 --- a/ChenXiaoxu/LeetCode/.settings/org.eclipse.jdt.core.prefs +++ /dev/null @@ -1,11 +0,0 @@ -eclipse.preferences.version=1 -org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled -org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.8 -org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve -org.eclipse.jdt.core.compiler.compliance=1.8 -org.eclipse.jdt.core.compiler.debug.lineNumber=generate -org.eclipse.jdt.core.compiler.debug.localVariable=generate -org.eclipse.jdt.core.compiler.debug.sourceFile=generate -org.eclipse.jdt.core.compiler.problem.assertIdentifier=error -org.eclipse.jdt.core.compiler.problem.enumIdentifier=error -org.eclipse.jdt.core.compiler.source=1.8 diff --git a/ChenXiaoxu/LeetCode/bin/.gitignore b/ChenXiaoxu/LeetCode/bin/.gitignore deleted file mode 100644 index 93b90f8..0000000 --- a/ChenXiaoxu/LeetCode/bin/.gitignore +++ /dev/null @@ -1,2 +0,0 @@ -/math/ -/bs/ diff --git a/ChenXiaoxu/LeetCode/bin/array/duplicates/I/Solution.class b/ChenXiaoxu/LeetCode/bin/array/duplicates/I/Solution.class deleted file mode 100644 index 173b2e8..0000000 Binary files a/ChenXiaoxu/LeetCode/bin/array/duplicates/I/Solution.class and /dev/null differ diff --git a/ChenXiaoxu/LeetCode/bin/array/duplicates/II/Solution.class b/ChenXiaoxu/LeetCode/bin/array/duplicates/II/Solution.class deleted file mode 100644 index 6368963..0000000 Binary files a/ChenXiaoxu/LeetCode/bin/array/duplicates/II/Solution.class and /dev/null differ diff --git a/ChenXiaoxu/LeetCode/bin/array/rotated/I/Solution.class b/ChenXiaoxu/LeetCode/bin/array/rotated/I/Solution.class deleted file mode 100644 index e69ac1d..0000000 Binary files a/ChenXiaoxu/LeetCode/bin/array/rotated/I/Solution.class and /dev/null differ diff --git a/ChenXiaoxu/LeetCode/bin/backtracking/nqueens_51/Solution.class b/ChenXiaoxu/LeetCode/bin/backtracking/nqueens_51/Solution.class deleted file mode 100644 index c3980bc..0000000 Binary files a/ChenXiaoxu/LeetCode/bin/backtracking/nqueens_51/Solution.class and /dev/null differ diff --git a/ChenXiaoxu/LeetCode/bin/linkedlist/List.class b/ChenXiaoxu/LeetCode/bin/linkedlist/List.class deleted file mode 100644 index 68c6e7b..0000000 Binary files a/ChenXiaoxu/LeetCode/bin/linkedlist/List.class and /dev/null differ diff --git a/ChenXiaoxu/LeetCode/bin/linkedlist/ListNode.class b/ChenXiaoxu/LeetCode/bin/linkedlist/ListNode.class deleted file mode 100644 index 363e4a0..0000000 Binary files a/ChenXiaoxu/LeetCode/bin/linkedlist/ListNode.class and /dev/null differ diff --git a/ChenXiaoxu/LeetCode/bin/linkedlist/duplicates/I/Solution.class b/ChenXiaoxu/LeetCode/bin/linkedlist/duplicates/I/Solution.class deleted file mode 100644 index 41d0ea3..0000000 Binary files a/ChenXiaoxu/LeetCode/bin/linkedlist/duplicates/I/Solution.class and /dev/null differ diff --git a/ChenXiaoxu/LeetCode/bin/linkedlist/duplicates/II/Solution.class b/ChenXiaoxu/LeetCode/bin/linkedlist/duplicates/II/Solution.class deleted file mode 100644 index b93642b..0000000 Binary files a/ChenXiaoxu/LeetCode/bin/linkedlist/duplicates/II/Solution.class and /dev/null differ diff --git a/ChenXiaoxu/LeetCode/bin/linkedlist/duplicates/SolutionTest.class b/ChenXiaoxu/LeetCode/bin/linkedlist/duplicates/SolutionTest.class deleted file mode 100644 index 99ebf3f..0000000 Binary files a/ChenXiaoxu/LeetCode/bin/linkedlist/duplicates/SolutionTest.class and /dev/null differ diff --git a/ChenXiaoxu/LeetCode/bin/linkedlist/merge/klist/Solution.class b/ChenXiaoxu/LeetCode/bin/linkedlist/merge/klist/Solution.class deleted file mode 100644 index 8ca6f80..0000000 Binary files a/ChenXiaoxu/LeetCode/bin/linkedlist/merge/klist/Solution.class and /dev/null differ diff --git a/ChenXiaoxu/LeetCode/bin/linkedlist/merge/klist/Solution.md b/ChenXiaoxu/LeetCode/bin/linkedlist/merge/klist/Solution.md deleted file mode 100644 index c140e7b..0000000 --- a/ChenXiaoxu/LeetCode/bin/linkedlist/merge/klist/Solution.md +++ /dev/null @@ -1,10 +0,0 @@ -# Merge k Sorted Lists - -## Naive - -**O(nk^2)** - - -## Divide and Conquer - -## Heap \ No newline at end of file diff --git a/ChenXiaoxu/LeetCode/bin/linkedlist/merge/klist/SolutionTest.class b/ChenXiaoxu/LeetCode/bin/linkedlist/merge/klist/SolutionTest.class deleted file mode 100644 index 239fb82..0000000 Binary files a/ChenXiaoxu/LeetCode/bin/linkedlist/merge/klist/SolutionTest.class and /dev/null differ diff --git a/ChenXiaoxu/LeetCode/bin/linkedlist/merge/twolist/Solution.class b/ChenXiaoxu/LeetCode/bin/linkedlist/merge/twolist/Solution.class deleted file mode 100644 index d9a99d1..0000000 Binary files a/ChenXiaoxu/LeetCode/bin/linkedlist/merge/twolist/Solution.class and /dev/null differ diff --git a/ChenXiaoxu/LeetCode/bin/linkedlist/merge/twolist/SolutionTest.class b/ChenXiaoxu/LeetCode/bin/linkedlist/merge/twolist/SolutionTest.class deleted file mode 100644 index e96502c..0000000 Binary files a/ChenXiaoxu/LeetCode/bin/linkedlist/merge/twolist/SolutionTest.class and /dev/null differ diff --git a/ChenXiaoxu/LeetCode/bin/str/atoi/README.md b/ChenXiaoxu/LeetCode/bin/str/atoi/README.md deleted file mode 100644 index b8ff215..0000000 --- a/ChenXiaoxu/LeetCode/bin/str/atoi/README.md +++ /dev/null @@ -1,20 +0,0 @@ -# String to Integer (atoi) - -## Problem - -The function first discards as many whitespace characters as necessary until the first non-whitespace character is found. Then, starting from this character, takes an optional initial plus or minus sign followed by as many numerical digits as possible, and interprets them as a numerical value. - -The string can contain additional characters after those that form the integral number, which are ignored and have no effect on the behavior of this function. - -If the first sequence of non-whitespace characters in str is not a valid integral number, or if no such sequence exists because either str is empty or it contains only whitespace characters, no conversion is performed. - -If no valid conversion could be performed, a zero value is returned. If the correct value is out of the range of representable values, INT_MAX (2147483647) or INT_MIN (-2147483648) is returned. - -## Method - -Traverse the string and convert it to integer, mainly pay attention to **corner case**. - -- whitespace -- plus or minus sign -- range -- non-numerical character diff --git a/ChenXiaoxu/LeetCode/bin/str/atoi/Solution.class b/ChenXiaoxu/LeetCode/bin/str/atoi/Solution.class deleted file mode 100644 index 05cde77..0000000 Binary files a/ChenXiaoxu/LeetCode/bin/str/atoi/Solution.class and /dev/null differ diff --git a/ChenXiaoxu/LeetCode/bin/str/palindrome/Solution.class b/ChenXiaoxu/LeetCode/bin/str/palindrome/Solution.class deleted file mode 100644 index 2f7ddcf..0000000 Binary files a/ChenXiaoxu/LeetCode/bin/str/palindrome/Solution.class and /dev/null differ diff --git a/ChenXiaoxu/LeetCode/bin/str/palindrome/SolutionTest.class b/ChenXiaoxu/LeetCode/bin/str/palindrome/SolutionTest.class deleted file mode 100644 index 94eb345..0000000 Binary files a/ChenXiaoxu/LeetCode/bin/str/palindrome/SolutionTest.class and /dev/null differ diff --git a/ChenXiaoxu/LeetCode/src.main.java/array/duplicates/I/Solution.java b/ChenXiaoxu/LeetCode/src.main.java/array/duplicates/I/Solution.java deleted file mode 100644 index 2bfc64e..0000000 --- a/ChenXiaoxu/LeetCode/src.main.java/array/duplicates/I/Solution.java +++ /dev/null @@ -1,22 +0,0 @@ -package array.duplicates.I; - -public class Solution { - - public int removeDuplicates(int[] nums) { - if (nums.length == 0 || nums.length == 1) - return nums.length; - int cur = 0; - for (int i = 1; i < nums.length; i++) { - if (nums[i] != nums[cur]) { - nums[++cur] = nums[i]; - } - } - return cur + 1; - } - - public static void main(String[] args) { - Solution so = new Solution(); - int[] nums = { 1, 2, 2, 3, 3, 4 }; - System.out.println(so.removeDuplicates(nums)); - } -} diff --git a/ChenXiaoxu/LeetCode/src.main.java/array/duplicates/II/Solution.java b/ChenXiaoxu/LeetCode/src.main.java/array/duplicates/II/Solution.java deleted file mode 100644 index 122c38b..0000000 --- a/ChenXiaoxu/LeetCode/src.main.java/array/duplicates/II/Solution.java +++ /dev/null @@ -1,17 +0,0 @@ -package array.duplicates.II; - -public class Solution { - - public int removeDuplicates(int[] nums) { - if (nums.length <= 2) - return nums.length; - int cur = 2, pre = 1; - while (cur < nums.length) { - if (nums[cur] == nums[pre] && nums[cur] == nums[pre - 1]) - cur++; - else - nums[++pre] = nums[cur++]; - } - return pre + 1; - } -} diff --git a/ChenXiaoxu/LeetCode/src.main.java/array/rotated/I/Solution.java b/ChenXiaoxu/LeetCode/src.main.java/array/rotated/I/Solution.java deleted file mode 100644 index 7394b29..0000000 --- a/ChenXiaoxu/LeetCode/src.main.java/array/rotated/I/Solution.java +++ /dev/null @@ -1,33 +0,0 @@ -package array.rotated.I; - -public class Solution { - - public int search(int[] nums, int target) { - if (nums == null || nums.length == 0) - return -1; - int left = 0, right = nums.length - 1; - while (left <= right) { - int mid = left + (right - left) / 2; - if (target == nums[mid]) - return mid; - - if (nums[mid] >= nums[left]) { - if (nums[left] <= target && target <= nums[mid]) - right = mid - 1; - else - left = mid + 1; - } else { - if (nums[mid] < target && target <= nums[right]) - left = mid + 1; - else - right = mid - 1; - } - } - return -1; - } - - public static void main(String[] args) { - // TODO Auto-generated method stub - } - -} diff --git a/ChenXiaoxu/LeetCode/src.main.java/array/rotated/II/Solution.java b/ChenXiaoxu/LeetCode/src.main.java/array/rotated/II/Solution.java deleted file mode 100644 index e69de29..0000000 diff --git a/ChenXiaoxu/LeetCode/src.main.java/backtracking/nqueens_51/Solution.md b/ChenXiaoxu/LeetCode/src.main.java/backtracking/nqueens_51/Solution.md deleted file mode 100644 index e69de29..0000000 diff --git a/ChenXiaoxu/LeetCode/src.main.java/backtracking/wordsearch/I/Solution.java b/ChenXiaoxu/LeetCode/src.main.java/backtracking/wordsearch/I/Solution.java deleted file mode 100644 index e69de29..0000000 diff --git a/ChenXiaoxu/LeetCode/src.main.java/bs/README.md b/ChenXiaoxu/LeetCode/src.main.java/bs/README.md deleted file mode 100644 index e69de29..0000000 diff --git a/ChenXiaoxu/LeetCode/src.main.java/linkedlist/List.java b/ChenXiaoxu/LeetCode/src.main.java/linkedlist/List.java deleted file mode 100644 index 21a7cdb..0000000 --- a/ChenXiaoxu/LeetCode/src.main.java/linkedlist/List.java +++ /dev/null @@ -1,23 +0,0 @@ -package linkedlist; - -public class List { - public ListNode head; - - public List() { - head = null; - } - - public void insert(int val) { - ListNode tmp = new ListNode(val); - if (head != null) { - tmp.next = head; - head = tmp; - } else { - head = tmp; - } - } - - void delete(ListNode node) { - - } -} \ No newline at end of file diff --git a/ChenXiaoxu/LeetCode/src.main.java/linkedlist/ListNode.java b/ChenXiaoxu/LeetCode/src.main.java/linkedlist/ListNode.java deleted file mode 100644 index 0a7a07e..0000000 --- a/ChenXiaoxu/LeetCode/src.main.java/linkedlist/ListNode.java +++ /dev/null @@ -1,10 +0,0 @@ -package linkedlist; - -public class ListNode { - public int val; - public ListNode next; - - public ListNode(int x) { - val = x; - } -} \ No newline at end of file diff --git a/ChenXiaoxu/LeetCode/src.main.java/linkedlist/duplicates/I/Solution.java b/ChenXiaoxu/LeetCode/src.main.java/linkedlist/duplicates/I/Solution.java deleted file mode 100644 index c1167a1..0000000 --- a/ChenXiaoxu/LeetCode/src.main.java/linkedlist/duplicates/I/Solution.java +++ /dev/null @@ -1,18 +0,0 @@ -package linkedlist.duplicates.I; - -import linkedlist.ListNode; - -public class Solution { - public ListNode deleteDuplicates(ListNode head) { - if (head==null||head.next==null) - return head; - ListNode p = head; - while (p.next != null) { - if (p.val == p.next.val) - p.next = p.next.next; - else - p = p.next; - } - return head; - } -} diff --git a/ChenXiaoxu/LeetCode/src.main.java/linkedlist/merge/klist/Solution.md b/ChenXiaoxu/LeetCode/src.main.java/linkedlist/merge/klist/Solution.md deleted file mode 100644 index c140e7b..0000000 --- a/ChenXiaoxu/LeetCode/src.main.java/linkedlist/merge/klist/Solution.md +++ /dev/null @@ -1,10 +0,0 @@ -# Merge k Sorted Lists - -## Naive - -**O(nk^2)** - - -## Divide and Conquer - -## Heap \ No newline at end of file diff --git a/ChenXiaoxu/LeetCode/src.main.java/math/README.md b/ChenXiaoxu/LeetCode/src.main.java/math/README.md deleted file mode 100644 index f5d0089..0000000 --- a/ChenXiaoxu/LeetCode/src.main.java/math/README.md +++ /dev/null @@ -1,18 +0,0 @@ -#��ֵ��������Ŀ(NUMERIC CALCULATION) - -Ӧע�����¼������⣺ - -1. һ����ö��ַ����н��� -2. ע���������͡����Ⱥͱ߽����� - -# Problem set - -## 69. Sqrt(x) - -�Ǹ�����n��ƽ������ȡֵ��ΧΪ0~n������ȷn/2+1), �ڴ˷�Χ�ڽ��ж�������������⣬��ע��ȡ���ͱ߽����⣨��������֮���п��ܳ���int��Χ���� -ʱ�临�Ӷ� O(logn), �ռ临�Ӷ�O(1)�� - -## 50. Pow(x, n) - - - diff --git a/ChenXiaoxu/LeetCode/src.main.java/str/atoi/README.md b/ChenXiaoxu/LeetCode/src.main.java/str/atoi/README.md deleted file mode 100644 index b8ff215..0000000 --- a/ChenXiaoxu/LeetCode/src.main.java/str/atoi/README.md +++ /dev/null @@ -1,20 +0,0 @@ -# String to Integer (atoi) - -## Problem - -The function first discards as many whitespace characters as necessary until the first non-whitespace character is found. Then, starting from this character, takes an optional initial plus or minus sign followed by as many numerical digits as possible, and interprets them as a numerical value. - -The string can contain additional characters after those that form the integral number, which are ignored and have no effect on the behavior of this function. - -If the first sequence of non-whitespace characters in str is not a valid integral number, or if no such sequence exists because either str is empty or it contains only whitespace characters, no conversion is performed. - -If no valid conversion could be performed, a zero value is returned. If the correct value is out of the range of representable values, INT_MAX (2147483647) or INT_MIN (-2147483648) is returned. - -## Method - -Traverse the string and convert it to integer, mainly pay attention to **corner case**. - -- whitespace -- plus or minus sign -- range -- non-numerical character diff --git a/ChenXiaoxu/LeetCode/src.main.java/str/atoi/Solution.java b/ChenXiaoxu/LeetCode/src.main.java/str/atoi/Solution.java deleted file mode 100644 index 02ebe70..0000000 --- a/ChenXiaoxu/LeetCode/src.main.java/str/atoi/Solution.java +++ /dev/null @@ -1,35 +0,0 @@ -package str.atoi; - -public class Solution { - public int myAtoi(String str) { - if (str == null || str.isEmpty()) - return 0; - - str = str.trim(); - - int index = 0; - int sign = 1; - long result = 0; - if (str.charAt(index) == '-') { - sign = -1; - index++; - } else if (str.charAt(index) == '+') { - index++; - } - for (; index < str.length(); index++) { - if (!Character.isDigit(str.charAt(index))) - break; - result = result * 10 + (str.charAt(index) - '0'); - if (result > Integer.MAX_VALUE) - break; - } - - result = sign * result; - if (result >= Integer.MAX_VALUE) - return Integer.MAX_VALUE; - if (result <= Integer.MIN_VALUE) - return Integer.MIN_VALUE; - - return (int) result; - } -} diff --git a/ChenXiaoxu/LeetCode/src.main.java/str/palindrome/Solution.java b/ChenXiaoxu/LeetCode/src.main.java/str/palindrome/Solution.java deleted file mode 100644 index a4e6303..0000000 --- a/ChenXiaoxu/LeetCode/src.main.java/str/palindrome/Solution.java +++ /dev/null @@ -1,26 +0,0 @@ -package str.palindrome; - -public class Solution { - public boolean isPalindrome(String s) { - if (s == null || s.isEmpty()) - return true; - int l = 0, r = s.length() - 1; - while (l < r) { - if (!Character.isLetterOrDigit(s.charAt(l))) { - l++; - continue; - } - if (!Character.isLetterOrDigit(s.charAt(r))) { - r--; - continue; - } - if (Character.toLowerCase(s.charAt(l)) == Character.toLowerCase(s.charAt(r))) { - l++; - r--; - } else { - return false; - } - } - return true; - } -} \ No newline at end of file diff --git a/ChenXiaoxu/LeetCode/src.test.java/linkedlist/duplicates/SolutionTest.java b/ChenXiaoxu/LeetCode/src.test.java/linkedlist/duplicates/SolutionTest.java deleted file mode 100644 index 87e5ebd..0000000 --- a/ChenXiaoxu/LeetCode/src.test.java/linkedlist/duplicates/SolutionTest.java +++ /dev/null @@ -1,33 +0,0 @@ -package linkedlist.duplicates; - -import static org.junit.Assert.*; - -import org.junit.Before; -import org.junit.Test; - -import linkedlist.List; -import linkedlist.ListNode; -import linkedlist.duplicates.I.Solution; - -public class SolutionTest { - - private Solution solution = new Solution(); - - @Before - public void setUp() throws Exception { - } - - @Test - public void testDeleteDuplicates() { - List li = new List(); - li.insert(3); - li.insert(3); - li.insert(2); - li.insert(1); - li.insert(1); - solution.deleteDuplicates(li.head); - assertEquals(li.head.val, 1); - assertEquals(li.head.next.val, 2); - } - -} diff --git a/ChenXiaoxu/LeetCode/src.test.java/linkedlist/merge/klist/SolutionTest.java b/ChenXiaoxu/LeetCode/src.test.java/linkedlist/merge/klist/SolutionTest.java deleted file mode 100644 index 82e5b91..0000000 --- a/ChenXiaoxu/LeetCode/src.test.java/linkedlist/merge/klist/SolutionTest.java +++ /dev/null @@ -1,61 +0,0 @@ -package linkedlist.merge.klist; - -import static org.junit.Assert.*; - -import org.junit.Before; -import org.junit.Test; - -import linkedlist.List; -import linkedlist.ListNode; - -public class SolutionTest { - - private Solution solution = new Solution(); - - @Before - public void setUp() throws Exception { - - } - - @Test - public void testMergeKLists() { - - ListNode[] lists0 = null; - ListNode[] lists1 = new ListNode[3]; - List l1 = new List(); - List l2 = new List(); - List l3 = new List(); - l1.insert(11); - l1.insert(8); - l1.insert(8); - l1.insert(3); - - l2.insert(20); - l2.insert(15); - l2.insert(11); - l2.insert(9); - l2.insert(8); - l2.insert(6); - l2.insert(2); - - l3.insert(20); - l3.insert(1); - lists1[0] = l1.head; - lists1[1] = l2.head; - lists1[2] = l3.head; - - ListNode[] list2 = new ListNode[2]; - List l20 = new List(); - List l21 = new List(); - l21.insert(1); - list2[0] = l20.head; - list2[1] = l21.head; - - assertEquals(null, solution.mergeKLists(lists0)); - - assertEquals(1, solution.mergeKLists(lists1).val); - - assertEquals(1, solution.mergeKLists(list2).val); - } - -} diff --git a/ChenXiaoxu/LeetCode/src.test.java/linkedlist/merge/twolist/SolutionTest.java b/ChenXiaoxu/LeetCode/src.test.java/linkedlist/merge/twolist/SolutionTest.java deleted file mode 100644 index f8ac98f..0000000 --- a/ChenXiaoxu/LeetCode/src.test.java/linkedlist/merge/twolist/SolutionTest.java +++ /dev/null @@ -1,49 +0,0 @@ -package linkedlist.merge.twolist; - -import static org.junit.Assert.*; - -import org.junit.Before; -import org.junit.Test; - -import linkedlist.List; -import linkedlist.merge.twolist.Solution; - -public class SolutionTest { - - private Solution solution = new Solution(); - private List l1 = new List(); - private List l2 = new List(); - - @Before - public void setUp() throws Exception { - } - - @Test - public void testMergeTwoLists() { - // null, null - assertEquals(null, solution.mergeTwoLists(l1.head, l2.head)); - // 3,5,8,11 - // 2,6,8,9,11,15,20 - - l1.insert(11); - - assertEquals(11, solution.mergeTwoLists(l1.head, l2.head).val); - l1.insert(8); - l1.insert(8); - l1.insert(3); - - l2.insert(20); - l2.insert(15); - l2.insert(11); - l2.insert(9); - l2.insert(8); - l2.insert(6); - l2.insert(2); - - assertEquals(2, solution.mergeTwoLists(l1.head, l2.head).val); - - System.out.println(); - - } - -} diff --git a/ChenXiaoxu/LeetCode/src.test.java/math/sqrt/SolutionTest.java b/ChenXiaoxu/LeetCode/src.test.java/math/sqrt/SolutionTest.java deleted file mode 100644 index 57e050b..0000000 --- a/ChenXiaoxu/LeetCode/src.test.java/math/sqrt/SolutionTest.java +++ /dev/null @@ -1,31 +0,0 @@ -package math.sqrt; - -import static org.junit.Assert.*; - -import java.util.ArrayList; -import java.util.List; - -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; - -import math.Solution; - -public class SolutionTest { - - private Solution s = new Solution(); - - @Before - public void setUp() throws Exception { - } - - @Test - public void testMySqrt() { - int[] testCase = {0,1,2,3,4,5,6,7,8,9}; - int[] expect = {0, 1, 1, 1, 2, 2, 2, 2, 2, 3}; - for (int i=0; i ugly = new ArrayList(n); + ugly.add(1); + int p2 = 0, p3 = 0, p5 = 0; + while (ugly.size() < n) { + int min = min(ugly.get(p2) * 2, ugly.get(p3) * 3, ugly.get(p5) * 5); + if (min == ugly.get(p2) * 2) + p2 += 1; + if (min == ugly.get(p3) * 3) + p3 += 1; + if (min == ugly.get(p5) * 5) + p5 += 1; + ugly.add(min); + } + return ugly.get(n - 1); + } + + int min(int a, int b, int c) { + int min = Math.min(a, b); + min = Math.min(min, c); + return min; + } + + // 62. Unique Paths + public int uniquePaths(int m, int n) { + int[][] res = new int[m][n]; + for (int i = 0; i < m; i++) + res[i][0] = 1; + for (int j = 0; j < n; j++) + res[0][j] = 1; + for (int i = 1; i < m; i++) + for (int j = 1; j < n; j++) + res[i][j] = res[i - 1][j] + res[i][j - 1]; + return res[m - 1][n - 1]; + } + + // 63. Unique Paths II + public int uniquePathsWithObstacles(int[][] obstacleGrid) { + int m = obstacleGrid.length, n = obstacleGrid[0].length; + int[][] res = new int[m][n]; + res[0][0] = (obstacleGrid[0][0] == 1) ? 0 : 1; + for (int i = 1; i < m; i++) { + res[i][0] = (obstacleGrid[i][0] == 1) ? 0 : res[i - 1][0]; + } + for (int j = 1; j < n; j++) { + res[0][j] = (obstacleGrid[0][j] == 1) ? 0 : res[0][j - 1]; + } + for (int i = 1; i < m; i++) + for (int j = 1; j < n; j++) { + if (obstacleGrid[i][j] == 1) + res[i][j] = 0; + else + res[i][j] = res[i - 1][j] + res[i][j - 1]; + res[i][j] = (obstacleGrid[i][j] == 1) ? 0 : (res[i - 1][j] + res[i][j - 1]); + } + return res[m - 1][n - 1]; + } + + // 115. Distinct Subsequences + public int numDistinct(String s, String t) { + int m = s.length(), n = t.length(); + int[][] f = new int[m][n]; + for (int i = 0; i < m; i++) + f[i][0] = 1; + for (int j = 0; j < n; j++) + for (int i = 0; i < m && i < j; i++) + f[i][j] = 0; + for (int i = 1; i < m; i++) + for (int j = 1; j < n; j++) { + if (i == j) + f[i][j] = s.substring(0, i) == t.substring(0, j) ? 1 : 0; + else { + if (s.charAt(i) == s.charAt(j)) + f[i][j] = f[i - 1][j - 1] + f[i - 1][j]; + else + f[i][j] = f[i - 1][j]; + } + } + return f[m - 1][n - 1]; + } + + // 6. ZigZag Conversion + public String convert(String s, int numRows) { + if (numRows <= 1) + return s; + int cycle = 2 * numRows - 2; + StringBuffer res = new StringBuffer(); + for (int i = 0; i < numRows; i++) { + for (int j = i; j < s.length(); j += cycle) { + if (j < s.length()) + res.append(s.charAt(j)); + if (i < numRows - 1 && i > 0) { + int p = j + cycle - 2 * i; + if (p < s.length()) + res.append(s.charAt(p)); + } + } + } + return res.toString(); + } + + // 20. Valid Parentheses + public boolean isValid(String s) { + Stack stack = new Stack(); + String left = "([{", right = ")]}"; + for (int i = 0; i < s.length(); i++) { + if (s.charAt(i) == '(' || s.charAt(i) == '{' || s.charAt(i) == '[') { + stack.push(s.charAt(i)); + } else { + if (stack.isEmpty() || s.charAt(i) != right.charAt(left.indexOf(stack.peek()))) + return false; + stack.pop(); + } + } + if (!stack.isEmpty()) + return false; + return true; + } + + // 67. Add Binary + public String addBinary(String a, String b) { + StringBuffer res = new StringBuffer(); + int carry = 0; + int i, j; + for (i = a.length() - 1, j = b.length() - 1; i >= 0 && j >= 0; i--, j--) { + int m = a.charAt(i) - '0', n = b.charAt(j) - '0'; + int r = m ^ n ^ carry; + carry = (m + n + carry) > 1 ? 1 : 0; + res.append(r); + } + if (i < 0 && j >= 0) { + while (j >= 0) { + res.append((b.charAt(j) - '0') ^ carry); + carry = (b.charAt(j) - '0') & carry; + j--; + } + if (carry == 1) + res.append(carry); + } else if (j < 0 && i >= 0) { + while (i >= 0) { + res.append((a.charAt(i) - '0') ^ carry); + carry = (a.charAt(i) - '0') & carry; + i--; + } + if (carry == 1) + res.append(carry); + } else { + if (carry > 0) + res.append(1); + } + return res.reverse().toString(); + } + + // 49. Group Anagrams + public List> groupAnagrams(String[] strs) { + List> res = new ArrayList>(); + Map> map = new HashMap>(); + for (String str : strs) { + char[] tmp = str.toCharArray(); + Arrays.sort(tmp); + String key = new String(tmp); + List li = map.get(key); + if (li == null) { + li = new ArrayList(); + } + li.add(str); + map.put(key, li); + } + for (String key : map.keySet()) { + List value = map.get(key); + Collections.sort(value); + res.add(value); + } + return res; + } + + // 165. Compare Version Numbers + public int compareVersion(String version1, String version2) { + String[] v1 = version1.split("\\."), v2 = version2.split("\\."); + int maxLen = Math.max(v1.length, v2.length); + for (int i = 0; i < maxLen; i++) { + int n1 = i >= v1.length ? 0 : Integer.parseInt(v1[i]); + int n2 = i >= v2.length ? 0 : Integer.parseInt(v2[i]); + if (n1 > n2) + return 1; + else if (n1 < n2) + return -1; + else + continue; + } + return 0; + } + + // 38. Count and Say + public String countAndSay(int n) { + if (n <= 0) + return ""; + String pre = "1"; + for (int i = 2; i <= n; i++) { + StringBuffer next = new StringBuffer(); + int count = 1; + for (int j = 1; j < pre.length(); j++) { + if (pre.charAt(j) == pre.charAt(j - 1)) + count++; + else { + next.append(count); + next.append(pre.charAt(j - 1)); + count = 1; + } + } + next.append(count); + next.append(pre.charAt(pre.length() - 1)); + pre = next.toString(); + } + return pre; + } + + // 1. Two Sum + public int[] twoSum(int[] nums, int target) { + for (int i = 0; i < nums.length; i++) { + for (int j = i; j < nums.length; j++) { + if (nums[j] + nums[i] == target) + return new int[] { i, j }; + } + } + return null; + } + + // 91. Decode Ways + public int numDecodings(String s) { + if (s.length() == 0) + return 0; + int[] res = new int[s.length() + 1]; + res[0] = 1; + for (int i = 1; i <= s.length(); i++) { + if (s.charAt(i - 1) > '0') + res[i] += res[i - 1]; + if (i > 1 && Integer.parseInt(s.substring(i - 2, i)) >= 10 && Integer.parseInt(s.substring(i - 2, i)) <= 26) + res[i] += res[i - 2]; + } + return res[s.length()]; + } + + // 79. Word Search + public boolean exist(char[][] board, String word) { + boolean isVisit[][] = new boolean[board.length][board[0].length]; + for (int i = 0; i < board.length; i++) + for (int j = 0; j < board[0].length; j++) + if (search(board, isVisit, word, 0, i, j)) + return true; + return false; + } + + private boolean search(char[][] board, boolean[][] isVisit, String word, int index, int i, int j) { + if (index == word.length()) + return true; + if (i < 0 || j < 0 || i >= board.length || j >= board[0].length || isVisit[i][j] + || board[i][j] != word.charAt(index)) + return false; + isVisit[i][j] = true; + boolean result = search(board, isVisit, word, index + 1, i + 1, j) + || search(board, isVisit, word, index + 1, i - 1, j) + || search(board, isVisit, word, index + 1, i, j + 1) + || search(board, isVisit, word, index + 1, i, j - 1); + isVisit[i][j] = false; + return result; + } + + // 319. Bulb Switcher + public int bulbSwitch(int n) { + boolean[] bulbs = new boolean[n]; + for (int i = 0; i < n; i++) { + for (int j = i; j < n; j = j + i + 1) + bulbs[j] = !bulbs[j]; + } + int count = 0; + for (int i = 0; i < n; i++) { + if (bulbs[i]) + count++; + } + return count; + } + + // 224. Basic Calculator + public int calculate(String s) { + int sign = 1, res = 0, len = s.length(); + Stack stack = new Stack(); + for (int i = 0; i < len; i++) { + if (Character.isDigit(s.charAt(i))) { + int sum = s.charAt(i) - '0'; + while (i + 1 < len && Character.isDigit(s.charAt(i + 1))) { + sum = sum * 10 + s.charAt(i + 1) - '0'; + i++; + } + res += sum * sign; + } else if (s.charAt(i) == '+') { + sign = 1; + } else if (s.charAt(i) == '-') { + sign = -1; + } else if (s.charAt(i) == '(') { + stack.push(res); + stack.push(sign); + res = 0; + sign = 1; + } else if (s.charAt(i) == ')') { + res = res * stack.pop() + stack.pop(); + } + } + return res; + } + + // 43. Multiply Strings + public String multiply(String num1, String num2) { + int len1 = num1.length(), len2 = num2.length(); + int[] res = new int[len1 + len2]; + for (int i = 0; i < len1; i++) + for (int j = 0; j < len2; j++) { + int mul = (num1.charAt(i) - '0') * (num2.charAt(j) - '0'); + int sum = mul + res[i + j + 1]; + res[i + j] += sum / 10; + res[i + j + 1] = sum % 10; + } + StringBuffer sb = new StringBuffer(); + for (int p : res) + if (!(sb.length() == 0 && p == 0)) + sb.append(p); + return sb.length() == 0 ? "0" : sb.toString(); + } + + // 166. Fraction to Recurring Decimal + public String fractionToDecimal(int numerator, int denominator) { + StringBuffer res = new StringBuffer(); + String sign = (numerator < 0 == denominator < 0 || numerator == 0) ? "" : "-"; + long num = Math.abs((long) numerator), den = Math.abs((long) denominator); + res.append(sign); + res.append(num / den); + long remainder = num % den; + if (remainder == 0) + return res.toString(); + res.append("."); + HashMap map = new HashMap(); + while (!map.containsKey(remainder)) { + map.put(remainder, res.length()); + res.append(10 * remainder / den); + remainder = 10 * remainder % den; + } + int index = map.get(remainder); + res.insert(index, "("); + res.append(")"); + return res.toString().replace("(0)", ""); + } + + // 204. Count Primes + public int countPrimes(int n) { + boolean[] isPrimes = new boolean[n]; + for (int i = 2; i < n; i++) + isPrimes[i] = true; + for (int i = 2; i * i < n; i++) { + if (isPrimes[i]) { + for (int j = i * i; j < n; j += i) + isPrimes[j] = false; + } + } + int count = 0; + for (int i = 2; i < n; i++) { + if (isPrimes[i]) + count++; + } + return count; + } + + public ListNode rotateRight(ListNode head, int k) { + if (head == null) + return head; + ListNode dummyHead = new ListNode(0); + dummyHead.next = head; + ListNode p = head, q = head; + + int len = 1; + while (q.next != null) { + q = q.next; + len++; + } + for (int i = 0; i < len - k % len; i++) + p = p.next; + + q.next = dummyHead.next; + dummyHead.next = p.next; + p.next = null; + + return dummyHead.next; + } + + // 151. Reverse Words in a String + public String reverseWords(String s) { + StringBuilder reversed = new StringBuilder(); + int j = s.length(); + for (int i = s.length() - 1; i >= 0; i--) { + if (s.charAt(i) == ' ') { + j = i; + } else if (i == 0 || s.charAt(i - 1) == ' ') { + if (reversed.length() != 0) { + reversed.append(' '); + } + reversed.append(s.substring(i, j)); + } + } + return reversed.toString(); + } + + // 3. Longest Substring Without Repeating Characters + public int lengthOfLongestSubstring(String s) { + boolean[] exists = new boolean[256]; + int i = 0, maxLen = 0, len = s.length(); + for (int j = 0; j < len; j++) { + while (exists[s.charAt(j)]) { + exists[s.charAt(i++)] = false; + } + exists[s.charAt(j)] = true; + maxLen = Math.max(j - i + 1, maxLen); + } + return maxLen; + } + + public static void main(String[] args) { + Solution s = new Solution(); + System.out.println(s.uniquePaths(2, 3)); + int obstacleGrid[][] = new int[][] { { 0 }, { 1 } }; + System.out.println(s.uniquePathsWithObstacles(obstacleGrid)); + + System.out.println(s.numDistinct("abbc", "abc")); + + System.out.println(s.convert("PAYPALISHIRING", 3)); + + System.out.println(s.isValid("[")); + + System.out.println(s.addBinary("1", "1")); + + System.out.println(s.compareVersion("1.0", "1")); + + System.out.println(s.twoSum(new int[] { 2, 3, 4 }, 6).toString()); + + System.out.println(s.numDecodings("101")); + + char[][] board = { "ABCE".toCharArray(), "SFES".toCharArray(), "ADEE".toCharArray() }; + System.out.println(s.exist(board, "ABCESEEEFS")); + char[][] board1 = { "bb".toCharArray(), "ab".toCharArray(), "ba".toCharArray() }; + System.out.println(s.exist(board1, "a")); + + for (int i = 0; i < 50; i++) { + System.out.println(i + ": " + s.bulbSwitch(i)); + } + + System.out.println(s.fractionToDecimal(-1, -2147483648)); + + ListNode head = new ListNode(1); + ListNode node2 = new ListNode(2); + ListNode node3 = new ListNode(3); + ListNode node4 = new ListNode(4); + ListNode node5 = new ListNode(5); + head.next = node2; + node2.next = node3; + node3.next = node4; + node4.next = node5; + node5.next = null; + + s.rotateRight(head, 4).toString(); + + System.out.println(s.reverseWords("the sky is blue")); + } + +} + +class ListNode { + int val; + ListNode next; + + ListNode(int x) { + val = x; + }; +} \ No newline at end of file diff --git "a/ChenXiaoxu/template - \345\211\257\346\234\254 (3).md" "b/ChenXiaoxu/template - \345\211\257\346\234\254 (3).md" new file mode 100644 index 0000000..9a69efa --- /dev/null +++ "b/ChenXiaoxu/template - \345\211\257\346\234\254 (3).md" @@ -0,0 +1,17 @@ +# Title + +## Problem + +tag: + +## Solution + +**java** +```java + +``` + +**go** +```go + +``` \ No newline at end of file diff --git "a/ChenXiaoxu/template - \345\211\257\346\234\254 (4).md" "b/ChenXiaoxu/template - \345\211\257\346\234\254 (4).md" new file mode 100644 index 0000000..9a69efa --- /dev/null +++ "b/ChenXiaoxu/template - \345\211\257\346\234\254 (4).md" @@ -0,0 +1,17 @@ +# Title + +## Problem + +tag: + +## Solution + +**java** +```java + +``` + +**go** +```go + +``` \ No newline at end of file diff --git a/ChenXiaoxu/template.md b/ChenXiaoxu/template.md new file mode 100644 index 0000000..9a69efa --- /dev/null +++ b/ChenXiaoxu/template.md @@ -0,0 +1,17 @@ +# Title + +## Problem + +tag: + +## Solution + +**java** +```java + +``` + +**go** +```go + +``` \ No newline at end of file diff --git a/CuiGuangfan/src/com/xingkong/BinaryTreeZigzagLevelOrderTraversal_103.java b/CuiGuangfan/src/com/xingkong/BinaryTreeZigzagLevelOrderTraversal_103.java new file mode 100644 index 0000000..049f266 --- /dev/null +++ b/CuiGuangfan/src/com/xingkong/BinaryTreeZigzagLevelOrderTraversal_103.java @@ -0,0 +1,109 @@ +package com.xingkong; + +import java.util.ArrayList; +import java.util.LinkedList; +import java.util.List; +import java.util.Queue; +import java.util.Stack; + +/** + * @author cuiguangfan 736068048@qq.com: + * @version create time��2016��1��6�� ����10:29:04 class description + */ +public class BinaryTreeZigzagLevelOrderTraversal_103 { + private static class TreeNode { + int val; + TreeNode left; + TreeNode right; + TreeNode(int x) { + val = x; + } + @Override + public String toString() { + return "TreeNode [val=" + val+ "]"; + } + } + + public List> zigzagLevelOrder(TreeNode root) { + List> list=new ArrayList>(); + if(root==null) return list; + Queue queue=new LinkedList(); + Stack stack=new Stack(); + queue.add(root); + stack.push(root); + int flag=0; + //ż���ζ����У������ζ�ջ + while(!queue.isEmpty()&&!stack.isEmpty()){ + List tempList=new ArrayList(); + Queue currentQueue=new LinkedList(); + Stack currentStack=new Stack(); + if(flag%2==0){ + while(!queue.isEmpty()){ + TreeNode tnValue = queue.poll(); + tempList.add(tnValue.val); + TreeNode tnNext =tnValue; + if(tnNext.left!=null){ + currentQueue.add(tnNext.left); + currentStack.push(tnNext.left); + } + if(tnNext.right!=null){ + currentQueue.add(tnNext.right); + currentStack.push(tnNext.right); + } + } + }else{ + while(!stack.isEmpty()){ + TreeNode tnValue = stack.pop(); + tempList.add(tnValue.val); + TreeNode tnNext =queue.poll(); + if(tnNext.left!=null){ + currentQueue.add(tnNext.left); + currentStack.push(tnNext.left); + } + if(tnNext.right!=null){ + currentQueue.add(tnNext.right); + currentStack.push(tnNext.right); + } + + + } + } + list.add(tempList); + queue=currentQueue; + stack=currentStack; + flag++; + } + return list; + } + + public static void main(String[] args) { +// TreeNode tn1=new TreeNode(3); +// TreeNode tn2=new TreeNode(9); +// TreeNode tn3=new TreeNode(20); +// TreeNode tn4=new TreeNode(11); +// TreeNode tn5=new TreeNode(4); +// TreeNode tn6=new TreeNode(15); +// TreeNode tn7=new TreeNode(7); +// TreeNode tn8=new TreeNode(8); +// TreeNode tn9=new TreeNode(6); +// TreeNode tn10=new TreeNode(13); +// TreeNode tn11=new TreeNode(14); +// TreeNode tn12=new TreeNode(22); +// TreeNode tn13=new TreeNode(23); +// tn1.left=tn2; +// tn1.right=tn3; +// tn2.left=tn4; +// tn2.right=tn5; +// tn3.left=tn6; +// tn3.right=tn7; +// tn4.left=tn8; +// tn4.right=tn9; +// tn5.left=tn10; +// tn6.right=tn11; +// tn10.left=tn12; +// tn11.right=tn13; + BinaryTreeZigzagLevelOrderTraversal_103 btzlo=new BinaryTreeZigzagLevelOrderTraversal_103(); + System.out.println(btzlo.zigzagLevelOrder(null)); + } + +} diff --git a/CuiGuangfan/src/com/xingkong/ConstructBinaryTreeFromPreorderandInorderTraversal_105.java b/CuiGuangfan/src/com/xingkong/ConstructBinaryTreeFromPreorderandInorderTraversal_105.java new file mode 100644 index 0000000..5597c4a --- /dev/null +++ b/CuiGuangfan/src/com/xingkong/ConstructBinaryTreeFromPreorderandInorderTraversal_105.java @@ -0,0 +1,65 @@ +package com.xingkong; + +import java.util.HashMap; +import java.util.Map; + +/** + * @author cuiguangfan 736068048@qq.com: + * @version create time��2016��1��7�� ����9:32:10 + * class description + */ +public class ConstructBinaryTreeFromPreorderandInorderTraversal_105 { +// private Map preOrderMap=new HashMap(); + private Map inOrderMap=new HashMap(); + public static class TreeNode { + int val; + TreeNode left; + TreeNode right; + TreeNode(int x) { + val = x; + } + @Override + public String toString() { + return "TreeNode [val=" + val+ "]"; + } + } + + /** + * @param preorder + * @param inorder + * @param rootIndex preorder�е���һ��Ԫ�� + * @param startIndex ���εݹ��inorder�еĿ�ʼ�±� + * @param endIndex ���εݹ��inorder�еĽ����±� + * @return + */ + public TreeNode backTrace(int[] preorder, int[] inorder,int rootIndex,int startIndex,int endIndex){ + if(startIndex>endIndex) return null; + int midIndex=inOrderMap.get(preorder[rootIndex]); + TreeNode root=new TreeNode(inorder[midIndex]); + if(startIndex==endIndex) + return root; + int leftLength=midIndex-startIndex;//ͨ�����������ȡ������ + int rightLength=endIndex-midIndex;//ͨ�����������ȡ������ + //��ȡ���������� + root.left=backTrace(preorder,inorder,rootIndex+1,midIndex-leftLength,midIndex-1); + //��ȡ���������� + root.right=backTrace(preorder,inorder,rootIndex+leftLength+1,midIndex+1,midIndex+rightLength); + return root; + } + public TreeNode buildTree(int[] preorder, int[] inorder) { + for(int i=0;i countSmaller(int[] nums) { + List returnList=new ArrayList(); + if(nums.length==0) return returnList; + returnList.add(0); + TreeNode treeRoot = new TreeNode(nums[nums.length - 1]); + for (int i = nums.length - 2; i >= 0; i--) { + TreeNode currentRoot = treeRoot; + Integer count=0; + while (currentRoot!=null) { + if (nums[i] > currentRoot.value) { + count+=currentRoot.leftCount+currentRoot.thisCount; + if (currentRoot.right != null) { + currentRoot = currentRoot.right; + } else { + currentRoot.right = new TreeNode(nums[i]); + break; + } + } else if(nums[i] < currentRoot.value){ + currentRoot.leftCount++; + if (currentRoot.left != null) { + currentRoot = currentRoot.left; + } else { + currentRoot.left = new TreeNode(nums[i]); + break; + } + }else{ + count+=currentRoot.leftCount; + currentRoot.thisCount++; + break; + } + } + returnList.add(count); + } + Collections.reverse(returnList); + return returnList; + } + + public static void main(String[] args) { + CountOfSmallerNumbersAfterSelf_315 csn=new CountOfSmallerNumbersAfterSelf_315(); + System.out.println(csn.countSmaller(new int[]{26,78,27,100,33,67,90,23,66,5,38,7,35,23,52,22,83,51,98,69,81,32,78,28,94,13,2,97,3,76,99,51,9,21,84,66,65,36,100,41})); + } + +} diff --git a/CuiGuangfan/src/com/xingkong/HouseRobber_198.java b/CuiGuangfan/src/com/xingkong/HouseRobber_198.java new file mode 100644 index 0000000..f979080 --- /dev/null +++ b/CuiGuangfan/src/com/xingkong/HouseRobber_198.java @@ -0,0 +1,33 @@ +package com.xingkong; + +/** + * @author cuiguangfan 736068048@qq.com: + * @version create time��2016��1��20�� ����8:44:09 class description + */ +public class HouseRobber_198 { + + /** + * ת�Ʒ��̣�money[(i)=max{money(i-1),money(i-2)+nums[i]} + * @param nums + * @return + */ + public int rob(int[] nums) { + if (nums.length == 0) + return 0; + int[] money = new int[nums.length]; + money[0] = nums[0]; + if (nums.length >= 2) + money[1] = nums[1] > nums[0] ? nums[1] : nums[0]; + for (int i = 2; i < nums.length; i++) { + money[i] = money[i - 1] >= (money[i - 2] + nums[i]) ? money[i - 1] : (money[i - 2] + nums[i]); + } + return money[nums.length - 1]; + } + + public static void main(String[] args) { + // TODO Auto-generated method stub + HouseRobber_198 hr = new HouseRobber_198(); + System.out.println(hr.rob(new int[] {})); + } + +} diff --git a/CuiGuangfan/src/com/xingkong/LongestPalindromicSubstring.java b/CuiGuangfan/src/com/xingkong/LongestPalindromicSubstring.java new file mode 100644 index 0000000..163cb58 --- /dev/null +++ b/CuiGuangfan/src/com/xingkong/LongestPalindromicSubstring.java @@ -0,0 +1,74 @@ +package com.xingkong; + +/** +* @author cuiguangfan 736068048@qq.com: +* @version create time��2016��1��4�� ����8:35:38 +* class description +*/ +public class LongestPalindromicSubstring { + //�����ִ�ͳ�������ᵼ�³�ʱ�����Ӷ�Ϊo(n3) + public String longestPalindrome1(String s) { + int maxPalinLength = 0; + String longestPalindrome = null; + int length = s.length(); + + // check all possible sub strings + for (int i = 0; i < length; i++) { + for (int j = i + 1; j < length; j++) { + int len = j - i; + String curr = s.substring(i, j + 1); + if (isPalindrome(curr)) { + if (len > maxPalinLength) { + longestPalindrome = curr; + maxPalinLength = len; + } + } + } + } + + return longestPalindrome; + } + private static boolean isPalindrome(String s) { + for (int i = 0; i < s.length() - 1; i++) { + if (s.charAt(i) != s.charAt(s.length() - 1 - i)) { + return false; + } + } + + return true; + } + public String longestPalindrome(String s){ + char[] chars=s.toCharArray(); + boolean[][] records=new boolean[chars.length][chars.length]; + for(int i=0;i=j) records[i][j]=true;//������=����Ϊ[i][i]Ҳ�ǻ��� + else records[i][j]=false; + } + } + int maxLengthOfPalind=1; + int begin = 0; + int end=chars.length-1; + for (int j = 1; j < chars.length; j++) { + for (int i = 0; i < j; i++) { + if(chars[i]==chars[j]){ + records[i][j]=records[i+1][j-1]; + if(records[i][j]==true){ + if(j-i+1>maxLengthOfPalind){ + maxLengthOfPalind=j-i+1; + begin=i; + end=j; + } + } + }else{ + records[i][j]=false; + } + } + } + return s.substring(begin,end+1);//end+1����Ϊbegin��end�ǻ��ģ����Խ�ȡ��ĩβӦ��+1 + } + public static void main(String[] args){ + LongestPalindromicSubstring lps=new LongestPalindromicSubstring(); + System.out.println(lps.longestPalindrome("aaabaaaa")); + } +} diff --git a/CuiGuangfan/src/com/xingkong/N_11_Container_With_Most_Water.java b/CuiGuangfan/src/com/xingkong/N_11_Container_With_Most_Water.java new file mode 100644 index 0000000..92ee4e4 --- /dev/null +++ b/CuiGuangfan/src/com/xingkong/N_11_Container_With_Most_Water.java @@ -0,0 +1,34 @@ +package com.xingkong; +/** +* @author cuiguangfan 736068048@qq.com: +* @version create time��2016��3��6�� ����10:48:22 +* class description +*/ +public class N_11_Container_With_Most_Water { + public static int maxArea(int[] height) { + int left=0; + int right=height.length-1; + int k=0; + int result=0; + while(leftnewResult?result:newResult; + if(height[left]left&&height[k]<=height[right])k--; + right=k; + } + } + return result; + } + + public static void main(String[] args) { + // TODO Auto-generated method stub + System.out.println(N_11_Container_With_Most_Water.maxArea(new int[]{1,1})); + } + +} diff --git a/CuiGuangfan/src/com/xingkong/N_12_Integer_to_Roman.java b/CuiGuangfan/src/com/xingkong/N_12_Integer_to_Roman.java new file mode 100644 index 0000000..7de14d6 --- /dev/null +++ b/CuiGuangfan/src/com/xingkong/N_12_Integer_to_Roman.java @@ -0,0 +1,27 @@ +package com.xingkong; + +/** + * @author cuiguangfan 736068048@qq.com: + * @version create time��2016��3��7�� ����9:47:33 class description + */ +public class N_12_Integer_to_Roman { + public static String intToRoman(int num) { + String c[][]=new String[][]{{"0","I","II","III","IV","V","VI","VII","VIII","IX"},{"0","X","XX","XXX","XL","L","LX" + ,"LXX","LXXX","XC"},{"0","C","CC","CCC","CD","D", + "DC","DCC","DCCC","CM"},{"0","M","MM","MMM"}}; + int t=1; + int tmp=num; + String st = ""; + if(tmp/1000!=0) st+=c[3][tmp/1000]; + if((tmp%1000)/100!=0) st+=c[2][(tmp%1000)/100]; + if((tmp%100)/10!=0) st+=c[1][(tmp%100)/10]; + if(tmp%10!=0) st+=c[0][tmp%10]; + return st; + } + + public static void main(String[] args) { + // TODO Auto-generated method stub + System.out.println(N_12_Integer_to_Roman.intToRoman(1980)); + } + +} diff --git a/CuiGuangfan/src/com/xingkong/N_133_Clone_Graph.java b/CuiGuangfan/src/com/xingkong/N_133_Clone_Graph.java new file mode 100644 index 0000000..09cc434 --- /dev/null +++ b/CuiGuangfan/src/com/xingkong/N_133_Clone_Graph.java @@ -0,0 +1,89 @@ +package com.xingkong; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.HashSet; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; +import java.util.Queue; +import java.util.Set; + +/** + * @author cuiguangfan 736068048@qq.com: + * @version create time��2016��3��16�� ����10:21:42 class description + */ +public class N_133_Clone_Graph { + private static class UndirectedGraphNode { + int label; + List neighbors; + UndirectedGraphNode(int x) { + label = x; + neighbors = new ArrayList(); + } + }; + + /** + * ����map�������õ��ص������ģ�û����һ���½ڵ㣬����map��ţ�ÿ������ͬlabel�Ľڵ㣬�������mapȡ�������������������� + * @param node + * @return + */ + public UndirectedGraphNode cloneGraph_0(UndirectedGraphNode node) {//20ms 1.7% + if(node==null) return null; + Set labelSet=new HashSet(); + Queue queue=new LinkedList(); + queue.add(node); + Map map=new HashMap(); + map.put(node.label, new UndirectedGraphNode(node.label)); + while(!queue.isEmpty()){ + UndirectedGraphNode tempNode=queue.poll(); + labelSet.add(tempNode.label); + List resultList=new ArrayList(); + List tempList=tempNode.neighbors; + if(tempList!=null){ + for(UndirectedGraphNode temp:tempList){ + if(!labelSet.contains(temp.label)){ + queue.add(temp); + + } + if(!map.containsKey(temp.label)) map.put(temp.label, new UndirectedGraphNode(temp.label)); + resultList.add(map.get(temp.label)); + } + //if(!map.containsKey(tempNode.label)) map.put(tempNode.label, new UndirectedGraphNode(tempNode.label)); + map.get(tempNode.label).neighbors=resultList; + } + } + return map.get(node.label); + } + public UndirectedGraphNode cloneGraph_1(UndirectedGraphNode node) {// 10ms 31.35% ȥ����set����Ϊset��map����������ͬ�� + if(node==null) return null; + Queue queue=new LinkedList(); + queue.add(node); + Map map=new HashMap(); + map.put(node.label, new UndirectedGraphNode(node.label)); + while(!queue.isEmpty()){ + UndirectedGraphNode tempNode=queue.poll(); + List resultList=new ArrayList(); + List tempList=tempNode.neighbors; + if(tempList!=null){ + for(UndirectedGraphNode temp:tempList){ + if(!map.containsKey(temp.label)){ + queue.add(temp); + map.put(temp.label, new UndirectedGraphNode(temp.label)); + } + resultList.add(map.get(temp.label)); + } + map.get(tempNode.label).neighbors=resultList; + } + } + return map.get(node.label); + } + + public static void main(String[] args) { + // TODO Auto-generated method stub + N_133_Clone_Graph n=new N_133_Clone_Graph(); + UndirectedGraphNode node=new UndirectedGraphNode(-1); + System.out.println(n.cloneGraph_1(node)); + } + +} diff --git a/CuiGuangfan/src/com/xingkong/N_136_Single_Number.java b/CuiGuangfan/src/com/xingkong/N_136_Single_Number.java new file mode 100644 index 0000000..f20fde3 --- /dev/null +++ b/CuiGuangfan/src/com/xingkong/N_136_Single_Number.java @@ -0,0 +1,20 @@ +package com.xingkong; +/** +* @author cuiguangfan 736068048@qq.com: +* @version create time��2016��3��9�� ����11:29:29 +* class description +*/ +public class N_136_Single_Number { + public static int singleNumber(int[] nums) { + int result=nums[0]; + for(int i=1;i>i)&1; + } + if(array[i]%3!=0) + result+=1< result=new ArrayList(); + public List wordBreak(String s, Set wordDict) {//timeout + Map> map=new HashMap>(); + for(String word:wordDict){ + int pos=s.indexOf(word); + while(pos!=-1){ + Integer start=pos; + Integer end=pos+word.length(); + if(!map.containsKey(start)) + map.put(start, new ArrayList()); + map.get(start).add(end); + pos=s.indexOf(word,start+1); + } + } + recusive(0,map,s,""); + return this.result; + } + + private void recusive(int key,Map> map,String orginal,String s){ + if(key>=orginal.length()) { + if(!s.trim().equals("")) + result.add(s.trim()); + return; + } + if(!map.containsKey(key)) return ; + List list=map.get(key); + for(Integer i:list){ + //System.out.println(i); + recusive(i,map,orginal,orginal.substring(key,i)+" "+s); + } + } + HashMap> map = new HashMap>(); + public List wordBreak1(String s, Set wordDict) {//15ms + List res = new ArrayList(); + if(s.isEmpty()) + return res; // return empty list upon empty string + + if(map.containsKey(s)) + return map.get(s); + + for(int i=0; i rest = wordBreak1(s.substring(i+1),wordDict); + if(rest.isEmpty()) { + if(i==s.length()-1) + res.add(firstWord); + } else { + for(String str : rest) + res.add(firstWord + " " + str); + } + } + } + + map.put(s,res); + + return res; + } + public static void main(String[] args){ + N_140_Word_Break_II n=new N_140_Word_Break_II(); + Set set=new HashSet(); + set.add("a"); + set.add("aa"); + set.add("aaa"); + set.add("aaaa"); + set.add("aaaaa"); + set.add("aaaaaa"); + set.add("aaaaaaa"); + set.add("aaaaaaaa"); + set.add("aaaaaaaaa"); + System.out.println(n.wordBreak("aaaaaaa" //7 + + "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"//36 + + "aaaaaaaaaabaaaaaaaaaaaaaaaaaa"//28 + + "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" + + "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" + + "aaaaaaaaaaaaaaa", set)); + } +} diff --git a/CuiGuangfan/src/com/xingkong/N_14_Longest_Common_Prefix.java b/CuiGuangfan/src/com/xingkong/N_14_Longest_Common_Prefix.java new file mode 100644 index 0000000..2e08e32 --- /dev/null +++ b/CuiGuangfan/src/com/xingkong/N_14_Longest_Common_Prefix.java @@ -0,0 +1,34 @@ +package com.xingkong; + +import java.util.Arrays; + +/** +* @author cuiguangfan 736068048@qq.com: +* @version create time��2016��3��7�� ����10:07:26 +* class description +*/ +public class N_14_Longest_Common_Prefix { + public static String longestCommonPrefix(String[] strs) { + if(strs==null||strs.length==0) return ""; + char[] array=strs[0].toCharArray(); + char[] tempArray; + for(int i=1;i> threeSum_0(int[] nums) {//��һ�泬ʱ����Ϊ��ʹ����һ��list + Set> set=new HashSet>(); + List> result=new ArrayList>(); + Arrays.sort(nums); + for(int p1=0;p10&&nums[p1]==nums[p1-1]) continue; + int p2=p1+1; + int p3=nums.length-1; + while(p2 list=new ArrayList(); + list.add(nums[p1]); + list.add(nums[p2]); + list.add(nums[p3]); + if(!set.contains(list)){ + set.add(list); + result.add(list); + } + p2++; + p3--; + }else if(nums[p1]+nums[p2]+nums[p3]>0){ + p3--; + }else{ + p2++; + } + } + } + return result; + } + public List> threeSum_1(int[] nums) {//ȥ����result��7%��49ms + Set> set=new HashSet>(); + //List> result=new ArrayList>(); + Arrays.sort(nums); + for(int p1=0;p1 list=new ArrayList(); + list.add(nums[p1]); + list.add(nums[p2]); + list.add(nums[p3]); + if(!set.contains(list)){ + set.add(list); + //result.add(list); + } + p2++; + p3--; + }else if(nums[p1]+nums[p2]+nums[p3]>0){ + p3--; + }else{ + p2++; + } + } + } + return new ArrayList>(set); + } + public static List> threeSum_2(int[] nums) {//9ms + //Set> set=new HashSet>(); + List> result=new ArrayList>();//�Ż���1 + Arrays.sort(nums); + for(int p1=0;p10&&nums[p1]==nums[p1-1]) continue;//�Ż���2 + int p2=p1+1; + int p3=nums.length-1; + while(p2 list=new ArrayList(); + list.add(nums[p1]); + list.add(nums[p2]); + list.add(nums[p3]); +// if(!set.contains(list)){ +// set.add(list); +// //result.add(list); +// } + result.add(list);//�����Ż�������ã����ԣ�����Ҫset�� + while (p2 < p3 && nums[p3] == nums[p3 - 1]){//�Ż���3�������ظ��� + p3--; + } + p3--; + while (p2 < p3 && nums[p2] == nums[p2+1]){//�Ż���4 + p2++; + } + p2++; + }else if(nums[p1]+nums[p2]+nums[p3]>0){ + while (p2 < p3 && nums[p3] == nums[p3 - 1]){//�Ż���5 + p3--; + } + p3--; + }else{ + while (p2 < p3 && nums[p2] == nums[p2+1]){//�Ż���6 + p2++; + } + p2++; + } + } + } + return result; + } + public static void main(String[] args) { + // TODO Auto-generated method stub + System.out.println(N_15_3Sum.threeSum_2(new int[]{-2,0,1,1,2})); + } + +} diff --git a/CuiGuangfan/src/com/xingkong/N_166_Fraction_to_Recurring_Decimal.java b/CuiGuangfan/src/com/xingkong/N_166_Fraction_to_Recurring_Decimal.java new file mode 100644 index 0000000..9664e38 --- /dev/null +++ b/CuiGuangfan/src/com/xingkong/N_166_Fraction_to_Recurring_Decimal.java @@ -0,0 +1,65 @@ +package com.xingkong; + +import java.util.HashMap; +import java.util.Map; + +/** +* @author cuiguangfan 736068048@qq.com: +* @version create time��2016��3��3�� ����2:24:34 +* class description +* û�н�� +*/ +public class N_166_Fraction_to_Recurring_Decimal { + public static String fractionToDecimal(int numerator, int denominator) { + if (numerator == 0) return "0"; + if (denominator == 0) return ""; + + String ans = ""; + + //������Ϊ���� + if ((numerator < 0) ^ (denominator < 0)) { + ans += "-"; + } + + //����Ҫ����������תΪ������Ϊ���������intתΪlong + long num = numerator, den = denominator; + num = Math.abs(num); + den = Math.abs(den); + + //������������� + long res = num / den; + ans += String.valueOf(res); + + //����ܹ����������ؽ�� + long rem = (num % den) * 10; + if (rem == 0) return ans; + + //�����С������ + HashMap map = new HashMap(); + ans += "."; + while (rem != 0) { + //���ǰ���Ѿ����ֹ�����������ô���Ὺʼѭ�� + if (map.containsKey(rem)) { + int beg = map.get(rem); //ѭ���忪ʼ��λ�� + String part1 = ans.substring(0, beg); + String part2 = ans.substring(beg, ans.length()); + ans = part1 + "(" + part2 + ")"; + return ans; + } + + //�������³� + map.put(rem, ans.length()); + res = rem / den; + ans += String.valueOf(res); + rem = (rem % den) * 10; + } + + return ans; + } + public static void main(String[] args) { + // TODO Auto-generated method stub + System.out.println(N_166_Fraction_to_Recurring_Decimal.fractionToDecimal(1, 99)); + //System.out.println(1*1.0/90); + } + +} diff --git a/CuiGuangfan/src/com/xingkong/N_16_3Sum_Closest.java b/CuiGuangfan/src/com/xingkong/N_16_3Sum_Closest.java new file mode 100644 index 0000000..e3d864a --- /dev/null +++ b/CuiGuangfan/src/com/xingkong/N_16_3Sum_Closest.java @@ -0,0 +1,48 @@ +package com.xingkong; + +import java.util.ArrayList; +import java.util.Arrays; + +/** +* @author cuiguangfan 736068048@qq.com: +* @version create time��2016��3��15�� ����10:21:00 +* class description +*/ +public class N_16_3Sum_Closest { + public int threeSumClosest(int[] nums, int target) { + Arrays.sort(nums); + int min=Integer.MAX_VALUE; + int finalMin=0; + for(int p1=0;p10&&nums[p1]==nums[p1-1]) continue;//�Ż���2 + int p2=p1+1; + int p3=nums.length-1; + while(p2> resultMap=new HashMap>(); + Map> dictMap=new HashMap>(); + private void init(){ + dictMap.put("2", Arrays.asList(new String[]{"a","b","c"})); + dictMap.put("3", Arrays.asList(new String[]{"d","e","f"})); + dictMap.put("4", Arrays.asList(new String[]{"g","h","i"})); + dictMap.put("5", Arrays.asList(new String[]{"j","k","l"})); + dictMap.put("6", Arrays.asList(new String[]{"m","n","o"})); + dictMap.put("7", Arrays.asList(new String[]{"p","q","r","s"})); + dictMap.put("8", Arrays.asList(new String[]{"t","u","v"})); + dictMap.put("9", Arrays.asList(new String[]{"w","x","y","z"})); + } + public List letterCombinations(String digits) {//����������鷳�� + if(dictMap.isEmpty()) init(); + List list=new ArrayList(); + if(digits.trim().equals("")) + return list; + if(resultMap.containsKey(digits)) + return resultMap.get(digits); + //for(int i=0;i tempList=letterCombinations(digits.substring(1)); + List mapStr=dictMap.get(tempStr); + for(String tempMapStr:mapStr){ + if(tempList.isEmpty()){ + //if(i==digits.length()-1) + list.add(tempMapStr); + }else{ + for(String temp:tempList){ + list.add(tempMapStr+temp); + } + } + } + //} + resultMap.put(digits, list); + return list; + } + public static void main(String[] args) { + // TODO Auto-generated method stub + N_17_Letter_Combinations_of_a_Phone_Number n=new N_17_Letter_Combinations_of_a_Phone_Number(); + System.out.println(n.letterCombinations("23")); + } + +} diff --git a/CuiGuangfan/src/com/xingkong/N_19_Remove_Nth_Node_From_End_of_List.java b/CuiGuangfan/src/com/xingkong/N_19_Remove_Nth_Node_From_End_of_List.java new file mode 100644 index 0000000..51947a1 --- /dev/null +++ b/CuiGuangfan/src/com/xingkong/N_19_Remove_Nth_Node_From_End_of_List.java @@ -0,0 +1,34 @@ +package com.xingkong; +/** +* @author cuiguangfan 736068048@qq.com: +* @version create time��2016��3��7�� ����10:28:04 +* class description +*/ +public class N_19_Remove_Nth_Node_From_End_of_List { + private class ListNode{ + int val; + ListNode next; + ListNode(int x){val=x;} + } + public ListNode removeNthFromEnd(ListNode head, int n) { + + ListNode first=head; + ListNode second=first; + while(n-->0) { + second=second.next; + if(second==null){ + return head.next; + } + } + while(second.next!=null){ + first=first.next; + second=second.next; + } + first.next=first.next!=null?first.next.next:null; + return head; + } + public static void main(String[] args) { + // TODO Auto-generated method stub + //һ�β���ͨ��������д���� + } +} diff --git a/CuiGuangfan/src/com/xingkong/N_204_Count_Primes.java b/CuiGuangfan/src/com/xingkong/N_204_Count_Primes.java new file mode 100644 index 0000000..d712988 --- /dev/null +++ b/CuiGuangfan/src/com/xingkong/N_204_Count_Primes.java @@ -0,0 +1,32 @@ +package com.xingkong; +/** +* @author cuiguangfan 736068048@qq.com: +* @version create time��2016��2��29�� ����8:49:52 +* class description +*/ +public class N_204_Count_Primes { + public static int countPrimes(int n) { + boolean[]isPrime=new boolean[n]; + for(int i=2;i v=new Stack(); + for(int i=0;i> adjLists = new ArrayList>(); + for (int i = 0; i < numCourses; i++) { + adjLists.add(new HashSet()); + } + + for (int i = 0; i < prerequisites.length; i++) { + adjLists.get(prerequisites[i][1]).add(prerequisites[i][0]); + } + + int[] indegrees = new int[numCourses]; + for (int i = 0; i < numCourses; i++) { + for (int x : adjLists.get(i)) { + indegrees[x]++; + } + } + + Queue queue = new LinkedList(); + for (int i = 0; i < numCourses; i++) { + if (indegrees[i] == 0) { + queue.offer(i); + } + } + + int[] res = new int[numCourses]; + int count = 0; + while (!queue.isEmpty()) { + int cur = queue.poll(); + for (int x : adjLists.get(cur)) { + indegrees[x]--; + if (indegrees[x] == 0) { + queue.offer(x); + } + } + res[count++] = cur; + } + + if (count == numCourses) return res; + return new int[0]; + } + public static void main(String[] args) { + // TODO Auto-generated method stub + N_210_Course_Schedule_II n=new N_210_Course_Schedule_II(); + int[] temp=n.findOrder(2, new int[][]{{0,1},{1,0}});//{1,0},{2,0},{3,1},{3,2} + for(int i=0;i stack,int count){ + //�ȼ����������� + if(y+count>matrix[0].length-1||x+count>matrix.length-1||matrix[x][y+count]!='1'||matrix[x+count][y]!='1'){ + return count; + } + Stack thisStack=new Stack(); + //���ջ�е� + while(!stack.isEmpty()){ + Entity e=stack.pop(); + if(matrix[e.x+1][e.y+1]!='1'){ + return count; + } + thisStack.push(new Entity(e.x+1,e.y+1)); + } + thisStack.push(new Entity(x,y+count)); + thisStack.push(new Entity(x+count,y)); + return recursion(matrix,x,y,thisStack,count+1); + } + public static int maximalSquare(char[][] matrix) {//53ms 1.22% + int max=0; + for(int i=0;i stack=new Stack(); + stack.push(new Entity(i,j)); + int tempMax=recursion(matrix,i,j,stack,1); + if(tempMax>max){ + max=tempMax; + } + } + } + return max*max; + } + public static void main(String[] args) { + // TODO Auto-generated method stub + System.out.println(N_221_Maximal_Square.maximalSquare(new char[][]{ + {'1','0','1','0','0'}, + {'1','0','1','1','1'}, + {'1','1','1','1','1'}, + {'1','0','0','1','1'} + })); + } + +} diff --git a/CuiGuangfan/src/com/xingkong/N_224_Basic_Calculator.java b/CuiGuangfan/src/com/xingkong/N_224_Basic_Calculator.java new file mode 100644 index 0000000..31e0461 --- /dev/null +++ b/CuiGuangfan/src/com/xingkong/N_224_Basic_Calculator.java @@ -0,0 +1,69 @@ +package com.xingkong; + +import java.util.Stack; + +/** +* @author cuiguangfan 736068048@qq.com: +* @version create time��2016��2��29�� ����10:14:26 +* class description +*/ +public class N_224_Basic_Calculator { + public static int calculate(String s) { + char[] array=s.trim().replaceAll(" ", "").toCharArray(); + Stack numberStack=new Stack(); + Stack operatorStack=new Stack(); + for(int i=0;i reverseNumberStack=new Stack(); + while(!numberStack.isEmpty()){ + reverseNumberStack.push(numberStack.pop()); + } + Stack resultStack=new Stack(); + while(!reverseNumberStack.isEmpty()){ + String temp=reverseNumberStack.pop(); + if(temp.equals("+")||temp.equals("-")){ + Integer number1=Integer.valueOf(resultStack.pop()); + Integer number2=Integer.valueOf(resultStack.pop()); + if(temp.equals("+")){ + resultStack.push(String.valueOf(number1+number2)); + }else{ + resultStack.push(String.valueOf(number2-number1)); + } + }else{ + resultStack.push(temp); + } + } + return Integer.valueOf(resultStack.pop()); + } + public static void main(String[] args) { + // TODO Auto-generated method stub + System.out.println(N_224_Basic_Calculator.calculate(" 30")); + } + +} diff --git a/CuiGuangfan/src/com/xingkong/N_26_Remove_Duplicates_from_Sorted_Array.java b/CuiGuangfan/src/com/xingkong/N_26_Remove_Duplicates_from_Sorted_Array.java new file mode 100644 index 0000000..a7ab73b --- /dev/null +++ b/CuiGuangfan/src/com/xingkong/N_26_Remove_Duplicates_from_Sorted_Array.java @@ -0,0 +1,25 @@ +package com.xingkong; +/** +* @author cuiguangfan 736068048@qq.com: +* @version create time��2016��3��9�� ����8:56:42 +* class description +*/ +public class N_26_Remove_Duplicates_from_Sorted_Array { + public static int removeDuplicates(int[] nums) { + int count=0; + int i=0; + while(i> mapRow=new HashMap>(); + Map> mapColumn=new HashMap>(); + Map> mapRect=new HashMap>(); + for(int i=0;i()); + if(!mapRow.get(i).contains(board[i][j])) mapRow.get(i).add(board[i][j]); + else + return false; + if(!mapColumn.containsKey(j)) mapColumn.put(j, new HashSet()); + if(!mapColumn.get(j).contains(board[i][j])) mapColumn.get(j).add(board[i][j]); + else + return false; + if(!mapRect.containsKey(3*(i/3)+j/3)) mapRect.put(3*(i/3)+j/3, new HashSet()); + if(!mapRect.get(3*(i/3)+j/3).contains(board[i][j])) mapRect.get(3*(i/3)+j/3).add(board[i][j]); + else + return false; + } + } + } + return true; + } + public static void main(String[] args) { + N_36_Valid_Sudoku n=new N_36_Valid_Sudoku(); + System.out.println(n.isValidSudoku(new char[][]{ + {'.','8','7','6','5','4','3','2','1'},{'2','.','.','.','.','.','.','.','.'},{'3','.','.','.','.','.','.','.','.'}, + {'4','.','.','.','.','.','.','.','.'},{'5','.','.','.','.','.','.','.','.'},{'6','.','.','.','.','.','.','.','.'}, + {'7','.','.','.','.','.','.','.','.'},{'8','.','.','.','.','.','.','.','.'},{'9','.','.','.','.','.','.','.','.'} + })); + + } + +} diff --git a/CuiGuangfan/src/com/xingkong/N_43_Multiply_Strings.java b/CuiGuangfan/src/com/xingkong/N_43_Multiply_Strings.java new file mode 100644 index 0000000..f912ba4 --- /dev/null +++ b/CuiGuangfan/src/com/xingkong/N_43_Multiply_Strings.java @@ -0,0 +1,48 @@ +package com.xingkong; +/** +* @author cuiguangfan 736068048@qq.com: +* @version create time��2016��3��3�� ����8:42:55 +* class description +*/ +public class N_43_Multiply_Strings { + + public static String multiply(String num1, String num2) { + char[] array1=num1.toCharArray(); + char[] array2=num2.toCharArray(); + char[] num1Array=array1; + char[] num2Array=array2; + + if(array1.length=0;i--){ + int addition=0; + int j=num1Array.length-1; + for(;j>=0;j--){ + int temp=result[i+j+1]-48+(num2Array[i]-48)*(num1Array[j]-48)+addition; + result[i+j+1]=(char) (temp%10+48); + addition=temp/10; + } + if(addition>0&&jnums2[n2Mid]){ + return recursion(nums1,nums2,n1Begin,n1Mid,n2Mid,n2End,n1Sum+n1End-n1Mid,n2Sum+n2Mid-n2Begin); + }else if(nums1[n1Mid]0){ + char firstChar=str.charAt(0); + if(firstChar<'0'){ + if(firstChar=='-'){ + negative=true; + limit=Integer.MIN_VALUE; + }else if(firstChar!='+'){ + return 0; + } + if(str.length()==1){ + return 0; + } + i++; + } + int multmin=limit/radix; + int digit=0; + while(i=multmin����ô�������result*=radix����overflow + return negative?Integer.MIN_VALUE:Integer.MAX_VALUE; + } + result*=radix; + if(resultInteger.MAX_VALUE||result> result=new HashSet>(); + //ÿ�δӺ���ȥһ����num[i]���滻num[cur]�� + // ��Ϊnum�ڴ�����ͬ������Ҳ����˵��num[k] ���ܺ�num[j]��ͬ�� + // ������num[i]�Ѿ���cur���λ���ϳ��ֹ�����num[j]����ֱ������ȥ�����ԣ�Ӧ�ô�curλ�ÿ�ʼһֱ��j������������ڲ鿴����num[i]�Ƿ�����num[j]��ͬ�����֣���cur<=i=nums.length){ + List temp=new ArrayList(); + for(int value:nums){ + temp.add(value); + } + result.add(temp); + + } + for(int i=currentIndex;i> permuteUnique(int[] nums) { + Arrays.sort(nums); + backTrace(nums,0); + return new ArrayList>(result); + + } + public static void main(String[] args) { + PermutationsII_47 pI=new PermutationsII_47(); + System.out.println(pI.permuteUnique(new int[]{1,1,2})); + } + +} diff --git a/CuiGuangfan/src/com/xingkong/PopulatingNextRightPointersInEachNode_116.java b/CuiGuangfan/src/com/xingkong/PopulatingNextRightPointersInEachNode_116.java new file mode 100644 index 0000000..5054111 --- /dev/null +++ b/CuiGuangfan/src/com/xingkong/PopulatingNextRightPointersInEachNode_116.java @@ -0,0 +1,33 @@ +package com.xingkong; + +/** + * @author cuiguangfan 736068048@qq.com: + * @version create time��2016��1��9�� ����9:39:21 class description + */ +public class PopulatingNextRightPointersInEachNode_116 { + public class TreeLinkNode { + int val; + TreeLinkNode left, right, next; + + TreeLinkNode(int x) { + val = x; + } + @Override + public String toString() { + return "TreeLinkNode [val=" + val + "]"; + } + } + public void connect(TreeLinkNode root) { + if(root==null||root.left==null) + return; + root.left.next=root.right; + if(root.next!=null) + root.right.next=root.next.left; + connect(root.left); + connect(root.right); + } + public static void main(String[] args) { + + } + +} diff --git a/CuiGuangfan/src/com/xingkong/PopulatingNextRightPointersInEachNode_117.java b/CuiGuangfan/src/com/xingkong/PopulatingNextRightPointersInEachNode_117.java new file mode 100644 index 0000000..abc6599 --- /dev/null +++ b/CuiGuangfan/src/com/xingkong/PopulatingNextRightPointersInEachNode_117.java @@ -0,0 +1,87 @@ +package com.xingkong; + +/** + * @author cuiguangfan 736068048@qq.com: + * @version create time��2016��1��9�� ����9:39:21 class description + * δ������������! + */ +public class PopulatingNextRightPointersInEachNode_117 { + public static class TreeLinkNode { + int val; + TreeLinkNode left, right, next; + + TreeLinkNode(int x) { + val = x; + } + + @Override + public String toString() { + return "TreeLinkNode [val=" + val + "]"; + } + } + + public void connectNode(TreeLinkNode root) { + //����ĸ��ڵ� + TreeLinkNode rootHeadNode = root; + while (rootHeadNode != null) { + TreeLinkNode headNode = null; + TreeLinkNode currentNode = rootHeadNode; + boolean flag = true; + while (currentNode != null) { + TreeLinkNode lastNode=null; + TreeLinkNode linkedToRight = null; + if (currentNode.left != null) { + currentNode.left.next = currentNode.right; + linkedToRight = currentNode.left; + lastNode=currentNode.left; + if (flag) { + headNode = currentNode.left; + flag = false; + } + } + if (currentNode.right != null) { + linkedToRight = currentNode.right; + lastNode=currentNode.left; + if (flag) { + headNode = currentNode.right; + flag = false; + } + } + TreeLinkNode linkedToLeft = null; + if (currentNode.next != null) { + if (currentNode.next.left != null) { + currentNode.next.left.next = currentNode.next.right; + linkedToLeft = currentNode.next.left; + lastNode=currentNode.next.left; + if (flag) { + headNode = currentNode.next.left; + flag = false; + } + } else { + linkedToLeft = currentNode.next.right; + if(currentNode.next.right!=null) + lastNode=currentNode.next.right; + if (flag) { + headNode = currentNode.next.right; + flag = false; + } + } + } + if (linkedToRight != null) { + linkedToRight.next = linkedToLeft; + }else if(lastNode!=null){ + lastNode.next=linkedToLeft; + } + currentNode = currentNode.next; + } + rootHeadNode = headNode; + } + } + + public static void main(String[] args) { + PopulatingNextRightPointersInEachNode_117 t=new PopulatingNextRightPointersInEachNode_117(); + TreeLinkNode tln=new TreeLinkNode(0); + t.connectNode(tln); + } + +} diff --git a/CuiGuangfan/src/com/xingkong/Test.java b/CuiGuangfan/src/com/xingkong/Test.java index 64adacd..d6d65a8 100644 --- a/CuiGuangfan/src/com/xingkong/Test.java +++ b/CuiGuangfan/src/com/xingkong/Test.java @@ -3,34 +3,47 @@ import java.util.ArrayList; import java.util.List; -/** -* @author cuiguangfan 736068048@qq.com: -* @version create time��2015��12��29�� ����9:21:14 -* class description -*/ +/** + * @author cuiguangfan 736068048@qq.com: + * @version create time��2015��12��29�� ����9:21:14 class description + */ public class Test { - - public static void main(String[] args) { - String[]test=new String[3]; - for(String i:test) - System.out.println(i); - } - - public static String listToString(List stringList){ - if (stringList==null) { - return null; - } - StringBuilder result=new StringBuilder(); - boolean flag=false; - for (String string : stringList) { - if (flag) { - result.append(","); - }else { - flag=true; + public static class ListNode { + int val; + ListNode next; + ListNode(int x) { + val = x; + } + } + static ListNode getLeftNodeFromList(ListNode head) { + ListNode next = head; + while(next!=null) { + next = next.next; + if(next==null) { + break; + } + next = next.next; + if(next==null) { + break; } - result.append(string); + head = head.next; } - return result.toString(); + return head; } + public static void main(String[] args) { + ListNode pre=new ListNode(1); + ListNode head=pre; + for(int i=2;i<=9;i++){ + ListNode temp=new ListNode(i); + pre.next=temp; + pre=temp; + } + ListNode check=head; + while(check!=null){ + System.out.print(check.val+" "); + check=check.next; + } + System.out.println("\n"+getLeftNodeFromList(head).val); + } } diff --git a/CuiGuangfan/src/com/xingkong/UglyNumberII.java b/CuiGuangfan/src/com/xingkong/UglyNumberII.java new file mode 100644 index 0000000..0cea096 --- /dev/null +++ b/CuiGuangfan/src/com/xingkong/UglyNumberII.java @@ -0,0 +1,42 @@ +package com.xingkong; +/** +* @author cuiguangfan 736068048@qq.com: +* @version create time��2016��1��22�� ����8:53:43 +* class description +*/ +public class UglyNumberII { + private int min(int num1,int num2,int num3){ + int min=Integer.MAX_VALUE; + if(num1 generateTrees(int n) { + if(n==0) { + return new ArrayList(); + } +// if(n==1){ +// List temp=new ArrayList(); +// temp.add(new TreeNode(1)); +// return temp; +// } + return generate(1,n);//1-n��n��Ԫ�� + + } + private List generate(int start,int end){ + List result=new ArrayList(); + if(start>end) { + result.add(null); + return result; + } + for(int separate=start;separate<=end;separate++){ + List left=generate(start,separate-1); + List right=generate(separate+1,end); + for(TreeNode leftTemp:left){ + for(TreeNode rightTemp:right){ + TreeNode tn=new TreeNode(separate); + tn.left=leftTemp; + tn.right=rightTemp; + result.add(tn); + } + } + } + return result; + } + public static void main(String[]args){ + UniqueBinarySearchTreesII_95 ubs=new UniqueBinarySearchTreesII_95(); + System.out.println(ubs.generateTrees(1)); + } +} diff --git a/CuiGuangfan/src/com/xingkong/ZigZagConversion_6.java b/CuiGuangfan/src/com/xingkong/ZigZagConversion_6.java new file mode 100644 index 0000000..99b8885 --- /dev/null +++ b/CuiGuangfan/src/com/xingkong/ZigZagConversion_6.java @@ -0,0 +1,47 @@ +package com.xingkong; + +import java.util.HashMap; +import java.util.Map; + +/** +* @author cuiguangfan 736068048@qq.com: +* @version create time��2016��2��27�� ����8:45:29 +* class description +*/ +public class ZigZagConversion_6 { + public static String convert(String s, int numRows) { + String[] array=new String[s.length()]; + Map map=new HashMap(); + for(int i=0;i=3?numRows-2:0; + int index=0; + while(true){ + //һ����ȡnumRows�� + String temp=index+numRows<=s.length()?s.substring(index, index+numRows):s.substring(index); + for(int i=0;i=s.length()) break; + temp=index+margin<=s.length()?s.substring(index, index+margin):s.substring(index); + for(int i=0;i=s.length()) + break; + index+=margin; + } + String finalString=""; + for(int i=0;imaxSum) + maxSum=thisSum; + else if(thisSum<0){ + thisSum=0; + } + } + return maxSum; + } +} diff --git a/CuiGuangfan/src/com/xingkong/exercise/Pow.java b/CuiGuangfan/src/com/xingkong/exercise/Pow.java new file mode 100644 index 0000000..e1c5575 --- /dev/null +++ b/CuiGuangfan/src/com/xingkong/exercise/Pow.java @@ -0,0 +1,18 @@ +package com.xingkong.exercise; +/** +* @author cuiguangfan 736068048@qq.com: +* @version create time��2016��2��24�� ����10:20:03 +* ������ +*/ +public class Pow { + public static long pow(long x,int n){ + if(n==0) + return 1; + if(n==1) + return x; + if(n%2==0)//���n��ż�� + return pow(x*x,n/2); + else//���n������ + return pow(x*x,n/2)*x; + } +} diff --git a/CuiGuangfan/src/com/xingkong/exercise/Test.java b/CuiGuangfan/src/com/xingkong/exercise/Test.java new file mode 100644 index 0000000..1f045a3 --- /dev/null +++ b/CuiGuangfan/src/com/xingkong/exercise/Test.java @@ -0,0 +1,57 @@ +package com.xingkong.exercise; + +import java.util.TreeMap; + +/** +* @author cuiguangfan 736068048@qq.com: +* @version create time��2016��2��24�� ����2:37:01 +* class description +*/ +//public class Test { +// +// public static void main(String[] args) { +// String str1 = "a"; +// String str2 = "bc"; +// String str3 = "a"+"bc"; +// String str4 = str1+str2; +// String str5 = "abc"; +// System.out.println(str3==str4); +// System.out.println(str4==str5); +// str4 = (str1+str2).intern(); +// System.out.println(str3==str4); +// System.out.println(str4==str5); +// String str6=new String("123"); +// System.out.println(str6.intern()==str6); +// String str7="123"; +// System.out.println(str6==str7); +// System.out.println(str6.intern()==str6); +// String str8=new StringBuilder("ja").append("vaaaaaaaaaaaaa").toString(); +// System.out.println(str8.intern()==str8); +// } +// +//} +public class Test extends Base{ + + static{ + System.out.println("test static"); + } + + public Test(){ + System.out.println("test constructor"); + } + + public static void main(String[] args) { + new Test(); + } +} + +class Base{ + + static{ + System.out.println("base static"); + } + + public Base(){ + System.out.println("base constructor"); + } +} \ No newline at end of file diff --git a/CuiYanling/Distinct Subsequences b/CuiYanling/Distinct Subsequences new file mode 100644 index 0000000..6b05ae3 --- /dev/null +++ b/CuiYanling/Distinct Subsequences @@ -0,0 +1,15 @@ +public class Solution { + public int numDistinct(String s, String t) { + char[] ss= s.toCharArray(); + char[] tt = t.toCharArray(); + int sub[][] = new int[ss.length+1][tt.length+1]; + for(int i=0;i<=ss.length;++i) sub[i][0] = 1; + + for(int i=0;i0) dp[j]+=dp[j-1]; + return dp[n-1]; + } +} diff --git a/DuanShikai/week07-08/_031_Next_Permutation.java b/DuanShikai/week07-08/_031_Next_Permutation.java new file mode 100644 index 0000000..a5ac7e6 --- /dev/null +++ b/DuanShikai/week07-08/_031_Next_Permutation.java @@ -0,0 +1,63 @@ +package com.sky.leetcode; +/** + * @author DuanSky + * @date 2016年1月12日 下午2:22:15 + * @content + */ + +public class _031_Next_Permutation { + + public static void main(String args[]){ + int[] nums={1,2}; + _031_Next_Permutation test = new _031_Next_Permutation(); + test.nextPermutation(nums); + } + + public void nextPermutation(int[] nums) { + if(nums.length<=1) return; + int start=nums.length-1, i=start; + for(;i>0;i--){ + if(nums[i]>nums[i-1]){ //找到第一个逆序的位置。 + start = i; + break; + } + } + if(i==0) sort_(nums,0); + else sort(nums,start-1); + } + + private void sort(int[] nums, int start) { + int rep = findMinLargerPos(nums,start+1,nums[start]); + swap(nums,rep,start); //交换 + for(int i=start+1;i=nums.length || start<0) return -1; + int minPos = start; + for(int i=start+1;ikey && nums[i] < nums[minPos] ? i : minPos; + return minPos; + } + + private int findMinPos(int[] nums, int start){ + if(start>=nums.length || start<0) return -1; + int minPos = start; + for(int i=start+1;i= size-1 ? count : -1; + } + + + //o(n^2) TLE + public int jump(int[] nums) { + int size = nums.length; + int[] d=new int[size]; + for(int i=1;i=i) + minStep = Math.min(minStep,d[j]+1); + d[i]=minStep; + } + return d[size-1]; + } + + // TLE + public int jump_(int[] nums){ + int size = nums.length; + int[] d=new int[size]; + for(int i=0;i=size-1) + return d[i]+1; + for(int k=i+1;k<=nums[i]+i;k++){ + d[k] = d[k]==0 ? d[i]+1 : d[k]; + } + } + return d[size-1]; + } +} diff --git a/DuanShikai/week07-08/_046_Permutations.java b/DuanShikai/week07-08/_046_Permutations.java new file mode 100644 index 0000000..202a968 --- /dev/null +++ b/DuanShikai/week07-08/_046_Permutations.java @@ -0,0 +1,49 @@ +package com.sky.leetcode; + +import java.util.ArrayList; +import java.util.LinkedList; +import java.util.List; + +/** + * @author DuanSky + * @date 2016年1月12日 下午12:23:31 + * @content + * + * String[] words = {"ace", "boom", "crew", "dog", "eon"}; + List wordList = Arrays.asList(words); + + Integer[] test = {1,2,3,4}; + List testList = Arrays.asList(test); + */ + +public class _046_Permutations { + + public static void main(String args[]){ + int[] nums={1,2,3}; + List> result = permute(nums); + } + + public static List> permute(int[] nums) { + List> result = new ArrayList<>(); + List left = new LinkedList(); + for(int num : nums) left.add(num); + generate(result,new ArrayList(),left); + return result; + } + + public static void generate(List> result, List current, List left){ + if(left.isEmpty()) + result.add(new ArrayList(current)); + else{ + int size = left.size(); + for(int i=0;i> result = permuteUnique(nums); + } + + public static List> permuteUnique(int[] nums) { + List> result = new ArrayList<>(); + List left = new LinkedList(); + Arrays.sort(nums); + for(int num : nums) left.add(num); + generate(result,new ArrayList(),left); + return result; + } + + public static void generate(List> result, List current, List left){ + if(left.isEmpty()) + result.add(new ArrayList(current)); + else{ + int size = left.size(); Integer last = left.get(0)+1; //MISTAKE 注意这里不能通过简单的取反,因为0本身就是0的相反数o(╯□╰)o。 + for(int i=0;i= nums.length-1; + } + + //2ms o(n^2) + public boolean canJump(int[] nums) { + for(int i=0;i=0;k--){ + if(nums[k]+k>i) break; + } + if(k==-1) return false; + } + } + return true; + } + +} diff --git a/DuanShikai/week07-08/_060_Permutation_Sequence.java b/DuanShikai/week07-08/_060_Permutation_Sequence.java new file mode 100644 index 0000000..9f6d3f2 --- /dev/null +++ b/DuanShikai/week07-08/_060_Permutation_Sequence.java @@ -0,0 +1,59 @@ +package com.sky.leetcode; + +import java.util.ArrayList; +import java.util.List; + +/** + * @author DuanSky + * @date 2016年1月12日 下午3:26:11 + * @content + */ + +public class _060_Permutation_Sequence { + + public static void main(String args[]){ + int n=4; int k=5; + _060_Permutation_Sequence test = new _060_Permutation_Sequence(); + for(int i=1;i<=test.getFactorial(n);i++) + System.out.println(test.getPermutation(n, i)); + System.out.println("======="); + System.out.println(test.getPermutation(n, k)); + } + + public String getPermutation(int n, int k) { + String result=""; + List list = new ArrayList(); + for(int i=1;i<=n;i++) list.add(i); + result = generate(result,list,k); + return result; + } + + private String generate(String s,List left, int k){ + if(left.isEmpty()) return s; + if(left.size()==1) { + s+=left.get(0)+""; + return s; + } + int size=getFactorial(left.size()-1), m=k%size, n=k/size; + if(m==0){//刚好被整除,说明是以n元素开头的最后一个元素。 + s+=left.get(n-1); left.remove(n-1); + String temp=""; + for(Integer num : left) + temp=num+temp; + s+=temp; + return s; + } + else{//如果没有被整除,说明有余数,即用完了前面n个元素,那么该元素是以n+1开头的。 + s+=left.get(n);left.remove(n); + return generate(s,left,k-n*size); + } + } + + private int getFactorial(int n){ + int res=1; + for(int i=1;i<=n;i++) + res*=i; + return res; + } + +} diff --git a/DuanShikai/week07-08/_315_Count_of_Smaller_Numbers_After_Self.java b/DuanShikai/week07-08/_315_Count_of_Smaller_Numbers_After_Self.java new file mode 100644 index 0000000..d6e290d --- /dev/null +++ b/DuanShikai/week07-08/_315_Count_of_Smaller_Numbers_After_Self.java @@ -0,0 +1,103 @@ +package com.sky.leetcode; + +import java.util.ArrayList; +import java.util.List; + +/** + * @author DuanSky + * @date 2016年1月12日 下午8:33:23 + * @content + */ + +public class _315_Count_of_Smaller_Numbers_After_Self { + + public static void main(String args[]){ + _315_Count_of_Smaller_Numbers_After_Self test = new _315_Count_of_Smaller_Numbers_After_Self(); + int[] nums={5,2,6,3,4,7,1}; + System.out.println(test.conutSmaller_1(nums)); + System.out.println(test.countSmaller(nums)); + System.out.println(test.countSmaller_(nums)); + + } + + public List conutSmaller_1(int[] nums){ + List res = new ArrayList<>(); + int size = nums.length; + if(size==0) return res; + List tmp = new ArrayList<>(); + for(int i=size-1;i>=0;i--){ + res.add(0,insertAndGet(tmp,nums[i])); + } + return res; + } + + private Integer insertAndGet(List tmp, int key) { + int size = tmp.size(); + if(size==0){ + tmp.add(key); return 0; + } + //找到元素插入的位置 + int low = 0 , high = size-1, mid=(low+high)/2; + if(key>tmp.get(high)){tmp.add(key); return size;} + while(low countSmaller_(int[] nums){ + List res = new ArrayList<>(); + int size = nums.length; + if(size == 0) return res; + res.add(0); + for(int i=size-2;i>=0;i--){ + int pos = findPos(nums,i+1,nums[i]); + insert(nums,i,pos-1); + res.add(0,pos-i-1); + } + return res; + } + + //find left pos. + public int findPos(int[] nums,int start,int key){ + int low = start, high = nums.length-1,mid=(low+high)/2; + if(low == high && nums[low] countSmaller(int[] nums) { + List res = new ArrayList<>(); + int size = nums.length; + for(int i=0;inums[j]) counter++; + } + res.add(counter); + } + res.add(0); + return res; + } +} diff --git a/DuanShikai/week09-10/_022_Generate_Parentheses.java b/DuanShikai/week09-10/_022_Generate_Parentheses.java new file mode 100644 index 0000000..88d4255 --- /dev/null +++ b/DuanShikai/week09-10/_022_Generate_Parentheses.java @@ -0,0 +1,33 @@ +package com.sky.leetcode; + +import java.util.ArrayList; +import java.util.List; + +/** + * @author DuanSky + * @date 2016年2月29日 下午8:39:46 + * @content + */ + +public class _022_Generate_Parentheses { + + public static void main(String args[]){ + _022_Generate_Parentheses test = new _022_Generate_Parentheses(); + List res = test.generateParenthesis(2); + } + + public List generateParenthesis(int n) { + List result = new ArrayList(); + String s=""; + solve(0,0,n,s,result); + return result; + } + + public void solve(int left,int right,int n,String s,List result){ + if(left == right && right == n) result.add(s);//左边的括号和右边的括号都已经用完,而且达到指定数目,程序可以输出了。 + if(left >= right){//左边的括号数目多于或等于右边的元素数目 + if(left<=n) solve(left+1,right,n,s+"(",result); + if(right<=n) solve(left,right+1,n,s+")",result); + } + } +} diff --git a/DuanShikai/week09-10/_029_Divide_Two_Integers.java b/DuanShikai/week09-10/_029_Divide_Two_Integers.java new file mode 100644 index 0000000..7801da0 --- /dev/null +++ b/DuanShikai/week09-10/_029_Divide_Two_Integers.java @@ -0,0 +1,32 @@ +package com.sky.leetcode; +/** + * @author DuanSky + * @date 2016年3月2日 下午5:30:42 + * @content + */ + +public class _029_Divide_Two_Integers { + + public static void main(String args[]){ + _029_Divide_Two_Integers test = new _029_Divide_Two_Integers(); + //System.out.println(Integer.MAX_VALUE +":"+ Integer.MIN_VALUE); + int dividend = Integer.MIN_VALUE; + int divisor = -1; + System.out.println(test.divide(dividend, divisor)); + } + + public int divide(int dividend, int divisor) { + if(divisor == 0 ||(dividend == Integer.MIN_VALUE && divisor==-1)) + return Integer.MAX_VALUE; + int sign = ((dividend<0) ^ (divisor<0)) == true ? -1 : 1 ; + //MISTAKE 注意,这里需要将其转换成long类型 + long divd = Math.abs((long)dividend), divr = Math.abs((long)divisor); + if(divd=0;i--){ + temp = multiplySingle(nums1,nums2.charAt(i)+""); + if(!temp.equals("0")){ + for(int k=0;k=0){ + temp = Integer.parseInt(nums.charAt(p)+"") * Integer.parseInt(single) + carry ; + carry = temp / 10; + left = temp % 10; + res = Integer.toString(left) + res; + p--; + } + return carry > 0 ? Integer.toString(carry) + res : res; + } + + public void changeIfNecy(String nums1,String nums2){ + if(nums1.length()=0 || p2>=0){ + if(p1>=0 && p2>=0){ + temp = Integer.parseInt(nums1.charAt(p1)+"") + Integer.parseInt(nums2.charAt(p2)+"") + carry; + p1--;p2--; + } + else if(p1>=0 && p2<0){ + temp = Integer.parseInt(nums1.charAt(p1)+"") + carry; + p1--; + } + else { + temp = Integer.parseInt(nums2.charAt(p2)+"") + carry; + p2--; + } + carry = temp / 10; + left = temp % 10; + res=Integer.toString(left)+res; + } + return carry>0 ? "1"+res : res; + } + +} diff --git a/DuanShikai/week09-10/_086_Partition_List.java b/DuanShikai/week09-10/_086_Partition_List.java new file mode 100644 index 0000000..86ee40e --- /dev/null +++ b/DuanShikai/week09-10/_086_Partition_List.java @@ -0,0 +1,38 @@ +package com.sky.leetcode; +/** + * @author DuanSky + * @date 2016年2月25日 上午11:27:51 + * @content + */ + +public class _086_Partition_List { + + public static void main(String args[]){ + _086_Partition_List test = new _086_Partition_List(); + ListNode head = new ListNode(1); + head.next=new ListNode(2); + ListNode result = test.partition(head, 0); + } + + //采用用两个指针,一个指针存储的是=key值的元素列表,再把两个指针合并即可。 + public ListNode partition(ListNode head, int x) { + + if(head==null || head.next==null) return head; + ListNode firstTail=new ListNode(0),firstHead=firstTail; + ListNode secondTail=new ListNode(0),secondHead=secondTail; + while(head!=null){ + if(head.val=0 && p2>=0){ + if(nums1[p1]>nums2[p2]) + nums1[p--]=nums1[p1--]; + else + nums1[p--]=nums2[p2--]; + } + while(p2>=0) + nums1[p--]=nums2[p2--]; + } + + //这样是从前往后merge,nums1中的元素需要不断地往后移动操作。 2ms + public void merge_2(int[] nums1, int m, int[] nums2, int n) { + int p1=0,p2=0; + while(p1nums2[p2]){//需要把nums2中的元素插入到p1中 + for(int curr=p2+m;curr>p1+p2;curr--) //后面的元素整体往后挪动 + nums1[curr]=nums1[curr-1]; + nums1[p1+p2]=nums2[p2]; + p2++; + } + else + p1++; + } + //需要把剩余的元素拷贝到数组nums1中 + while(p2 wordDict = new HashSet<>(Arrays.asList(new String[]{"aa","aaaa"})); + System.out.println(test.wordBreak_4(s, wordDict)); + } + + //14ms MISTAKE 注意哪些地方需要 i+1 哪些地方需要取等。 + public boolean wordBreak_4(String s,Set wordDict){ + if(s == null || s.length()==0 || wordDict == null || wordDict.size()==0) return false; + boolean[] d = new boolean[s.length()+1]; d[0] = true; + for(int i = 0; i < s.length(); i ++){ + for(int j = -1; j < i; j ++){ //j是s[0,1,2...i]中的一个切分点.. + String t = s.substring(j+1,i+1); + if(d[j+1] && wordDict.contains(t)){ + d[i+1] = true; + wordDict.add(s.substring(0,i+1)); //增加了这一行 可以提速到7ms + break; + } + } + } + return d[s.length()]; + } + + //神作,不知道啥意思 + Map isBreakable = new HashMap<>(); + public boolean wordBreak_3(String s, Set wordDict) { + if (s.equals("")) { + return true; + } + for (int i=1; i<=s.length(); ++i) { + if (wordDict.contains(s.substring(0, i))) { + Boolean result = isBreakable.get(i); + if (result == null) { + result = wordBreak_3(s.substring(i), wordDict); + isBreakable.put(i, result); + } + if (result) { + return true; + } + } + } + return false; + } + + public boolean wordBreak_2(String s,Set wordDict){ + if(s==null || s.length()==0 || wordDict==null || wordDict.size()==0) return false; + boolean r = divide_2(s,wordDict,new HashMap()); + return r; + } + + private Set wordLength(Set wordDict){ + Set set = new HashSet<>(); + for(String word : wordDict) + set.add(word.length()); + return set; + } + + //从左往右截断 + private boolean divide_2(String s, Set wordDict,Map map) { + if(map.containsKey(s)) return map.get(s); + if(wordDict.contains(s)) return true; + for(int i = 1; i < s.length(); i ++){ + if( wordDict.contains(s.substring(0,i))){ + boolean curr = divide_2(s.substring(i),wordDict,map); + if(curr){ + map.put(s.substring(i), true); + return true; + } + else + map.put(s.substring(i), false); + } + } + return false; + } + + //Solution Time Limit Exceeded !!! + public boolean wordBreak_1(String s, Set wordDict) { + if(s==null || s.length()==0 || wordDict==null || wordDict.size()==0) return false; + Set wordDelete = new HashSet(); + boolean r = divide_1(s,wordDict,wordDelete); + return r; + } + + public boolean divide_1(String s,Set wordDict,Set wordDelete){ + if(wordDelete.contains(s)) return false; + if(wordDict.contains(s)) return true; //如果该字符串直接就存在,则返回true. + for(int i = 1; i < s.length(); i ++){ + //将原来的字符串切分成两半,分别验证左右两半是否可以由词典构成 + String ls = s.substring(0,i); + String rs = s.substring(i,s.length()); + boolean lb = false, rb = false; + if(wordDict.contains(ls)) lb = true; //如果左半部分可以构成单词。 + else lb = wordDelete.contains(ls) ? false : divide_1(ls,wordDict,wordDelete); //如果左半部分不能构成单词,则继续往下切分 + if(!lb) {//如果左半部分没有找到,则记录下来,重新分割。 + wordDelete.add(ls); + continue; + } + if(wordDict.contains(rs)) rb = true; + else rb =wordDelete.contains(rs) ? false : divide_1(rs,wordDict,wordDelete); + if(!rb){ + wordDelete.add(ls); + continue; + } + wordDict.add(s); + return true; + } + wordDelete.add(s); + return false; + } +} diff --git a/DuanShikai/week09-10/_140_Word_Break_II.java b/DuanShikai/week09-10/_140_Word_Break_II.java new file mode 100644 index 0000000..16d462b --- /dev/null +++ b/DuanShikai/week09-10/_140_Word_Break_II.java @@ -0,0 +1,80 @@ +package com.sky.leetcode; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; + +/** + * @author DuanSky + * @date 2016年3月11日 下午1:11:27 + * @content + * "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaabaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" +["a","aa","aaa","aaaa","aaaaa","aaaaaa","aaaaaaa","aaaaaaaa","aaaaaaaaa","aaaaaaaaaa"] +"catsanddog" +["cat","cats","and","sand","dog"] + */ + +public class _140_Word_Break_II { + + public static void main(String args[]){ + _140_Word_Break_II test = new _140_Word_Break_II(); + String s = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaabaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"; + Set wordDict = new HashSet<>(Arrays.asList(new String[]{"a","aa","aaa","aaaa","aaaaa","aaaaaa","aaaaaaa","aaaaaaaa","aaaaaaaaa","aaaaaaaaaa"})); + System.out.println(test.wordBreak_1(s, wordDict)); + } + + + //算法 o(n^2)复杂度 Time Limit Exceeded !!! + private List wordBreak(String s, Set wordDict) { + if(s == null || s.length() == 0 || wordDict == null || wordDict.size() == 0) return new ArrayList(); + List[] d = new ArrayList[s.length()]; + for(int i=0;i(); + if(wordDict.contains(s.substring(0,i+1))) + d[i].add(s.substring(0,i+1)); + for(int j=1;j<=i;j++){ //j 是 分裂点,将原来的串分解成 d[j-1],s[j~i] + String tail = s.substring(j,i+1); + if(wordDict.contains(tail)){ + if(d[j-1].size() != 0){ + for(String temp : d[j-1]){ + d[i].add(temp +" " + tail); + // wordDict.add(temp+" "+tail); + } + } + } + } + } + return d[s.length()-1]; + } + + + //很朴素直白的想法,但是效率依旧很慢。Time Limit Exceeded + public List wordBreak_1(String s, Set wordDict) { + Map> cache = new HashMap<>(); + return core_(s,wordDict,cache); + } + public List core_(String s,Set wordDict,Map> cache){ + if(cache.containsKey(s)) return cache.get(s); + List res = new ArrayList(); + if(wordDict.contains(s)){ + res.add(s); + } + for(int i = 0; i < s.length(); i++){ + String temp = s.substring(0,i+1); //固定左边进行分解 + if(wordDict.contains(temp)){ //如果左边是一个单词 + List list = core_(s.substring(i+1),wordDict,cache); //这个是右边的分解情况 + if(list!=null && list.size()!=0){ //右边不为空,即右边可分解 + for(String curr : list){ + res.add(temp + " " + curr); + } + } + } + } + cache.put(s, res); + return res; + } +} diff --git a/DuanShikai/week09-10/_166_Fraction_to_Recurring_Decimal.java b/DuanShikai/week09-10/_166_Fraction_to_Recurring_Decimal.java new file mode 100644 index 0000000..216e7ab --- /dev/null +++ b/DuanShikai/week09-10/_166_Fraction_to_Recurring_Decimal.java @@ -0,0 +1,87 @@ +package com.sky.leetcode; + +import java.util.HashMap; +import java.util.Map; + +/** + * @author DuanSky + * @date 2016年3月3日 上午10:59:10 + * @content + * -1 +-2147483648 + */ + +public class _166_Fraction_to_Recurring_Decimal { + + public static void main(String args[]){ + int numerator =0; + int denominator = 3; + _166_Fraction_to_Recurring_Decimal test = new _166_Fraction_to_Recurring_Decimal(); + System.out.println(test.fractionToDecimal(numerator, denominator)); + System.out.println((double)numerator/denominator); + } + + + + private String fractionToDecimal(int numerator, int denominator) { + if(numerator==0) return "0"; //MISTAKE 注意考察 0 的情况!! + boolean flag =( (numerator>0) ^ (denominator>0) ) ? false : true; //MISTAKE 注意需要考虑符号问题!! + long nume = Math.abs((long)numerator), deno = Math.abs((long)denominator); //MISTAKE 注意最小负数的绝对值是要大于最大正数的绝对值,所以可能造成溢出!!! + if(nume%deno==0) return (flag ? "" : "-") + nume/deno; + //head + long head = nume / deno; + String res = (flag ? "" : "-") +head +"."; + nume = nume - head * deno; + Map map = new HashMap<>(); + while(!map.containsKey(nume)){ + map.put(nume, res.length()); + if(nume*10 map = new HashMap<>(); + int zeroNum = 0; + while(numerator stack=new Stack(); int i=0; + while(i 0 && nums.length - i + j > k && nums[i] > res[j-1]) + j--; + if( j < k) res[j++] = nums[i]; + } + return res; + } + // 02 两个整数所能组成的最大整数 + public int[] merge(int[] nums1,int[] nums2){ + if(nums1==null || nums1.length == 0) return nums2; + if(nums2 == null || nums2.length == 0) return nums1; + int n1 = nums1.length, n2 = nums2.length; + int[] res = new int[n1+n2]; + for(int k = 0, i = 0, j = 0; k < n1 + n2; k ++){ + res[k] = greater(nums1,i,nums2,j) ? nums1[i++] : nums2[j++]; + } + return res; + } + + private boolean greater(int[] nums1, int i, int[] nums2, int j) { + while(inums2[j]); + } + + + + + + +} diff --git a/DuanShikai/week11-12/_025_Reverse_Nodes_in_k_Group.java b/DuanShikai/week11-12/_025_Reverse_Nodes_in_k_Group.java new file mode 100644 index 0000000..bf1bfa4 --- /dev/null +++ b/DuanShikai/week11-12/_025_Reverse_Nodes_in_k_Group.java @@ -0,0 +1,46 @@ +package com.sky.leetcode; +/** + * @author DuanSky + * @date 2016年3月17日 下午1:12:03 + * @content + */ + +public class _025_Reverse_Nodes_in_k_Group { + + public static void main(String args[]){ + _025_Reverse_Nodes_in_k_Group test = new _025_Reverse_Nodes_in_k_Group(); + ListNode head = ListNode.generate(new int[]{1,2}); + int k = 2; + ListNode t = test.reverseKGroup(head, k); + } + + + public ListNode reverseKGroup(ListNode head, int k) { + if(head == null || head.next == null) return head; //至少需要两个元素才有翻转的必要 + ListNode lastTail = new ListNode(0), res = lastTail,thisNext = null, nextHead = head, curr = head; + while(curr != null){ + int counter = 1; + while(nextHead != null && counter < k) { //记录需要反转的链表 + nextHead = nextHead.next; + counter ++; + } + ListNode thisHead = curr; + if( nextHead != null && counter == k){ //需要反转 + nextHead = nextHead.next; + ListNode thisTail = null; + while(curr!=nextHead){ + thisNext = curr.next; + curr.next = thisTail; + thisTail = curr; + curr = thisNext; + } + lastTail.next = thisTail; + lastTail = thisHead; + }else{ + lastTail.next = thisHead; + break; + } + } + return res.next; + } +} diff --git a/DuanShikai/week11-12/_133_Clone_Graph.java b/DuanShikai/week11-12/_133_Clone_Graph.java new file mode 100644 index 0000000..fb9a70e --- /dev/null +++ b/DuanShikai/week11-12/_133_Clone_Graph.java @@ -0,0 +1,60 @@ +package com.sky.leetcode; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** + * @author DuanSky + * @date 2016年3月18日 下午9:15:20 + * @content + */ + +public class _133_Clone_Graph { + + public static void main(String args[]){ + _133_Clone_Graph test = new _133_Clone_Graph(); + UndirectedGraphNode node = new UndirectedGraphNode(0); + node.neighbors.add(node); + node.neighbors.add(node); + test.cloneGraph(node); + } + + + public UndirectedGraphNode cloneGraph(UndirectedGraphNode node){ + if(node == null) return null; //MISTAKE 注意需要考虑为空的情况 + return core(node,new HashMap()); + } + + public UndirectedGraphNode core(UndirectedGraphNode node, Map map){ + if(map.containsKey(node.label)) return map.get(node.label); //如果之前新建的这样的一个对象,则直接返回这个对象 + UndirectedGraphNode copy = new UndirectedGraphNode(node.label); + map.put(copy.label, copy); + List neighbors = node.neighbors; + for(UndirectedGraphNode neighbor : neighbors){ + copy.neighbors.add(core(neighbor,map)); + } + return copy; + } + + //==================================================================================== + public UndirectedGraphNode cloneGraph_wrong_answer(UndirectedGraphNode node) { + if(node == null) return null; + List neighbors = node.neighbors; + List copy = new ArrayList(); + for(UndirectedGraphNode neighbor : neighbors){ + copy.add(cloneGraph_wrong_answer(neighbor)); //MISTAKE 当出现环路的时候,会陷入死循环。 + } + UndirectedGraphNode root = new UndirectedGraphNode(node.label); + root.neighbors = copy; + return root; + } + +} + +class UndirectedGraphNode { + int label; + List neighbors; + UndirectedGraphNode(int x) { label = x; neighbors = new ArrayList(); } +} diff --git a/DuanShikai/week11-12/_210_Course_Schedule_II.java b/DuanShikai/week11-12/_210_Course_Schedule_II.java new file mode 100644 index 0000000..b57347f --- /dev/null +++ b/DuanShikai/week11-12/_210_Course_Schedule_II.java @@ -0,0 +1,55 @@ +package com.sky.leetcode; + +import java.util.LinkedList; +import java.util.Queue; + +/** + * @author DuanSky + * @date 2016年3月18日 下午4:07:49 + * @content + */ + +public class _210_Course_Schedule_II { + + public static void main(String args[]){ + _210_Course_Schedule_II test = new _210_Course_Schedule_II(); + int numCourses = 2; + int[][] prerequisites = {}; + int[] res = test.findOrder(numCourses, prerequisites); + } + + public int[] findOrder(int numCourses, int[][] prerequisites) { + int[][] matrix = new int[numCourses][numCourses]; + int[] indegree = new int[numCourses]; + + for(int i = 0; i < prerequisites.length; i++){ + int from = prerequisites[i][0], to = prerequisites[i][1]; + if(matrix[to][from]==0) indegree[from]++; + matrix[to][from] = 1; + } + + int counter = -1; + Queue queue = new LinkedList(); + int[] res = new int[numCourses]; + + for(int i = 0; i < numCourses; i++){ + if(indegree[i]==0) queue.add(i); + } + + while(!queue.isEmpty()){ + counter ++; + int curr = queue.poll(); + res[counter] = curr; + for(int i = 0; i < numCourses; i++){ + if(matrix[curr][i]==1){ + if(--indegree[i]==0){ + + queue.add(i); + } + } + } + } + return counter+1 == numCourses ? res : new int[0]; + } + +} diff --git a/DuanShikai/week11-12/_336_Palindrome_Pairs.java b/DuanShikai/week11-12/_336_Palindrome_Pairs.java new file mode 100644 index 0000000..af30517 --- /dev/null +++ b/DuanShikai/week11-12/_336_Palindrome_Pairs.java @@ -0,0 +1,106 @@ +package com.sky.leetcode; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.HashSet; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; +import java.util.Set; + +/** + * @author DuanSky + * @date 2016年3月16日 下午7:36:01 + * @content + */ + +public class _336_Palindrome_Pairs { + + + public static void main(String args[]){ + _336_Palindrome_Pairs test = new _336_Palindrome_Pairs(); + String s = "abcdefdcba"; + String[] words = {"aihhieeegdebhb","acajjajbbibaab","ddjihhebahcead","cehdaiaeaggai","di","bcacdfjadgfjgiicghc","ddhigcdidggfcejib","djbgdcadgiaaieh","fggfdajadcfhajhag","dfahbdjcbgdf","dfbhhdfjdcfefij","fjgbegdifedgf","ffeice","gdgjcaichica","gigjifehagcacggg","ehjgha","ddj","igffdiddgecidcjfj","cca","heeig","cdghidigcgdaeda","jbbachabahheidacd","feahagifaacejg","abdbgidheigfcabffe","ehcbieidgfagijafd","gcji","f","jddgd","ibachgei","eeabadcbiebdchiaha","baejcdeef","cagbjjhaecgi","ijfcfecdccchee","jhiidcdba","dgdibjihcbbhg","fcibbcbbjhhbiiiaag","fggefjgbjdajcbcgjbj","gg","hhadjfeaa","aghbgcjfcdcihfc","bfffcggfeddeajbhafge","dggfafhafc","dcdbhcifbbbgbcaeh","dacacdhbjd","ghhifd","aabifcjhadibhfdjbga","baejceehiagaabchabff","bjagbabf","hgijgdifccjdehjaccbf","gbfejbfddgcja","iiedgaigdg","eeieg","cei","bchicbfcihbcjejjfg","jhjdfi","ebdgaghfbjhfceh","bdjdgegfdddadiieaici","abeecj","g","jcadaigbcabcggeddjcd","h","ajjg","iebcbgfbjhbfbai","ghj","gidafdigfgfcjfg","hgjacihicbcfifghgcbc","gaaibecj","ifjciedfgdegfi","bfcbdddjfjjhfahbjfaa","fafgijfgahf","gcjacdbgdbecghif","gjdgah","fdbbcbidbhbgf","ghihccifb","ghjeecjgfefd","b","egigbdaicefieddicee","gjg","baae","jeiehgccjefedjib","jjcjgeaajcj","ihjbhbjgejgcheb","accce","jhc","gjj","icaadccfihj","bafefdchbhibibdfggg","egehfbegjedcicdfjfge","fbcdighdcieideh","bjfibbjigc","daidhjjb","aeeec","ed","dgdbjjibccjdafh","bbde","biejhahgd","bjhhdiidcbe","dibceifgj","c","hedi","fjjfihdejifjfba","hd","bffbd","gdjaaaaihgbiahicde","gdehfchcd","icgidjcj","gd","jddfjhcgiefjee","daajiighijhdfbi","bggj","ecgfbahaacfiajc","ggdffajibaidjib","jf","fhicadfghdcchiiifj","aji","gfjacgcfbicgdjad","cfhfcggadigidigihdid","bfcdidiifgfbc","ahiidhjhbfdiahic","edecdcd","cigigjfafdbhbdhhhjf","fbjefgghghcheja","dhcheddfjffeejb","ffcd","ificcdfdb","ghjgafhiffdcgghjja","jgfadaecjgh","fifahiijidjgcdiedee","dccejgdfaggdadfccd","aeghbjdjgifah","gejaehchdfhfdeegie","bafa","aebgccebdfcgc","abdgbcg","dcedgfjbbgc","jbfhaddbbdaiiegjic","jegdijdaebj","ejgajggidiahadgddeab","ece","i","hegjjfbgegijdjgb","aiiee","eefad","cdbeifbfa","afej","hagaadb","egfdib","hfaiididcidfjccf","debf","ddhceh","hjgecgjjihf","fjjfj","gjceffcedjff","aaaghiabbdagbchhg","dgaieejgbfjdhcbcijfa","cacf","cbjbijehadihhjdi","fiabgiiccbba","eagi","edaagghhehgddic","egcaghjcfci","cjbhgfbdfddh","jbjdhghgjjjacgidfbeg","icjihhgeffbhihhdh","caceeibgbihcfidbig","efij","ahjgfdegbig","cieifgigjdbje","iebahhbjjbjiegaca","bjiheaiaacajdjbdbe","gbgbcdge","bdaijhgefjibfhcedc","gjgfbhhdedhb","hedbgdbajfg","eiebdiiedhagad","a","digcdgjejhf","aaiafddgcefj","dhba","d","ag","bbchdccbgjfbjcgfci","afg","cbjgjfffj","ccgifgeccjgc","jhbgb","dfggiifehbf","hfhedbgjdhfghgdja","fagjbdge","cejhjbccgjggihcgeaf","dbhbfebffgaf","cdhdjhcj","hacjbaifjb","gjejjbbbecidahjched","jadfiigjidfgfa","efjggaebaa","heieaihfffj","ejeafadace","jfajijdifijacbhjc","fig","cehegedcdjcijehaeac","dgjeijfae","dcbeddfdb","gdd","ad","eafdbedfdgeiiif","dagihgebabiahhaf","fiifhdbfhhbb","dfc","eajigcfifjjdhdhjadf","egccbbhgddggebehebhc","debahdfadag","fhhcedjachdcjhd","iaaicjbgejjaihcdaab","jggbiee","gigdjccjficebidhjdcj","fa","aehaghjbfibcd","ceiicfbfgccbfjbi","ieheijg","bhcffafei","ahhihfjja","bdiihbciicfbhead","bebihe","dedigbeddahabdfa","dcehfcbhibiihhg","bdbdaifcbediabebhee","ghbgecjcidafbgfad","bfiaafcbdijj","jffeijjijcbeihgbccfj","fafbbjgagjbdd","jcejgd","dffgjfdibfabjgddcb","acdhaebbiiacffgcdj","ifibah","fighebjccg","jehejgdgiddebehfhdba","ffebafcaafcgadfjai","icjcdgachddebbbhj","hcchjbecfigah","cdjfffgafhie","fedaejjeedahhccg","gdedhijcjh","aaccbgifg","dibffhffigaeegfg","ba","hg","efa","acifijeg","cichjibjdhgajcdc","ccejgejcgabafgb","dhfi","cdgdfcfbhaefbdddh","aebdjf","fdghbigifah","jeegcicbfejc","bebehc","dgfgdhg","jjfbifgfj","gejbebejbfhb","ghfhheeaddc","iedah","hfjchb","hjhdfbjfigdbgbgggf","ebfiecdghcfg","eheiicbhiedi","fjaa","ccbeheejcicahhhj","ebbjbd","hafebbhfgdjbde","aibjfcfe","jbbdbjac","ghdaec","gbabhj","e","fcbjgibadfcdbd","afahbhjjbad","adadeiibjgchihgcdfjh","dgadgfji","ecidcfhajhdfcf","dfeeebggedhfidede","cadejafjaajaicd","ibd","dagf","eigfajhfgdcbhi","ce","jdbgiefed","bgffchfeebhejgh","fj","geddhdghcb","jcabjacjhbiejjaehih","gfchcjceadifii","cgjjaai","jicfgjciciihagd","agcheaeahddheje","jaaiehdhfhcbg","ciafhfadeahiedgac","fdecghgehfdigfa","hajffedb","hcjefhfeggbaafgcheh","fdddcdchbhjgfig","aghggjdcbehgccd","ehfdj","gbbgdb","cdgjifidcdiejfga","gbjdi","fegicbfdhbdeicdac","ijfbegfdjcbjcaddbcgg","hihfjdadifh","fdccdcdchdh","ciciaejifbeefcciigb","afcccc","jfci","fccje","fd","ebbgfdi","bdcig","ehbaji","cbdjiffgfagagjbaid","bejhcgdcaeaaibibca","fhigfbfddfbai","cgbadcgdchia","jh","aahjbj","fddfahebabfajafgceb","cbficcbhadchedcidg","iihjdaedbb","bbigheagfee","ffggehgfificifdejga","acidhghj","bbbggfegjh","bfcbhdied","bejadihbdjid","ajhfgjehaaabb","fhgjjedajhb","jejghcjfbgda","ef","jdcahjiahgfejaacc","fjacgcjjfeb","ggefjf","jfejaah","fbgfhefcegcbbihf","igefidejfgdefjeg","beaecfgjcda","dffccaecieicbcgheeeh","hbfaebjdi","eddgcfjhbh","ieheecbefgjhcjficb","ia","iibfefchhdei","fjdcdccaefi","gebcjejihhdjjbf","jgee","fc","gdfaejbfbgeffffibb","iciabibhihfcejdjggba","bcfhfafj","cchgaibghghjifehgdac","gheheg","fddbc","jfebecgifdajh","bjichcbbdhg","eaeaaadc","febhcc","dba","bafchg","cbjbghgfjij","ae","cihijabjhd","abjb","ijiagdeh","cjhdbbgdfh","ffdgagecchicae","iii","iiejcideejjifiia","dcb","cgjc","eeddie","jedbfgdb","bjiadfef","fddjiejeghhafhjefb","ebdfbfdbgdhcdjddigj","hgiffaigdgehfdb","geggc","beiiagf","gfbhjej","jagadabjcgiceija","gghidjhaeficjej","eibggjgccfbhcad","hhijjeaebbg","chddicbchb","iifgcbed","ehcfbjaeahfbbdjgf","idcdaajf","ch","aigigiehdbiehh","egacbfbejh","chhchhdfccagdidhed","bceefjjjhhjdbj","fgjdcigjaabiccfba","bjhddhjjbbiajbchia","fjbicdcgffadhgbdc","gbgba","ajjdffgegahf","cbjfeeja","egfjbfgghjeaeaaeiej","edhgdgjgfiddfjddd","hc","dhaffehdh","abaca","fdfiajaehcddi","ebddcj","dejh","jjfigabh","bgiijbecafcag","dfffjdabhegej","fgjdjdcjhcidjgbhb","adgaca","jbadfgjfd","ggbdbehbdbjbjif","dbibg","ifdgaihcaaif","hfcicghddi","dfgieidbddhcdbcc","cg","ecajej","cegigiaejcbddgef","j","bbddbjebeccgjbbbifeg","dgffdedej","bcffhigji","bacgeah","cehfdaebaagjecfbfjeh","ffdjbfjigfejheacec","bhicaf","feifehchcf","eh","cc","fgebehacgggaafecahbi","jdjdeg","ceiegifagjdig","egjf","ichajgibiijbffhgjd","hehjhhgjecihiaeh","jjbfbjjgdjijhdefhe","ieijjbabdiggbej","jhggbgcbajigebb","bb","ciigfdigbajfjaajghh","eai","eaggcf","jeefebecid","fhaifhfiiighdgdgicf","fcj","iifd","gbgcaefcf","jjddcjfdchcdchce","ee","hiffa","dcfda","ijcfbbfbae","hcbdhhg","aheifdcjdgbccccjgadc","ecjabjjbdefgjbbhj","bfdjjcfbdfdcef","icjfheiee","hecff","hccccjdgeafdjeebabca","gibiafaihd","idbaahbddg","iieigidefdbddjc","bcahbdifgjcfahcdfea","djadjjgaebcg","idjaeegcc","beehcdcb","ehbfdhffaa","djjff","igacfgdbjiedffia","hdgabjaefahhcibiba","bca","eehfjb","iibfigca","gifgcaafddebajaedjdg","ai","ijgbjcjj","ifdjjjfcabhijjgc","hh","ecfijbhfcajbfc","iifcdifc","ehf","hjfedgdbcdcif","ihhedgbedddegebcfi","gc","cfj","eicigiaacghhfgch","fjcdjadd","idihdhjbfgdjeg","fddbdfigfbgchdcaaehc","cgdfef","idicdcbihehdcdi","bceibi","ifehjcfbihjefaabhcc","ieegghfahacidc","adbicied","ghbcdegb","jeijjbbfgcdgjied","geaad","ajjbccgbifcdggafc","accddbbhjcbhe","fbfb","jifgjhaadchj","hgjhdifeiji","gcjaddjjdgchdbcigch","dghgehia","jdiab","fbad","ebgiaabdbdehjce","hahehbifa","heigfcjigjabhaiedb","cjjc","ffhjbhahegji","bihddjfdbhhigcf","djccffcfjfcdbedcj","jcfbhifieihfibgbbe","jdbgiebfgch","hgfgaibcabf","idbaiaeadficihfd","hihjaadeebegcbddi","cdhahbjgjaifideb","ecficjfgc","dehjdf","fffe","ffeghcihcfab","ahdbee","gfccgc","ahbffbiah","ccg","ecicgiddgebfgcdgi","bc","dbhggffhdbjhhab","idjiijfgi","afch","hcghdedadhhchhjafcji","eaigidgj","bbgb","bghibhjaahcebgf","fjjffj","deaaaaeeheaecj","icjjcdijghgcg","chjh","jgcaahhbdjadfgjcg","gfafjdgh","fdggghejhh","hahhjfidghfbcfjgji","ejg","bjachejdcfjc","ibbbcgdbj","hjjhccggidaie","iiaehchic","jgheggigbbfa","afgieeeafaiaiccaag","eejjfbihhiegbbbgfeh","fjdbcaijfjc","igeedcfegceaajbe","aafjhaeahbedcf","agbcbeifeahh","fafjajddaabefcjdcff","aajfahafedejifaga","hbag","ca","bffdfecaebaghccfbdej","id","cdbbihchhebfi","cjaihigib","bfahhjjjabdeeeje","bhcagbgc","ejjfhebejadiidehdcgb","ecigdhfifbjch","jgagf","bhjdaejfbgjc","hbjfiediiajbej","cjgd","acejgdhecef","jhjdbi","ijidbeaaheaiahjcfcd","gjdfjgcechcjc","bfidjacdhegegibhh","egbefbdbicbid","biga","igebachebcjcecge","dbfciciahgfebecb","ffaig","ebcdeaciibfjefb","hcaibiidejh","hbfebahiid","ffgehig","dfcgidibacf","efdjbchgaihf","abjjhfcah","ijjbeibhedhi"}; + System.out.println(test.palindromePairs_1(words)); + } + + //my solution. + public List> palindromePairs_1(String[] words) { + List> res = new LinkedList<>(); + if (words == null) return res; + Map map = new HashMap<>(); + for(int i = 0; i < words.length; i ++) map.put(words[i], i); + for(int i = 0; i < words.length; i ++){ + int l = 0, r = 0; // l 和 r 分别是左边界和右边界,这两个值只有一个为0,不可能同时为0。l为0时,是固定左边部分 + while(l <= r){ //需要循环取出所有的情况 + String s = words[i].substring(l,r); + Integer j = map.get(new StringBuilder(s).reverse().toString()); //MISTAKE 注意这里需要反转 + if(j!=null && i!=j && isPalindrome(words[i].substring(l == 0 ? r : 0, l == 0 ? words[i].length() : l))) //MISTAKE 注意这里需要考虑i!=j,因为不能自己跟自己组成回文 + res.add(Arrays.asList(l == 0 ? new Integer[]{i,j} : new Integer[]{j,i})); + if(r < words[i].length()) r++; //r先加到右边界 + else l++; //l在加到左边界 + } + } + return res; + } + + //beautiful solution. + public List> palindromePairs_(String[] words) { + List> pairs = new LinkedList<>(); + if (words == null) return pairs; + HashMap map = new HashMap<>(); + for (int i = 0; i < words.length; ++ i) map.put(words[i], i); + for (int i = 0; i < words.length; ++ i) { + int l = 0, r = 0; + while (l <= r) { + String s = words[i].substring(l, r); + Integer j = map.get(new StringBuilder(s).reverse().toString()); + if (j != null && i != j && isPalindrome(words[i].substring(l == 0 ? r : 0, l == 0 ? words[i].length() : l))) + pairs.add(Arrays.asList(l == 0 ? new Integer[]{i, j} : new Integer[]{j, i})); + if (r < words[i].length()) ++r; + else ++l; + } + } + return pairs; + } + + //暴力检测 68ms 未通过 + public List> palindromePairs(String[] words) { + List> res = new ArrayList<>(); + for(int i = 0; i < words.length; i++){ + for(int j = i + 1; j < words.length; j++){ + if(!canMakePalindrome(words[i]+words[j])) continue; + if(isPalindrome(words[i]+words[j])) + res.add(Arrays.asList(new Integer[]{i,j})); + if(isPalindrome(words[j]+words[i])) + res.add(Arrays.asList(new Integer[]{j,i})); + } + } + return res; + } + + //判断一个字符串是否可以构成回文 + private boolean isPalindrome(String s) { + if(s == null || s.length() < 2) return true; + int i = 0, j = s.length()-1; + while(i set = new HashSet(); + for(int i = 0; i < s.length(); i++){ + char a = s.charAt(i); + if(set.contains(a)) set.remove(a); + else set.add(a); + } + return set.size()<=1; + } + +} diff --git a/LiangJianhua/task7/BestTimeToBuyAndSellStockIII.java b/LiangJianhua/task7/BestTimeToBuyAndSellStockIII.java new file mode 100644 index 0000000..ab84a92 --- /dev/null +++ b/LiangJianhua/task7/BestTimeToBuyAndSellStockIII.java @@ -0,0 +1,84 @@ +package com.josh.task7; + +import org.junit.Test; +/* + * ���⣺ + * �����д洢���µ�i��Ĺ�Ʊ�۸� + * ����ѹ�Ʊ����ʱ�� + * ע��һ�������һ������Ϊһ�ν��� + */ +public class BestTimeToBuyAndSellStockIII { + @Test + public void test(){ + int[] prices={3,2,6,5,0,3}; + System.out.println(maxProfit3(prices)); + } + /* + *Ҫ��ֻ����һ�ν��ף��������� + * ���������е����ֵ����Сֵ������СֵҪ�����ֵǰ�� + */ + public int maxProfit1(int[] prices) { + if(prices.length <= 1) return 0; + int minPrice = prices[0],maxPrice=prices[0],minPrice2 = prices[0]; + for(int i=0;imaxPrice || prices[i]-minPrice2>maxPrice-minPrice){ + minPrice = minPrice2; + maxPrice = prices[i]; + } + if(prices[i]=0;j--){//���ű�����i��֮���������� + curMax = Math.max(curMax, prices[j]); + maxProfit = Math.max(maxProfit, curMax-prices[j]); + postProfit[j] = maxProfit; + } + maxProfit = preProfit[0]+postProfit[0]; + for(int k=0;kmaxProfit){ + maxProfit = preProfit[k]+postProfit[k]; + } + } + return maxProfit; + } +} diff --git a/LiangJianhua/task7/CountOfRangeSum.java b/LiangJianhua/task7/CountOfRangeSum.java new file mode 100644 index 0000000..943312c --- /dev/null +++ b/LiangJianhua/task7/CountOfRangeSum.java @@ -0,0 +1,62 @@ +package com.josh.task7; + +import java.util.ArrayList; +import java.util.List; + + +import org.junit.Test; +/* + * ���⣺ + * ����һ�����飬һ�����޺����� + * ��������������ڸ�������֮������ĸ��� + * ע�������е�����������������޷�Χ��Ҳ�� + */ +public class CountOfRangeSum { + @Test + public void test(){ + int[] a = {-2,5,1}; + int i = countRangeSum(a,-2,2); + System.out.println(i); + } + /* + * ������������������������������ÿ������Ӻͣ����Ƿ��������� + */ + public int countRangeSum(int[] nums, int lower, int upper) { + if(null == nums || nums.length == 0) + return 0; + int[] b = new int[nums.length]; + List list = new ArrayList<>(); + getCombination(nums, 0, b, 0,lower,upper,list); + return list.size(); + } + //��ȡ����a�����������������b�д����a��һ�������� + private void getCombination(int[] a, int begin, int b[], int index,int lower,int upper,List list) { + if(index >= a.length) + return; + for(int i = begin; i < a.length; i++){ + b[index] = a[i]; + //printArray(b,index); + sum(b, index,lower,upper,list); + getCombination(a, i+1, b, index+1,lower,upper,list); + } + } + //��b������Ԫ�صĺ� + private void sum(int[] b, int index ,int lower,int upper,List list) { + int sum = 0; + for(int i = 0; i < index+1; i++){ + sum = sum + b[i]; + //System.out.print(b[i] + " "); + } + //List list = new ArrayList<>(); + if(sum>=lower && sum<=upper) list.add(sum); + //System.out.println(sum); + } +// private void printArray(int[] b, int index) { +// +// for(int i = 0; i < index+1; i++){ +// System.out.print(b[i] + " "); +// } +// System.out.println(); +// } + +} diff --git a/LiangJianhua/task7/JumpGameII.java b/LiangJianhua/task7/JumpGameII.java new file mode 100644 index 0000000..fa5f462 --- /dev/null +++ b/LiangJianhua/task7/JumpGameII.java @@ -0,0 +1,70 @@ +package com.josh.task7; +import org.junit.Test; + +/* + * ����һ���Ǹ����飬�����е�Ԫ�ش����ӵ�ǰλ�ÿ����ƶ�������� + * ��ʼ��λ��0 + */ +public class JumpGameII { + + @Test + public void test(){ + int[] nums = {1,1,1,0}; + int i = jump(nums); + System.out.print(i); + boolean b = canJump(nums); + System.out.println(b); + } + //Jump Gam II + /* + * �󵽴�����ĩβ�����ٲ��� + * �������ӿ�ʼλ��Ѱ�ҿɵ�����Զ�������һ���� + * ֱ�������ӿ�ʼλ���ܵ������Զ����λ��Ϊ����ʼλ������+��ʼλ�õ�Ԫ��ֵ=��Զλ������ + * ����ʵ�������������ǻ�Ҫ����"��ʼλ��"��"��ʼλ������+��ʼԪ��ֵ"λ��֮�������Ԫ�� + * �������ܵ������Զ�����Ƿ��"��Զλ������"Զ����Զ���Ե�ǰλ��Ϊ��һ����ʼλ�� + */ + public int jump(int[] nums) { + int steps = 1; + if(nums.length == 0 || nums.length == 1) return 0; + if(nums[0]>=(nums.length-1)) return 1; + return findPosi(nums, 0, steps); + } + public int findPosi(int[] nums ,int start,int steps){ + while(start + nums[start]=maxLen){ + maxLen = i+nums[i]; + start = i; + } + } + steps++; + } + return steps; + } + //Jump Gam I + //����ĩβ�Ƿ�ɴ� + /*������ + * ���ɴ�λ��һ������0�����֣����Ա������飬��û��0�����Ȼ�ɴ� + * ����0����0λ�ÿ�ʼ�жϣ�֮ǰ�����Ƿ���Ծ���0�������ɾ��������ʾ���ɴ���ɾ������ɴ� + * + */ + public boolean canJump(int[] nums) { + if(nums.length == 0) return false; + if(nums.length == 1 || nums[0]>=(nums.length-1)) return true; + for(int i=0;i=0;j--){ + if(j+nums[j]>i+nums[i]){ + flag = true; + break;//���Ծ���0λ�ã�����ѭ�� + } + } + if(flag == false) return false; + } + } + return true; + } +} diff --git a/LiangJianhua/task7/PermutationsII.java b/LiangJianhua/task7/PermutationsII.java new file mode 100644 index 0000000..95a7f99 --- /dev/null +++ b/LiangJianhua/task7/PermutationsII.java @@ -0,0 +1,65 @@ +package com.josh.task7; + +import java.util.ArrayList; +import java.util.HashSet; +import java.util.Iterator; +import java.util.List; +import java.util.Set; + +import org.junit.Test; + +/* + * ����һ�����飬�������ظ�Ԫ�أ������в��ظ���������� + */ +public class PermutationsII { + @Test + public void test(){ + List> list = new ArrayList>(); + //Set> set = new HashSet>(); + int[] nums = {3,3,0,0,2,3,2}; + //per(nums, 0, nums.length-1, set); + list = permuteUnique(nums); + //������ + for(int i=0;i> permuteUnique(int[] nums) { + List> list = new ArrayList>(); + Set> set = new HashSet>(); + per(nums,0,nums.length-1,set); + Iterator> it = set.iterator(); + while(it.hasNext()){//��set�е�Ԫ��ת����list�� + list.add(it.next()); + } + return list; + } + //������nums���������� + /* + * �ݹ� + */ + public Set> per(int[] nums,int start,int end ,Set> set){ + if(start == end){//��ֻ��һ��Ԫ��ʱ��һ�����ȫ���� + List perList = new ArrayList(); + for(int i=0;i=0 && next=0;i--){ + reverseStr = reverseStr + str.charAt(i); + } + return reverseStr; + } +} diff --git a/LiangJianhua/task8/DistinctSubsequences.java b/LiangJianhua/task8/DistinctSubsequences.java new file mode 100644 index 0000000..ee268b8 --- /dev/null +++ b/LiangJianhua/task8/DistinctSubsequences.java @@ -0,0 +1,75 @@ +package com.josh.task8; +import org.junit.Test; +/* + * ��s��ɾ�����ɸ��ַ������Բ������ٸ���t��ͬ���Ӵ� + * ��̬�滮 + * + */ +public class DistinctSubsequences { + @Test + public void test(){ + String s="aabdbaabeeadcbbdedacbbeecbabebaeeecaeabaedadcbdbcdaabebdadbbaeabdadeaabbabbecebbebcaddaacccebeaeedababedeacdeaaaeeaecbe"; + String t="bddabdcae"; + //String s="abceabc",t="abc"; + System.out.println(numDistinct(s,t)); + } + public int numDistinct(String S, String T) {//DP Internet 10582116 + int[][] dp = new int[S.length() + 1][T.length() + 1]; + dp[0][0] = 1;//initial + for(int j = 1; j <= T.length(); j++)//S is empty + dp[0][j] = 0; + + for (int i = 1; i <= S.length(); i++)//T is empty + dp[i][0] = 1; + + for (int i = 1; i <= S.length(); i++) { + for (int j = 1; j <= T.length(); j++) { + dp[i][j] = dp[i - 1][j]; + if (S.charAt(i - 1) == T.charAt(j - 1)) + dp[i][j] += dp[i - 1][j - 1]; + } + } + return dp[S.length()][T.length()]; + } + + public int numDistinct1(String s, String t) {//���� ��ʱ������ + if(s.length() ==0){ + return t.length()==0?1:0; + } + if(t.length()==0){ + return 1; + } + int count =0; + for(int i=0;i count){ +// if(s==t || t.length()==0) return count.size()+1; +// if(s.length()-s_begin < t.length()-t_begin) return count.size(); +// //����һ�������¼t��ÿ���ַ���s�е�λ�� +// int[] A = new int[t.length()-t_begin]; +// int i=s_begin,j=t_begin,index = 0; +// while(i=0;k--){//�ݹ�Ѱ������ƥ���Ӵ� +// like(s, t, A[k]+1, k, count); +// } +// } +// return count.size(); +// } +} diff --git a/LiangJianhua/task8/HouseRobber.java b/LiangJianhua/task8/HouseRobber.java new file mode 100644 index 0000000..6b687e3 --- /dev/null +++ b/LiangJianhua/task8/HouseRobber.java @@ -0,0 +1,50 @@ +package com.josh.task8; + + +import org.junit.Test; +/* + * ��һ��������ȡ��һ����������������ʹ������ + * ��̬�滮 + */ +public class HouseRobber { + @Test + public void test(){ + int[] nums = {2,1,1,2}; + System.out.println(rob2(nums)); + } + /* + * ��̬�滮 �ؼ������ҵ�״̬ת�Ʒ��̺ͳ�ʼ״̬ + * ��������dp[i]�洢��λ��iʱ�����ֵ + * ״̬ת�Ʒ��̣�dp[i] = max(dp[i-1],dp[i-2]+nums[i]) + * ��󷵻�dp[nums.length-1] + */ + public int rob(int[] nums) { + if(nums.length == 0) return 0; + if(nums.length == 1) return nums[0]; + if(nums.length == 2) return Math.max(nums[0], nums[1]); + int[] dp = new int[nums.length]; + dp[0] = nums[0];//��ʼ״̬ + dp[1] = Math.max(nums[0], nums[1]); + for(int i=2;i res = new ArrayList<>(); + int p2=0,p3=0,p5=0,curUglyNum=1,v2=0,v3=0,v5=0; + res.add(1); + while(res.size() list = new ArrayList<>(); + List res = new ArrayList<>(); + res.add(1); + while(res.size()0) + list.add(res.get(res.size()-1)*2); + if(!list.contains(res.get(res.size()-1)*3) && (res.get(res.size()-1)*2)>0 && (res.get(res.size()-1)*3)>0) + list.add(res.get(res.size()-1)*3); + if(!list.contains(res.get(res.size()-1)*5) && (res.get(res.size()-1)*2)>0 && (res.get(res.size()-1)*3)>0 && (res.get(res.size()-1)*5)>0) + list.add(res.get(res.size()-1)*5); + Collections.sort(list); + res.add(list.get(0)); + list.remove(0); + } + return res.get(res.size()-1); + } + /* + * �ж�һ�����Ƿ��dz�ª����ֻ��2,3����5�����������ӣ�1Ҳ�dz�ª�� + * e.g. 1,2,3,4,5,6,8,9,10,12,���� + * �ܱ�2,3,5��ȫ���� + * + */ + public boolean isUgly(int num) { + if(num==0) return false; + while(num%2==0){ + num=num/2; + } + while(num%3==0){ + num=num/3; + } + while(num%5==0){ + num=num/5; + } + if(num==1) return true; + else return false; + } + /* + * ���n����ª�� + */ + public int nthUglyNumber(int n) { + int count = 0; + int i=1; + while(count!=n){ + if(isUgly(i)){ + count++; + } + i++; + } + return i-1; + } + +} diff --git a/LiangJianhua/task8/UniqueBinarySearchTrees.java b/LiangJianhua/task8/UniqueBinarySearchTrees.java new file mode 100644 index 0000000..b0fdcc0 --- /dev/null +++ b/LiangJianhua/task8/UniqueBinarySearchTrees.java @@ -0,0 +1,51 @@ +package com.josh.task8; + +import org.junit.Test; + +public class UniqueBinarySearchTrees { + @Test + public void test(){ + System.out.println(numTrees2(3)); + } + //���������ⷨ + public int numTrees(int n) { + long[] c = new long[n+1]; + c[0] = 1; + for(int i=1;i0){//������ +// if(x==0 && y==0) visit[0][0]--; +// grid[x][y+1]=1; +// visit[x][y+1]--; +// y++; +// }else if(x+10){//������ +// if(x==0 && y==0) visit[0][0]--; +// grid[x+1][y]=1; +// visit[x+1][y]--; +// x++; +// }else{//���¶��߲�ͨ�����������1 ���߲����ˣ�������һ����2 �����յ��ˣ�Ҳ���˵���һ�� +// if(visit[0][0]==0) break; +// if(x==m-1 && y==n-1){//�����յ㡢������һ�� +// count++; +// visit[x][y]=1; +//// if(count==2){ +//// System.err.println("ee"); +//// }//����ѭ�� +// } +// grid[preX][preY]=0;//ǰһλֵ�ɷ��� +// preX=x;preY=y; +// grid[preX][preY]=-1;//��ǰһλ��������Ϊ-1 +// if(y>=1 && grid[x][y-1]==1){//���˵���һ��λ�� +// y=y-1; +// }else if(x>=1 && grid[x-1][y]==1){ +// x=x-1; +// }else { +// //break; +// } +// } +// } +// return count; +// } +} diff --git a/LuoSonglei/README.md b/LuoSonglei/README.md index 4d5dbf3..9300103 100644 --- a/LuoSonglei/README.md +++ b/LuoSonglei/README.md @@ -12,4 +12,4 @@ Each solution file will cover the source URI, basic solution and if possible som #Assistant resources -------------------- -There is a test.c file which is often used to demonstrate some grammar features or check some output and the like; the utils.\* files are used to produce random array, sorting methods and array printing functions. +There is a test.c file which is often used to demonstrate some grammar features or check some output and the like; the utils.\* files are used to produce random array, sorting methods and array printing functions. At last there is also a file named reminder used to record some memos and urls for later use. diff --git a/LuoSonglei/reminder b/LuoSonglei/reminder index 8fb76db..243d4f9 100644 --- a/LuoSonglei/reminder +++ b/LuoSonglei/reminder @@ -1,6 +1,44 @@ +Algorithms should be re-checked: https://leetcode.com/problems/median-of-two-sorted-arrays/ https://leetcode.com/problems/largest-rectangle-in-histogram/ https://leetcode.com/problems/n-queens/ https://leetcode.com/problems/word-ladder/ https://leetcode.com/problems/word-ladder-ii/ +https://leetcode.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal/ - there is an awesome solution using hash; +https://leetcode.com/problems/best-time-to-buy-and-sell-stock-iv/ +https://leetcode.com/problems/single-number-ii/ +http://www.geeksforgeeks.org/swap-two-numbers-without-using-temporary-variable/ +https://leetcode.com/discuss/56982/o-sqrt-n-in-ruby-c-c +https://leetcode.com/problems/maximal-square/ +http://www.geeksforgeeks.org/longest-monotonically-increasing-subsequence-size-n-log-n/ +https://leetcode.com/problems/decode-ways/ +https://leetcode.com/problems/word-break-ii/ +https://leetcode.com/problems/create-maximum-number/ +https://leetcode.com/problems/substring-with-concatenation-of-all-words/ +https://leetcode.com/problems/missing-number/ +https://leetcode.com/problems/missing-number/ +https://leetcode.com/problems/add-binary/ +https://leetcode.com/problems/count-primes/ +https://leetcode.com/problems/basic-calculator/ +https://leetcode.com/problems/bulb-switcher/ +https://leetcode.com/problems/fraction-to-recurring-decimal/ +https://leetcode.com/problems/add-and-search-word-data-structure-design/ +https://leetcode.com/problems/clone-graph/ +https://leetcode.com/problems/course-schedule-ii/ +https://leetcode.com/problems/minimum-height-trees/ +https://leetcode.com/problems/copy-list-with-random-pointer/ +https://leetcode.com/problems/anagrams/ +https://leetcode.com/problems/peeking-iterator/ +https://leetcode.com/problems/wiggle-sort-ii/ +https://leetcode.com/problems/range-sum-query-mutable/ +https://leetcode.com/problems/palindrome-pairs/ +https://leetcode.com/problems/basic-calculator-ii/ +https://leetcode.com/problems/maximum-gap/ +https://leetcode.com/problems/the-skyline-problem/ +https://leetcode.com/problems/longest-consecutive-sequence/?sort=votes +https://leetcode.com/problems/single-number-ii/ +https://leetcode.com/problems/lru-cache/ +2016年 02月 07日 星期日 23:05:46 CST +ToDo: +Always be clear on your target - choose the right path before making the final decisions - sophisticated company with specific technical major area. diff --git a/LuoSonglei/test.c b/LuoSonglei/test.c index 5f2e3c5..5cfbbcc 100644 --- a/LuoSonglei/test.c +++ b/LuoSonglei/test.c @@ -2,7 +2,7 @@ Author: LHearen E-mail: LHearen@126.com Time : 2015-12-04 08:23 -Description: +Description: Used to assist others for testing; Source: *******************************************/ //this file is used to test some C features; @@ -57,8 +57,15 @@ void main() /*sort(numbers, SIZE);*/ /*printArray(numbers, SIZE);*/ /*checkAscending(numbers, SIZE);*/ - char s[80]; - sprintf(s, "%d->%d", 2, 3); - printf("length: %d\n",strlen(s)); - + /*char s[80];*/ + /*sprintf(s, "%d->%d", 2, 3);*/ + /*printf("length: %d\n",strlen(s));*/ + int a = 1; + for(int i = 0; i <= 32; i++) + { + printf("%d,", a); + a *= 2; + if(i % 10 == 0) + printf("\n"); + } } diff --git a/LuoSonglei/test.c~ b/LuoSonglei/test.c~ new file mode 100644 index 0000000..5f2e3c5 --- /dev/null +++ b/LuoSonglei/test.c~ @@ -0,0 +1,64 @@ +/******************************************* +Author: LHearen +E-mail: LHearen@126.com +Time : 2015-12-04 08:23 +Description: +Source: +*******************************************/ +//this file is used to test some C features; +#include"utils.h" +void sort(int *nums, int numsSize) +{ + int m = 1; + int tmp = 0; + int v = 0; + int closestSum = nums[0] + nums[1] + nums[2]; + for(;m < numsSize; m = 3*m + 1); + for(; m > 0; m /= 3) + for(int i = m; i < numsSize; i++) + { + int j = i; + v = nums[i]; + while(j >= m && v < nums[j - m]) + { + tmp = nums[j]; + nums[j] = nums[j-m]; + nums[j-m] = tmp; + j -= m; + } + nums[j] = v; + } +} +void sort1(int *nums, int numsSize) +{ + int h = 1; + for(; h <= numsSize/9; h = 3 * h + 1); + for(; h > 0; h /= 3) + for(int i = h; i < numsSize; i++) + { + int tmp = nums[i]; + int j = i; + while(j >= h && tmp < nums[j - h])//This condition is quite critical; + { + nums[j] = nums[j - h]; + j -= h; + } + nums[j] = tmp; + } + +} +void main() +{ + /*int numbers[SIZE];*/ + /*randomIntArray(numbers, SIZE, 0, MAX);*/ + /*printArray(numbers, SIZE);*/ + /*checkAscending(numbers, SIZE);*/ + /*printf("After sorting:\n***********************\n");*/ + /*sort(numbers, SIZE);*/ + /*printArray(numbers, SIZE);*/ + /*checkAscending(numbers, SIZE);*/ + char s[80]; + sprintf(s, "%d->%d", 2, 3); + printf("length: %d\n",strlen(s)); + +} diff --git a/LuoSonglei/week-6/ConstructBTFromPreorderandInorder.c b/LuoSonglei/week-6/ConstructBTFromPreorderandInorder.c index af03add..caf1175 100644 --- a/LuoSonglei/week-6/ConstructBTFromPreorderandInorder.c +++ b/LuoSonglei/week-6/ConstructBTFromPreorderandInorder.c @@ -13,55 +13,49 @@ struct TreeNode struct TreeNode* left; struct TreeNode* right; }; -#define FOO - struct TreeNode* build(int* preorder, int pBegin, int pEnd, int* inorder, int iBegin, int iEnd) { - #ifdef FOO - printf("pBegin: %d\tpEnd: %d\tiBegin: %d\tiEnd: %d\n", pBegin, pEnd, iBegin, iEnd); - #endif if(pBegin > pEnd) return NULL; if(pBegin == pEnd) { struct TreeNode* last = (struct TreeNode*)malloc(sizeof(struct TreeNode)); + last->left = NULL, last->right = NULL; last->val = preorder[pBegin]; return last; } struct TreeNode* root = (struct TreeNode*)malloc(sizeof(struct TreeNode)); + root->left = NULL, root->right = NULL; int mid = iBegin; for(; mid <= iEnd; mid++) if(inorder[mid] == preorder[pBegin]) break; int left = mid - iBegin; - #ifdef FOO - printf("\n\n**********root value: %d\n", inorder[mid]); - printf("left part\n"); - printf("preorder\n"); - for(int i = pBegin+1; i<=pBegin+left; i++) - printf("%d\t", preorder[i]); - printf("\ninorder\n"); - for(int i = iBegin; i<=mid-1; i++) - printf("%d\t", inorder[i]); - printf("\nright part***************\n"); - printf("preorder\n"); - for(int i = pBegin+left+1; i<=pEnd; i++) - printf("%d\t", preorder[i]); - printf("\ninorder\n"); - for(int i = mid+1; i<=iEnd; i++) - printf("%d\t", inorder[i]); - printf("\nend of root: %d****************\n\n\n", inorder[mid]); - #endif root->val = preorder[pBegin]; root->left = build(preorder, pBegin+1, pBegin+left, inorder, iBegin, mid-1); root->right = build(preorder, pBegin+left+1, pEnd, inorder, mid+1, iEnd); return root; } -//Run through encountered test cases but just Runtime Error! -struct TreeNode* buildTree(int* preorder, int pSize, int* inorder, int iSize) +//AC - 20ms; +//Initialization part should be handled carefully otherwise weird error might occur; +struct TreeNode* buildTree0(int* preorder, int pSize, int* inorder, int iSize) { if(pSize == 0) return NULL; return build(preorder, 0, pSize-1, inorder, 0, iSize-1); } + +//AC - 16ms; +struct TreeNode* buildTree1(int* preorder, int pSize, int* inorder, int iSize) +{ + if(pSize == 0) + return NULL; + struct TreeNode *root = ( struct TreeNode* )malloc(sizeof( struct TreeNode )); + root->val = *preorder; + int i = 0; + while(inorder[i] != *preorder) i++; + root->left = buildTree(preorder+1, i, inorder, i); + root->right = buildTree(preorder+i+1, pSize-i-1, inorder+i+1, iSize-i-1); + return root; +} diff --git a/LuoSonglei/week-6/ConvertSortedList2BST.c b/LuoSonglei/week-6/ConvertSortedList2BST.c index 814d8cf..7066a08 100644 --- a/LuoSonglei/week-6/ConvertSortedList2BST.c +++ b/LuoSonglei/week-6/ConvertSortedList2BST.c @@ -19,15 +19,15 @@ struct TreeNode struct TreeNode* right; }; -//Currently the tested cases are all passed but -//the Runtime Error just came out from nowhere; -struct TreeNode* sortedListToBST(struct ListNode* head) +//AC - 12ms; +struct TreeNode* sortedListToBST0(struct ListNode* head) { if(head == NULL) return NULL; if(head->next == NULL) { struct TreeNode *t = (struct TreeNode*)malloc(sizeof(struct TreeNode)); + t->right = t->left = NULL; t->val = head->val; return t; } @@ -40,28 +40,36 @@ struct TreeNode* sortedListToBST(struct ListNode* head) } struct ListNode *left=head, *right=slow->next; slow->next = NULL; - #ifdef FOO - struct ListNode *p = left, *q = right; - printf("left part: \t"); - while(p != NULL) - { - printf("%d\t", p->val); - p = p->next; - - } - printf("\n"); - printf("right part: \t"); - while(q != NULL) - { - printf("%d\t", q->val); - q = q->next; - } - printf("\n"); - //printf("left: %d\tcenter: %d\tright: %d\n", left.next->val, right.next->val, right.next->next->val); - #endif struct TreeNode* root = (struct TreeNode*)malloc(sizeof(struct TreeNode)); root->val = right->val; root->left = sortedListToBST(left); root->right = sortedListToBST(right->next); return root; } + +//AC - 8ms; +struct TreeNode* sortedListToBST1(struct ListNode* head) +{ + if(head == NULL) + return NULL; + if(head->next == NULL) + { + struct TreeNode *t = (struct TreeNode*)malloc(sizeof(struct TreeNode)); + t->right = t->left = NULL; + t->val = head->val; + return t; + } + struct ListNode* slow = head; + struct ListNode* fast = head->next->next; + while(fast && fast->next) + { + slow = slow->next; + fast = fast->next->next; + } + struct TreeNode* root = (struct TreeNode*)malloc(sizeof(struct TreeNode)); + root->val = slow->next->val; + root->right = sortedListToBST(slow->next->next); + slow->next = NULL; + root->left = sortedListToBST(head); + return root; +} diff --git a/LuoSonglei/week-6/CountSmallerNumbersAfterSelf-20ms.c b/LuoSonglei/week-6/CountSmallerNumbersAfterSelf-20ms.c new file mode 100644 index 0000000..753c88a --- /dev/null +++ b/LuoSonglei/week-6/CountSmallerNumbersAfterSelf-20ms.c @@ -0,0 +1,66 @@ +/******************************************* +Author : LHearen +E-mail : LHearen@126.com +Time : 2016-01-28 16:05 +Description : +Source : https://leetcode.com/problems/count-of-smaller-numbers-after-self/ +*******************************************/ +#include +struct MyTreeNode +{ + int val, lessCount, count; + struct MyTreeNode *left, *right; +}; +typedef struct MyTreeNode TreeNode; + +TreeNode* makeTreeNode(int val) +{ + TreeNode *node = (TreeNode*)malloc(sizeof(TreeNode)); + node->val = val; + node->lessCount = 0; + node->count = 1; + node->left = node->right = NULL; + return node; +} + +void insert(TreeNode* root, int val, int *lessCount) +{ + int curVal = root->val; + if(val < curVal) + { + root->lessCount++; + if(NULL == root->left) + root->left = makeTreeNode(val); + else + insert(root->left, val, lessCount); + } + else if(val > curVal) + { + *lessCount += root->lessCount + root->count; + if(NULL == root->right) + root->right = makeTreeNode(val); + else + insert(root->right, val, lessCount); + } + else + { + *lessCount += root->lessCount; + root->count++; + return ; + } +} + +//AC - 20ms; +int* countSmaller(int* nums, int size, int* returnSize) +{ + *returnSize = size; + if(size == 0) + return NULL; + int *count = (int*)malloc(sizeof(int)*size); + memset(count, 0, sizeof(int)*size); + TreeNode *root = makeTreeNode(nums[size-1]); + for(int i = size-2; i > -1; i--) + insert(root, nums[i], count+i); + return count; +} + diff --git a/LuoSonglei/week-6/CountSmallerNumbersAfterSelf-24ms.c b/LuoSonglei/week-6/CountSmallerNumbersAfterSelf-24ms.c new file mode 100644 index 0000000..251a66b --- /dev/null +++ b/LuoSonglei/week-6/CountSmallerNumbersAfterSelf-24ms.c @@ -0,0 +1,61 @@ +/******************************************* +Author : LHearen +E-mail : LHearen@126.com +Time : 2016-01-28 16:05 +Description : +Source : https://leetcode.com/problems/count-of-smaller-numbers-after-self/ +*******************************************/ +#include + +struct MyTreeNode +{ + int val, lessCount; + struct MyTreeNode *left, *right; +}; + +typedef struct MyTreeNode TreeNode; + +TreeNode* makeTreeNode(int val) +{ + TreeNode *node = (TreeNode*)malloc(sizeof(TreeNode)); + node->val = val; + node->lessCount = 0; + node->left = node->right = NULL; + return node; +} + +void insert(TreeNode* root, int val, int *lessCount) +{ + if(val < root->val) + { + root->lessCount++; + if(NULL == root->left) + root->left = makeTreeNode(val); + else + insert(root->left, val, lessCount); + } + else + { + *lessCount += root->lessCount; + if(val > root->val) + (*lessCount)++; + if(NULL == root->right) + root->right = makeTreeNode(val); + else + insert(root->right, val, lessCount); + } +} + +//AC - 24ms; +int* countSmaller(int* nums, int size, int* returnSize) +{ + *returnSize = size; + if(size == 0) + return NULL; + int *count = (int*)malloc(sizeof(int)*size); + memset(count, 0, sizeof(int)*size); + TreeNode *root = makeTreeNode(nums[size-1]); + for(int i = size-2; i > -1; i--) + insert(root, nums[i], count+i); + return count; +} diff --git a/LuoSonglei/week-6/CountSmallerNumbersAfterSelf.c b/LuoSonglei/week-6/CountSmallerNumbersAfterSelf.c deleted file mode 100644 index 2d29a09..0000000 --- a/LuoSonglei/week-6/CountSmallerNumbersAfterSelf.c +++ /dev/null @@ -1,32 +0,0 @@ -/******************************************* -Author : LHearen -E-mail : LHearen@126.com -Time : 2016-01-11 08:54 -Description : -Source : https://leetcode.com/problems/count-of-smaller-numbers-after-self/ -*******************************************/ -//Time Limit Exceeded; -int* countSmaller(int* nums, int size, int* returnSize) -{ - int* counts = (int*)malloc(sizeof(int)*size); - *returnSize = size; - for(int i = 0; i < size; i++) - counts[i] = 0; - for(int i = size-2; i > -1; i--) - { - int cur = i; - for(int j = i+1; j < size; j++) - { - if(nums[cur] > nums[j]) - { - counts[cur]++; - if(nums[j] > 0) - { - counts[cur] += counts[j]; - break; - } - } - } - } - return counts; -} diff --git a/LuoSonglei/week-7/BinaryTreePaths.c b/LuoSonglei/week-7/BinaryTreePaths.c new file mode 100644 index 0000000..a7d5c2c --- /dev/null +++ b/LuoSonglei/week-7/BinaryTreePaths.c @@ -0,0 +1,86 @@ +/******************************************* +Author : LHearen +E-mail : LHearen@126.com +Time : 2016-01-14 16:42 +Description : +Source : https://leetcode.com/problems/binary-tree-paths/ +*******************************************/ +#include +#define LEN 1000 +struct TreeNode +{ + int val; + struct TreeNod *left, *right; +}; +char* int2Str(int a) +{ + int minus = 0; + if(a < 0) + { + minus = 1; + a *= -1; + } + int index = 0; + char* s = (char*)malloc(sizeof(char)*32); + char* t = (char*)malloc(sizeof(char)*32); + while(a > 0) + { + t[index++] = a%10+'0'; + a /= 10; + } + int j = 0; + if(minus) + s[j++] = '-'; + for(int i = 0; i < index; i++) + s[j++] = t[index-i-1]; + s[j] = '\0'; + return s; +} +void traverse( struct TreeNode* root, struct TreeNode** stack, int top, char** sArr, int* count ) +{ + if(root->left == NULL && root->right == NULL) + { + int size = top*3+1; + sArr[*count] = (char*)malloc(sizeof(char)*size); + sArr[*count][0] = '\0'; + int index = 0; + int i = 0; + for(; i < top; i++) + { + char* s = int2Str(stack[i]->val); + strcat(sArr[*count], s); + strcat(sArr[*count], "->"); + } + char* s = int2Str(stack[i]->val); + strcat(sArr[*count], s); + (*count)++; + } + else + { + if(root->left != NULL) + { + stack[++top] = root->left; + traverse(root->left, stack, top, sArr, count); + } + if(root->right != NULL) + { + if(root->left) + --top; + stack[++top] = root->right; + traverse(root->right, stack, top, sArr, count); + } + } +} + +//AC - 4ms; +char** binaryTreePaths( struct TreeNode* root, int* returnSize ) +{ + if(root == NULL) + return NULL; + int top = -1; + struct TreeNode **stack = ( struct TreeNode **)malloc(sizeof( struct TreeNode *)*LEN); + stack[++top] = root; + char** ss = (char**)malloc(sizeof(char*)*LEN); + traverse(root, stack, top, ss, returnSize); + return ss; +} diff --git a/LuoSonglei/week-7/BuySellStock.c b/LuoSonglei/week-7/BuySellStock.c new file mode 100644 index 0000000..ef41d62 --- /dev/null +++ b/LuoSonglei/week-7/BuySellStock.c @@ -0,0 +1,23 @@ +/******************************************* +Author : LHearen +E-mail : LHearen@126.com +Time : 2016-01-18 17:17 +Description : +Source : https://leetcode.com/problems/best-time-to-buy-and-sell-stock/ +*******************************************/ +#include +//Time Limit Exceeded; +int maxProfit(int* prices, int size) +{ + int max = INT_MIN; + for(int i = 0; i < size; i++) + { + for(int j = i+1; j < size; j++) + { + int gain = prices[j] - prices[i]; + if(gain > max) + max = gain; + } + } + return max; +} diff --git a/LuoSonglei/week-7/CountofRangeSum.c b/LuoSonglei/week-7/CountofRangeSum.c index 57be82a..2bc3a5d 100644 --- a/LuoSonglei/week-7/CountofRangeSum.c +++ b/LuoSonglei/week-7/CountofRangeSum.c @@ -5,6 +5,7 @@ Time : 2016-01-14 20:42 Description : Source : https://leetcode.com/problems/count-of-range-sum/ *******************************************/ +#include void swap(long*p, long*q) { long t = *p; @@ -32,7 +33,7 @@ void swiftSort(long* arr, int low, int high) swiftSort(arr, l, high); } -int indexOf(long* arr, int size, float a) +int indexOf(long* arr, int size, double a) { int l = 0, r = size-1, m; while(l <= r) @@ -67,9 +68,13 @@ int counter(long* nums, int l, int h, int low, int high) return counter(nums, l, m, low, high) + counter(nums, m+1, h, low, high) + count; } +//AC - 72ms; int countRangeSum(int* nums, int size, int low, int high) { if(size == 0) return 0; - return counter(nums, 0, size-1, low, high); + long *a = (long*)malloc(sizeof(long)*size); + for(int i = 0; i < size; i++) + nums[i] == INT_MIN? (a[i] = -1*INT_MIN) : (a[i] = nums[i]); + return counter(a, 0, size-1, low, high); } diff --git a/LuoSonglei/week-7/CountofRangeSum2.c b/LuoSonglei/week-7/CountofRangeSum2.c new file mode 100644 index 0000000..921f809 --- /dev/null +++ b/LuoSonglei/week-7/CountofRangeSum2.c @@ -0,0 +1,75 @@ +/******************************************* +Author : LHearen +E-mail : LHearen@126.com +Time : 2016-01-29 15:58 +Description : +Source : https://leetcode.com/problems/count-of-range-sum/ +*******************************************/ +int countWhileMergeSort0(long* sums, int begin, int end, int lower, int upper) +{ + if(end-begin <= 1) return 0; + int mid = begin + (end-begin)/2; + int count = countWhileMergeSort(sums, begin, mid, lower, upper)+countWhileMergeSort(sums, mid, end, lower, upper); + int l = mid, h = mid, r = mid; + int size = end - begin; + long* cache = (long*)malloc(sizeof(long)*size); + for(int i = begin, index=0; i < mid;) + { + long newLower = sums[i]+lower; + long newUpper = sums[i]+upper; + while(l= lower && sums[begin] <= upper)? 1 : 0; + int mid = begin + (end-begin)/2; + int count = countWhileMergeSort1(sums, begin, mid, lower, upper) + countWhileMergeSort1(sums, mid+1, end, lower, begin); + int l, h, r; + l = h = r = mid+1; + int size = end-begin+1; + long *cache = (long*)malloc(sizeof(long)*size); + for(int i = begin, index=0; i <= mid; ) + { + long newLower = sums[i]+lower; + long newUpper = sums[i]+upper; + while(l<=end && sums[l]= size-1)//check the current longest distance; + return ++jump; + int max = 0, next = 0; + for(int j = 1; j <= nums[i]; j++) + { + if(j+nums[i+j] > max)//the distance; + { + max = j+nums[i+j]; + next = j; + } + } + i += next; + jump++; + } +} diff --git a/LuoSonglei/week-7/ShortestPalindrome.c b/LuoSonglei/week-7/ShortestPalindrome.c new file mode 100644 index 0000000..ad5499e --- /dev/null +++ b/LuoSonglei/week-7/ShortestPalindrome.c @@ -0,0 +1,40 @@ +/******************************************* +Author : LHearen +E-mail : LHearen@126.com +Time : 2016-01-18 11:09 +Description : +Source : https://leetcode.com/problems/shortest-palindrome/ +*******************************************/ +int findCenter(char*s, int size) +{ + int center = 0; + for(int i = 0; i <= size/2; i++) + { + int l = i, r = i; + while(s[l] == s[r]) + { + l--, r++; + if(l < 0) + break; + } + if(l == -1) + center = i; + } + return center; +} +char* shortestPalindrome(char* s) +{ + int len = strlen(s); + int center = findCenter(s, len); + int size = (len-center)*2; + char* str = (char*)malloc(sizeof(char)*size); + int l = center, r = center; + int index = 0; + for(int i = len-1; i >= center; i--) + str[index++] = s[i]; + for(int i = center+1; i < len; i++) + str[index++] = s[i]; + str[index] = '\0'; + printf("center: %d\tstr: %s\n", center, str); + return str; +} diff --git a/LuoSonglei/week-8/BTLevelOrderTraversal.c b/LuoSonglei/week-8/BTLevelOrderTraversal.c new file mode 100644 index 0000000..1542f62 --- /dev/null +++ b/LuoSonglei/week-8/BTLevelOrderTraversal.c @@ -0,0 +1,49 @@ +/******************************************* +Author : LHearen +E-mail : LHearen@126.com +Time : 2016-01-20 10:03 +Description : +Source : https://leetcode.com/problems/binary-tree-level-order-traversal/ +*******************************************/ +#include +#define LEN 1000 +struct TreeNode +{ + int val; + struct TreeNod *left, *right; +}; +//AC - 4ms; +int** levelOrder( struct TreeNode* root, int** colSizes, int* returnSize ) +{ + if(!root) + return NULL; + struct TreeNode** stack0 = ( struct TreeNode** )malloc(sizeof( struct TreeNode* )*LEN); + struct TreeNode** stack1 = ( struct TreeNode** )malloc(sizeof( struct TreeNode* )*LEN); + struct TreeNode** t; + int top0 = -1; + int top1 = -1; + *colSizes = (int*)malloc(sizeof(int)*LEN); + int** arrs = (int**)malloc(sizeof(int*)*LEN); + stack0[++top0] = root; + *returnSize = 0; + while(top0 > -1) + { + top1 = -1; + (*colSizes)[*returnSize] = top0+1; //the brackets are quite essential here for colSizes; + arrs[*returnSize] = (int*)malloc(sizeof(int)*(top0+1)); + for(int i = 0; i <= top0; i++) + { + arrs[*returnSize][i] = stack0[i]->val; + if(stack0[i]->left) + stack1[++top1] = stack0[i]->left; + if(stack0[i]->right) + stack1[++top1] = stack0[i]->right; + } + (*returnSize)++; + top0 = top1; + t = stack0; + stack0 = stack1; + stack1 = t; + } + return arrs; +} diff --git a/LuoSonglei/week-8/ClimbingStairs.c b/LuoSonglei/week-8/ClimbingStairs.c new file mode 100644 index 0000000..97e1e21 --- /dev/null +++ b/LuoSonglei/week-8/ClimbingStairs.c @@ -0,0 +1,25 @@ +/******************************************* +Author : LHearen +E-mail : LHearen@126.com +Time : 2016-01-19 15:33 +Description : +Source : https://leetcode.com/problems/climbing-stairs/ +*******************************************/ +//Time Limit Exceeded; +int climbStairs0(int n) +{ + if(n <= 1) + return 1; + else + return climbStairs(n-1) + climbStairs(n-2); +} + +//AC - 0ms; +int climbStairs(int n) +{ + int *arr = (int*)malloc(sizeof(int)*(n+1)); + arr[0] = arr[1] = 1; + for(int i = 2; i <= n; i++) + arr[i] = arr[i-1] + arr[i-2]; + return arr[n]; +} diff --git a/LuoSonglei/week-8/CompareVersionNumbers.c b/LuoSonglei/week-8/CompareVersionNumbers.c new file mode 100644 index 0000000..8246ba0 --- /dev/null +++ b/LuoSonglei/week-8/CompareVersionNumbers.c @@ -0,0 +1,48 @@ +/******************************************* +Author : LHearen +E-mail : LHearen@126.com +Time : 2016-01-22 16:53 +Description : +Source : https://leetcode.com/problems/compare-version-numbers/ +*******************************************/ +int compare(int a, int b) +{ + if(a > b) + return 1; + else if(a == b) + return 0; + else + return -1; +} + +//AC - 0ms; +int compareVersion(char* v1, char* v2) +{ + while(*v1 != '\0' || *v2 != '\0') + { + int version1 = 0; + int version2 = 0; + while((*v1 != '.' && *v1 != '\0') || (*v2 != '.' && *v2 != '\0')) + { + if(*v1 != '.' && *v1 != '\0') + { + version1 = 10*version1 + (*v1 - '0'); + v1++; + } + if(*v2 != '.' && *v2 != '\0') + { + version2 = 10*version2 + (*v2 - '0'); + v2++; + } + } + int ret = compare(version1, version2); + if(ret != 0) + return ret; + else if(*v1 == '\0' && *v2 == '\0') + return 0; + if(*v1 == '.') + v1++; + if(*v2 == '.') + v2++; + } +} diff --git a/LuoSonglei/week-8/ContainsDuplicate.c b/LuoSonglei/week-8/ContainsDuplicate.c new file mode 100644 index 0000000..b5e7f17 --- /dev/null +++ b/LuoSonglei/week-8/ContainsDuplicate.c @@ -0,0 +1,70 @@ +/******************************************* +Author : LHearen +E-mail : LHearen@126.com +Time : 2016-01-19 08:55 +Description : +Source : https://leetcode.com/problems/contains-duplicate/ +*******************************************/ +#include +//AC - 1620mc; +bool containsDuplicate0(int* nums, int size) +{ + for(int i = 0; i < size; i++) + for(int j = i+1; j < size; j++) + if(nums[i] == nums[j]) + return true; + return false; +} + +void swap(int* p, int* q) +{ + int t = *p; + *p = *q; + *q = t; +} + +void swiftSort(int* a, int low, int high) +{ + int l = low, h = high; + int v = a[l+(h-l)/2]; + while(l <= h) + { + while(a[l] < v) l++; + while(a[h] > v) h--; + if(l <= h) + { + swap(a+l, a+h); + l++, h--; + } + } + if(h > low) + swiftSort(a, low, h); + if(l < high) + swiftSort(a, l, high); +} + +//AC - 12ms; +bool containsDuplicate1(int* nums, int size) +{ + swiftSort(nums, 0, size-1); + for(int i = 1; i < size; i++) + if(nums[i] == nums[i-1]) + return true; + return false; +} + +//This method can only be used in limited range of +//array elements which should also be positive for indexing; +bool containsDuplicate2(int* nums, int size) +{ + int max = 0; + for(int i = 0; i < size; i++) + if(nums[i] > max) + max = nums[i]; + max++; + int* a = (int*)malloc(sizeof(int)*max); + for(int i = 0; i < size; i++) + if(a[nums[i]]++ > 0) + return true; + return false; +} diff --git a/LuoSonglei/week-8/ContainsDuplicate2.c b/LuoSonglei/week-8/ContainsDuplicate2.c new file mode 100644 index 0000000..4aa3a67 --- /dev/null +++ b/LuoSonglei/week-8/ContainsDuplicate2.c @@ -0,0 +1,69 @@ +/******************************************* +Author : LHearen +E-mail : LHearen@126.com +Time : 2016-01-21 09:02 +Description : +Source : https://leetcode.com/problems/contains-duplicate-ii/ +*******************************************/ +#include +#include +//AC - 1040ms; +bool containsNearbyDuplicate0(int* nums, int size, int k) +{ + for(int i = 0; i < size; i++) + for(int j = i+1; j < i+k+1 && j < size; j++) + if(nums[i] == nums[j]) + return true; + return false; +} + +typedef struct hash_node +{ + int value; + int index; + struct hash_node *next; +} hash_node_t; + + +//AC - 8ms; +bool containsNearbyDuplicate(int* nums, int numsSize, int k) { + hash_node_t **table; + table = calloc(numsSize, sizeof(hash_node_t)); + memset(table, 0, sizeof(hash_node_t) * numsSize ); + int i = 0; + int key = 0; + hash_node_t *node = NULL; + hash_node_t *p = NULL; + bool result = false; + for (i = 0; (i < numsSize && result == false); i++) + { + key = abs(*nums) % numsSize; + node = malloc(sizeof(hash_node_t)); + node->value = *nums; + node->index = i; + node->next = table[key]; + table[key] = node; + p = table[key]->next; + while(p) + { + if ((p->value == *nums) && ((i - p->index) <= k)) + { + result = true; + break; + } + p = p->next; + } + nums++; + } + for (i = 0; i < numsSize; i++) + { + while(table[i]) + { + p = table[i]->next; + free(table[i]); + table[i] = p; + } + } + free(table); + return result; +} diff --git a/LuoSonglei/week-8/ContainsDuplicate3.c b/LuoSonglei/week-8/ContainsDuplicate3.c new file mode 100644 index 0000000..9e91438 --- /dev/null +++ b/LuoSonglei/week-8/ContainsDuplicate3.c @@ -0,0 +1,66 @@ +/******************************************* +Author : LHearen +E-mail : LHearen@126.com +Time : 2016-01-21 09:09 +Description : +Source : https://leetcode.com/problems/contains-duplicate-iii/ +*******************************************/ +#include +#include +//Timi Limit Exceeded; +bool containsNearbyAlmostDuplicate0(int* nums, int size, int k, int t) +{ + for(int i = 0; i < size; i++) + for(int j = i+1; j < i+k+1 && j < size; j++) + { + long d = (long)nums[i]-(long)nums[j]; + if(d <= t && d >= -1*t) + return true; + } + return false; +} + +void swap(int *p, int *q) +{ + int t = *p; + *p = *q; + *q = t; +} + +void sort(int* nums, int* indexes, int low, int high) +{ + int l = low, h = high; + int v = nums[l+(h-l)/2]; + while(l <= h) + { + while(nums[l] < v) l++; + while(nums[h] > v) h--; + if(l <= h) + { + swap(nums+l, nums+h); + swap(indexes+l, indexes+h); + l++, h--; + } + } + if(h > low) + sort(nums, indexes, low, h); + if(l < high) + sort(nums, indexes, l, high); +} + +//AC - 8ms; +bool containsNearbyAlmostDuplicate1(int* nums, int size, int k, int t) +{ + int *indexes = (int*)malloc(sizeof(int)*size); + for(int i = 0; i < size; i++) + indexes[i] = i; + sort(nums, indexes, 0, size-1); + for(int i = 0; i < size; i++) + { + int top = nums[i]+t; + for(int j = i+1; j < size && nums[j] <= top; j++) + if(abs(indexes[i] - indexes[j]) <= k) + return true; + } + return false; +} diff --git a/LuoSonglei/week-8/DistinctSubsequences.c b/LuoSonglei/week-8/DistinctSubsequences.c new file mode 100644 index 0000000..c54a25e --- /dev/null +++ b/LuoSonglei/week-8/DistinctSubsequences.c @@ -0,0 +1,29 @@ +/******************************************* +Author : LHearen +E-mail : LHearen@126.com +Time : 2016-01-24 11:42 +Description : +Source : https://leetcode.com/problems/distinct-subsequences/ +*******************************************/ +//AC - 4ms; +int numDistinct(char* s, char* t) +{ + int sLen = strlen(s), tLen = strlen(t); + int *pre = (int*)malloc(sizeof(int)*(sLen+1)); + int *cur = (int*)malloc(sizeof(int)*(sLen+1)); + for(int i = 0; i <= sLen; i++) + pre[i] = 1; + for(int i = 1; i <= tLen; i++) + { + for(int j = 1; j <= sLen; j++) + { + if(t[i-1] != s[j-1]) + cur[j] = cur[j-1]; + else + cur[j] = cur[j-1]+pre[j-1]; + } + for(int i=0; i <= sLen; i++) + pre[i] = cur[i]; + } + return pre[sLen]; +} diff --git a/LuoSonglei/week-8/ExcelSheetColumnNumber.c b/LuoSonglei/week-8/ExcelSheetColumnNumber.c new file mode 100644 index 0000000..344add5 --- /dev/null +++ b/LuoSonglei/week-8/ExcelSheetColumnNumber.c @@ -0,0 +1,15 @@ +/******************************************* +Author : LHearen +E-mail : LHearen@126.com +Time : 2016-01-19 08:24 +Description : +Source : https://leetcode.com/problems/excel-sheet-column-number/ +*******************************************/ +//AC - 4ms; +int titleToNumber(char* s) +{ + int sum = 0; + while(*s) + sum += 26*sum+(*(s++)-'A'+1); + return sum; +} diff --git a/LuoSonglei/week-8/ExcelSheetColumnTitile.c b/LuoSonglei/week-8/ExcelSheetColumnTitile.c new file mode 100644 index 0000000..4e2cea2 --- /dev/null +++ b/LuoSonglei/week-8/ExcelSheetColumnTitile.c @@ -0,0 +1,25 @@ +/******************************************* +Author : LHearen +E-mail : LHearen@126.com +Time : 2016-01-19 08:45 +Description : +Source : https://leetcode.com/problems/excel-sheet-column-title/ +*******************************************/ +//AC - 0ms; +char* convertToTitle(int n) +{ + char* s = (char*)malloc(sizeof(char)*10); + int index = 0; + while(n) + { + s[index++] = (n-1)%26 + 'A'; + n = (n-1) / 26; + } + for(int i = 0; i < index/2; i++) + { + char t = s[i]; + s[i] = s[index-i-1]; + s[index-i-1] = t; + } + return s; +} diff --git a/LuoSonglei/week-8/FactorialTrailingZeores.c b/LuoSonglei/week-8/FactorialTrailingZeores.c new file mode 100644 index 0000000..eef3fe5 --- /dev/null +++ b/LuoSonglei/week-8/FactorialTrailingZeores.c @@ -0,0 +1,43 @@ +/******************************************* +Author : LHearen +E-mail : LHearen@126.com +Time : 2016-01-20 09:40 +Description : +Source : https://leetcode.com/problems/factorial-trailing-zeroes/ +*******************************************/ +int countFactors(int a, int b) +{ + int count = 0; + while(a) + { + if(a%b == 0) + count++; + a /= b; + } + return count; +} + +//Time Limit Exceeded; +//Wrong Result; +int trailingZeroes0(int n) +{ + int count2 = 0; + int count5 = 0; + for(int i = 1; i <= n; i++) + count2 += countFactors(i, 2); + for(int i = 1; i <= n; i++) + count5 += countFactors(i, 5); + return count2 > count5? count5 : count2; +} + +//AC - 0ms; +int trailingZeroes(int n) +{ + int count = 0; + while(n) + { + count += n/5; + n /= 5; + } + return count; +} diff --git a/LuoSonglei/week-8/HappyNumber.c b/LuoSonglei/week-8/HappyNumber.c new file mode 100644 index 0000000..4bb2b13 --- /dev/null +++ b/LuoSonglei/week-8/HappyNumber.c @@ -0,0 +1,23 @@ +/******************************************* +Author : LHearen +E-mail : LHearen@126.com +Time : 2016-01-19 16:07 +Description : +Source : https://leetcode.com/problems/happy-number/ +*******************************************/ +#include +//AC - 0ms; +//https://www.kidscodecs.com/happy-numbers/ +int isHappy(int n) +{ + int sum = 0; + for(; n; n/=10) + sum += (n%10)*(n%10); + if(sum == 1) + return true; + int arr[] = {4, 16, 37, 58, 89, 145, 42, 20}; + for(int i = 0; i < sizeof(arr)/sizeof(int); i++) + if(sum == arr[i]) + return false; + return isHappy(sum); +} diff --git a/LuoSonglei/week-8/HouseRobber.c b/LuoSonglei/week-8/HouseRobber.c new file mode 100644 index 0000000..8415045 --- /dev/null +++ b/LuoSonglei/week-8/HouseRobber.c @@ -0,0 +1,29 @@ +/******************************************* +Author : LHearen +E-mail : LHearen@126.com +Time : 2016-01-22 16:47 +Description : +Source : https://leetcode.com/problems/house-robber/ +*******************************************/ +//AC - 0ms; +int rob(int* nums, int size) +{ + if(size == 0) + return 0; + if(size == 1) + return nums[0]; + int *arr = (int*)malloc(sizeof(int)*size); + arr[0] = nums[0]; + if(nums[1] > nums[0]) + arr[1] = nums[1]; + else + arr[1] = nums[0]; + for(int i = 2; i < size; i++) + { + int count = arr[i-2]+nums[i]; + if(count < arr[i-1]) + count = arr[i-1]; + arr[i] = count; + } + return arr[size-1]; +} diff --git a/LuoSonglei/week-8/IntersectionOfTwoLinkedLists.c b/LuoSonglei/week-8/IntersectionOfTwoLinkedLists.c new file mode 100644 index 0000000..15b3db3 --- /dev/null +++ b/LuoSonglei/week-8/IntersectionOfTwoLinkedLists.c @@ -0,0 +1,66 @@ +/******************************************* +Author : LHearen +E-mail : LHearen@126.com +Time : 2016-01-20 14:14 +Description : +Source : https://leetcode.com/problems/intersection-of-two-linked-lists/ +*******************************************/ +#include +struct ListNode +{ + int val; + struct ListNode *next; +}; +//Time Limit Exceeded; +struct ListNode* getIntersectionNode0( struct ListNode* headA, struct ListNode* headB ) +{ + struct ListNode *t = headB; + while(headA) + { + t = headB; + while(t) + { + if(t==headA) + return t; + t = t->next; + } + headA = headA->next; + } + return NULL; +} + +//AC - 32ms; +struct ListNode* getIntersectionNode( struct ListNode* headA, struct ListNode* headB ) +{ + int lenA = 0; + int lenB = 0; + struct ListNode *t0 = headA; + struct ListNode *t1 = headB; + while(t0) + lenA++, t0 = t0->next; + while(t1) + lenB++, t1 = t1->next; + int difference = 0; + if(lenA > lenB) + { + difference = lenA - lenB; + t0 = headA; + t1 = headB; + } + else + { + difference = lenB - lenA; + t0 = headB; + t1 = headA; + } + while(difference) + t0 = t0->next, difference--; + while(t0) + { + if(t0 == t1) + return t0; + t0 = t0->next; + t1 = t1->next; + } + return NULL; +} diff --git a/LuoSonglei/week-8/InvertBinaryTree.c b/LuoSonglei/week-8/InvertBinaryTree.c new file mode 100644 index 0000000..73bc675 --- /dev/null +++ b/LuoSonglei/week-8/InvertBinaryTree.c @@ -0,0 +1,25 @@ +/******************************************* +Author : LHearen +E-mail : LHearen@126.com +Time : 2016-01-19 08:12 +Description : +Source : https://leetcode.com/problems/invert-binary-tree/ +*******************************************/ +struct TreeNode +{ + int val; + struct TreeNod *left, *right; +}; +//AC - 0ms; +struct TreeNode* invertTree( struct TreeNode* root ) +{ + if(root) + { + struct TreeNode *t = root->left; + root->left = root->right; + root->right = t; + invertTree(root->left); + invertTree(root->right); + } + return root; +} diff --git a/LuoSonglei/week-8/LengthOfLastWord.c b/LuoSonglei/week-8/LengthOfLastWord.c new file mode 100644 index 0000000..edb137b --- /dev/null +++ b/LuoSonglei/week-8/LengthOfLastWord.c @@ -0,0 +1,34 @@ +/******************************************* +Author : LHearen +E-mail : LHearen@126.com +Time : 2016-01-21 09:32 +Description : +Source : https://leetcode.com/problems/length-of-last-word/ +*******************************************/ +#include +//AC - 0ms; +int lengthOfLastWord(char* s) +{ + int len = 0; + int in = false; + int pre = 0; + while(*s) + { + if(isalpha(*s)) + { + len++; + in = true; + } + else + { + if(in) + pre = len; + in = false; + len = 0; + } + s++; + } + if(isalpha(*(s-1))) + return len; + return pre; +} diff --git a/LuoSonglei/week-8/LowestCommonAncestorBT.c b/LuoSonglei/week-8/LowestCommonAncestorBT.c new file mode 100644 index 0000000..e8fdacc --- /dev/null +++ b/LuoSonglei/week-8/LowestCommonAncestorBT.c @@ -0,0 +1,37 @@ +/******************************************* +Author : LHearen +E-mail : LHearen@126.com +Time : 2016-01-19 14:32 +Description : +Source : https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-tree/ +*******************************************/ +struct TreeNode +{ + int val; + struct TreeNod *left, *right; +}; + +//AC - 16ms; +struct TreeNode* lowestCommonAncestor0( struct TreeNode* root, struct TreeNode *p, struct TreeNode* q ) +{ + if(!root || root == p || root == q) return root; + struct TreeNode *left = lowestCommonAncestor(root->left, p, q); + struct TreeNode *right = lowestCommonAncestor(root->right, p, q); + if(left&&right) return root; + if(!left) return right; + if(!right) return left; +} + +//AC - 12ms; +struct TreeNode* lowestCommonAncestor1( struct TreeNode* root, struct TreeNode *p, struct TreeNode* q ) +{ + if(!p) return q; + if(!q) return p; + if(!root || root == p || root == q) return root; + struct TreeNode *left = lowestCommonAncestor(root->left, p, q); + struct TreeNode *right = lowestCommonAncestor(root->right, p, q); + if(left&&right) return root; + if(!left) return right; + if(!right) return left; +} + diff --git a/LuoSonglei/week-8/LowestCommonancestorBST.c b/LuoSonglei/week-8/LowestCommonancestorBST.c new file mode 100644 index 0000000..48bb28e --- /dev/null +++ b/LuoSonglei/week-8/LowestCommonancestorBST.c @@ -0,0 +1,57 @@ +/******************************************* +Author : LHearen +E-mail : LHearen@126.com +Time : 2016-01-19 14:10 +Description : +Source : https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-search-tree/ +*******************************************/ +#include +struct TreeNode +{ + int val; + struct TreeNod *left, *right; +}; + +//AC - 20ms; +struct TreeNode* lowestCommonAncestor( struct TreeNode* root, struct TreeNode *p, struct TreeNode* q ) +{ + if(root == NULL || root == p || root == q || + (root->val > p->val && root->val < q->val) || + (root->val < p->val && root->val > q->val)) return root; + if(root->val > p->val && root->val > q->val) + return lowestCommonAncestor(root->left, p, q); + else + return lowestCommonAncestor(root->right, p, q); +} + +//AC - 24ms; +struct TreeNode* lowestCommonAncestor1( struct TreeNode* root, struct TreeNode* p, struct TreeNode* q ) +{ + if(root == NULL || root == p || root == q) + return root; + int min = p->val > q->val? q->val : p->val; + int max = p->val < q->val? q->val : p->val; + while(1) + { + if(root->val > max) + root = root->left; + else if(root->val < min) + root = root->right; + else + return root; + } +} + +//AC - 24ms; +struct TreeNode* lowestCommonAncestor2( struct TreeNode* root, struct TreeNode *p, struct TreeNode* q ) +{ + if(!p) return q; + if(!q) return p; + if(!root || root == p || root == q) return root; + struct TreeNode *left = lowestCommonAncestor(root->left, p, q); + struct TreeNode *right = lowestCommonAncestor(root->right, p, q); + if(left&&right) return root; + if(!left) return right; + if(!right) return left; +} + diff --git a/LuoSonglei/week-8/MaxDepthBinaryTree.c b/LuoSonglei/week-8/MaxDepthBinaryTree.c new file mode 100644 index 0000000..30973e1 --- /dev/null +++ b/LuoSonglei/week-8/MaxDepthBinaryTree.c @@ -0,0 +1,22 @@ +/******************************************* +Author : LHearen +E-mail : LHearen@126.com +Time : 2016-01-19 08:06 +Description : +Source : https://leetcode.com/problems/maximum-depth-of-binary-tree/ +*******************************************/ +#include +struct TreeNode +{ + int val; + struct TreeNod *left, *right; +}; +//AC - 4ms; +int maxDepth( struct TreeNode * root ) +{ + if(root == NULL) + return 0; + int lDepth = maxDepth(root->left); + int rDepth = maxDepth(root->right); + return 1 + (lDepth > rDepth ? lDepth : rDepth); +} diff --git a/LuoSonglei/week-8/MergeSortedArray.c b/LuoSonglei/week-8/MergeSortedArray.c new file mode 100644 index 0000000..72808e9 --- /dev/null +++ b/LuoSonglei/week-8/MergeSortedArray.c @@ -0,0 +1,22 @@ +/******************************************* +Author : LHearen +E-mail : LHearen@126.com +Time : 2016-01-20 13:57 +Description : +Source : https://leetcode.com/problems/merge-sorted-array/ +*******************************************/ +//AC - 0ms; +void merge(int* nums1, int m, int* nums2, int n) +{ + int index = m+n-1; + int i = m-1, j = n-1; + while(i > -1 && j > -1) + { + if(nums1[i] > nums2[j]) nums1[index--] = nums1[i--]; + else nums1[index--] = nums2[j--]; + } + while(i > -1) + nums1[index--] = nums1[i--]; + while(j > -1) + nums1[index--] = nums2[j--]; +} diff --git a/LuoSonglei/week-8/MergeTwoSortedLists.c b/LuoSonglei/week-8/MergeTwoSortedLists.c new file mode 100644 index 0000000..0e1076a --- /dev/null +++ b/LuoSonglei/week-8/MergeTwoSortedLists.c @@ -0,0 +1,37 @@ +/******************************************* +Author : LHearen +E-mail : LHearen@126.com +Time : 2016-01-19 16:38 +Description : +Source : https://leetcode.com/problems/merge-two-sorted-lists/ +*******************************************/ +struct ListNode +{ + int val; + struct ListNode *next; +}; +//AC - 4ms; +struct ListNode* mergeTwoLists( struct ListNode* l1, struct ListNode* l2 ) +{ + struct ListNode *t = ( struct ListNode* )malloc(sizeof( struct ListNode )); + struct ListNode *t0 = t; + while(l1 && l2) + { + if(l1->val > l2->val) + { + t0->next = l2; + l2 = l2->next; + } + else + { + t0->next = l1; + l1 = l1->next; + } + t0 = t0->next; + } + if(l1) + t0->next = l1; + if(l2) + t0->next = l2; + return t->next; +} diff --git a/LuoSonglei/week-8/Number1Bits.c b/LuoSonglei/week-8/Number1Bits.c new file mode 100644 index 0000000..852c564 --- /dev/null +++ b/LuoSonglei/week-8/Number1Bits.c @@ -0,0 +1,19 @@ +/******************************************* +Author : LHearen +E-mail : LHearen@126.com +Time : 2016-01-19 11:14 +Description : +Source : https://leetcode.com/problems/number-of-1-bits/ +*******************************************/ +//AC - 4ms; +int hammingWeight(uint32_t n) +{ + int count = 0; + while(n) + { + if(n & 1) + count++; + n >>= 1; + } + return count; +} diff --git a/LuoSonglei/week-8/OddEvenLinkedList.c b/LuoSonglei/week-8/OddEvenLinkedList.c new file mode 100644 index 0000000..ae71de7 --- /dev/null +++ b/LuoSonglei/week-8/OddEvenLinkedList.c @@ -0,0 +1,31 @@ +/******************************************* +Author : LHearen +E-mail : LHearen@126.com +Time : 2016-01-19 10:54 +Description : +Source : https://leetcode.com/problems/odd-even-linked-list/ +*******************************************/ +#include +struct ListNode +{ + int val; + struct ListNode *next; +}; +//AC - 4ms; +struct ListNode* oddEvenList( struct ListNode* head ) +{ + if(head == NULL || head->next == NULL) + return head; + struct ListNode *odd = head; + struct ListNode *even = head->next; + struct ListNode *eHead = even; + while(odd && even && even->next) + { + odd->next = even->next; + odd = odd->next; + even->next = odd->next; + even = even->next; + } + odd->next = eHead; + return head; +} diff --git a/LuoSonglei/week-8/PalindromeNumber.c b/LuoSonglei/week-8/PalindromeNumber.c new file mode 100644 index 0000000..022769d --- /dev/null +++ b/LuoSonglei/week-8/PalindromeNumber.c @@ -0,0 +1,28 @@ +/******************************************* +Author : LHearen +E-mail : LHearen@126.com +Time : 2016-01-20 11:32 +Description : +Source : https://leetcode.com/problems/palindrome-number/ +*******************************************/ +#include +//AC - 56ms; +bool isPalindrome(int n) +{ + if(n < 0) + return false; + if(n < 2) + return true; + if(n%10 == 0) + return false; + int t = 0; + while(t < n) + { + t = t*10+n%10; + n /= 10; + } + if(n == t) + return true; + else + return t/10 == n; +} diff --git a/LuoSonglei/week-8/PascalTriangle.c b/LuoSonglei/week-8/PascalTriangle.c new file mode 100644 index 0000000..d70cf32 --- /dev/null +++ b/LuoSonglei/week-8/PascalTriangle.c @@ -0,0 +1,29 @@ +/******************************************* +Author : LHearen +E-mail : LHearen@126.com +Time : 2016-01-20 10:33 +Description : +Source : https://leetcode.com/problems/pascals-triangle/ +*******************************************/ +#include +//AC - 0ms; +int** generate(int rSize, int** colSizes, int* returnSize) +{ + if(rSize == 0) + return NULL; + *returnSize = rSize; + *colSizes = (int*)malloc(sizeof(int)*rSize); + int** arrs = (int**)malloc(sizeof(int*)*rSize); + for(int i = 0; i < rSize; i++) + { + (*colSizes)[i] = i+1; + arrs[i] = (int*)malloc(sizeof(int)*(i+1)); + for(int j = 0; j < i+1; j++) + arrs[i][j] = 1; + } + for(int i = 2; i < rSize; i++) + for(int j = 1; j < (*colSizes)[i]; j++) + if(j < (*colSizes)[i-1]) + arrs[i][j] = arrs[i-1][j-1]+arrs[i-1][j]; + return arrs; +} diff --git a/LuoSonglei/week-8/PascalTriangle2.c b/LuoSonglei/week-8/PascalTriangle2.c new file mode 100644 index 0000000..659cff1 --- /dev/null +++ b/LuoSonglei/week-8/PascalTriangle2.c @@ -0,0 +1,52 @@ +/******************************************* +Author : LHearen +E-mail : LHearen@126.com +Time : 2016-01-20 11:09 +Description : +Source : https://leetcode.com/problems/pascals-triangle-ii/ +*******************************************/ +#include +//AC - 0ms; +int* getRow(int rSize, int* returnSize) +{ + rSize++; + if(rSize == 0) + return NULL; + *returnSize = rSize; + int *colSizes = (int*)malloc(sizeof(int)*rSize); + int** arrs = (int**)malloc(sizeof(int*)*rSize); + for(int i = 0; i < rSize; i++) + { + colSizes[i] = i+1; + arrs[i] = (int*)malloc(sizeof(int)*(i+1)); + for(int j = 0; j < i+1; j++) + arrs[i][j] = 1; + } + for(int i = 2; i < rSize; i++) + for(int j = 1; j < colSizes[i]; j++) + if(j < colSizes[i-1]) + arrs[i][j] = arrs[i-1][j-1]+arrs[i-1][j]; + return arrs[rSize-1]; +} + +//AC - 0ms; +int* getRow1(int index, int* returnSize) +{ + int size = index+1; + *returnSize = size; + int* arr0 = (int*)malloc(sizeof(int)*size); + int* arr1 = (int*)malloc(sizeof(int)*size); + int *t; + for(int i = 0; i < size; i++) + arr0[i] = arr1[i] = 1; + for(int i = 2; i < size; i++) + { + for(int j = 1; j <= i; j++) + if(j < i) + arr0[j] = arr1[j] + arr1[j-1]; + t = arr0; + arr0 = arr1; + arr1 = t; + } + return arr1; +} diff --git a/LuoSonglei/week-8/PathSum.c b/LuoSonglei/week-8/PathSum.c new file mode 100644 index 0000000..a4812f0 --- /dev/null +++ b/LuoSonglei/week-8/PathSum.c @@ -0,0 +1,79 @@ +/******************************************* +Author : LHearen +E-mail : LHearen@126.com +Time : 2016-01-21 08:32 +Description : +Source : https://leetcode.com/problems/path-sum/ +*******************************************/ +#include +#include +struct TreeNode +{ + int val; + struct TreeNod *left, *right; +}; +bool traverse(struct TreeNode** stack, int top, int sum ) +{ + struct TreeNode *root = stack[top]; + if(root->left==NULL && root->right==NULL) + { + int t = 0; + for(int i = 0; i <= top; i++) + t += stack[i]->val; + return t == sum; + } + else + { + int t = top; + bool left=false, right=false; + if(root->left) + { + stack[++t] = root->left; + left = traverse(stack, t, sum); + } + if(root->right) + { + stack[++top] = root->right; + right = traverse(stack, top, sum); + } + return left || right; + } +} + +//the testing results are weird; +//the leaf node is that node without any child; +//AC - 8ms; +bool hasPathSum0( struct TreeNode* root, int sum ) +{ + if(root == NULL) + return false; + int len = 100; + struct TreeNode** stack = ( struct TreeNode** )malloc(sizeof( struct TreeNode* )*len); + int top = -1; + stack[++top] = root; + return traverse(stack, top, sum); +} + + + +//AC - 8ms; +bool hasPathSum1( struct TreeNode* root, int sum ) +{ + if(!root) + return false; + if(root->left==NULL && root->right==NULL && root->val==sum) + return true; + int newSum = sum-root->val; + return hasPathSum(root->left, newSum) || hasPathSum(root->right, newSum); +} + +//AC - 4ms; +bool hasPathSum2( struct TreeNode* root, int sum ) +{ + if(!root) + return false; + int newSum = sum-root->val; + if(newSum==0 && root->left==NULL && root->right==NULL) + return true; + return hasPathSum(root->left, newSum) || hasPathSum(root->right, newSum); +} diff --git a/LuoSonglei/week-8/PlusOne.c b/LuoSonglei/week-8/PlusOne.c new file mode 100644 index 0000000..af9bb7b --- /dev/null +++ b/LuoSonglei/week-8/PlusOne.c @@ -0,0 +1,35 @@ +/******************************************* +Author : LHearen +E-mail : LHearen@126.com +Time : 2016-01-20 09:30 +Description : +Source : https://leetcode.com/problems/plus-one/ +*******************************************/ +//AC - 0ms; +int* plusOne(int* digits, int size, int* returnSize) +{ + int unit = 10; + digits[size-1] += 1; + int c = 0; + for(int i = size-1; i > 0; i--) + { + if(digits[i] >= unit) + { + digits[i-1]++; + digits[i] = 0; + } + } + if(digits[0] >= unit) + { + digits[0] = 0; + *returnSize = size+1; + int *a = (int*)malloc(sizeof(int)*(*returnSize)); + a[0] = 1; + for(int i = 0; i < size; i++) + a[i+1] = digits[i]; + return a; + } + else + *returnSize = size; + return digits; +} diff --git a/LuoSonglei/week-8/PowerofTwo.c b/LuoSonglei/week-8/PowerofTwo.c new file mode 100644 index 0000000..e3ec09b --- /dev/null +++ b/LuoSonglei/week-8/PowerofTwo.c @@ -0,0 +1,51 @@ +/******************************************* +Author : LHearen +E-mail : LHearen@126.com +Time : 2016-01-19 16:10 +Description : +Source : https://leetcode.com/problems/power-of-two/ +*******************************************/ +#include +//AC - 8ms; +bool isPowerOfTwo0(int n) +{ + int arr[] = {1, + 2,4,8,16,32,64,128,256,512,1024, + 2048,4096,8192,16384,32768,65536,131072,262144,524288,1048576, + 2097152,4194304,8388608,16777216,33554432,67108864,134217728,268435456,536870912,1073741824}; + for(int i = 0; i < sizeof(arr)/sizeof(int); i++) + if(n == arr[i]) + return true; + return false; +} + +//AC - 4ms; +bool isPowerOfTwo1(int n) +{ + while(n) + { + if(n == 1) + return true; + if(n%2) + return false; + n /= 2; + } +} + +//AC - 4ms; +bool isPowerOfTwo2(int n) +{ + if(n < 1) + return false; + int count = 0; + while(n) + { + if(n & 1) + count++; + n >>= 1; + } + if(count > 1) + return false; + else + return true; +} diff --git a/LuoSonglei/week-8/RectangleArea.c b/LuoSonglei/week-8/RectangleArea.c new file mode 100644 index 0000000..27624c1 --- /dev/null +++ b/LuoSonglei/week-8/RectangleArea.c @@ -0,0 +1,20 @@ +/******************************************* +Author : LHearen +E-mail : LHearen@126.com +Time : 2016-01-21 08:55 +Description : +Source : https://leetcode.com/problems/rectangle-area/ +*******************************************/ +//AC - 20ms; +int computeArea(int a, int b, int c, int d, int e, int f, int g, int h) +{ + int size = (c-a)*(d-b)+(g-e)*(h-f); + if(a>=g || c<=e || b>=h || d<=f)//without overlap; + return size; + //overlapped area; + int leftMax = a > e? a : e; + int bottomMax = b > f? b : f; + int rightMin = c < g? c : g; + int topMin = d < h? d : h; + return size - (rightMin-leftMax)*(topMin-bottomMax); +} diff --git a/LuoSonglei/week-8/RemoveDuplicateFromSortedArray.c b/LuoSonglei/week-8/RemoveDuplicateFromSortedArray.c new file mode 100644 index 0000000..67a9dfb --- /dev/null +++ b/LuoSonglei/week-8/RemoveDuplicateFromSortedArray.c @@ -0,0 +1,30 @@ +/******************************************* +Author : LHearen +E-mail : LHearen@126.com +Time : 2016-01-20 08:21 +Description : +Source : https://leetcode.com/problems/remove-duplicates-from-sorted-array/ +*******************************************/ +//AC - 16ms; +int removeDuplicates0(int* nums, int size) +{ + if(size == 0) + return 0; + int pre = 0, cur = 1; + for(; cur < size; cur++) + if(nums[cur] != nums[pre]) + nums[++pre] = nums[cur]; + return pre+1; +} + +//AC - 12ms; +int removeDuplicates1(int* nums, int size) +{ + if(size == 0) + return 0; + int pre = 0; + for(int cur = 1; cur < size; cur++) + if(nums[cur] != nums[pre]) + nums[++pre] = nums[cur]; + return pre+1; +} diff --git a/LuoSonglei/week-8/RemoveDuplicatesFromSortedList.c b/LuoSonglei/week-8/RemoveDuplicatesFromSortedList.c new file mode 100644 index 0000000..58ddf98 --- /dev/null +++ b/LuoSonglei/week-8/RemoveDuplicatesFromSortedList.c @@ -0,0 +1,33 @@ +/******************************************* +Author : LHearen +E-mail : LHearen@126.com +Time : 2016-01-19 11:18 +Description : +Source : https://leetcode.com/problems/remove-duplicates-from-sorted-list/ +*******************************************/ +#include +struct ListNode +{ + int val; + struct ListNode *next; +}; + +//AC - 4ms; +struct ListNode* deleteDuplicates( struct ListNode* head ) +{ + struct ListNode *t = ( struct ListNode* )malloc(sizeof( struct ListNode )); + struct ListNode *pre = t, *cur = head; + while(cur) + { + if(pre == t || pre->val != cur->val) + { + pre->next = cur; + pre = cur; + cur = cur->next; + pre->next = NULL; + } + else + cur = cur->next; + } + return t->next; +} diff --git a/LuoSonglei/week-8/RemoveElement.c b/LuoSonglei/week-8/RemoveElement.c new file mode 100644 index 0000000..084851b --- /dev/null +++ b/LuoSonglei/week-8/RemoveElement.c @@ -0,0 +1,25 @@ +/******************************************* +Author : LHearen +E-mail : LHearen@126.com +Time : 2016-01-20 08:08 +Description : +Source : https://leetcode.com/problems/remove-element/ +*******************************************/ +//AC - 0ms; +int removeElement(int* nums, int size, int val) +{ + int l = 0, r = size-1; + while(l <= r) + { + while(l <= r && nums[l] != val) l++; + while(nums[r] == val) r--; + if(l < r) + { + int t = nums[l]; + nums[l] = nums[r]; + nums[r] = t; + r--; + } + } + return l; +} diff --git a/LuoSonglei/week-8/RemoveLinkedListElements.c b/LuoSonglei/week-8/RemoveLinkedListElements.c new file mode 100644 index 0000000..1fe377c --- /dev/null +++ b/LuoSonglei/week-8/RemoveLinkedListElements.c @@ -0,0 +1,31 @@ +/******************************************* +Author : LHearen +E-mail : LHearen@126.com +Time : 2016-01-22 09:12 +Description : +Source : https://leetcode.com/problems/remove-linked-list-elements/ +*******************************************/ +#include +struct ListNode +{ + int val; + struct ListNode *next; +}; +//AC - 12ms; +struct ListNode* removeElements( struct ListNode* head, int val ) +{ + struct ListNode *t = ( struct ListNode* )malloc(sizeof( struct ListNode )); + struct ListNode *pre = t, *cur = head; + t->next = NULL; + while(cur) + { + if(cur->val != val) + { + pre->next = cur; + pre = pre->next; + } + cur = cur->next; + } + pre->next = NULL; + return t->next; +} diff --git a/LuoSonglei/week-8/RemoveNthNodeFromEndOfList.c b/LuoSonglei/week-8/RemoveNthNodeFromEndOfList.c new file mode 100644 index 0000000..28e55d2 --- /dev/null +++ b/LuoSonglei/week-8/RemoveNthNodeFromEndOfList.c @@ -0,0 +1,38 @@ +/******************************************* +Author : LHearen +E-mail : LHearen@126.com +Time : 2016-01-22 08:59 +Description : +Source : https://leetcode.com/problems/remove-nth-node-from-end-of-list/ +*******************************************/ +#include +struct ListNode +{ + int val; + struct ListNode *next; +}; + +//AC - 0ms; +struct ListNode* removeNthFromEnd( struct ListNode* head, int n ) +{ + struct ListNode *t0 = head, *t1 = head; + while(n) + t0 = t0->next, n--; + if(!t0) + { + if(head->next == NULL) + return NULL; + else + return head->next; + } + while(t0->next) + { + t0 = t0->next; + t1 = t1->next; + } + if(t1->next->next) + t1->next = t1->next->next; + else + t1->next = NULL; + return head; +} diff --git a/LuoSonglei/week-8/ReverseBits.c b/LuoSonglei/week-8/ReverseBits.c new file mode 100644 index 0000000..7fdce21 --- /dev/null +++ b/LuoSonglei/week-8/ReverseBits.c @@ -0,0 +1,27 @@ +/******************************************* +Author : LHearen +E-mail : LHearen@126.com +Time : 2016-01-21 08:37 +Description : +Source : https://leetcode.com/problems/reverse-bits/ +*******************************************/ +#include +//AC - 4ms; +uint32_t reverseBits(uint32_t n) +{ + if(n == 0) + return 0; + int i = n; + int count = 0; + while(n%2==0) + count++, n /= 2; + i = 0; + while(n) + { + i = (i<<1) + n%2; + n /= 2; + } + while(!((1<<(31-count))&i)) + i <<= 1; + return i; +} diff --git a/LuoSonglei/week-8/SameTree.c b/LuoSonglei/week-8/SameTree.c new file mode 100644 index 0000000..4d9e872 --- /dev/null +++ b/LuoSonglei/week-8/SameTree.c @@ -0,0 +1,23 @@ +/******************************************* +Author : LHearen +E-mail : LHearen@126.com +Time : 2016-01-19 08:20 +Description : +Source : https://leetcode.com/problems/same-tree/ +*******************************************/ +#include +struct TreeNode +{ + int val; + struct TreeNod *left, *right; +}; +//AC - 0ms; +bool isSameTree( struct TreeNode* p, struct TreeNode* q ) +{ + if(!p && !q) + return true; + if(p && q && p->val == q->val && isSameTree(p->left, q->left) + && isSameTree(p->right, q->right)) + return true; + return false; +} diff --git a/LuoSonglei/week-8/UglyNumber2.c b/LuoSonglei/week-8/UglyNumber2.c new file mode 100644 index 0000000..f39f853 --- /dev/null +++ b/LuoSonglei/week-8/UglyNumber2.c @@ -0,0 +1,35 @@ +/******************************************* +Author : LHearen +E-mail : LHearen@126.com +Time : 2016-01-22 16:18 +Description : +Source : https://leetcode.com/problems/ugly-number-ii/ +*******************************************/ +//AC - 4ms; +int nthUglyNumber(int n) +{ + if(n < 1) return 0; + if(n == 1) return 1; + int *arr = (int*)malloc(sizeof(int)*n); + int i2=0, i3=0, i5=0; + arr[0] = 1; + for(int i = 1; i < n; i++) + { + int t2 = arr[i2]*2; + int t3 = arr[i3]*3; + int t5 = arr[i5]*5; + int min = t2; + if(min > t3) + min = t3; + if(min > t5) + min = t5; + arr[i] = min; + if(min == t2) + i2++; + if(min == t3) + i3++; + if(min == t5) + i5++; + } + return arr[n-1]; +} diff --git a/LuoSonglei/week-8/UniqueBSTs.c b/LuoSonglei/week-8/UniqueBSTs.c new file mode 100644 index 0000000..d1e2e6e --- /dev/null +++ b/LuoSonglei/week-8/UniqueBSTs.c @@ -0,0 +1,20 @@ +/******************************************* +Author : LHearen +E-mail : LHearen@126.com +Time : 2016-01-23 10:51 +Description : +Source : https://leetcode.com/problems/unique-binary-search-trees/ +*******************************************/ +//AC - 0ms; +int numTrees(int n) +{ + int *arr = (int*)malloc(sizeof(int)*(n+1)); + for(int i = 0; i < n; i++) + arr[i] = 0; + arr[0] = 1; + arr[1] = 1; + for(int i = 2; i <= n; i++) + for(int j = 0; j <= i-1; j++) + arr[i] += arr[j] * arr[i-j-1]; + return arr[n]; +} diff --git a/LuoSonglei/week-8/UniquePath2.c b/LuoSonglei/week-8/UniquePath2.c new file mode 100644 index 0000000..4001663 --- /dev/null +++ b/LuoSonglei/week-8/UniquePath2.c @@ -0,0 +1,67 @@ +/******************************************* +Author : LHearen +E-mail : LHearen@126.com +Time : 2016-01-22 14:59 +Description : +Source : https://leetcode.com/problems/unique-paths-ii/ +*******************************************/ +//AC - 0ms; +int uniquePathsWithObstacles0(int** grid, int rSize, int cSize) +{ + int** arrs = (int**)malloc(sizeof(int*)*rSize); + for(int i = 0; i < rSize; i++) + arrs[i] = (int*)malloc(sizeof(int)*cSize); + for(int i = 0; i < rSize; i++) + for(int j = 0; j < cSize; j++) + { + if(i==0 && j==0 && grid[i][j]==0) + { + arrs[i][j] = 1; + continue; + } + if(grid[i][j] == 1) + { + arrs[i][j] = 0; + continue; + } + int count = 0; + if(j-1 > -1) + count += arrs[i][j-1]; + if(i-1 > -1) + count += arrs[i-1][j]; + arrs[i][j] = count; + } + return arrs[rSize-1][cSize-1]; +} + + +int traverse(int** grid, int row, int col, int** arrs) +{ + if(row < 0 || col < 0) + return 0; + if(arrs[row][col] != -1) + return arrs[row][col]; + int count = 0; + if(grid[row][col] == 1) + count = 0; + else if(row == 0 && col == 0) + count = 1; + else + count = traverse(grid, row-1, col, arrs) + traverse(grid, row, col-1, arrs); + arrs[row][col] = count; + return count; +} + +//AC - 4ms; +int uniquePathsWithObstacles1(int** grid, int rSize, int cSize) +{ + int **arrs = (int**)malloc(sizeof(int*)*rSize); + for(int i = 0; i < rSize; i++) + { + arrs[i] = (int*)malloc(sizeof(int)*cSize); + for(int j = 0; j < cSize; j++) + arrs[i][j] = -1; + } + traverse(grid, rSize-1, cSize-1, arrs); + return arrs[rSize-1][cSize-1]; +} diff --git a/LuoSonglei/week-8/ValidSudoku.c b/LuoSonglei/week-8/ValidSudoku.c new file mode 100644 index 0000000..417fb6f --- /dev/null +++ b/LuoSonglei/week-8/ValidSudoku.c @@ -0,0 +1,49 @@ +/******************************************* +Author : LHearen +E-mail : LHearen@126.com +Time : 2016-01-20 14:47 +Description : +Source : https://leetcode.com/problems/valid-sudoku/ +*******************************************/ +#include +//AC - 4ms; +bool isValidSudoku(char** board, int rSize, int cSize) +{ + int a[10]; + for(int i = 0; i < rSize; i++) + { + for(int i = 0; i < 10; i++) + a[i] = 0; + for(int j = 0; j < cSize; j++) + { + if(board[i][j] != '.') + if(a[board[i][j]-'0']++) + return false; + } + } + for(int i = 0; i < cSize; i++) + { + for(int i = 0; i < 10; i++) + a[i] = 0; + for(int j = 0; j < rSize; j++) + { + if(board[j][i] != '.') + if(a[board[j][i]-'0']++) + return false; + } + } + for(int row = 0; row < 9; row += 3) + for(int col = 0; col < 9; col +=3) + { + for(int i = 0; i < 10; i++) + a[i] = 0; + for(int i = 0; i < 3; i++) + for(int j = 0; j < 3; j++) + { + if(board[row+i][col+j] != '.') + if(a[board[row+i][col+j]-'0']++) + return false; + } + } + return true; +} diff --git a/LuoSonglei/week-9/heapSort.c b/LuoSonglei/week-9/heapSort.c new file mode 100644 index 0000000..a792db1 --- /dev/null +++ b/LuoSonglei/week-9/heapSort.c @@ -0,0 +1,71 @@ +/******************************************* +Author : LHearen +E-mail : LHearen@126.com +Time : 2016-01-29 09:30 +Description : Used to achieve heap sorting, + this method is quicker than + normal methods but slower than + quick and merge sorting; +*******************************************/ +void swap(int *p, int *q) +{ + int t = *p; + *p = *q; + *q = t; +} + +void fixUp(int* a, int k) +{ + while(k > 1 && a[k/2] < a[k]) + swap(a+k/2, a+k), k /= 2; +} + +void fixDown(int* a, int size, int k) +{ + int j; + while(2*k < size) + { + j = 2*k; + if(j < size-1 && a[j] < a[j+1]) j++;//select the bigger one; + if(a[k] >= a[j]) break; + swap(a+k, a+j), k = j; + } +} + + +void heapSort0(int* a, int size) +{ + for(int k=size/2+1; k >= 0; k--) + fixDown(a, size, k); + while(size > 1) + { + swap(a, a+size-1); + fixDown(a, --size, 0); + } +} + +//More portable; +void headSort1(int *a, int l, int r) +{ + int size = r-l+1; + for(int k=size/2; k >= 0; k--) + fixDown(a+l, size, k); + while(size > 1) + { + swap(a+l, a+l+size-1); + fixDown(a+l, --size, 0); + } +} + +void main() +{ + int numbers[10000]; + int size = rand()%1000 + 200; + randomIntArray(numbers, size, 0, 10000); + printArray(numbers, size); + checkAscending(numbers, size); + printf("After sorting:\n***********************\n"); + heapSort(numbers, size); + printArray(numbers, size); + checkAscending(numbers, size); +} diff --git a/LuoSonglei/week-9/heapSort.c~ b/LuoSonglei/week-9/heapSort.c~ new file mode 100644 index 0000000..749811d --- /dev/null +++ b/LuoSonglei/week-9/heapSort.c~ @@ -0,0 +1,70 @@ +/******************************************* +Author : LHearen +E-mail : LHearen@126.com +Time : 2016-01-29 09:30 +Description : Used to achieve heap sorting, + this method is quicker than + normal methods but slower than + quick and merge sorting; +*******************************************/ +void swap(int *p, int *q) +{ + int t = *p; + *p = *q; + *q = t; +} + +void fixUp(int* a, int k) +{ + while(k > 1 && a[k/2] < a[k]) + swap(a+k/2, a+k), k /= 2; +} + +void fixDown(int* a, int size, int k) +{ + int j; + while(2*k < size) + { + j = 2*k; + if(j < size-1 && a[j] < a[j+1]) j++; + if(a[k] >= a[j]) break; + swap(a+k, a+j), k = j; + } +} + + +void heapSort0(int* a, int size) +{ + for(int k=size/2+1; k >= 0; k--) + fixDown(a, size, k); + while(size > 1) + { + swap(a, a+size-1); + fixDown(a, --size, 0); + } +} + +void headSort1(int *a, int l, int r) +{ + int size = r-l+1; + for(int k=size/2; k >= 0; k--) + fixDown(a+l, size, k); + while(size > 1) + { + swap(a+l, a+l+size-1); + fixDown(a+l, --size, 0); + } +} + +void main() +{ + int numbers[10000]; + int size = rand()%1000 + 200; + randomIntArray(numbers, size, 0, 10000); + printArray(numbers, size); + checkAscending(numbers, size); + printf("After sorting:\n***********************\n"); + heapSort(numbers, size); + printArray(numbers, size); + checkAscending(numbers, size); +} diff --git a/LuoSonglei/week-91/BestTimeBuySellStock.c b/LuoSonglei/week-91/BestTimeBuySellStock.c new file mode 100644 index 0000000..cb5a66b --- /dev/null +++ b/LuoSonglei/week-91/BestTimeBuySellStock.c @@ -0,0 +1,42 @@ +/******************************************* +Author : LHearen +E-mail : LHearen@126.com +Time : 2016-02-11 15:49 +Description : +Source : https://leetcode.com/problems/best-time-to-buy-and-sell-stock/ +*******************************************/ +//AC - 4ms; +int maxProfit0(int *prices, int size) +{ + if(size == 0) + return 0; + int min = prices[0]; + int profit = 0; + for(int i = 0; i < size; i++) + { + if(prices[i] < min) + min = prices[i]; + int t = prices[i] - min; + if(t > profit) + profit = t; + } + return profit; +} + +//AC - 4ms; +int maxProfit(int *prices, int size) +{ + if(size <= 1) + return 0; + int *profits = (int)malloc(sizeof(int)*size); + profits[0] = 0; + int min = prices[0]; + for(int i = 1; i < size; i++) + { + if(prices[i] < min) + min = prices[i]; + int t = prices[i] - min; + profits[i] = (t < profits[i-1] ? profits[i-1] : t); + } + return profits[size-1]; +} diff --git a/LuoSonglei/week-91/BestTimeBuySellStock2.c b/LuoSonglei/week-91/BestTimeBuySellStock2.c new file mode 100644 index 0000000..e7cff6c --- /dev/null +++ b/LuoSonglei/week-91/BestTimeBuySellStock2.c @@ -0,0 +1,44 @@ +/******************************************* +Author : LHearen +E-mail : LHearen@126.com +Time : 2016-02-11 15:52 +Description : +Source : https://leetcode.com/problems/best-time-to-buy-and-sell-stock-ii/ +*******************************************/ +//AC - 4ms; +int maxProfit0(int* prices, int size) +{ + if(size == 0) + return 0; + int min = prices[0]; + int profit = 0; + for(int i = 1; i < size; i++) + { + if(min > prices[i]) + min = prices[i]; + //Searching for the local min and max; + if((i < size-1 && prices[i] > prices[i-1] && prices[i] >= prices[i+1]) + || (i==size-1 && prices[i] > prices[i-1])) + { + profit += prices[i]-min; + if(i < size-1)//update the min searching for the next range; + min = prices[i+1]; + } + } + return profit; +} + +//AC - 4ms; +int maxProfit1(int* prices, int size) +{ + if(size <= 1) + return 0; + int profit = 0; + for(int i = 1; i < size; i++) + { + if(prices[i] > prices[i-1]) + profit += prices[i]-prices[i-1]; + } + return profit; +} + diff --git a/LuoSonglei/week-91/BestTimeBuySellStock3.c b/LuoSonglei/week-91/BestTimeBuySellStock3.c new file mode 100644 index 0000000..b9a706a --- /dev/null +++ b/LuoSonglei/week-91/BestTimeBuySellStock3.c @@ -0,0 +1,65 @@ +/******************************************* +Author : LHearen +E-mail : LHearen@126.com +Time : 2016-02-11 16:21 +Description : +Source : https://leetcode.com/problems/best-time-to-buy-and-sell-stock-iii/ +*******************************************/ +//AC - 4ms; +int maxProfit0(int* prices, int size) +{ + if(size <= 1) + return 0; + int *lProfits = (int*)malloc(sizeof(int)*size); + int *rProfits = (int*)malloc(sizeof(int)*size); + int min = prices[0]; + lProfits[0] = 0; + for(int i = 1; i < size; i++) + { + if(prices[i] < min) + min = prices[i]; + int t = prices[i] - min; + lProfits[i] = (t < lProfits[i-1] ? lProfits[i-1] : t); + } + int max = prices[size-1]; + rProfits[size-1] = 0; + for(int i = size-2; i > -1; i--) + { + if(prices[i] > max) + max = prices[i]; + int t = max - prices[i]; + rProfits[i] = (t < rProfits[i+1]? rProfits[i+1] : t); + } + int profit = 0; + for(int i = 0; i < size; i++) + { + int t = lProfits[i] + rProfits[i]; + if(t > profit) + profit = t; + } + return lProfits[size-1] > profit ? lProfits[size-1] : profit; +} + +//AC - 4ms; +#include +#define MAX(a, b) (a)>(b)? (a):(b) +int maxProfit(int* prices, int size) +{ + int k = 2; + int *holds = (int*)malloc(sizeof(int)*(k+1)); + int *solds = (int*)malloc(sizeof(int)*(k+1)); + memset(solds, 0, sizeof(int)*(k+1)); + for(int i = 0; i <= k; i++) + holds[i] = INT_MIN; + int cur = 0; + for(int i=0; i < size; i++) + { + cur = prices[i]; + for(int j = k; j > 0; j--) + { + solds[j] = MAX(solds[j], holds[j]+cur); + holds[j] = MAX(holds[j], solds[j-1]-cur); + } + } + return solds[k]; +} diff --git a/LuoSonglei/week-91/BestTimeBuySellStock4.c b/LuoSonglei/week-91/BestTimeBuySellStock4.c new file mode 100644 index 0000000..6d5e0e8 --- /dev/null +++ b/LuoSonglei/week-91/BestTimeBuySellStock4.c @@ -0,0 +1,39 @@ +/******************************************* +Author : LHearen +E-mail : LHearen@126.com +Time : 2016-02-11 17:15 +Description : +Source : https://leetcode.com/problems/best-time-to-buy-and-sell-stock-iv/ +*******************************************/ +//AC - 4ms; +#include +#define MAX(a, b) (a)>(b)? (a):(b) +int maxProfit(int k, int* prices, int size) +{ + if(size < 2) + return 0; + if(k > size/2) + { + int profit = 0; + for(int i=1; i < size; i++) + if(prices[i] > prices[i-1]) + profit += prices[i]-prices[i-1]; + return profit; + } + int *holds = (int*)malloc(sizeof(int)*(k+1)); + int *solds = (int*)malloc(sizeof(int)*(k+1)); + memset(solds, 0, sizeof(int)*(k+1)); + for(int i = 0; i <= k; i++) + holds[i] = INT_MIN; + int cur = 0; + for(int i=0; i < size; i++) + { + cur = prices[i]; + for(int j = k; j > 0; j--) + { + solds[j] = MAX(solds[j], holds[j]+cur); + holds[j] = MAX(holds[j], solds[j-1]-cur); + } + } + return solds[k]; +} diff --git a/LuoSonglei/week-91/BestTimeBuySellStockWithCoolDown.c b/LuoSonglei/week-91/BestTimeBuySellStockWithCoolDown.c new file mode 100644 index 0000000..775d622 --- /dev/null +++ b/LuoSonglei/week-91/BestTimeBuySellStockWithCoolDown.c @@ -0,0 +1,24 @@ +/******************************************* +Author : LHearen +E-mail : LHearen@126.com +Time : 2016-02-11 21:39 +Description : +Source : https://leetcode.com/problems/best-time-to-buy-and-sell-stock-with-cooldown/ +*******************************************/ +#include +//AC - 4ms; +//https://leetcode.com/discuss/71354/share-my-thinking-process +#define MAX(a, b) (a)>(b)? (a):(b) +int maxProfit(int* prices, int size) +{ + int preBuy = INT_MIN, curBuy = INT_MIN; + int preSell = 0, curSell = 0; + for(int i = 0; i < size; i++) + { + curBuy = MAX(preBuy, preSell-prices[i]); + preBuy = curBuy; + preSell = curSell; + curSell = MAX(curSell, preBuy+prices[i]); + } + return curSell; +} diff --git a/LuoSonglei/week-91/CoinChange.c b/LuoSonglei/week-91/CoinChange.c new file mode 100644 index 0000000..38b0cb1 --- /dev/null +++ b/LuoSonglei/week-91/CoinChange.c @@ -0,0 +1,54 @@ +/******************************************* +Author : LHearen +E-mail : LHearen@126.com +Time : 2016-02-13 15:05 +Description : +Source : https://leetcode.com/problems/coin-change/ +*******************************************/ +//AC - 44ms; +int coinChange0(int* coins, int size, int amount) +{ + int *mins = (int*)malloc(sizeof(int)*(amount+1)); + mins[0] = 0; + for(int i = 1; i <= amount; i++) + { + int min = -1; + for(int j = 0; j < size; j++) + { + int t = i-coins[j]; + if(t >= 0 && mins[t] != -1) + { + if(min == -1) + min = mins[t]+1; + else if(mins[t]+1 < min) + min = mins[t]+1; + } + } + mins[i] = min; + } + return mins[amount]; +} + +//AC - 40ms; +int coinChange(int* coins, int size, int amount) +{ + int *mins = (int*)malloc(sizeof(int)*(amount+1)); + for(int i = 1; i <= amount; i++) + { + int min = amount+1; + for(int j = 0; j < size; j++) + { + int t = i-coins[j]; + if(t >= 0) + { + t = mins[t]+1; + min = t < min? t : min; + } + } + mins[i] = min; + } + if(mins[amount] > amount) + return -1; + else + return mins[amount]; +} diff --git a/LuoSonglei/week-91/DecodeWays.c b/LuoSonglei/week-91/DecodeWays.c new file mode 100644 index 0000000..395b1aa --- /dev/null +++ b/LuoSonglei/week-91/DecodeWays.c @@ -0,0 +1,30 @@ +/******************************************* +Author : LHearen +E-mail : LHearen@126.com +Time : 2016-02-13 16:35 +Description : +Source : https://leetcode.com/problems/decode-ways/ +*******************************************/ +int isValid(char a, char b) +{ + return a=='1' || (a=='2' && b<'7'); +} + +//AC - 0ms; +int numDecodings(char* s) +{ + int len = strlen(s); + if(len == 0 || s[0] == '0') return 0; + if(len == 1) return 1; + int t, f1 = 1, f2 = 1; + for(int i = 1; i < len; i++) + { + if(s[i]!='0' && isValid(s[i-1], s[i])) t = f1+f2; + if(s[i]!='0' && !isValid(s[i-1], s[i])) t = f2; + if(s[i]=='0' && isValid(s[i-1], s[i])) t = f1; + if(s[i]=='0' && !isValid(s[i-1], s[i])) return 0; + f1=f2; + f2=t; + } + return t; +} diff --git a/LuoSonglei/week-91/HouseRobber2.c b/LuoSonglei/week-91/HouseRobber2.c new file mode 100644 index 0000000..535b557 --- /dev/null +++ b/LuoSonglei/week-91/HouseRobber2.c @@ -0,0 +1,64 @@ +/******************************************* +Author : LHearen +E-mail : LHearen@126.com +Time : 2016-02-13 16:21 +Description : +Source : https://leetcode.com/problems/house-robber-ii/ +*******************************************/ +int rob0(int* nums, int size) +{ + int *profits = (int*)malloc(sizeof(int)*(size+1)); + profits[0] = 0; + for(int i = 0; i < size; i++) + { + int t; + if(i) + { + t = profits[i]; + int profit = nums[i]; + if(i == 1 && profit > t) + t = profit; + else + { + profit += profits[i-1]; + if(profit > t) + t = profit; + } + } + else + t = nums[i]; + profits[i+1] = t; + } + return profits[size]; +} + +int rob1(int* nums, int size) +{ + if(size == 0) + return 0; + if(size == 1) + return nums[0]; + int *profits = (int*)malloc(sizeof(int)*size); + profits[0] = nums[0]; + profits[1] = nums[1] > nums[0] ? nums[1] : nums[0]; + for(int i = 2; i < size; i++) + { + int profit = profits[i-2] + nums[i]; + if(profits[i-1] > profit) + profit = profits[i-1]; + profits[i] = profit; + } + return profits[size-1]; +} + +//AC - 0ms; +int rob(int* nums, int size) +{ + if(size == 0) + return 0; + if(size == 1) + return nums[0]; + int profit0 = rob0(nums, size-1); + int profit1 = rob0(nums+1, size-1); + return profit0 > profit1? profit0 : profit1; +} diff --git a/LuoSonglei/week-91/LongestIncreasingSubsequence.c b/LuoSonglei/week-91/LongestIncreasingSubsequence.c new file mode 100644 index 0000000..c7057d7 --- /dev/null +++ b/LuoSonglei/week-91/LongestIncreasingSubsequence.c @@ -0,0 +1,26 @@ +/******************************************* +Author : LHearen +E-mail : LHearen@126.com +Time : 2016-02-13 12:01 +Description : +Source : https://leetcode.com/problems/longest-increasing-subsequence/ +*******************************************/ +//AC - 28ms; +int lengthOfLIS(int* nums, int size) +{ + if(size < 2) return size; + int *lens = (int*)malloc(sizeof(int)*(size+1)); + lens[0] = 0, lens[1] = 1; + int max = 1; + for(int i = 0; i < size; i++) + { + int t = 0; + for(int j = i-1; j >= 0; j--) + if(nums[i] > nums[j] && lens[j+1] > t) + t = lens[j+1]; + lens[i+1] = t+1; + if(lens[i+1] > max) + max = lens[i+1]; + } + return max; +} diff --git a/LuoSonglei/week-91/MaxProductSubarray.c b/LuoSonglei/week-91/MaxProductSubarray.c new file mode 100644 index 0000000..5be48b1 --- /dev/null +++ b/LuoSonglei/week-91/MaxProductSubarray.c @@ -0,0 +1,26 @@ +/******************************************* +Author : LHearen +E-mail : LHearen@126.com +Time : 2016-02-12 15:02 +Description : +Source : https://leetcode.com/problems/maximum-product-subarray/ +*******************************************/ +//AC - 4ms; +#define MAX(a, b) (a)>(b)? (a):(b) +#define MIN(a, b) (a)<(b)? (a):(b) +int maxProduct(int* nums, int size) +{ + int max = nums[0]; + for(int i=1, imax=max, imin=max; i < size; i++) + { + int t; + if(nums[i] < 0) + t = imax, imax = imin, imin = t; + t = imax*nums[i]; + imax = MAX(nums[i], t); + t = imin*nums[i]; + imin = MIN(nums[i], t); + max = MAX(imax, max); + } + return max; +} diff --git a/LuoSonglei/week-91/MaxSquare.c b/LuoSonglei/week-91/MaxSquare.c new file mode 100644 index 0000000..f1ee7f5 --- /dev/null +++ b/LuoSonglei/week-91/MaxSquare.c @@ -0,0 +1,46 @@ +/******************************************* +Author : LHearen +E-mail : LHearen@126.com +Time : 2016-02-13 10:58 +Description : +Source : https://leetcode.com/problems/maximal-square/ +*******************************************/ +//AC - 4ms; +//https://leetcode.com/discuss/38489/easy-solution-with-detailed-explanations-8ms-time-and-space +int maximalSquare(char** matrix, int rSize, int cSize) +{ + int max = 0; + int *pre = (int*)malloc(sizeof(int)*cSize); + int *cur = (int*)malloc(sizeof(int)*cSize); + for(int r=0; r 0) + { + int t = cur[c-1]; + if(pre[c] < t) + t = pre[c]; + if(pre[c-1] < t) + t = pre[c-1]; + cur[c] = t+1; + } + else + cur[c] = 1; + } + else + cur[c] = 0; + } + if(cur[c] > max) + max = cur[c]; + } + int *t = pre; + pre = cur; + cur = t; + return max*max; +} diff --git a/LuoSonglei/week-91/MaxSubarray.c b/LuoSonglei/week-91/MaxSubarray.c new file mode 100644 index 0000000..f087460 --- /dev/null +++ b/LuoSonglei/week-91/MaxSubarray.c @@ -0,0 +1,24 @@ +/******************************************* +Author : LHearen +E-mail : LHearen@126.com +Time : 2016-02-12 14:49 +Description : +Source : https://leetcode.com/problems/maximum-subarray/ +*******************************************/ +#include +//AC - 4ms; +int maxSubArray(int* nums, int size) +{ + int sum = 0; + int max = INT_MIN; + for(int i = 0; i < size; i++) + { + if(sum >= 0) + sum += nums[i]; + else + sum = nums[i]; + if(sum > max) + max = sum; + } + return max; +} diff --git a/LuoSonglei/week-91/MinPathSum.c b/LuoSonglei/week-91/MinPathSum.c new file mode 100644 index 0000000..535824c --- /dev/null +++ b/LuoSonglei/week-91/MinPathSum.c @@ -0,0 +1,29 @@ +/******************************************* +Author : LHearen +E-mail : LHearen@126.com +Time : 2016-02-12 14:43 +Description : +Source : https://leetcode.com/problems/minimum-path-sum/ +*******************************************/ +//AC - 20ms; +int minPathSum(int** grid, int rSize, int cSize) +{ + int *t, *sums0, *sums1; + sums0 = (int*)malloc(sizeof(int)*cSize); + sums1 = (int*)malloc(sizeof(int)*cSize); + sums0[0] = grid[0][0]; + for(int i = 1; i < cSize; i++) + sums0[i] = sums0[i-1] + grid[0][i]; + for(int r=1; r 0 && min > sums1[c-1]) + min = sums1[c-1]; + sums1[c] = min+grid[r][c]; + } + t=sums0, sums0=sums1, sums1=t; + } + return sums0[cSize-1]; +} diff --git a/LuoSonglei/week-91/PalindromePartition2.c b/LuoSonglei/week-91/PalindromePartition2.c new file mode 100644 index 0000000..f061c18 --- /dev/null +++ b/LuoSonglei/week-91/PalindromePartition2.c @@ -0,0 +1,37 @@ +/******************************************* +Author : LHearen +E-mail : LHearen@126.com +Time : 2016-02-13 20:16 +Description : +Source : https://leetcode.com/problems/palindrome-partitioning-ii/ +*******************************************/ +#include +//AC - 12ms; +int minCut(char *s) +{ + int len = strlen(s); + if(len == 0) return 0; + bool **isPal = (int**)malloc(sizeof(bool*)*len); //Used to record the whether the substring from i to j inclusive is a palindrome or not; + for(int i=0; i -1; i--) + { + minCuts[i]=len-i-1; //the default minimal cuts; + for(int j=i; j +//AC - 144ms; +int numSquares0(int n) +{ + int *mins = (int*)malloc(sizeof(int)*(n+1)); + mins[0] = 0; + for(int i = 1; i <= n; i++) + { + int min = INT_MAX; + int square = 1; + for(int r=1; square <= i; r++) + { + int t = mins[i-square]+1; + min = t < min? t : min; + square = r*r; + } + mins[i] = min; + } + return mins[n]; +} + +//AC - 4ms; +//https://leetcode.com/discuss/56982/o-sqrt-n-in-ruby-c-c +int numSquares(int n) +{ + while(n%4 == 0) + n >>= 2; + if(n%8 == 7) + return 4; + for(int a=0; a*a <= n; ++a) + { + int b = sqrt(n-a*a); + if(a*a + b*b == n) + return 1+!!a; + } + return 3; +} diff --git a/LuoSonglei/week-91/RangeSumQuery2DImmutable.c b/LuoSonglei/week-91/RangeSumQuery2DImmutable.c new file mode 100644 index 0000000..0e097ef --- /dev/null +++ b/LuoSonglei/week-91/RangeSumQuery2DImmutable.c @@ -0,0 +1,52 @@ +/******************************************* +Author : LHearen +E-mail : LHearen@126.com +Time : 2016-02-12 10:43 +Description : +Source : https://leetcode.com/problems/range-sum-query-2d-immutable/ +*******************************************/ +struct NumMatrix +{ + int** sumMatrix; +}; + +struct NumMatrix* NumMatrixCreate(int** matrix, int rSize, int cSize) +{ + struct NumMatrix *t = (struct NumMatrix*)malloc(sizeof(struct NumMatrix)); + t->sumMatrix = (int**)malloc(sizeof(int*)*rSize); + int *sums = (int*)malloc(sizeof(int)*(cSize+1)); + for(int r = 0; r < rSize; r++) + { + (t->sumMatrix)[r] = (int*)malloc(sizeof(int)*cSize); + sums[0] = matrix[r][0]; + for(int i = 0; i < cSize; i++) + { + if(i > 0) + sums[i] = sums[i-1]+matrix[r][i]; + (t->sumMatrix)[r][i] = sums[i]; + if(r > 0) + (t->sumMatrix)[r][i] += (t->sumMatrix)[r-1][i]; + } + } + return t; +} + +//AC - 256ms; +int sumRegion(struct NumMatrix* numMatrix, int row1, int col1, int row2, int col2) +{ + int** sumMatrix = numMatrix->sumMatrix; + int ret = sumMatrix[row2][col2]; + if(row1 > 0) + ret -= sumMatrix[row1-1][col2]; + if(col1 > 0) + ret -= sumMatrix[row2][col1-1]; + if(row1 > 0 && col1 > 0) + ret += sumMatrix[row1-1][col1-1]; + return ret; +} + +void NumMatrixFree(struct NumMatrix* numMatrix) +{ + free(numMatrix->sumMatrix); + free(numMatrix); +} diff --git a/LuoSonglei/week-91/RangeSumQueryImmutable.c b/LuoSonglei/week-91/RangeSumQueryImmutable.c new file mode 100644 index 0000000..742c10c --- /dev/null +++ b/LuoSonglei/week-91/RangeSumQueryImmutable.c @@ -0,0 +1,35 @@ +/******************************************* +Author : LHearen +E-mail : LHearen@126.com +Time : 2016-02-12 09:18 +Description : +Source : https://leetcode.com/problems/range-sum-query-immutable/ +*******************************************/ +struct NumArray +{ + int* sums; +}; + +struct NumArray* NumArrayCreate(int* nums, int size) +{ + struct NumArray *t = (struct NumArray*)malloc(sizeof(struct NumArray)); + int space = sizeof(int)*(size+1); + t->sums = (int*)malloc(space); + memset(t->sums, 0, sizeof(int)); + for(int i = 0; i < size; i++) + t->sums[i+1] = t->sums[i] + nums[i]; + return t; +} + +//AC - 568ms; +int sumRange(struct NumArray* numArray, int i, int j) +{ + int *sums = numArray->sums; + return sums[j+1] - sums[i]; +} + +void NumArrayFree(struct NumArray* numArray) +{ + free(numArray->sums); + free(numArray); +} diff --git a/LuoSonglei/week-91/RgxMatching.c b/LuoSonglei/week-91/RgxMatching.c new file mode 100644 index 0000000..1a71c99 --- /dev/null +++ b/LuoSonglei/week-91/RgxMatching.c @@ -0,0 +1,34 @@ +/******************************************* +Author : LHearen +E-mail : LHearen@126.com +Time : 2016-02-14 16:09 +Description : +Source : https://leetcode.com/problems/regular-expression-matching/ +*******************************************/ +#include +//AC - 4ms; +bool isMatch(char* s, char* p) +{ + int sLen = strlen(s), pLen = strlen(p); + sLen++, pLen++; + bool *pre = (bool*)malloc(sizeof(bool)*pLen); + bool *cur = (bool*)malloc(sizeof(bool)*pLen); + memset(pre, 0, sizeof(bool)*pLen); + memset(cur, 0, sizeof(bool)*pLen); + pre[0] = cur[0] = true; + for(int i=0; i < sLen; i++)//i and j here represent length instead of index; + { + if(i) cur[0]=false; + for(int j=1; j < pLen; j++) + { + char c=*(p+j-1); + if(c != '*') + cur[j] = i>0 && pre[j-1] && (c=='.' || c==*(s+i-1)); + else + cur[j] = (j>1 && cur[j-2]) || //two different situations: match zero or not zero; + (i>0 && pre[j] && (*(p+j-2)=='.' || *(p+j-2) == *(s+i-1))); + } + bool *t = pre; pre = cur, cur = t; + } + return pre[pLen-1]; +} diff --git a/LuoSonglei/week-91/SingleNumber.c b/LuoSonglei/week-91/SingleNumber.c new file mode 100644 index 0000000..4334259 --- /dev/null +++ b/LuoSonglei/week-91/SingleNumber.c @@ -0,0 +1,17 @@ +/******************************************* +Author : LHearen +E-mail : LHearen@126.com +Time : 2016-02-11 20:16 +Description : +Source : https://leetcode.com/problems/single-number/ +*******************************************/ +//AC - 8ms; +int singleNumber(int* nums, int size) +{ + if(size == 0) + return 0; + int ret = nums[0]; + for(int i=1; i < size; i++) + ret ^= nums[i]; + return ret; +} diff --git a/LuoSonglei/week-91/SingleNumber2.c b/LuoSonglei/week-91/SingleNumber2.c new file mode 100644 index 0000000..c11eb63 --- /dev/null +++ b/LuoSonglei/week-91/SingleNumber2.c @@ -0,0 +1,38 @@ +/******************************************* +Author : LHearen +E-mail : LHearen@126.com +Time : 2016-02-11 21:07 +Description : +Source : https://leetcode.com/problems/single-number-ii/ +*******************************************/ +//AC - 8ms; +//direct method - calculate each bit and find the single one; +int singleNumber0(int* nums, int size) +{ + int b, ret = 0; + int len = sizeof(int)*8; + for(int i = 0; i < len; i++) + { + b = 1 << i; + int count = 0; + for(int j = 0; j < size; j++) + if(b & nums[j]) + count++; + if(count%3) + ret |= b; + } + return ret; +} +//AC - 4ms; +//inspired by logical circuit design and boolean algebra; +//counter - unit of 3; +int singleNumber(int* nums, int size) +{ + int one = 0, two = 0; + for(int i = 0; i < size; i++) + { + one = (one ^ nums[i]) & ~two; + two = (two ^ nums[i]) & ~one; + } + return one; +} diff --git a/LuoSonglei/week-91/SingleNumber3.c b/LuoSonglei/week-91/SingleNumber3.c new file mode 100644 index 0000000..aded6f7 --- /dev/null +++ b/LuoSonglei/week-91/SingleNumber3.c @@ -0,0 +1,26 @@ +/******************************************* +Author : LHearen +E-mail : LHearen@126.com +Time : 2016-02-12 08:10 +Description : +Source : https://leetcode.com/problems/single-number-iii/ +*******************************************/ +//AC - 4ms; +int* singleNumber(int* nums, int size, int* returnSize) +{ + *returnSize = 2; + int *arr = (int*)malloc(sizeof(int)*2); + memset(arr, 0, sizeof(int)*2); + int ret = 0; + for(int i = 0; i < size; i++) //get the xor-ed result of the two distincts; + ret ^= nums[i]; + int splitter = ret & -ret; //find the first 'true' bit; + for(int i = 0; i < size; i++) + { + if(splitter & nums[i]) + arr[0] ^= nums[i]; + else + arr[1] ^= nums[i]; + } + return arr; +} diff --git a/LuoSonglei/week-91/Triangle.c b/LuoSonglei/week-91/Triangle.c new file mode 100644 index 0000000..2a842e1 --- /dev/null +++ b/LuoSonglei/week-91/Triangle.c @@ -0,0 +1,72 @@ +/******************************************* +Author : LHearen +E-mail : LHearen@126.com +Time : 2016-02-12 10:12 +Description : +Source : https://leetcode.com/problems/triangle/ +*******************************************/ +//AC - 8ms; +int minimumTotal0(int** triangle, int rSize, int *cSize) +{ + int len = sizeof(int)*cSize[rSize-1]; + int *mins0 = (int*)malloc(len); + int *mins1 = (int*)malloc(len); + mins0[0] = triangle[0][0]; + for(int r = 1; r < rSize; r++) + { + for(int c = 0; c < cSize[r]; c++) + { + if(c == 0) + { + mins1[c] = mins0[c]+triangle[r][c]; + continue; + } + if(c == cSize[r]-1) + { + mins1[c] = mins0[c-1]+triangle[r][c]; + continue; + } + int t = triangle[r][c] + mins0[c]; + if(mins0[c] > mins0[c-1]) + t = triangle[r][c] + mins0[c-1]; + mins1[c] = t; + } + int *t = mins0; + mins0 = mins1; + mins1 = t; + } + int t = mins0[0]; + for(int i = 0; i < cSize[rSize-1]; i++) + if(t > mins0[i]) + t = mins0[i]; + return t; +} + +//AC - 8ms; +int minimumTotal(int** triangle, int rSize, int *cSize) +{ + int len = sizeof(int)*cSize[rSize-1]; + int *mins0 = (int*)malloc(len); + int *mins1 = (int*)malloc(len); + mins0[0] = triangle[0][0]; + for(int r = 1; r < rSize; r++) + { + for(int c = 0; c < cSize[r]; c++) + { + if(c == cSize[r]-1) + mins0[c] = mins0[c-1]; + int t = triangle[r][c] + mins0[c]; + if(c > 0 && mins0[c] > mins0[c-1]) + t = triangle[r][c] + mins0[c-1]; + mins1[c] = t; + } + int *t = mins0; + mins0 = mins1; + mins1 = t; + } + int t = mins0[0]; + for(int i = 0; i < cSize[rSize-1]; i++) + if(t > mins0[i]) + t = mins0[i]; + return t; +} diff --git a/LuoSonglei/week-91/WildcardMatching.c b/LuoSonglei/week-91/WildcardMatching.c new file mode 100644 index 0000000..900aa8f --- /dev/null +++ b/LuoSonglei/week-91/WildcardMatching.c @@ -0,0 +1,80 @@ +/******************************************* +Author : LHearen +E-mail : LHearen@126.com +Time : 2016-02-14 15:11 +Description : +Source : https://leetcode.com/problems/wildcard-matching/ +*******************************************/ +#include +#include +//AC - 12ms; - not a DP solution +//can be optimized to 8ms by simplify the variable names; +bool isMatch0(char* s, char* p) +{ + const char *pAsterisk = NULL, *sAsterisk = NULL; + while(*s) + { + if(*p=='?' || *s==*p){p++, s++; continue;} + if(*p=='*'){pAsterisk=p++, sAsterisk=s; continue;} + if(pAsterisk){p=pAsterisk+1, s=++sAsterisk; continue;} + return false; + } + while(*p=='*') p++; + return !*p; +} + + +//AC - 28ms - DP solution; +bool isMatch1(char* s, char* p) +{ + int sLen=strlen(s), pLen=strlen(p); + int count = 0; + for(int i = 0; i < pLen; i++) + if(p[i] == '*') count++; + if((count==0 && pLen!=sLen) || (pLen-count>sLen)) return false; + bool *match = (bool*)malloc(sizeof(bool)*(sLen+1)); + memset(match, 0, sizeof(bool)*(sLen+1)); + match[0] = true; + for(int i = 0; i < pLen; i++) + { + if(p[i] == '*') + { + for(int j = 1; j <= sLen; j++) + match[j] = match[j-1] || match[j]; + } + else + { + for(int j = sLen; j > 0; j--) + match[j] = (p[i] == '?' || p[i] == s[j-1]) && match[j-1]; + match[0] = false; + } + } + return match[sLen]; +} + +//AC - 132ms - a typical DP solution; +bool isMatch(char* s, char* p) +{ + int sLen=strlen(s), pLen=strlen(p); + sLen++, pLen++; + bool **match = (bool**)malloc(sizeof(bool*)*sLen); + for(int i = 0; i < sLen; i++) + match[i] = (bool*)malloc(sizeof(bool)*pLen); + match[sLen-1][pLen-1] = true; + for(int i = pLen-2; i > -1; i--) + if(p[i] != '*') + break; + else + match[sLen-1][i] = true; + for(int i = sLen-2; i > -1; i--) + for(int j = pLen-2; j > -1; j--) + { + if(s[i]==p[j] || p[j]=='?') + match[i][j] = match[i+1][j+1]; + else if(p[j] == '*') + match[i][j] = match[i+1][j] || match[i][j+1]; + else + match[i][j] = false; + } + return **match; +} diff --git a/LuoSonglei/week-92/BBT.c b/LuoSonglei/week-92/BBT.c new file mode 100644 index 0000000..6a135a5 --- /dev/null +++ b/LuoSonglei/week-92/BBT.c @@ -0,0 +1,37 @@ +/******************************************* +Author : LHearen +E-mail : LHearen@126.com +Time : 2016-02-18 21:19 +Description : +Source : https://leetcode.com/problems/balanced-binary-tree/ +*******************************************/ +#include +struct TreeNode +{ + int val; + struct TreeNod *left, *right; +}; +int height(struct TreeNode* root) +{ + if(!root) return 0; + if(!root->left && !root->right) return 1; + int lHeight=0, rHeight=0; + if(root->left) + lHeight = height(root->left)+1; + if(root->right) + rHeight = height(root->right)+1; + return lHeight > rHeight? lHeight : rHeight; +} + +//AC - 8ms; +bool isBalanced(struct TreeNode* root) +{ + if(!root) return true; + int lHeight = height(root->left); + int rHeight = height(root->right); + int min = lHeight > rHeight? rHeight : lHeight; + int max = lHeight > rHeight? lHeight : rHeight; + if(max-min > 1) + return false; + return isBalanced(root->left) && isBalanced(root->right); +} diff --git a/LuoSonglei/week-92/BTLevelOrderTraversal.c b/LuoSonglei/week-92/BTLevelOrderTraversal.c new file mode 100644 index 0000000..a6fa1f2 --- /dev/null +++ b/LuoSonglei/week-92/BTLevelOrderTraversal.c @@ -0,0 +1,45 @@ +/******************************************* +Author : LHearen +E-mail : LHearen@126.com +Time : 2016-02-18 20:16 +Description : +Source : https://leetcode.com/problems/binary-tree-level-order-traversal/ +*******************************************/ +struct TreeNode +{ + int val; + struct TreeNod *left, *right; +}; +#include +//AC - 0ms; +int** levelOrder( struct TreeNode* root, int** colSize, int* returnSize ) +{ + if(!root) return NULL; + struct TreeNode** queue0 = (struct TreeNode*)malloc(sizeof(struct TreeNode*)); + struct TreeNode** queue1 = (struct TreeNode*)malloc(sizeof(struct TreeNode*)); + int size = 1; + queue0[0] = root; + int **arr = (int**)malloc(sizeof(int*)); //before revoking realloc, we have to provide an address first; + *returnSize = 0; + while(size) + { + *returnSize += 1; + *colSize = (int*)realloc(*colSize, sizeof(int)*(*returnSize)); + (*colSize)[*returnSize-1] = size; + arr = (int**)realloc(arr, sizeof(int*)*(*returnSize)); + arr[*returnSize-1] = (int*)malloc(sizeof(int)*size); + queue1 = (struct TreeNode*)realloc(queue1, sizeof(struct TreeNode*)*2*size); + int index = 0; + for(int i = 0; i < size; i++) + { + arr[*returnSize-1][i] = queue0[i]->val; + if(queue0[i]->left) + queue1[index++] = queue0[i]->left; + if(queue0[i]->right) + queue1[index++] = queue0[i]->right; + } + struct TreeNode** t = queue0; queue0 = queue1; queue1 = t; + size = index; + } + return arr; +} diff --git a/LuoSonglei/week-92/BTLevelOrderTraversal2.c b/LuoSonglei/week-92/BTLevelOrderTraversal2.c new file mode 100644 index 0000000..34ad497 --- /dev/null +++ b/LuoSonglei/week-92/BTLevelOrderTraversal2.c @@ -0,0 +1,52 @@ +/******************************************* +Author : LHearen +E-mail : LHearen@126.com +Time : 2016-02-18 21:06 +Description : +Source : https://leetcode.com/problems/binary-tree-level-order-traversal-ii/ +*******************************************/ +struct TreeNode +{ + int val; + struct TreeNod *left, *right; +}; +#include +//AC - 0ms; +int** levelOrderBottom(struct TreeNode* root, int** colSize, int* returnSize) +{ + if(!root) return NULL; + struct TreeNode** queue0 = (struct TreeNode*)malloc(sizeof(struct TreeNode*)); + struct TreeNode** queue1 = (struct TreeNode*)malloc(sizeof(struct TreeNode*)); + int size = 1; + queue0[0] = root; + int **arr = (int**)malloc(sizeof(int*)); //before revoking realloc, we have to provide an address first; + *returnSize = 0; + while(size) + { + *returnSize += 1; + *colSize = (int*)realloc(*colSize, sizeof(int)*(*returnSize)); + (*colSize)[*returnSize-1] = size; + arr = (int**)realloc(arr, sizeof(int*)*(*returnSize)); + arr[*returnSize-1] = (int*)malloc(sizeof(int)*size); + queue1 = (struct TreeNode*)realloc(queue1, sizeof(struct TreeNode*)*2*size); + int index = 0; + for(int i = 0; i < size; i++) + { + arr[*returnSize-1][i] = queue0[i]->val; + if(queue0[i]->left) + queue1[index++] = queue0[i]->left; + if(queue0[i]->right) + queue1[index++] = queue0[i]->right; + } + struct TreeNode** t = queue0; queue0 = queue1; queue1 = t; + size = index; + } + size = *returnSize; + for(int i = 0; i < size/2; i++) + { + int t0 = (*colSize)[i]; (*colSize)[i]=(*colSize)[size-i-1]; (*colSize)[size-i-1]=t0; + int *t1 = arr[i]; arr[i]=arr[size-i-1]; arr[size-i-1]=t1; + } + return arr; +} + diff --git a/LuoSonglei/week-92/BinarySearchTreeIterator.c b/LuoSonglei/week-92/BinarySearchTreeIterator.c new file mode 100644 index 0000000..035e662 --- /dev/null +++ b/LuoSonglei/week-92/BinarySearchTreeIterator.c @@ -0,0 +1,58 @@ +/******************************************* +Author : LHearen +E-mail : LHearen@126.com +Time : 2016-02-20 09:16 +Description : +Source : https://leetcode.com/problems/binary-search-tree-iterator/ +*******************************************/ +struct TreeNode +{ + int val; + struct TreeNode *left, *right; +}; + +#define LEN 100 +struct BSTIterator +{ + struct TreeNode** stack; + int size; +}; + +void collectLeft(struct TreeNode* root, struct BSTIterator* t) +{ + for(struct TreeNode* l=root; l; l=l->left) + { + /*t->stack = (struct TreeNode**)realloc(t->stack, sizeof(struct TreeNode*)*(t->size+1));*/ + t->stack[(t->size)++] = l; + } +} + +//AC - 16ms; - using a fixed size is better in this case - removing realloc method; +//AC - 12ms; +struct BSTIterator* bstIteratorCreate(struct TreeNode* root) +{ + struct BSTIterator* t = (struct BSTIterator*)malloc(sizeof(struct BSTIterator)); + t->stack = (struct TreeNode**)malloc(sizeof(struct TreeNode*)*LEN); + t->size = 0; + collectLeft(root, t); + return t; +} + +bool bstIteratorHasNext(struct BSTIterator* iter) +{ + return iter->size; +} + +int bstIteratorNext(struct BSTIterator* iter) +{ + int ret = iter->stack[iter->size-1]->val; + iter->size--; + collectLeft(iter->stack[iter->size]->right, iter); //since the current node is being popped, collecting the next bigger part - its right children; + return ret; +} + +void bstIteratorFree(struct BSTIterator* iter) +{ + free(iter->stack); + free(iter); +} diff --git a/LuoSonglei/week-92/BinaryTreeInorderTraversal.c b/LuoSonglei/week-92/BinaryTreeInorderTraversal.c new file mode 100644 index 0000000..9cb2b06 --- /dev/null +++ b/LuoSonglei/week-92/BinaryTreeInorderTraversal.c @@ -0,0 +1,107 @@ +/******************************************* +Author : LHearen +E-mail : LHearen@126.com +Time : 2016-02-19 15:39 +Description : +Source :https://leetcode.com/problems/binary-tree-inorder-traversal/ +*******************************************/ +struct TreeNode +{ + int val; + struct TreeNode *left, *right; +}; +#include +void traverse(struct TreeNode* root, int** arr, int* returnSize) +{ + if(!root) return ; + if(root->left) + traverse(root->left, arr, returnSize); + *returnSize += 1; + *arr = (int*)realloc(*arr, sizeof(int)*(*returnSize)); + (*arr)[*returnSize-1] = root->val; + if(root->right) + traverse(root->right, arr, returnSize); +} + +//AC - 0ms; +int* inorderTraversal0(struct TreeNode* root, int* returnSize) +{ + if(!root) return NULL; + *returnSize = 0; + int* arr = (int*)malloc(sizeof(int)); + traverse(root, &arr, returnSize); + return arr; +} + + +void collectLeftNodes(struct TreeNode* root, struct TreeNode*** stack, int* size) +{ + while(root) + { + *stack = (struct TreeNode**)realloc(*stack, sizeof(struct TreeNode*)*(*size+1)); + (*stack)[(*size)++] = root; + root = root->left; + } +} +//AC - 0ms; +int* inorderTraversal1(struct TreeNode* root, int* returnSize) +{ + if(!root) return NULL; + int* arr = (int*)malloc(sizeof(int)); + *returnSize = 0; + struct TreeNode** stack = (struct TreeNode**)malloc(sizeof(struct TreeNode*)); + int size = 0; //the size of the stack index of top=size-1; + collectLeftNodes(root, &stack, &size); + while(size) + { + root = stack[size-1]; + size--; + *returnSize += 1; + arr = (int*)realloc(arr, sizeof(int)*(*returnSize)); + arr[*returnSize-1] = root->val; //collecting the leftmost; + root = root->right; //preparing to collect the right children of the leftmost node; + collectLeftNodes(root, &stack, &size); + } + return arr; +} + +//http://stackoverflow.com/questions/5502916/explain-morris-inorder-tree-traversal-without-using-stacks-or-recursion +//http://www.cnblogs.com/AnnieKim/archive/2013/06/15/MorrisTraversal.html +//AC - 0ms; +//non-recursion and non-stack; +int* inorderTraversal(struct TreeNode* root, int* returnSize) +{ + if(!root) return NULL; + int* arr = (int*)malloc(sizeof(int)); + *returnSize = 0; + while(root) + { + if(!root->left) + { + *returnSize += 1; + arr = (int*)realloc(arr, sizeof(int)*(*returnSize)); + arr[*returnSize-1] = root->val; + root = root->right; + } + else + { + struct TreeNode *pre = root->left; //check whether the current has been traversed; + while(pre->right && pre->right != root) + pre = pre->right; + if(!pre->right)//not traversed before, connect the current to the rightmost of the left child for later traversal; + { + pre->right = root; + root = root->left; + } + else //traversed before and now it's time to record its value; + { + *returnSize += 1; + arr = (int*)realloc(arr, sizeof(int)*(*returnSize)); + arr[*returnSize-1] = root->val; + pre->right = NULL; //restore the modified node; + root = root->right; + } + } + } + return arr; +} diff --git a/LuoSonglei/week-92/BinaryTreeMaxPathSum.c b/LuoSonglei/week-92/BinaryTreeMaxPathSum.c new file mode 100644 index 0000000..4b166bb --- /dev/null +++ b/LuoSonglei/week-92/BinaryTreeMaxPathSum.c @@ -0,0 +1,36 @@ +/******************************************* +Author : LHearen +E-mail : LHearen@126.com +Time : 2016-02-20 20:05 +Description : +Source : https://leetcode.com/problems/binary-tree-maximum-path-sum/ +*******************************************/ +#define MAX(a, b) ((a) > (b)? (a) : (b)) +struct TreeNode +{ + int val; + struct TreeNode *left, *right; +}; + +int max(int a, int b) +{ + return a > b? a : b; +} + +//return the max sum ended with root and refresh *max accordingly; +int helper(struct TreeNode* root, int* Max) +{ + if(!root) return 0; + int lMax = max(0, helper(root->left, Max)); //if the result of helper in left is negative, select nothing; + int rMax = max(0, helper(root->right, Max)); + *Max = max(*Max, lMax+root->val+rMax); + return max(lMax, rMax)+root->val; +} +//AC - 16ms; +int maxPathSum(struct TreeNode* root) +{ + if(!root) return 0; + int max = 0; + helper(root, &max); + return max; +} diff --git a/LuoSonglei/week-92/BinaryTreePostorderTraversal.c b/LuoSonglei/week-92/BinaryTreePostorderTraversal.c new file mode 100644 index 0000000..5266410 --- /dev/null +++ b/LuoSonglei/week-92/BinaryTreePostorderTraversal.c @@ -0,0 +1,124 @@ +/******************************************* +Author : LHearen +E-mail : LHearen@126.com +Time : 2016-02-20 15:08 +Description : +Source : https://leetcode.com/problems/binary-tree-postorder-traversal/ +*******************************************/ +struct TreeNode +{ + int val; + struct TreeNode *left, *right; +}; +#include +void traverse(struct TreeNode* root, int** arr, int* returnSize) +{ + if(root->left) + traverse(root->left, arr, returnSize); + if(root->right) + traverse(root->right, arr, returnSize); + *returnSize += 1; + *arr = (int*)realloc(*arr, sizeof(int)*(*returnSize)); + (*arr)[*returnSize-1] = root->val; +} + +//AC - 0ms; +int* postorderTraversal0(struct TreeNode* root, int* returnSize) +{ + if(!root) return NULL; + int* arr = (int*)malloc(sizeof(int)); + *returnSize = 0; + traverse(root, &arr, returnSize); + return arr; +} + +//AC - 0ms; +int* postorderTraversal1(struct TreeNode* root, int* returnSize) +{ + if(!root) return NULL; + int* arr = (int*)malloc(sizeof(int)); + *returnSize = 0; + struct TreeNode** stack = (struct TreeNode**)malloc(sizeof(struct TreeNode*)); + int size = 0; + stack[size++] = root; + while(size) + { + root = stack[size-1]; + size--; + *returnSize += 1; + arr = (int*)realloc(arr, sizeof(int)*(*returnSize)); + arr[*returnSize-1] = root->val; + if(root->left) + { + size++; + stack = (struct TreeNode**)realloc(stack, sizeof(struct TreeNode*)*size); + stack[size-1] = root->left; + } + if(root->right) + { + size++; + stack = (struct TreeNode**)realloc(stack, sizeof(struct TreeNode*)*size); + stack[size-1] = root->right; + } + } + size = *returnSize; + for(int i = 0; i < size/2; i++)//reverse the previous result - mid+right+left customized preorder; + { + int t=arr[i]; arr[i]=arr[size-i-1]; arr[size-i-1]=t; + } + return arr; +} + +//AC - 0ms; +#define LEN 1000 +int* postorderTraversal(struct TreeNode* root, int* returnSize) +{ + if(!root) return NULL; + int* arr = (int*)malloc(sizeof(int)*LEN); + *returnSize = 0; + struct TreeNode** stack = (struct TreeNode**)malloc(sizeof(struct TreeNode*)*LEN); + int size = 0; + stack[size++] = root; + struct TreeNode* pre = NULL; //either the parent or the child of cur; + while(size) + { + struct TreeNode *cur = stack[size-1]; + if(!pre || pre->left==cur || pre->right==cur) //pushing only one child to the stack each time; + //from the current node to collect the children; + { + if(cur->left) + stack[size++] = cur->left; + else + { + if(cur->right) + stack[size++] = cur->right; + else + { + *returnSize += 1; + arr[*returnSize-1] = cur->val; + size--; + } + } + } + //start to collect the right part from bottom to top; + else if(cur->left == pre) //left part has been handled; + { + if(cur->right) + stack[size++] = cur->right; + else + { + *returnSize += 1; + arr[*returnSize-1] = cur->val; + size--; + } + } + else if(cur->right == pre) + { + *returnSize += 1; + arr[*returnSize-1] = cur->val; + size--; + } + pre = cur; + } + return arr; +} diff --git a/LuoSonglei/week-92/BinaryTreePreorderTraversal.c b/LuoSonglei/week-92/BinaryTreePreorderTraversal.c new file mode 100644 index 0000000..8923e06 --- /dev/null +++ b/LuoSonglei/week-92/BinaryTreePreorderTraversal.c @@ -0,0 +1,106 @@ +/******************************************* +Author : LHearen +E-mail : LHearen@126.com +Time : 2016-02-19 16:17 +Description : +Source : https://leetcode.com/problems/binary-tree-preorder-traversal/ +*******************************************/ +#include +struct TreeNode +{ + int val; + struct TreeNode *left, *right; +}; + +void traverse(struct TreeNode* root, int** arr, int* returnSize) +{ + *returnSize += 1; + *arr = (int*)realloc(*arr, sizeof(int)*(*returnSize)); + (*arr)[*returnSize-1] = root->val; + if(root->left) + traverse(root->left, arr, returnSize); + if(root->right) + traverse(root->right, arr, returnSize); +} +//AC - 0ms; +int* preorderTraversal0(struct TreeNode* root, int* returnSize) +{ + if(!root) return NULL; + int* arr = (int*)malloc(sizeof(int)); + *returnSize = 0; + traverse(root, &arr, returnSize); + return arr; +} + +void storeAndCollectLeftNodes(struct TreeNode* root, struct TreeNode*** stack, int* size, int** arr, int* returnSize) +{ + while(root) + { + *returnSize += 1; + *arr = (int*)realloc(*arr, sizeof(int)*(*returnSize)); + (*arr)[*returnSize-1] = root->val; + *stack = (struct TreeNode**)realloc(*stack, sizeof(struct TreeNode*)*(*size+1)); + *size += 1; + (*stack)[*size-1] = root; + root = root->left; + } +} + +//AC - 0ms; +int* preorderTraversal1(struct TreeNode* root, int* returnSize) +{ + if(!root) return NULL; + int* arr = (int*)malloc(sizeof(int)); + *returnSize = 0; + struct TreeNode** stack = (struct TreeNode**)malloc(sizeof(struct TreeNode*)); + int size = 0; + storeAndCollectLeftNodes(root, &stack, &size, &arr, returnSize); + while(size) + { + root = stack[size-1]; + size--; + if(root->right) //handle the right children of leftmost nodes; + storeAndCollectLeftNodes(root->right, &stack, &size, &arr, returnSize); + } + return arr; +} + + +//AC - 0ms; +//Using Morris Traversal to traverse in preorder; +int* preorderTraversal(struct TreeNode* root, int* returnSize) +{ + if(!root) return NULL; + int* arr = (int*)malloc(sizeof(int)); + *returnSize = 0; + while(root) + { + if(!root->left) + { + *returnSize += 1; + arr = (int*)realloc(arr, sizeof(int)*(*returnSize)); + arr[*returnSize-1] = root->val; + root = root->right; + } + else + { + struct TreeNode* pre = root->left; + while(pre->right && pre->right!=root) + pre = pre->right; + if(!pre->right) //before moving to the left, collect it now; + { + *returnSize += 1; + arr = (int*)realloc(arr, sizeof(int)*(*returnSize)); + arr[*returnSize-1] = root->val; + pre->right = root; + root = root->left; + } + else + { + pre->right = NULL; //restore the modified nodes; + root = root->right; + } + } + } + return arr; +} diff --git a/LuoSonglei/week-92/BinaryTreeRightSideView.c b/LuoSonglei/week-92/BinaryTreeRightSideView.c new file mode 100644 index 0000000..19b0b8f --- /dev/null +++ b/LuoSonglei/week-92/BinaryTreeRightSideView.c @@ -0,0 +1,42 @@ +/******************************************* +Author : LHearen +E-mail : LHearen@126.com +Time : 2016-02-19 16:44 +Description : +Source : https://leetcode.com/problems/binary-tree-right-side-view/ +*******************************************/ +struct TreeNode +{ + int val; + struct TreeNode *left, *right; +}; +#include +//AC - 0ms; +int* rightSideView(struct TreeNode* root, int* returnSize) +{ + if(!root) return NULL; + int* arr = (int*)malloc(sizeof(int)); + *returnSize = 0; + struct TreeNode** queue0 = (struct TreeNode**)malloc(sizeof(struct TreeNode*)); + struct TreeNode** queue1 = (struct TreeNode**)malloc(sizeof(struct TreeNode*)); + int size=1, count=0; + queue0[size-1] = root; + while(size) + { + count = 0; + queue1 = (struct TreeNode**)realloc(queue1, sizeof(struct TreeNode*)*2*size); + for(int i = 0; i < size; i++) + { + if(queue0[i]->left) + queue1[count++] = queue0[i]->left; + if(queue0[i]->right) + queue1[count++] = queue0[i]->right; + } + *returnSize += 1; + arr = (int*)realloc(arr, sizeof(int)*(*returnSize)); + arr[*returnSize-1] = queue0[size-1]->val; + struct TreeNode** t = queue0; queue0=queue1; queue1=t; + size = count; + } + return arr; +} diff --git a/LuoSonglei/week-92/BurstBalloons.c b/LuoSonglei/week-92/BurstBalloons.c new file mode 100644 index 0000000..71e6a5b --- /dev/null +++ b/LuoSonglei/week-92/BurstBalloons.c @@ -0,0 +1,34 @@ +/******************************************* +Author : LHearen +E-mail : LHearen@126.com +Time : 2016-02-17 21:14 +Description : +Source : https://leetcode.com/problems/burst-balloons/ +*******************************************/ +//AC - 12ms; +int maxCoins(int* nums, int size) +{ + int *nums1 = (int*)malloc(sizeof(int)*(size+2)); + nums1[0] = nums1[size+1] = 1; + for(int i = 0; i < size; i++) + nums1[i+1] = nums[i]; + size += 2; + int** maxs = (int**)malloc(sizeof(int*)*size); //maxs store the max result between index i and j exclusively; + for(int i = 0; i < size; i++) + { + maxs[i] = (int*)malloc(sizeof(int)*size); + memset(maxs[i], 0, sizeof(int)*size); + } + for(int i = 2; i < size; i++) //start from length - 2 till length - size-1; + for(int left = 0; left+i < size; left++) + { + int right = left+i; + for(int j = left+1; j < right; j++) + { + int t = maxs[left][j]+maxs[j][right]+nums1[left]*nums1[right]*nums1[j]; + if(t > maxs[left][right]) + maxs[left][right] = t; + } + } + return maxs[0][size-1]; //the max between the first and last - extra 1; +} diff --git a/LuoSonglei/week-92/ConstructBTFromInorderAndPostorder.c b/LuoSonglei/week-92/ConstructBTFromInorderAndPostorder.c new file mode 100644 index 0000000..341205b --- /dev/null +++ b/LuoSonglei/week-92/ConstructBTFromInorderAndPostorder.c @@ -0,0 +1,27 @@ +/******************************************* +Author : LHearen +E-mail : LHearen@126.com +Time : 2016-02-19 21:15 +Description : +Source : https://leetcode.com/problems/construct-binary-tree-from-inorder-and-postorder-traversal/ +*******************************************/ +struct TreeNode +{ + int val; + struct TreeNode *left, *right; +}; +#include +//AC - 20ms; +struct TreeNode* buildTree(int* inorder, int inSize, int* postorder, int postSize) +{ + if(inSize==0) return NULL; + int cur = 0; + for(; cur < inSize; cur++) + if(postorder[postSize-1] == inorder[cur]) + break; + struct TreeNode *root = (struct TreeNode*)malloc(sizeof(struct TreeNode)); + root->val = inorder[cur]; + root->left = buildTree(inorder, cur, postorder, cur); + root->right = buildTree(inorder+cur+1, inSize-cur-1, postorder+cur, inSize-cur-1); + return root; +} diff --git a/LuoSonglei/week-92/ConvertSortedArray2HeightBalancedBST.c b/LuoSonglei/week-92/ConvertSortedArray2HeightBalancedBST.c new file mode 100644 index 0000000..bcdbda4 --- /dev/null +++ b/LuoSonglei/week-92/ConvertSortedArray2HeightBalancedBST.c @@ -0,0 +1,38 @@ +/******************************************* +Author : LHearen +E-mail : LHearen@126.com +Time : 2016-02-20 08:23 +Description : +Source : https://leetcode.com/problems/convert-sorted-array-to-binary-search-tree/ +*******************************************/ +struct TreeNode +{ + int val; + struct TreeNode *left, *right; +}; +#include +//AC - 4ms; +struct TreeNode* sortedArrayToBST(int* nums, int size) +{ + if(!size) return NULL; + int mid = (size-1)>>1; //get the mid of the index part instead of size; + struct TreeNode* root = (struct TreeNode*)malloc(sizeof(struct TreeNode)); + root->val = nums[mid]; + root->left = sortedArrayToBST(nums, mid); + root->right = sortedArrayToBST(nums+mid+1, size-mid-1); + return root; +} + +//AC - 4ms; +struct TreeNode* sortedArrayToBST(int* nums, int size) +{ + if(!size) return NULL; + int mid = size>>1; //get the mid from the size; + struct TreeNode* root = (struct TreeNode*)malloc(sizeof(struct TreeNode)); + root->val = nums[mid]; + root->left=root->right=NULL; + if(size==1) return root; + root->left = sortedArrayToBST(nums, mid); + root->right = sortedArrayToBST(nums+mid+1, size-mid-1); //if size==1 nums+mid+1 will cross the line and result as error; + return root; +} diff --git a/LuoSonglei/week-92/CountCompleteTreeNodes.c b/LuoSonglei/week-92/CountCompleteTreeNodes.c new file mode 100644 index 0000000..97ae1f2 --- /dev/null +++ b/LuoSonglei/week-92/CountCompleteTreeNodes.c @@ -0,0 +1,74 @@ +/******************************************* +Author : LHearen +E-mail : LHearen@126.com +Time : 2016-02-19 19:53 +Description : +Source : https://leetcode.com/problems/count-complete-tree-nodes/ +*******************************************/ +struct TreeNode +{ + int val; + struct TreeNode *left, *right; +}; + + +//this traversal will slow the whole operation down dramatically; +//since it's a complete tree - TLE; +int traverse(struct TreeNode* root) +{ + if(!root->left && !root->right) return 1; + int sum = 1; + if(root->left) + sum += traverse(root->left); + if(root->right) + sum += traverse(root->right); + return sum; +} + + +int countNodes0(struct TreeNode* root) +{ + if(!root) return 0; + int lHeight=0, rHeight=0; + struct TreeNode* t = root; + while(t) + { + t = t->left; + lHeight++; + } + t = root; + while(t) + { + t = t->right; + rHeight++; + } + if(lHeight==rHeight) return (1<left); +} + +//AC - 152ms; +int countNodes1(struct TreeNode* root) +{ + if(!root) return 0; + int lHeight = leftHeight(root->left); + int rHeight = leftHeight(root->right); + return lHeight == rHeight? pow(2, lHeight)-1 : (1 << rHeight) + countNodes(root->left); +} + +//AC - 144ms; +int countNodes(struct TreeNode* root) +{ + if(!root) return 0; + int lHeight=0, rHeight=0; + for(struct TreeNode* l=root; l; l=l->left) lHeight++; + for(struct TreeNode* r=root; r; r=r->right) rHeight++; + if(lHeight==rHeight) return (1<left)+countNodes(root->right)+1; +} + diff --git a/LuoSonglei/week-92/DungeonGame.c b/LuoSonglei/week-92/DungeonGame.c new file mode 100644 index 0000000..087fba7 --- /dev/null +++ b/LuoSonglei/week-92/DungeonGame.c @@ -0,0 +1,64 @@ +/******************************************* +Author : LHearen +E-mail : LHearen@126.com +Time : 2016-02-17 13:52 +Description : +Source : https://leetcode.com/problems/dungeon-game/ +*******************************************/ +#include +#define MAX(a, b) ((a) > (b) ? (a) : (b)) +#define MIN(a, b) ((a) < (b) ? (a) : (b)) +//AC - 8ms; +int calculateMinimumHP0(int** dungeon, int rSize, int cSize) +{ + int** mins = (int**)malloc(sizeof(int*)*rSize); + for(int i = 0; i < rSize; i++) + { + mins[i] = (int*)malloc(sizeof(int)*cSize); + memset(mins[i], 0, sizeof(int)*cSize); + } + for(int i = rSize-1; i >= 0; i--) + for(int j = cSize-1; j >= 0; j--) + { + if(i==rSize-1 && j==cSize-1) + mins[i][j] = MAX(1, 1-dungeon[i][j]); + else if(i == rSize-1) + mins[i][j] = MAX(1, mins[i][j+1]-dungeon[i][j]); + else if(j == cSize-1) + mins[i][j] = MAX(1, mins[i+1][j]-dungeon[i][j]); + else + mins[i][j] = MAX(1, MIN(mins[i+1][j], mins[i][j+1])-dungeon[i][j]); + } + return mins[0][0]; +} + +//AC - 8ms - reduce the different conditions by adding an edge; +int calculateMinimumHP1(int** dungeon, int rSize, int cSize) +{ + int** mins = (int**)malloc(sizeof(int*)*(rSize+1)); + for(int i = 0; i <=rSize; i++) + mins[i] = (int*)malloc(sizeof(int)*(cSize+1)); + for(int i = 0; i <= rSize; i++) + mins[i][cSize] = INT_MAX; + for(int i = 0; i <= cSize; i++) + mins[rSize][i] = INT_MAX; + mins[rSize-1][cSize] = 1; //for the very start - mins[rSize-1][cSize-1]; + mins[rSize][cSize-1] = 1; + for(int i = rSize-1; i >= 0; i--) + for(int j = cSize-1; j >= 0; j--) + mins[i][j] = MAX(1, MIN(mins[i+1][j], mins[i][j+1])-dungeon[i][j]); + return mins[0][0]; +} + +//AC - 8ms; +int calculateMinimumHP(int** dungeon, int rSize, int cSize) +{ + int *mins = (int*)malloc(sizeof(int)*(cSize+1)); + for(int i = 0; i <= cSize; i++) + mins[i] = INT_MAX; + mins[cSize-1] = 1; + for(int i = rSize-1; i >= 0; i--) + for(int j = cSize-1; j >= 0; j--) + mins[j] = MAX(1, MIN(mins[j], mins[j+1])-dungeon[i][j]); + return mins[0]; +} diff --git a/LuoSonglei/week-92/EditDistance.c b/LuoSonglei/week-92/EditDistance.c new file mode 100644 index 0000000..e3df43d --- /dev/null +++ b/LuoSonglei/week-92/EditDistance.c @@ -0,0 +1,61 @@ +/******************************************* +Author : LHearen +E-mail : LHearen@126.com +Time : 2016-02-17 10:08 +Description : +Source : https://leetcode.com/problems/edit-distance/ +*******************************************/ +int min(int a, int b, int c) +{ + if(a > b) + return b < c? b : c; + else + return a < c? a : c; +} + +//AC - 12ms; +int minDistance0(char* s1, char* s2) +{ + int len1=strlen(s1), len2=strlen(s2); + int **mins = (int**)malloc(sizeof(int*)*(len1+1)); + for(int i = 0; i <= len1; i++) + { + mins[i] = (int*)malloc(sizeof(int)*(len2+1)); + memset(mins[i], 0, sizeof(int)*(len2+1)); + } + for(int i = 0; i <= len1; i++) + mins[i][0] = i; + for(int i = 0; i <= len2; i++) + mins[0][i] = i; + for(int i = 1; i <= len1; i++) + for(int j = 1; j <= len2; j++) + { + if(s1[i-1] == s2[j-1]) + mins[i][j] = mins[i-1][j-1]; + else + mins[i][j] = min(mins[i-1][j], mins[i][j-1], mins[i-1][j-1]) + 1; + } + return mins[len1][len2]; +} + +//AC - 12ms; +int minDistance(char* s1, char* s2) +{ + int len1=strlen(s1), len2=strlen(s2); + int *cur = (int*)malloc(sizeof(int)*(len2+1)); + int pre = 0; + for(int i = 0; i <= len2; i++) + cur[i] = i; + for(int i = 1; i <= len1; i++) + { + pre = cur[0]; + for(int j = 1; j <= len2; j++) + { + int t = cur[j]; //store the previous value of the previous row before being overwrittern; + cur[j] = s1[i-1] == s2[j-1]? pre : min(cur[j-1], cur[j], pre) + 1; + pre = t; + } + cur[0] = i; + } + return cur[len2]; +} diff --git a/LuoSonglei/week-92/FlattenBinaryTree2LinkedList.c b/LuoSonglei/week-92/FlattenBinaryTree2LinkedList.c new file mode 100644 index 0000000..21aeb38 --- /dev/null +++ b/LuoSonglei/week-92/FlattenBinaryTree2LinkedList.c @@ -0,0 +1,34 @@ +/******************************************* +Author : LHearen +E-mail : LHearen@126.com +Time : 2016-02-19 19:20 +Description : +Source : https://leetcode.com/problems/flatten-binary-tree-to-linked-list/ +*******************************************/ +struct TreeNode +{ + int val; + struct TreeNode *left, *right; +}; + +#include +struct TreeNode* traverseLeft(struct TreeNode* root) +{ + if(!root->left &&!root->right) return root; + struct TreeNode* t = root->right; + root->right = root->left; + struct TreeNode *leftmost = root; //in case of NULL left; + if(root->left) + leftmost = traverseLeft(root->left); + root->left = NULL; //make sure all the left pointer is NULL; + leftmost->right = t; //using the leftmost pointer to connect the right children; + if(t) + traverseLeft(t); +} + +//AC - 4ms; +void flatten(struct TreeNode* root) +{ + if(!root) return ; + traverseLeft(root); +} diff --git a/LuoSonglei/week-92/GasStation.c b/LuoSonglei/week-92/GasStation.c new file mode 100644 index 0000000..db8de6f --- /dev/null +++ b/LuoSonglei/week-92/GasStation.c @@ -0,0 +1,24 @@ +/******************************************* +Author : LHearen +E-mail : LHearen@126.com +Time : 2016-02-20 20:42 +Description : +Source : https://leetcode.com/problems/gas-station/ +*******************************************/ +//AC - 0ms; +//https://leetcode.com/discuss/87765/clean-simple-solution-well-explained-accepted-submission +int canCompleteCircuit(int* gas, int gSize, int* cost, int cSize) +{ + int index=-1, total=0, max=-1; + for(int i = cSize-1; i > -1; i--) + { + total += gas[i]-cost[i]; + if(total > max) + { + index=i; + max=total; + } + } + return total < 0? -1 : index; +} + diff --git a/LuoSonglei/week-92/InterleavingString.c b/LuoSonglei/week-92/InterleavingString.c new file mode 100644 index 0000000..e0312c5 --- /dev/null +++ b/LuoSonglei/week-92/InterleavingString.c @@ -0,0 +1,32 @@ +/******************************************* +Author : LHearen +E-mail : LHearen@126.com +Time : 2016-02-16 15:44 +Description : +Source : https://leetcode.com/problems/interleaving-string/ +*******************************************/ +#include +//AC - 0ms - DP solution; +bool isInterleave(char* s1, char* s2, char* s3) +{ + int len1=strlen(s1), len2=strlen(s2); + if(!len1 || !len2) return !strcmp(s1, s3) || !strcmp(s2, s3); + if(strlen(s3) != len1+len2) return false; + bool* cur=(bool*)malloc(sizeof(bool)*(len2+1)); + bool* pre=(bool*)malloc(sizeof(bool)*(len2+1)); + memset(pre, 0, sizeof(bool)*(len2+1)); + pre[0] = true; //initialize boundary condition; + for(int i = 1; i <= len2; i++) + if(s2[i-1] == s3[i-1]) + pre[i] = true; + else + break; + for(int i = 1; i <= len1; i++) //i and j represent length of s1 and s2 respectively; + { + for(int j = 0; j <= len2; j++) + cur[j] = (j>0 && cur[j-1] && s2[j-1]==s3[i+j-1]) || + (pre[j] && s1[i-1]==s3[i+j-1]); + bool *t = pre; pre = cur; cur = t; + } + return pre[len2]; +} diff --git a/LuoSonglei/week-92/JumpGame.c b/LuoSonglei/week-92/JumpGame.c new file mode 100644 index 0000000..bbdc359 --- /dev/null +++ b/LuoSonglei/week-92/JumpGame.c @@ -0,0 +1,60 @@ +/******************************************* +Author : LHearen +E-mail : LHearen@126.com +Time : 2016-02-20 20:56 +Description : +Source : https://leetcode.com/problems/jump-game/ +*******************************************/ +#include +//TLE; +bool canJump0(int* nums, int size) +{ + bool* jumpable = (bool*)malloc(sizeof(bool)*size); + memset(jumpable, 0, sizeof(bool)*size); + for(int i = size-1; i > -1; i--) + { + int len = nums[i]; + for(int j = 1; j <= len; j++) + { + if(i+j >= size) jumpable[i] = true; + else if(jumpable[i+j]) + { + jumpable[i] = true; + break; + } + } + } + return jumpable[0]; +} + +//AC - 4ms; +bool canJump1(int* nums, int size) +{ + if(size < 2) return true; + for(int cur=size-2; cur > -1; cur--) + { + if(nums[cur] == 0) + { + int len = 1; + while(len > nums[cur]) + { + len++; + cur--; + if(cur < 0) return false; + } + } + } + return true; +} + +//AC - 4ms; +bool canJump(int* nums, int size) +{ + int max = 0; + for(int i = 0; i < size; i++, max--) + { + max = max > nums[i]? max : nums[i]; + if(max<1 && i!=size-1) return false; + } + return true; +} diff --git a/LuoSonglei/week-92/LongestValidParentheses.c b/LuoSonglei/week-92/LongestValidParentheses.c new file mode 100644 index 0000000..19fdcad --- /dev/null +++ b/LuoSonglei/week-92/LongestValidParentheses.c @@ -0,0 +1,105 @@ +/******************************************* +Author : LHearen +E-mail : LHearen@126.com +Time : 2016-02-16 09:59 +Description : +Source : https://leetcode.com/problems/longest-valid-parentheses/ +*******************************************/ +//TLE; +int longestValidParentheses0(char* s) +{ + int len = strlen(s); + if(len < 2) return 0; + int max = 0; + for(int i = 0; i < len; i++) + { + if(s[i] == '(') + { + int leftCount = 0; + int count = 0; + for(int j = i; j < len; j++) + { + if(s[j] == '(') + leftCount++; + else + { + if(leftCount) + count += 2; + leftCount--; + } + if(count > max) + max = count; + if(leftCount < 0) + break; + } + } + } + return max; +} + +//AC - 4ms; +int longestValidParentheses1(char* s) +{ + int len = strlen(s); + int *stack = (int*)malloc(sizeof(int)*len); + int top = -1; + stack[++top] = -1; + int max = 0; + for(int i = 0; i < len; i++) + { + int t = stack[top]; + if(t!=-1 && s[i]==')' && s[t]=='(') + { + top--; + if(i-stack[top] > max) + max = i-stack[top]; + } + else + stack[++top] = i; + } + return max; +} + +//AC - 0ms - DP solution; +int longestValidParentheses2(char* s) +{ + int len = strlen(s); + if(len < 2) return 0; + int max = 0; + int *maxs = (int*)malloc(sizeof(int)*len); //record the max viable length ending with the current; + memset(maxs, 0, sizeof(int)*len); + for(int i = 1; i < len; i++) + { + if(s[i] == ')') + { + if(s[i-1] == '(') + { + maxs[i] = 2; + if(i > 1) + maxs[i] = 2+maxs[i-2]; + } + else if(i-maxs[i-1] > 0 && s[i-maxs[i-1]-1] == '(') + maxs[i] = maxs[i-1] + maxs[i-maxs[i-1]-2] + 2; + if(maxs[i] > max) + max = maxs[i]; + } + } + return max; +} + +//AC - 0ms - optimized DP solution - more terse and clean; +int longestValidParentheses(char* s) +{ + int len = strlen(s); + int max = 0; + int *maxs = (int*)malloc(sizeof(int)*len); //record the max viable length ending with the current; + memset(maxs, 0, sizeof(int)*len); + for(int i = 1; i < len; i++) + if(s[i] == ')') + { + int t = i-maxs[i-1]; + if(s[t-1] == '(') maxs[i] = maxs[i-1] + maxs[t-2] + 2; + if(maxs[i] > max) max = maxs[i]; + } + return max; +} diff --git a/LuoSonglei/week-92/MinDepthBT.c b/LuoSonglei/week-92/MinDepthBT.c new file mode 100644 index 0000000..2ccb930 --- /dev/null +++ b/LuoSonglei/week-92/MinDepthBT.c @@ -0,0 +1,56 @@ +/******************************************* +Author : LHearen +E-mail : LHearen@126.com +Time : 2016-02-18 19:45 +Description : +Source : https://leetcode.com/problems/minimum-depth-of-binary-tree/ +*******************************************/ +#include +struct TreeNode +{ + int val; + struct TreeNod *left, *right; +}; +//AC - 8ms; +int minDepth0( struct TreeNode* root ) +{ + if(!root) return 0; + if(!root->left && !root->right) return 1; + int lDepth=INT_MAX, rDepth=INT_MAX; //the current node is not a leaf; + if(root->left) + lDepth = minDepth(root->left)+1; + if(root->right) + rDepth = minDepth(root->right)+1; + return lDepth > rDepth? rDepth : lDepth; +} + +//AC - 4ms - level traversing; +int minDepth( struct TreeNode* root ) +{ + if(!root) return 0; + if(!root->left && !root->right) return 1; + struct TreeNode** queue0 = ( struct TreeNode** )malloc(sizeof( struct TreeNode* )); + struct TreeNode** queue1 = ( struct TreeNode** )malloc(sizeof( struct TreeNode* )); + int size = 1; + int level = 1; + queue0[size-1] = root; + while(size) + { + queue1 = ( struct TreeNode** )realloc(queue1, sizeof( struct TreeNode* )*2*size); + int index = 0; + for(int i = 0; i < size; i++) + { + if(!queue0[i]->left && !queue0[i]->right) + return level; + if(queue0[i]->left) + queue1[index++] = queue0[i]->left; + if(queue0[i]->right) + queue1[index++] = queue0[i]->right; + } + level++; //move to the next level; + struct TreeNode** t = queue0; + queue0 = queue1; + queue1 = t; + size = index; + } +} diff --git a/LuoSonglei/week-92/PathSum2.c b/LuoSonglei/week-92/PathSum2.c new file mode 100644 index 0000000..721e863 --- /dev/null +++ b/LuoSonglei/week-92/PathSum2.c @@ -0,0 +1,58 @@ +/******************************************* +Author : LHearen +E-mail : LHearen@126.com +Time : 2016-02-19 14:21 +Description : +Source : https://leetcode.com/problems/path-sum-ii/ +*******************************************/ +#include +struct TreeNode +{ + int val; + struct TreeNode *left, *right; +}; +void traverse(struct TreeNode* root, int sum, struct TreeNode** stack, int top, int*** arr, int** colSize, int* returnSize) +{ + if(!root->left && !root->right) + { + if(root->val == sum) + { + *returnSize += 1; + *arr = (int**)realloc(*arr, sizeof(int*)*(*returnSize)); + *colSize = (int*)realloc(*colSize, sizeof(int)*(*returnSize)); + int size = top+1; + (*colSize)[*returnSize-1] = size; + (*arr)[*returnSize-1] = (int*)malloc(sizeof(int)*size); + for(int i = 0; i < size; i++) + (*arr)[*returnSize-1][i] = (*stack)[i].val; + } + return ; + } + sum -= root->val; + *stack = (struct TreeNode*)realloc(*stack, sizeof(struct TreeNode)*(top+2)); + if(root->left) + { + (*stack)[1+top] = *(root->left); + traverse(root->left, sum, stack, top+1, arr, colSize, returnSize); + } + if(root->right) + { + (*stack)[1+top] = *(root->right); + traverse(root->right, sum, stack, top+1, arr, colSize, returnSize); + } +} + +//AC - 8ms - to realloc an array, we have to provide the address of the array like colSize and arr in this solution; +int** pathSum(struct TreeNode* root, int sum, int** colSize, int* returnSize) +{ + if(!root) return NULL; + int **arr = (int**)malloc(sizeof(int*)); + *colSize = (int*)malloc(sizeof(int*)); + *returnSize = 0; + struct TreeNode* stack = (struct TreeNode*)malloc(sizeof(struct TreeNode)); + int top = -1; + stack[++top] = *root; + traverse(root, sum, &stack, top, &arr, colSize, returnSize); + return arr; +} + diff --git a/LuoSonglei/week-92/PopulatingNextRightPointersInEachNode.c b/LuoSonglei/week-92/PopulatingNextRightPointersInEachNode.c new file mode 100644 index 0000000..49bfcb6 --- /dev/null +++ b/LuoSonglei/week-92/PopulatingNextRightPointersInEachNode.c @@ -0,0 +1,33 @@ +/******************************************* +Author : LHearen +E-mail : LHearen@126.com +Time : 2016-02-19 11:18 +Description : +Source : https://leetcode.com/problems/populating-next-right-pointers-in-each-node/ +*******************************************/ +struct TreeLinkNode +{ + int val; + struct TreeLinkNode *left, *right, *next; +}; +#include +//AC - 4ms; +void connect(struct TreeLinkNode* root) +{ + if(!root || !root->left) return ; + struct TreeLinkNode *p = root, *nextFirst; + root->next = NULL; + while(p && p->left) + { + nextFirst = p->left; + while(p && p->left) + { + p->left->next = p->right; + p->right->next = NULL; + if(p->next) + p->right->next = p->next->left; + p = p->next; + } + p = nextFirst; + } +} diff --git a/LuoSonglei/week-92/PopulatingNextRightPointersInEachNode2.c b/LuoSonglei/week-92/PopulatingNextRightPointersInEachNode2.c new file mode 100644 index 0000000..d8818f2 --- /dev/null +++ b/LuoSonglei/week-92/PopulatingNextRightPointersInEachNode2.c @@ -0,0 +1,55 @@ +/******************************************* +Author : LHearen +E-mail : LHearen@126.com +Time : 2016-02-19 12:21 +Description : +Source : https://leetcode.com/problems/populating-next-right-pointers-in-each-node-ii/ +*******************************************/ +struct TreeLinkNode +{ + int val; + struct TreeLinkNode *left, *right, *next; +}; +#include +//AC - 8ms; +void connect(struct TreeLinkNode* root) +{ + if(!root) return ; + struct TreeLinkNode *p = root, *nextFirst; + while(p) + { + nextFirst = NULL; //defaulted to NULL to jump out the loop; + while(p) //search for the first valid node of the next level; + { + if(p->left) + { + nextFirst = p->left; + break; + } + if(p->right) + { + nextFirst = p->right; + break; + } + p = p->next; + } + struct TreeLinkNode *cur=nextFirst, *next; + while(p) //connect the next level; + { + next = p->left; + if(next && cur!=next) //only valid nodes can be connected and the next cannot be the same with current node; + { + cur->next = next; + cur = next; + } + next = p->right; + if(next && cur!=next) + { + cur->next = next; + cur = next; + } + p = p->next; + } + p = nextFirst; //move to the next level; + } +} diff --git a/LuoSonglei/week-92/RecoverBinarySearchTree.c b/LuoSonglei/week-92/RecoverBinarySearchTree.c new file mode 100644 index 0000000..ff5a33c --- /dev/null +++ b/LuoSonglei/week-92/RecoverBinarySearchTree.c @@ -0,0 +1,38 @@ +/******************************************* +Author : LHearen +E-mail : LHearen@126.com +Time : 2016-02-20 19:19 +Description : +Source : https://leetcode.com/problems/recover-binary-search-tree/ +*******************************************/ +struct TreeNode +{ + int val; + struct TreeNode *left, *right; +}; +#include +void traverse(struct TreeNode* root, struct TreeNode** pre, struct TreeNode** first, struct TreeNode** second) +{ + if(!root) return ; + traverse(root->left, pre, first, second); + if((*pre) && (*pre)->val>root->val) //check whether the previous node is abnormal in in-order traversal; + { + if(!(*first)) //if *first is never used then it should be used to store the bigger; + *first=*pre; + *second = root; //the two swapped nodes can be adjacent and distant; + } + *pre = root; //store the previous node in in-order traversal; + traverse(root->right, pre, first, second); +} +//AC - 20ms; +void recoverTree(struct TreeNode* root) +{ + struct TreeNode *first=NULL, *second=NULL, *pre=NULL; + traverse(root, &pre, &first, &second); + if(first&&second) + { + int t = first->val; + first->val = second->val; + second->val = t; + } +} diff --git a/LuoSonglei/week-92/ScrambleString.c b/LuoSonglei/week-92/ScrambleString.c new file mode 100644 index 0000000..e519e17 --- /dev/null +++ b/LuoSonglei/week-92/ScrambleString.c @@ -0,0 +1,55 @@ +/******************************************* +Author : LHearen +E-mail : LHearen@126.com +Time : 2016-02-15 21:26 +Description : +Source : https://leetcode.com/problems/scramble-string/ +*******************************************/ +#include +bool isnScramble(char* s1, char* s2, int len) +{ + if(!strncmp(s1, s2, len)) return true; + int count[26] = {0}; + for(int i = 0; i < len; i++) //using this method can filter almost all useless traversals; + count[s1[i]-'a']++, count[s2[i]-'a']--; + for(int i = 0; i < 26; i++) + if(count[i]) return false; + for(int i=1; i < len; i++) + if(isnScramble(s1, s2, i) && isnScramble(s1+i, s2+i, len-i) || + isnScramble(s1, s2+len-i, i) && isnScramble(s1+i, s2, len-i)) return true; + return false; +} + +//AC - 0ms - beats 100% submissions; +bool isScramble1(char* s1, char* s2) +{ + int len = strlen(s1); + return isnScramble(s1, s2, len); +} + +//AC - 20ms - beats 100% submissions - DP solution; +bool isScramble(char* s1, char* s2) +{ + int len = strlen(s1); + if(!len) return true; + if(len==1) return *s1==*s2; + bool*** match = (bool***)malloc(sizeof(bool**)*(len+1)); //recording the states for different length of strings starting from index 1 and index 2 respectively; + for(int i = 0; i <= len; i++) + { + match[i] = (bool**)malloc(sizeof(bool*)*len); + for(int j = 0; j < len; j++) + { + match[i][j] = (bool*)malloc(sizeof(bool)*len); + memset(match[i][j], 0, sizeof(bool)*len); + } + } + for(int i = 0; i < len; i++) + for(int j = 0; j < len; j++) + match[1][i][j] = (s1[i] == s2[j]); + for(int size = 2; size <= len; size++) + for(int i = 0; i <= len-size; i++) + for(int j = 0; j <= len-size; j++) + for(int k = 1; k +char* toString(struct TreeNode* node) +{ + printf("inside toString\n"); + if(!node) return "-"; + int val = node->val; + char* s = (char*)malloc(sizeof(char)); + int size = 0; + while(val) + { + size++; + s = (char*)realloc(s, sizeof(char)*(size+1)); + s[size-1] = val%10+'0'; + val /= 10; + } + s[size] = '\0'; + printf("s: %s\n", s); + for(int i = 0; i < size/2; i++) + { + char t = s[i]; s[i] = s[size-i-1]; s[size-i-1] = t; + } + return s; +} + +char* serialize(struct TreeNode* root) +{ + printf("inside serialize\n"); + if(!root) return NULL; + struct TreeNode** arr = (struct TreeNode**)malloc(sizeof(struct TreeNode*)*2); + int pre=0, index = 1; + arr[1] = root; + while(1) + { + int top = index+1; + printf("pre: %d\tindex: %d\ttop: %d\n", pre, index, top); + int count = 0; + arr = (struct TreeNode**)realloc(arr, sizeof(struct TreeNode*)*2*top); + for(int i = pre+1, pre = index; i < top; i++) + { + index = 2*i; + arr[index] = NULL; + if(arr[i]->left) + arr[index] = arr[i]->left, count++; + index = 2*i + 1; + arr[index] = NULL; + if(arr[i]->right) + arr[index] = arr[i]->right, count++; + printf("i: %d\tindex: %d\n", i, index); + } + if(!count) + { + index = pre; + break; + } + pre = index; + } + printf("\n\nindex: %d\ncollecting...\n", index); + char* s = (char*)malloc(sizeof(char)); + for(int i = 1; i <= index; i++) + { + char *t = toString(arr[i]); + printf("i: %d\t%s\n", i, t); + int len = strlen(t); + s = (char*)realloc(s, sizeof(char)*(len+2)); + strcat(s, t); + strcat(s, ","); + } + s[strlen(s)-1] = '\0'; + printf("final result: %s\n", s); + return s; +} + +int toInt(char* s) +{ + int t = 0; + while(*s) + t += 10*t + (*s++)-'0'; + return t; +} +struct TreeNode* deserialize(char* data) +{ + char** arr = (char**)malloc(sizeof(char*)); + int size = 1; + int pre = 0, cur = 0; + while(*(data+cur)) + { + while(*(data+cur) != ',' && *(data+cur)) cur++; + int len = cur-pre; + cur++; + char *t = (char*)malloc(sizeof(char)*(len+1)); + *t = '\0'; + strncpy(t, data+pre, len); + arr = (char**)realloc(arr, sizeof(char*)*(size+1)); + arr[size] = t; + pre = cur; + size++; + } + for(int i = 1; i < size; i++) + { + + } +} diff --git a/LuoSonglei/week-92/SumRoot2LeafNumber.c b/LuoSonglei/week-92/SumRoot2LeafNumber.c new file mode 100644 index 0000000..8e13055 --- /dev/null +++ b/LuoSonglei/week-92/SumRoot2LeafNumber.c @@ -0,0 +1,49 @@ +/******************************************* +Author : LHearen +E-mail : LHearen@126.com +Time : 2016-02-19 08:56 +Description : +Source : https://leetcode.com/problems/sum-root-to-leaf-numbers/ +*******************************************/ +struct TreeNode +{ + int val; + struct TreeNode *left, *right; +}; +void traverse(struct TreeNode* root, struct TreeNode** stack, int* size, int* sum) +{ + if(!root->left && !root->right) + { + int t = (*stack)[0].val; + for(int i=1; i < *size; i++) + t = 10*t + (*stack)[i].val; + *sum += t; + } + if(root->left) + { + *size += 1; + *stack = (struct TreeNode*)realloc(*stack, sizeof(struct TreeNode)*(*size)); + (*stack)[*size-1] = *(root->left); + traverse(root->left, stack, size, sum); + *size -= 1; + } + if(root->right) + { + *size += 1; + *stack = (struct TreeNode*)realloc(*stack, sizeof(struct TreeNode)*(*size)); + (*stack)[*size-1] = *(root->right); + traverse(root->right, stack, size, sum); + *size -= 1; + } +} +//AC - 0ms; +int sumNumbers(struct TreeNode* root) +{ + if(!root) return 0; + int sum = 0; + struct TreeNode* stack = (struct TreeNode*)malloc(sizeof(struct TreeNode)); + int size = 1; + stack[size-1] = *root; + traverse(root, &stack, &size, &sum); + return sum; +} diff --git a/LuoSonglei/week-92/SymmetricTree.c b/LuoSonglei/week-92/SymmetricTree.c new file mode 100644 index 0000000..e08def9 --- /dev/null +++ b/LuoSonglei/week-92/SymmetricTree.c @@ -0,0 +1,76 @@ +/******************************************* +Author : LHearen +E-mail : LHearen@126.com +Time : 2016-02-18 17:02 +Description : +Source : https://leetcode.com/problems/symmetric-tree/ +*******************************************/ +struct TreeNode +{ + int val; + struct TreeNod *left, *right; +}; +#include +struct TreeNode** fillNext( struct TreeNode** stack, int size , int* newSize) +{ + struct TreeNode** t = ( struct TreeNode** )malloc(sizeof( struct TreeNode* )*2*size); + int index = 0; + for(int i = 0; i < size; i++) + { + if(stack[i]) + { + t[index++] = stack[i]->left; + t[index++] = stack[i]->right; + } + } + *newSize = index; + return t; +} + +//AC - 4ms; +bool isSymmetric0( struct TreeNode * root ) +{ + if(!root || (!(root->left) && !(root->right))) return true; + if(!root->left || !root->right) return false; + int count = 1; + struct TreeNode **lStack = ( struct TreeNode** )malloc(sizeof( struct TreeNode* )); + lStack[0] = root->left; + struct TreeNode **rStack = ( struct TreeNode** )malloc(sizeof( struct TreeNode* )); + rStack[0] = root->right; + while(count) + { + int lIndex = 0, rIndex = 0; + for(int i = 0; i < count; i++) + { + if(!lStack[i] || !rStack[count-i-1]) + { + if(!lStack[i] && !rStack[count-i-1]) + continue; + return false; + } + if(lStack[i]->val != rStack[count-i-1]->val) + return false; + } + int lCount=0, rCount=0; + lStack = fillNext(lStack, count, &lCount); + rStack = fillNext(rStack, count, &rCount); + if(lCount != rCount) return false; + count = lCount; + } + return true; +} + + +bool symmetric( struct TreeNode* left, struct TreeNode* right ) +{ + if(!left && !right) return true; + else if(!left || !right) return false; + if(left->val != right->val) return false; + return symmetric(left->right, right->left) && symmetric(left->left, right->right); +} +//AC - 4ms; +bool isSymmetric( struct TreeNode * root ) +{ + if(!root) return true; + return symmetric(root->left, root->right); +} diff --git a/LuoSonglei/week-92/ValidateBST.c b/LuoSonglei/week-92/ValidateBST.c new file mode 100644 index 0000000..4336f0d --- /dev/null +++ b/LuoSonglei/week-92/ValidateBST.c @@ -0,0 +1,36 @@ +/******************************************* +Author : LHearen +E-mail : LHearen@126.com +Time : 2016-02-18 21:25 +Description : +Source : https://leetcode.com/problems/validate-binary-search-tree/ +*******************************************/ +struct TreeNode +{ + int val; + struct TreeNod *left, *right; +}; +#include +void traverse(struct TreeNode* root, int** arr, int* size) +{ + if(root->left) + traverse(root->left, arr, size); + *size += 1; + *arr = (int*)realloc(*arr, sizeof(int)*(*size)); + (*arr)[*size-1] = root->val; + if(root->right) + traverse(root->right, arr, size); +} + +//AC - 8ms; +bool isValidBST(struct TreeNode* root) +{ + if(!root) return true; + int* arr = (int*)malloc(sizeof(int)); + int size = 0; + traverse(root, &arr, &size); + for(int i = 1; i < size; i++) + if(arr[i] <= arr[i-1]) + return false; + return true; +} diff --git a/LuoSonglei/week-92/WordBreak2.c b/LuoSonglei/week-92/WordBreak2.c new file mode 100644 index 0000000..fb31307 --- /dev/null +++ b/LuoSonglei/week-92/WordBreak2.c @@ -0,0 +1,104 @@ +/******************************************* +Author : LHearen +E-mail : LHearen@126.com +Time : 2016-02-17 16:49 +Description : +Source : https://leetcode.com/problems/word-break-ii/ +*******************************************/ +#include +#include +#define MAX(a, b) ((a) > (b) ? (a) : (b)) +#define MIN(a, b) ((a) < (b) ? (a) : (b)) +bool exist(char* s, int len, char** wordDict, int size) +{ + for(int i = 0; i < size; i++) + { + if(strlen(wordDict[i]) == len && !strncmp(wordDict[i], s, len)) + return true; + } + return false; +} + +char* merge(char* s, int len, const char* cur, int total, int space) +{ + printf("inside merge -- cur: %s\t len: %d\n", cur, strlen(cur)); + char* t = (char*)malloc(sizeof(char)*(total+space)); + *t = '\0'; + printf("len: %d\t%s\n", strlen(t), t); + strcat(t, cur); + printf("len: %d\t%s\n", strlen(t), t); + strncat(t, s, len); + if(space) strcat(t, " "); + printf("len: %d\t%s\n", strlen(t), t); + return t; +} + +void buildPath(bool* breakable, char* s, int pos, char** arr, int* returnSize, char* cur, char** wordDict, int size, int min, int max) +{ + printf("begin inside buildPath -- cur: %s\t len: %d\n", cur, strlen(cur)); + printf("current size: %d\n", *returnSize); + for(int i = 0; i < *returnSize; i++) + printf("%s\n", arr[i]); + int len = strlen(s); + for(int i = min; i <= MIN(max, len-pos); i++) + { + int total = i+strlen(cur)+1; + printf("checking len: %d\tmax: %d\tend: %d\n", i, max, len-pos); + if(breakable[i+pos] && exist(s+pos, i, wordDict, size)) + { + printf("pre: %s\n", cur); + printf("exists in wordDict\n"); + for(int j = 0; j < i; j++) + printf("%c", s[pos+j]); + printf("\n"); + if( pos+i == len) + { + (*returnSize)++; + arr = (char**)realloc(arr, sizeof(char*)*(*returnSize)); + arr[*returnSize-1] = merge(s+pos, i, cur, total, 0); + printf("---------ends here a new string: new size: %d\n", *returnSize); + for(int i = 0; i < *returnSize; i++) + printf("%s\n", arr[i]); + printf("\n\n"); + } + else + { + printf("processing inside buildPath -- cur: %s\t len: %d\n", cur, strlen(cur)); + buildPath(breakable, s, pos+i, arr, returnSize, merge(s+pos, i, cur, total, 1), wordDict, size, min, max); + } + } + } +} + +//RE - when hitting size - 5; +//"aaaaaaa" ["aaaa","aa","a"] +char** wordBreak(char* s, char** wordDict, int size, int* returnSize) +{ + char** arr = (char**)malloc(sizeof(char*)); + *returnSize = 0; + int min=INT_MAX, max=0; //get the min and max length of the word in wordDict; + int len = strlen(s); + bool* breakable = (bool*)malloc(sizeof(bool)*(len+1)); + memset(breakable, 0, sizeof(bool)*(len+1)); + breakable[len] = true; + for(int i = 0; i < size; i++) + { + min = MIN(min, strlen(wordDict[i])); + max = MAX(max, strlen(wordDict[i])); + } + printf("min: %d\tmax: %d\n", min, max); + for(int i = len-min; i >= 0; i--) + for(int j = min; j <= MIN(max, len-i); j++) + if(breakable[i+j] && exist(s+i, j, wordDict, size)) + { + breakable[i] = true; + break; + } + for(int i = 0; i <= len; i++) + printf("breakable: %d\t", breakable[i]); + printf("\n"); + char *cur = (char*)malloc(sizeof(char)*2*len); + *cur = '\0'; + if(breakable[0]) buildPath(breakable, s, 0, arr, returnSize, cur, wordDict, size, min, max); + return arr; +} diff --git a/LuoSonglei/week-92/kthSmallestInBST.c b/LuoSonglei/week-92/kthSmallestInBST.c new file mode 100644 index 0000000..f693157 --- /dev/null +++ b/LuoSonglei/week-92/kthSmallestInBST.c @@ -0,0 +1,61 @@ +/******************************************* +Author : LHearen +E-mail : LHearen@126.com +Time : 2016-02-20 14:22 +Description : +Source : https://leetcode.com/problems/kth-smallest-element-in-a-bst/ +*******************************************/ +struct TreeNode +{ + int val; + struct TreeNode *left, *right; +}; +#include + +//AC - 12ms - an inorder solution; +int helper(struct TreeNode* root, int* k) +{ + if(root) + { + int ret = helper(root->left, k); + if(!(*k)) return ret; + if(!(*k-=1)) return root->val; + return helper(root->right, k); + } +} +int kthSmallest0(struct TreeNode* root, int k) +{ + return helper(root, &k); +} + +//the test cases might not be modified; +int kthSmallest(struct TreeNode* root, int k) +{ + while(root) + { + if(!root->left) + { + k--; + if(!k) return root->val; + root = root->right; + } + else + { + struct TreeNode* pre = root->left; + while(pre->right && pre->right!=root) + pre = pre->right; + if(!pre->right) + { + pre->right = root; + root = root->left; + } + else + { + k--; + if(!k) return root->val; + pre->right = NULL; + root = root->right; + } + } + } +} diff --git a/LuoSonglei/week-93/3Sum.c b/LuoSonglei/week-93/3Sum.c new file mode 100644 index 0000000..65af2bc --- /dev/null +++ b/LuoSonglei/week-93/3Sum.c @@ -0,0 +1,65 @@ +/******************************************* +Author : LHearen +E-mail : LHearen@126.com +Time : 2016-02-23 16:36 +Description : +Source : https://leetcode.com/problems/3sum/ +*******************************************/ +void sort(int* nums, int begin, int end) +{ + int l=begin, r=end; + int v = nums[l+(r-l)/2]; + while(l <= r) + { + while(nums[l] < v) l++; + while(nums[r] > v) r--; + if(l <= r) + { + int t = nums[l]; + nums[l] = nums[r]; + nums[r] = t; + l++; r--; + } + } + if(r > begin) + sort(nums, begin, r); + if(l < end) + sort(nums, l, end); +} + +//AC - 24ms; +int** threeSum(int* nums, int size, int* returnSize) +{ + sort(nums, 0, size-1); + int left, right; + int** arr = (int**)malloc(sizeof(int*)); + *returnSize = 0; + for(int i = 0; i < size-2; i++) + { + while(i0 && nums[i]==nums[i-1]) i++; //avoid redundant traversal by isolating the duplicates; + left = i+1; + right = size-1; + int sum = -nums[i]; + while(left < right) //the searching process is the same with the 2-sum problem; + { + int t = nums[left]+nums[right]; + if(t > sum) right--; + else if(t < sum) left++; + else + { + if(!*returnSize || (*returnSize && (nums[i]!=arr[*returnSize-1][0] || + nums[left]!=arr[*returnSize-1][1]))) //collect the qualified and isolating the duplicates; + { + *returnSize += 1; + arr = (int**)realloc(arr, sizeof(int*)*(*returnSize)); + arr[*returnSize-1] = (int*)malloc(sizeof(int)*3); + arr[*returnSize-1][0] = nums[i]; + arr[*returnSize-1][1] = nums[left]; + arr[*returnSize-1][2] = nums[right]; + } + left++; + } + } + } + return arr; +} diff --git a/LuoSonglei/week-93/4Sum.c b/LuoSonglei/week-93/4Sum.c new file mode 100644 index 0000000..9c13756 --- /dev/null +++ b/LuoSonglei/week-93/4Sum.c @@ -0,0 +1,74 @@ +/******************************************* +Author : LHearen +E-mail : LHearen@126.com +Time : 2016-02-24 09:45 +Description : +Source : https://leetcode.com/problems/4sum/ +*******************************************/ +void sort(int* nums, int begin, int end) +{ + int l = begin; + int r = end; + int v = nums[l+(r-l)/2]; + while(l <= r) + { + while(nums[l] < v) l++; + while(nums[r] > v) r--; + if(l <= r) + { + int t = nums[l]; + nums[l] = nums[r]; + nums[r] = t; + l++; r--; + } + } + if(begin < r) + sort(nums, begin, r); + if(l < end) + sort(nums, l, end); +} + +//AC - 8ms; +int** fourSum(int* nums, int size, int target, int* returnSize) +{ + sort(nums, 0, size-1); + int** arr = (int**)malloc(sizeof(int*)); + *returnSize = 0; + for(int i = 0; i < size-3; i++) + { + if(i && nums[i]==nums[i-1]) continue; + int t0 = target-nums[i]; //target for 3Sum; + for(int j = i+1; j < size-2; j++) + { + if(j!=i+1 && nums[j]==nums[j-1]) continue; //the start position should be handled carefully, it's i+1 while removing redundancy; + int t1 = t0-nums[j]; //target for 2Sum; + if(nums[j+1]+nums[j+2] > t1) break; //the possible least sum is even bigger than the target - just try the next first candidate - i+1; + if(nums[size-1]+nums[size-2] < t1) continue; //the possible maximal sum is smaller than the target - just try the next second candidate to make it bigger - j+1; + int l = j+1; + int r = size-1; + while(l < r) //2Sum problem; + { + int t2 = nums[l]+nums[r]; + if(t1 > t2) l++; + else if(t1 < t2) r--; + else + { + if(!*returnSize || (*returnSize && (nums[i]!=arr[*returnSize-1][0] + || nums[j]!=arr[*returnSize-1][1] + || nums[l]!=arr[*returnSize-1][2]))) //avoid duplicates; + { + *returnSize += 1; + arr = (int**)realloc(arr, sizeof(int*)*(*returnSize)); + arr[*returnSize-1] = (int*)malloc(sizeof(int)*4); + arr[*returnSize-1][0] = nums[i]; + arr[*returnSize-1][1] = nums[j]; + arr[*returnSize-1][2] = nums[l]; + arr[*returnSize-1][3] = nums[r]; + } + l++; + } + } + } + } + return arr; +} diff --git a/LuoSonglei/week-93/AddBinary.c b/LuoSonglei/week-93/AddBinary.c new file mode 100644 index 0000000..802a65e --- /dev/null +++ b/LuoSonglei/week-93/AddBinary.c @@ -0,0 +1,53 @@ +/******************************************* +Author : LHearen +E-mail : LHearen@126.com +Time : 2016-02-27 23:19 +Description : +Source : https://leetcode.com/problems/add-binary/ +*******************************************/ +#include +//AC - 0ms; +char* addBinary(char* a, char* b) +{ + int aLen = strlen(a); + int bLen = strlen(b); + int len = aLen>bLen? aLen+2 : bLen+2; + char *s = (char*)malloc(sizeof(char*)*len); + int index = 0; + char c; //used to determine the result of two chars only; + bool C = false; //bit carry indicator; + while(aLen || bLen) + { + if(!aLen || !bLen) //one of them has reached its end; + c = !aLen? b[bLen-1] : a[aLen-1]; + else //both of them have not finish; + { + if(a[aLen-1]=='1' && b[bLen-1]=='1') + c = '0'; + else + { + if(a[aLen-1]=='1' || b[bLen-1]=='1') + c = '1'; + else + c = '0'; + } + } + if((C&&c=='0') || (!C&&c=='1')) //using the carry of the previous loop to determine the exact value of the current bit; + s[index++] = '1'; + else + s[index++] = '0'; + if((a[aLen-1]=='1'&&b[bLen-1]=='1') || (c=='1'&&C)) //update the carry indicator for the next bit; + C = true; + else + C = false; + if(aLen) aLen--; //if it has not finished, move further forward; + if(bLen) bLen--; + } + if(C) s[index++] = '1'; //check the last carry; + for(int i = 0; i < index/2; i++) //reverse the whole result since we are recording them reversely; + { + char t=s[i]; s[i]=s[index-i-1]; s[index-i-1]=t; + } + s[index] = '\0'; //set the end character; + return s; +} diff --git a/LuoSonglei/week-93/AddTwoNumbers.c b/LuoSonglei/week-93/AddTwoNumbers.c new file mode 100644 index 0000000..6370184 --- /dev/null +++ b/LuoSonglei/week-93/AddTwoNumbers.c @@ -0,0 +1,49 @@ +/******************************************* +Author : LHearen +E-mail : LHearen@126.com +Time : 2016-02-28 09:48 +Description : +Source : https://leetcode.com/problems/add-two-numbers/ +*******************************************/ +struct ListNode +{ + int val; + struct ListNode *next; +}; +#include +//AC - 20ms; +struct ListNode* addTwoNumbers(struct ListNode* link1, struct ListNode* link2) +{ + struct ListNode *head = (struct ListNode*)malloc(sizeof(struct ListNode)); + head->next = NULL; + struct ListNode *tmp = head; + struct ListNode *l1=link1, *l2=link2; + int val = 0; + int C = 0; + while(l1 || l2) + { + struct ListNode *t = (struct ListNode*)malloc(sizeof(struct ListNode)); + if(!l1 || !l2) + val = !l1? l2->val : l1->val; + else + val = l1->val+l2->val; + t->val = (val+C)%10; + t->next = NULL; + tmp->next = t; + tmp = tmp->next; + if((val+C)>=10) + C = 1; + else + C = 0; + if(l1) l1 = l1->next; + if(l2) l2 = l2->next; + } + if(C) + { + struct ListNode *t = (struct ListNode*)malloc(sizeof(struct ListNode)); + t->val = 1; + t->next = NULL; + tmp->next = t; + } + return head->next; +} diff --git a/LuoSonglei/week-93/Candy.c b/LuoSonglei/week-93/Candy.c new file mode 100644 index 0000000..c596dba --- /dev/null +++ b/LuoSonglei/week-93/Candy.c @@ -0,0 +1,27 @@ +/******************************************* +Author : LHearen +E-mail : LHearen@126.com +Time : 2016-02-22 09:43 +Description : +Source : https://leetcode.com/problems/candy/ +*******************************************/ +#define MAX(a, b) ((a) > (b) ? (a) : (b)) +#define MIN(a, b) ((a) < (b) ? (a) : (b)) +//AC - 16ms; +int candy(int* ratings, int size) +{ + if(!size) return 0; + int* limits = (int*)malloc(sizeof(int)*size); + limits[size-1] = 1; + for(int i = size-2; i >-1; i--) //from right to left; + if(ratings[i] > ratings[i+1]) limits[i] = limits[i+1]+1; + else limits[i] = 1; + int sum = limits[0]; + for(int i = 1; i < size; i++) //from left to right and collect the results; + { + if(ratings[i] > ratings[i-1]) limits[i] = MAX(limits[i], limits[i-1]+1); + else limits[i] = limits[i]; //only constrained by the right; + sum += limits[i]; + } + return sum; +} diff --git a/LuoSonglei/week-93/CombinationSum.c b/LuoSonglei/week-93/CombinationSum.c new file mode 100644 index 0000000..fe87896 --- /dev/null +++ b/LuoSonglei/week-93/CombinationSum.c @@ -0,0 +1,69 @@ +/******************************************* +Author : LHearen +E-mail : LHearen@126.com +Time : 2016-02-25 11:31 +Description : +Source : https://leetcode.com/problems/combination-sum/ +*******************************************/ +void sort(int* nums, int begin, int end) +{ + int l=begin, r=end; + int v = nums[l+(r-l)/2]; + while(l <= r) + { + while(nums[l] < v) l++; + while(nums[r] > v) r--; + if(l <= r) + { + int t = nums[l]; + nums[l] = nums[r]; + nums[r] = t; + l++; + r--; + } + } + if(begin < r) + sort(nums, begin, r); + if(l < end) + sort(nums, l, end); +} + +void helper(int* nums, int size, int target, int* stack, int top, int*** arr, int** colSizes, int* returnSize) +{ + if(target < 0) return ; + if(target == 0) + { + *returnSize += 1; + *colSizes = (int*)realloc(*colSizes, sizeof(int)*(*returnSize)); + (*colSizes)[*returnSize-1] = top+1; + *arr = (int**)realloc(*arr, sizeof(int*)*(*returnSize)); + (*arr)[*returnSize-1] = (int*)malloc(sizeof(int)*(top+1)); + for(int i = 0; i <= top; i++) + (*arr)[*returnSize-1][i] = stack[i]; + return ; + } + for(int i = 0; i < size; i++) + { + if(nums[i]>=stack[top]) + { + stack[top+1] = nums[i]; + helper(nums, size, target-nums[i], stack, top+1, arr, colSizes, returnSize); + } + } +} + +//AC - 8ms; +int** combinationSum(int* nums, int size, int target, int** colSizes, int* returnSize) +{ + sort(nums, 0, size-1); + int** arr = (int**)malloc(sizeof(int*)); + *returnSize = 0; + int* stack = (int*)malloc(sizeof(int)*(target/nums[0]+1)); + int top = -1; + for(int i = 0; i < size; i++) + { + stack[top+1] = nums[i]; + helper(nums, size, target-nums[i], stack, top+1, &arr, colSizes, returnSize); + } + return arr; +} diff --git a/LuoSonglei/week-93/CombinationSum2.c b/LuoSonglei/week-93/CombinationSum2.c new file mode 100644 index 0000000..09e7c29 --- /dev/null +++ b/LuoSonglei/week-93/CombinationSum2.c @@ -0,0 +1,72 @@ +/******************************************* +Author : LHearen +E-mail : LHearen@126.com +Time : 2016-02-25 11:31 +Description : +Source : https://leetcode.com/problems/combination-sum/ +*******************************************/ +void sort(int* nums, int begin, int end) +{ + int l=begin, r=end; + int v = nums[l+(r-l)/2]; + while(l <= r) + { + while(nums[l] < v) l++; + while(nums[r] > v) r--; + if(l <= r) + { + int t = nums[l]; + nums[l] = nums[r]; + nums[r] = t; + l++; + r--; + } + } + if(begin < r) + sort(nums, begin, r); + if(l < end) + sort(nums, l, end); +} + +void helper(int* nums, int size, int start, int target, int* stack, int top, int*** arr, int** colSizes, int* returnSize) +{ + if(target < 0) return ; + if(target == 0) + { + *returnSize += 1; + *colSizes = (int*)realloc(*colSizes, sizeof(int)*(*returnSize)); + (*colSizes)[*returnSize-1] = top+1; + *arr = (int**)realloc(*arr, sizeof(int*)*(*returnSize)); + (*arr)[*returnSize-1] = (int*)malloc(sizeof(int)*(top+1)); + for(int i = 0; i <= top; i++) + (*arr)[*returnSize-1][i] = stack[i]; + return ; + } + for(int i = start+1; i < size; i++) + { + if(i==start+1 || nums[i]!=nums[i-1]) //only different candidates can be allowed in each traversing level for further traversal; + { + stack[top+1] = nums[i]; + helper(nums, size, i, target-nums[i], stack, top+1, arr, colSizes, returnSize); + } + } +} + +//AC - 4ms; +int** combinationSum2(int* nums, int size, int target, int** colSizes, int* returnSize) +{ + sort(nums, 0, size-1); + int** arr = (int**)malloc(sizeof(int*)); + *returnSize = 0; + int* stack = (int*)malloc(sizeof(int)*(target/nums[0]+1)); + int top = -1; + for(int i = 0; i < size; i++) + { + if(!i || nums[i]!=nums[i-1]) //only different candidates can be allowed in each traversing level for further traversal; + { + stack[top+1] = nums[i]; + helper(nums, size, i, target-nums[i], stack, top+1, &arr, colSizes, returnSize); + } + } + return arr; +} diff --git a/LuoSonglei/week-93/CombinationSum3.c b/LuoSonglei/week-93/CombinationSum3.c new file mode 100644 index 0000000..7908cf0 --- /dev/null +++ b/LuoSonglei/week-93/CombinationSum3.c @@ -0,0 +1,89 @@ +/******************************************* +Author : LHearen +E-mail : LHearen@126.com +Time : 2016-02-25 20:26 +Description : + +Find all possible combinations of k numbers that add up to a number n, given that only numbers from 1 to 9 can be used and each combination should be a unique set of numbers. + +Ensure that numbers within the set are sorted in ascending order. + +Example 1: + +Input: k = 3, n = 7 + +Output: + +[[1,2,4]] + + +Example 2: + +Input: k = 3, n = 9 + +Output: + +[[1,2,6], [1,3,5], [2,3,4]] + +Source : https://leetcode.com/problems/combination-sum-iii/ +*******************************************/ +#include +#include +void traverse(int* nums, int size, int start, int k, int target, int* stack, int top, int*** arr, int** colSizes, int* returnSize) +{ + if(top+1 == k) //there are k elements in stack already; + { + if(target==0) //check whether the stack should be collected as a valid result; + { + *returnSize += 1; + *colSizes = (int*)realloc(*colSizes, sizeof(int)*(*returnSize)); + (*colSizes)[*returnSize-1] = k; + *arr = (int**)realloc(*arr, sizeof(int*)*(*returnSize)); + (*arr)[*returnSize-1] = (int*)malloc(sizeof(int)*k); + for(int i = 0; i < k; i++) + (*arr)[*returnSize-1][i] = stack[i]; + } + return ; + } + for(int i = start; i < size; i++) + { + if(nums[i] > target) return ; //pruning, since it's already bigger than the target, no need to move to the next round; + stack[top+1] = nums[i]; //collect the number if it's still less or equal to the target; + traverse(nums, size, i+1, k, target-nums[i], stack, top+1, arr, colSizes, returnSize); + } +} +int** combinationSum3(int k, int target, int** colSizes, int* returnSize) +{ + int nums[] = {1,2,3,4,5,6,7,8,9}; + int size = sizeof(nums)/sizeof(int); + int** arr = (int**)malloc(sizeof(int*)); + *returnSize = 0; + *colSizes = (int*)malloc(sizeof(int)); + int *stack = (int*)malloc(sizeof(int)*k); + int top = -1; + for(int i = 0; i < size; i++) + { + if(nums[i] > target) break; //pruning, since it's already bigger than the target, no need to move to the next round; + stack[top+1] = nums[i]; + traverse(nums, size, i+1, k, target-nums[i], stack, top+1, &arr, colSizes, returnSize); + } + return arr; +} + +int main() +{ + int k = 6; + int target = 30; + scanf("%d", &target); + printf("target: %d\n", target); + int *colSizes; + int size; + int **arr = combinationSum3(k, target, &colSizes, &size); + for(int i = 0; i < size; i++) + { + for(int j = 0; j < k; j++) + printf("%d\t", arr[i][j]); + printf("\n"); + } + return 0; +} diff --git a/LuoSonglei/week-93/ContainerWithMostWater.c b/LuoSonglei/week-93/ContainerWithMostWater.c new file mode 100644 index 0000000..3f4e0b9 --- /dev/null +++ b/LuoSonglei/week-93/ContainerWithMostWater.c @@ -0,0 +1,45 @@ +/******************************************* +Author : LHearen +E-mail : LHearen@126.com +Time : 2016-02-25 08:42 +Description : +Source : https://leetcode.com/problems/container-with-most-water/ +*******************************************/ +//AC - 12ms; +int maxArea1(int* heights, int size) +{ + int l = 0; + int r = size-1; + int max = 0; + while(l < r) + { + int len = r-l; + int area = 0; + if(heights[l] < heights[r]) + { + area = len*heights[l]; + max = max > area? max : area; + l++; + } + else + { + area = len*heights[r]; + max = max > area? max : area; + r--; + } + } + return max; +} + +//AC - 8ms; +int maxArea(int* heights, int size) +{ + int l=0, r=size-1; + int max = 0; + while(l < r) + { + int area = (r-l)*(heights[l] < heights[r]? heights[l++] : heights[r--]); + max = max > area? max : area; + } + return max; +} diff --git a/LuoSonglei/week-93/CountPrimes.c b/LuoSonglei/week-93/CountPrimes.c new file mode 100644 index 0000000..64c5c33 --- /dev/null +++ b/LuoSonglei/week-93/CountPrimes.c @@ -0,0 +1,50 @@ +/******************************************* +Author : LHearen +E-mail : LHearen@126.com +Time : 2016-02-28 10:56 +Description : +Source : https://leetcode.com/problems/count-primes/ +*******************************************/ +#include +bool isPrime(int a) +{ + int b = sqrt(a); + for(int i = 2; i <= b; i++) + if(a%i == 0) return false; + return true; +} + +//AC - 876ms; +int countPrimes0(int n) +{ + int count = 0; + for(int i = 1; i <= n; i++) + if(isPrime(i)) count++; + return count; +} + +//AC - 32ms - using Sieve of Eratosthenes algorithm; +int countPrimes(int n) +{ + if(n <= 2) return 0; + bool *arr = (bool*)malloc(sizeof(bool)*n); + memset(arr, 0, sizeof(bool)*n); + int root = sqrt(n); + int count = n-2; //original start, take 4, 5 to initialize; + int base = 2; + for(int i = 2; i <= root; i++) //sqrt is enough since n=p*q, one of them must be smaller or equal to sqrt; + { + if(!arr[i]) //unset; + { + for(int j=i*i; j < n; j+=i) //set all its multiples within n; + { + if(!arr[j]) + { + arr[j] = true; + count--; //set one multiples within n, decrease the amount of primes; + } + } + } + } + return count; +} diff --git a/LuoSonglei/week-93/FindMinimumInRotatedSortedArray2.c b/LuoSonglei/week-93/FindMinimumInRotatedSortedArray2.c new file mode 100644 index 0000000..1672a35 --- /dev/null +++ b/LuoSonglei/week-93/FindMinimumInRotatedSortedArray2.c @@ -0,0 +1,21 @@ +/******************************************* +Author : LHearen +E-mail : LHearen@126.com +Time : 2016-02-27 22:19 +Description : +Source : https://leetcode.com/problems/find-minimum-in-rotated-sorted-array-ii/ +*******************************************/ +//AC - 4ms; +int findMin(int* nums, int size) +{ + if(size == 1) return nums[0]; + int mid = size/2; + if(nums[mid] > nums[size-1]) return findMin(nums+mid+1, size-mid-1); //the condition itself can ensure the nums+mid+1 will be valid and as a result the size-mid-1 will be bigger than 1; + else if(nums[mid] < nums[size-1]) return findMin(nums, mid+1); //the second parameter is size, so to cover nums+mid the size will be mid+1; + else + { + int l = findMin(nums, mid); + int r = findMin(nums+mid, size-mid); //there is no condition like above situation; + return l > r? r : l; + } +} diff --git a/LuoSonglei/week-93/FirstMissingPositive.c b/LuoSonglei/week-93/FirstMissingPositive.c new file mode 100644 index 0000000..ee254df --- /dev/null +++ b/LuoSonglei/week-93/FirstMissingPositive.c @@ -0,0 +1,23 @@ +/******************************************* +Author : LHearen +E-mail : LHearen@126.com +Time : 2016-02-27 16:43 +Description : +Source : https://leetcode.com/problems/first-missing-positive/ +*******************************************/ +void swap(int* p, int* q) +{ + int t=*p; *p=*q; *q=t; +} + +//AC - 0ms; +int firstMissingPositive(int* nums, int size) +{ + for(int i = 0; i < size; i++) + while(nums[i]>0 && nums[i]<=size && nums[nums[i]-1]!=nums[i]) + swap(nums+i, nums+nums[i]-1); + for(int i = 0; i < size; i++) + if(nums[i] != i+1) + return i+1; + return size+1; +} diff --git a/LuoSonglei/week-93/GameOfLife.c b/LuoSonglei/week-93/GameOfLife.c new file mode 100644 index 0000000..e55b2c7 --- /dev/null +++ b/LuoSonglei/week-93/GameOfLife.c @@ -0,0 +1,27 @@ +/******************************************* +Author : LHearen +E-mail : LHearen@126.com +Time : 2016-02-25 21:20 +Description : +Source : https://leetcode.com/problems/game-of-life/ +*******************************************/ +#define MIN(a, b) ((a) < (b) ? (a) : (b)) +#define MAX(a, b) ((a) > (b) ? (a) : (b)) +//in-place solution using bit manipulation; +void gameOfLife(int** board, int rSize, int cSize) +{ + for(int i = 0; i < rSize; i++) + for(int j = 0; j < cSize; j++) + { + int count = 0; + for(int rr = MAX(i-1, 0); rr < MIN(i+1, rSize); rr++) + for(int cc = MAX(j-1, 0); cc < MIN(j+1, cSize); cc++) + count += board[rr][cc]&1; //in-place; + count -= board[i][j]; + if(count==3 || (board[i][j]&&count==2)) + board[i][j] |= 2; + } + for(int i = 0; i < rSize; i++) + for(int j = 0; j < cSize; j++) + board[i][j] >>= 1; +} diff --git a/LuoSonglei/week-93/InsertInterval.c b/LuoSonglei/week-93/InsertInterval.c new file mode 100644 index 0000000..415745d --- /dev/null +++ b/LuoSonglei/week-93/InsertInterval.c @@ -0,0 +1,50 @@ +/******************************************* +Author : LHearen +E-mail : LHearen@126.com +Time : 2016-02-27 12:36 +Description : +Source : https://leetcode.com/problems/insert-interval/ +*******************************************/ +struct Interval +{ + int start; + int end; +}; + +struct Interval* insert(struct Interval* intervals, int size, struct Interval newInterval, int* returnSize) +{ + size++; + struct Interval *arr = (struct Interval*)malloc(sizeof(struct Interval)*size); + int j = 0; + int i = 0; + int count=0; + while(i < size-1) //inserting newInterval into arr with all in ascending order; + { + if(intervals[i].start < newInterval.start || count) // newInterval already inserted then we need to collect the remained intervals or it's bigger then we need to collect the intervals first; + arr[i+count] = intervals[i++]; + else + arr[i] = newInterval, count++; //inserting newInterval and counter it as a flag; + } + if(count == 0) arr[i] = newInterval; //make sure newInterval is not missed at the end of the intervals; + *returnSize = 0; + int max = 0; + i = 0; + while(i < size) + { + struct Interval t; + t.start = arr[i].start; + int j = i+1; + max = arr[i].end; + while(j max) max = arr[j].end; + j++; + } + i = j; //update the next start index; + t.end = max; + *returnSize += 1; + arr[*returnSize-1] = t; //since we are merging, arr then can be reused; + } + return arr; +} + diff --git a/LuoSonglei/week-93/LinkedListCycle.c b/LuoSonglei/week-93/LinkedListCycle.c new file mode 100644 index 0000000..8d0122f --- /dev/null +++ b/LuoSonglei/week-93/LinkedListCycle.c @@ -0,0 +1,26 @@ +/******************************************* +Author : LHearen +E-mail : LHearen@126.com +Time : 2016-02-24 16:02 +Description : +Source : https://leetcode.com/problems/linked-list-cycle/ +*******************************************/ +#include +struct ListNode +{ + int val; + struct ListNode *next; +}; +bool hasCycle(struct ListNode* head) +{ + if(!head || !head->next) return false; + struct ListNode *slow=head, *fast=head->next; + while(fast && fast->next) + { + slow = slow->next; + fast = fast->next->next; + if(slow == fast) + return true; + } + return false; +} diff --git a/LuoSonglei/week-93/LongestConsecutiveSequence.c b/LuoSonglei/week-93/LongestConsecutiveSequence.c new file mode 100644 index 0000000..774f14b --- /dev/null +++ b/LuoSonglei/week-93/LongestConsecutiveSequence.c @@ -0,0 +1,48 @@ +/******************************************* +Author : LHearen +E-mail : LHearen@126.com +Time : 2016-02-27 11:03 +Description : +Source : https://leetcode.com/problems/longest-consecutive-sequence/ +*******************************************/ +void sort(int* nums, int begin, int end) +{ + int l=begin, r=end; + int v = nums[l+(r-l)/2]; + while(l <= r) + { + while(nums[l] < v) l++; + while(nums[r] > v) r--; + if(l <= r) + { + int t = nums[l]; + nums[l] = nums[r]; + nums[r] = t; + l++; r--; + } + } + if(begin < r) + sort(nums, begin, r); + if(l < end) + sort(nums, l, end); +} + +//AC - 4ms; +int longestConsecutive(int* nums, int size) +{ + sort(nums, 0, size-1); + int max = 1; + int count = 1; + for(int i = 1; i < size; i++) + { + if(nums[i] == nums[i-1]) continue; //just ignore the equivalent elements; + if(nums[i] == nums[i-1]+1) count++; + else //there is a gap - nonconsecutive; + { + max = max > count? max : count; + count = 1; //reset counter; + } + } + max = max > count? max : count; //collect the last section; + return max; +} diff --git a/LuoSonglei/week-93/MergeIntervals.c b/LuoSonglei/week-93/MergeIntervals.c new file mode 100644 index 0000000..57d7879 --- /dev/null +++ b/LuoSonglei/week-93/MergeIntervals.c @@ -0,0 +1,57 @@ +/******************************************* +Author : LHearen +E-mail : LHearen@126.com +Time : 2016-02-26 16:27 +Description : +Source : https://leetcode.com/problems/merge-intervals/ +*******************************************/ +struct Interval +{ + int start, end; +}; + +void sort(struct Interval* intervals, int begin, int end) +{ + int l=begin, r=end; + int v = intervals[l+(r-l)/2].start; + while(l <= r) + { + while(intervals[l].start < v) l++; + while(intervals[r].start > v) r--; + if(l <= r) + { + struct Interval t = intervals[l]; + intervals[l] = intervals[r]; + intervals[r] = t; + l++; r--; + } + } + if(begin < r) + sort(intervals, begin, r); + if(l < end) + sort(intervals, l, end); +} + +//AC - 576ms; +struct Interval* merge(struct Interval* intervals, int size, int* returnSize) +{ + struct Interval *arr = (struct Interval*)malloc(sizeof(struct Interval)); + *returnSize = 0; + sort(intervals, 0, size-1); + int i = 0; + while(i < size) + { + struct Interval t; + t.start = intervals[i].start; + int max = intervals[i].end; + int j = i+1; + for(; j intervals[j].end? max : intervals[j].end; + t.end = max; + i = j; + *returnSize += 1; + arr = (struct Interval*)realloc(arr, sizeof(struct Interval)*(*returnSize)); + arr[*returnSize-1] = t; + } + return arr; +} diff --git a/LuoSonglei/week-93/MissingNumber.c b/LuoSonglei/week-93/MissingNumber.c new file mode 100644 index 0000000..7774a4a --- /dev/null +++ b/LuoSonglei/week-93/MissingNumber.c @@ -0,0 +1,29 @@ +/******************************************* +Author : LHearen +E-mail : LHearen@126.com +Time : 2016-02-27 21:35 +Description : +Source : https://leetcode.com/problems/missing-number/ +*******************************************/ +#include +//AC - 12ms - using O(n) space; +int missingNumber0(int* nums, int size) +{ + bool *arr = (int*)malloc(sizeof(bool)*(size+1)); + memset(arr, 0, sizeof(bool)*(size+1)); + for(int i = 0; i < size; i++) + arr[nums[i]] = true; + for(int i = 0; i <= size; i++) + if(!arr[i]) + return i; +} + +//AC - 12ms; +//a^a=0 and 0^b=b; +int missingNumber(int* nums, int size) +{ + int t = size; + for(int i = 0; i < size; i++) + t ^= nums[i]^i; + return t; +} diff --git a/LuoSonglei/week-93/NextPermutation.c b/LuoSonglei/week-93/NextPermutation.c new file mode 100644 index 0000000..6d50cb4 --- /dev/null +++ b/LuoSonglei/week-93/NextPermutation.c @@ -0,0 +1,31 @@ +/******************************************* +Author : LHearen +E-mail : LHearen@126.com +Time : 2016-02-27 10:03 +Description : +Source : https://leetcode.com/problems/next-permutation/ +*******************************************/ +void swap(int* p, int* q) +{ + int t = *p; *p = *q; *q = t; +} +void reverse(int* nums, int begin, int end) +{ + for(int i = begin; i < (begin+end+1)/2; i++) + swap(nums+i, nums+end+begin-i); +} + +//AC - 4ms; +void nextPermutation(int* nums, int size) +{ + int i=size-1, j=size-1; + while(i>0 && nums[i]<=nums[i-1]) i--; //make sure the [i..size-1] is in descending order; + if(i==0) //the whole array is descending now, reverse it to the smallest as problem requires; + { + reverse(nums, 0, size-1); + return ; + } + while(nums[j] <= nums[i-1]) j--; //find the first bigger one backwards; + swap(nums+j, nums+i-1); //ensure the next is bigger; + reverse(nums, i, size-1); //since [i..size-1] is descending, after reverse it will be ascending and as a result - [i..size-1] will be the smallest - the smallest in the bigger results - the next permutation; +} diff --git a/LuoSonglei/week-93/PalindromeLinkedList.c b/LuoSonglei/week-93/PalindromeLinkedList.c new file mode 100644 index 0000000..cc107b4 --- /dev/null +++ b/LuoSonglei/week-93/PalindromeLinkedList.c @@ -0,0 +1,67 @@ +/******************************************* +Author : LHearen +E-mail : LHearen@126.com +Time : 2016-02-23 08:46 +Description : +Source : https://leetcode.com/problems/palindrome-linked-list/ +*******************************************/ +#include +struct ListNode +{ + int val; + struct ListNode *next; +}; +//AC - 12ms; +bool isPalindrome0(struct ListNode* head) +{ + int* arr = (int*)malloc(sizeof(int)); + int size = 0; + struct ListNode* p = head; + while(p) //collect all values; + { + size++; + arr = (int*)realloc(arr, sizeof(int)*size); + arr[size-1] = p->val; + p = p->next; + } + for(int i = 0; i < size/2; i++) //symmetric; + if(arr[i] != arr[size-i-1]) + return false; + return true; +} + +#include +//AC - 12ms; +bool isPalindrome(struct ListNode* head) +{ + if(!head || !head->next) return true; + struct ListNode *slow=head, *fast=head->next->next; + while(fast && fast->next) //split into two halves while the right part might longer by 1 if the length of the link is odd; + { + slow = slow->next; + fast = fast->next->next; + } + fast = slow->next; + slow->next = NULL; + struct ListNode *cur, *pre, *next; //reverse the left linked and slow will become the head; + cur = head->next; + pre = head; + pre->next = NULL; + while(cur) + { + next = cur->next; + cur->next = pre; + pre = cur; + cur = next; + } + if(fast->val != slow->val) fast = fast->next; //if the first node is unequal, move fast forward to the next; + while(fast) + { + if(fast->val != slow->val) + return false; + fast = fast->next; + slow = slow->next; + } + if(!fast || !slow) return false; //not all nodes have been compared - not symmetric; + return true; +} diff --git a/LuoSonglei/week-93/PartitionList.c b/LuoSonglei/week-93/PartitionList.c new file mode 100644 index 0000000..06b02ed --- /dev/null +++ b/LuoSonglei/week-93/PartitionList.c @@ -0,0 +1,37 @@ +/******************************************* +Author : LHearen +E-mail : LHearen@126.com +Time : 2016-02-24 16:23 +Description : +Source : https://leetcode.com/problems/partition-list/ +*******************************************/ +struct ListNode +{ + int val; + struct ListNode *next; +}; +#include +struct ListNode* partition(struct ListNode* head, int x) +{ + if(!head) return NULL; + struct ListNode *less = (struct ListNode*)malloc(sizeof(struct ListNode)); //used as head; + struct ListNode *greater = (struct ListNode*)malloc(sizeof(struct ListNode)); + struct ListNode *l=less, *g=greater; //used to track the chain for connecting; + while(head) + { + if(head->val < x) + { + l->next = head; + l = l->next; + } + else + { + g->next = head; + g = g->next; + } + head = head->next; + } + g->next = NULL; + l->next = greater->next; + return less->next; +} diff --git a/LuoSonglei/week-93/PatchingArray.c b/LuoSonglei/week-93/PatchingArray.c new file mode 100644 index 0000000..df87f19 --- /dev/null +++ b/LuoSonglei/week-93/PatchingArray.c @@ -0,0 +1,24 @@ +/******************************************* +Author : LHearen +E-mail : LHearen@126.com +Time : 2016-02-22 20:00 +Description : +Source : https://leetcode.com/problems/patching-array/ +*******************************************/ +//AC - 4ms; +int minPatches(int* nums, int size, int n) +{ + int count=0, index=0; + long long top = 0; + while(top < n) + { + if(index0 && nums[i]<=nums[i-1]) i--; //make sure the [i..n-1] is in descending order; + while(nums[j] <= nums[i-1]) j--; //find the first bigger one backwards; + swap(nums+j, nums+i-1); //ensure the next is bigger; + reverse(nums, i, n-1); //since [i..n-1] is descending, after reverse it will be ascending and as a result - [i..n-1] will be the smallest - the smallest in the bigger results - the next permutation; + } + char *s = (char*)malloc(sizeof(char)*(n+1)); + for(int i = 0; i < n; i++) + s[i] = nums[i]+'0'; + s[n] = '\0'; + return s; +} diff --git a/LuoSonglei/week-93/ProductOfArrayExceptSelf.c b/LuoSonglei/week-93/ProductOfArrayExceptSelf.c new file mode 100644 index 0000000..4dc23bc --- /dev/null +++ b/LuoSonglei/week-93/ProductOfArrayExceptSelf.c @@ -0,0 +1,22 @@ +/******************************************* +Author : LHearen +E-mail : LHearen@126.com +Time : 2016-02-26 15:34 +Description : +Source : https://leetcode.com/problems/product-of-array-except-self/ +*******************************************/ +int* productExceptSelf(int* nums, int size, int* returnSize) +{ + int* arr = (int*)malloc(sizeof(int)*size); + arr[0] = arr[size-1] = 1; + for(int i = 1; i < size; i++) + arr[i] = arr[i-1] * nums[i-1]; + int t = nums[size-1]; + for(int i = size-2; i > -1; i--) + { + arr[i] *= t; + t *= nums[i]; + } + *returnSize = size; + return arr; +} diff --git a/LuoSonglei/week-93/RemoveDuplicateLetters.c b/LuoSonglei/week-93/RemoveDuplicateLetters.c new file mode 100644 index 0000000..f9105be --- /dev/null +++ b/LuoSonglei/week-93/RemoveDuplicateLetters.c @@ -0,0 +1,72 @@ +/******************************************* +Author : LHearen +E-mail : LHearen@126.com +Time : 2016-02-22 10:41 +Description : +Source : https://leetcode.com/problems/remove-duplicate-letters/ +*******************************************/ +#include +#include +//AC - 0ms; +char* removeDuplicateLetters0(char* s) +{ + int count[26] = {0}; + bool visited[26] = {0}; + int len = strlen(s); + for(int i = 0; i < len ;i++) count[s[i]-'a']++; //count the frequency of each character; + char *t = (char*)malloc(sizeof(char)*27); + int size = 0; + for(int i = 0; i < len; i++) + { + int index = s[i]-'a'; + count[index]--; + if(visited[index]) continue; //stored already, needless to backtrack the rest will backtrack and remove it if necessary; + int j = size-1; //encounter this character the first time backtrack to find a suitable position; + for(; j > -1; j--) + { + int index = t[j]-'a'; + if(s[i] < t[j] && count[index]) visited[index] = false; //if the previous character is bigger and its counter is also above zero which means there is still such character in the remaining substring, to keep lexicographical order, we have to remove it from the final string and visited records; + else break; + } + size = j+1; //new size of the final string; + t[size++] = s[i]; + visited[index] = true; + } + t[size] = '\0'; + return t; +} + +void helper(char* s, char* t, int* returnSize) +{ + int len = strlen(s); + if(!len) return ; + int count[26] = {0}; + int index = 0; + for(int i = 0; i < len; i++) count[s[i]-'a']++; + for(int i = 0; i < len; i++) + { + if(s[i] < s[index]) //search for the smallest; + index = i; + if(!(--count[s[i]-'a'])) //ensure every letter appears at least once, do not exclude any letter; + break; + } + char c = s[index]; + *returnSize += 1; + t[*returnSize-1] = c; + int newIndex = 0; + for(int i = index+1; i < len; i++) //reconstructing the left substring by removing the collected character and the letters before the selected; + if(s[i] != c) + s[newIndex++] = s[i]; + s[newIndex] = '\0'; + helper(s, t, returnSize); +} + +//AC - 4ms; +char* removeDuplicateLetters(char* s) +{ + char* t = (char*)malloc(sizeof(char)*27); + int size = 0; + helper(s, t, &size); + t[size] = '\0'; + return t; +} diff --git a/LuoSonglei/week-93/ReverseInteger.c b/LuoSonglei/week-93/ReverseInteger.c new file mode 100644 index 0000000..1323f2d --- /dev/null +++ b/LuoSonglei/week-93/ReverseInteger.c @@ -0,0 +1,23 @@ +/******************************************* +Author : LHearen +E-mail : LHearen@126.com +Time : 2016-02-28 14:49 +Description : +Source : https://leetcode.com/problems/reverse-integer/ +*******************************************/ +#include +//AC - 4ms; +int reverse(int n) +{ + if(n==INT_MIN || n==INT_MAX) return 0; //two extreme values are ignored; + bool negative = n<0? true : false; + n = negative? -n : n; + long long a = 0; + while(n) //reverse n; + { + a = 10*a + n%10; + n /= 10; + } + if(a > INT_MAX) return 0; //in case of reversed big number; + return negative? -a : a; +} diff --git a/LuoSonglei/week-93/RotateArray.c b/LuoSonglei/week-93/RotateArray.c new file mode 100644 index 0000000..66dce71 --- /dev/null +++ b/LuoSonglei/week-93/RotateArray.c @@ -0,0 +1,24 @@ +/******************************************* +Author : LHearen +E-mail : LHearen@126.com +Time : 2016-02-25 11:15 +Description : +Source : https://leetcode.com/problems/rotate-array/ +*******************************************/ +void rotate0(int* nums, int size) +{ + for(int i = 0; i < size/2; i++) + { + int t = nums[i]; + nums[i] = nums[size-i-1]; + nums[size-i-1] = t; + } +} +//AC - 8ms; +void rotate(int* nums, int size, int k) +{ + k %= size; + rotate0(nums, size); + rotate0(nums, k); + rotate0(nums+k, size-k); +} diff --git a/LuoSonglei/week-93/RotateImage.c b/LuoSonglei/week-93/RotateImage.c new file mode 100644 index 0000000..9664a8e --- /dev/null +++ b/LuoSonglei/week-93/RotateImage.c @@ -0,0 +1,41 @@ +/******************************************* +Author : LHearen +E-mail : LHearen@126.com +Time : 2016-02-26 14:02 +Description : +Source : https://leetcode.com/problems/rotate-image/ +*******************************************/ +//AC - 0ms; +void rotate0(int** matrix, int rSize, int cSize) +{ + int** matrix0 = (int**)malloc(sizeof(int*)*rSize); + for(int i = 0; i < rSize; i++) + matrix0[i] = (int*)malloc(sizeof(int)*cSize); + for(int r = 0; r < rSize; r++) + for(int c = 0; c < cSize; c++) + matrix0[c][cSize-r-1] = matrix[r][c]; + for(int r = 0; r < rSize; r++) + for(int c = 0; c < cSize; c++) + matrix[r][c] = matrix0[r][c]; +} + +void swap(int* p, int* q) +{ + int t = *p; + *p = *q; + *q = t; +} +//AC - 0ms; +void rotate(int** matrix, int rSize, int cSize) +{ + int t = 0; + for(int r = 0; r < rSize/2; r++) //only half rows should be set as rotating start; + for(int c = r; c < cSize-r-1; c++) //the rotating area is shrinking as rotation goes on; + { + int t = matrix[r][c]; + swap(&t, &matrix[c][cSize-r-1]); + swap(&t, &matrix[cSize-r-1][cSize-c-1]); + swap(&t, &matrix[cSize-c-1][r]); + swap(&t, &matrix[r][c]); + } +} diff --git a/LuoSonglei/week-93/RotateList.c b/LuoSonglei/week-93/RotateList.c new file mode 100644 index 0000000..51810c2 --- /dev/null +++ b/LuoSonglei/week-93/RotateList.c @@ -0,0 +1,39 @@ +/******************************************* +Author : LHearen +E-mail : LHearen@126.com +Time : 2016-02-23 11:01 +Description : +Source : https://leetcode.com/problems/rotate-list/ +*******************************************/ +struct ListNode +{ + int val; + struct ListNode *next; +}; +#include +//AC - 4ms; +struct ListNode* rotateRight(struct ListNode* head, int k) +{ + if(!head) return NULL; + int len = 0; + struct ListNode* p = head; + while(p) + len++, p = p->next; + k %= len; //after a circle of rotation, the chain will be the same; + if(!k) return head; + struct ListNode *cur=head, *kth=head; + while(k) //move forward by k nodes; + kth=kth->next, k--; + while(kth->next) //there will be k nodes after cur - end of the loop; + { + cur = cur->next; + kth = kth->next; + } + kth = cur->next; //the head of the right chain; + cur->next = NULL; + cur = kth; //the new head; + while(kth->next) + kth = kth->next; //move to the end of the right chain; + kth->next = head; //connect the left to the end of the right; + return cur; +} diff --git a/LuoSonglei/week-93/SelfCrossing.c b/LuoSonglei/week-93/SelfCrossing.c new file mode 100644 index 0000000..a8ffe83 --- /dev/null +++ b/LuoSonglei/week-93/SelfCrossing.c @@ -0,0 +1,20 @@ +/******************************************* +Author : LHearen +E-mail : LHearen@126.com +Time : 2016-02-28 15:51 +Description : +Source : https://leetcode.com/problems/self-crossing/ +*******************************************/ +#include +//AC - 0ms; +//https://leetcode.com/discuss/89336/the-best-submission-searching-for-crossing-pattern-the-key +bool isSelfCrossing(int* x, int size) +{ + for(int i = 3; i < size; i++) + { + if(x[i]>=x[i-2] && x[i-1]<=x[i-3]) return true; + if(i>=4 && x[i-1]==x[i-3] && x[i]+x[i-4]>=x[i-2]) return true; + if(i>=5 && x[i-2]-x[i-4]>=0 && x[i]>=x[i-2]-x[i-4] && x[i-1]>=x[i-3]-x[i-5] && x[i-1]<=x[i-3]) return true; + } + return false; +} diff --git a/LuoSonglei/week-93/SetMatrixZeroes.c b/LuoSonglei/week-93/SetMatrixZeroes.c new file mode 100644 index 0000000..e58e82c --- /dev/null +++ b/LuoSonglei/week-93/SetMatrixZeroes.c @@ -0,0 +1,50 @@ +/******************************************* +Author : LHearen +E-mail : LHearen@126.com +Time : 2016-02-26 10:17 +Description : +Source : https://leetcode.com/problems/set-matrix-zeroes/ +*******************************************/ +#include +//AC - 44ms; +void setZeroes0(int** matrix, int rSize, int cSize) +{ + bool *rSet = (bool*)malloc(sizeof(bool)*rSize); + bool *cSet = (bool*)malloc(sizeof(bool)*cSize); + memset(rSet, 0, sizeof(bool)*rSize); + memset(cSet, 0, sizeof(bool)*cSize); + for(int r = 0; r < rSize; r++) + for(int c = 0; c < cSize; c++) + if(!matrix[r][c]) + { + rSet[r] = true; + cSet[c] = true; + } + for(int r = 0; r < rSize; r++) + if(rSet[r]) + memset(matrix[r], 0, sizeof(int)*cSize); + for(int c = 0; c < cSize; c++) + if(cSet[c]) + for(int r = 0; r < rSize; r++) + matrix[r][c] = 0; +} + +//AC - 44ms; +void setZeroes(int** matrix, int rSize, int cSize) +{ + int col0 = 1; //the first column can be affected by the other columes of the first row; + for(int r = 0; r < rSize; r++) + { + if(matrix[r][0]==0) col0 = 0; + for(int c = 1; c < cSize; c++) + if(matrix[r][c]==0) + matrix[r][0] = matrix[0][c] = 0; + } + for(int r = rSize-1; r > -1; r--) //using reverse direction to ensure previously set value will not affect the latter ones; + { + for(int c = cSize-1; c > 0; c--) + if(matrix[r][0]==0 || matrix[0][c]==0) + matrix[r][c] = 0; + if(col0==0) matrix[r][0] = 0; //ensure the first column will not affect the other columns in the same row; + } +} diff --git a/LuoSonglei/week-93/SpiralMatrix.c b/LuoSonglei/week-93/SpiralMatrix.c new file mode 100644 index 0000000..2be5ad4 --- /dev/null +++ b/LuoSonglei/week-93/SpiralMatrix.c @@ -0,0 +1,31 @@ +/******************************************* +Author : LHearen +E-mail : LHearen@126.com +Time : 2016-02-26 08:42 +Description : +Source : https://leetcode.com/problems/spiral-matrix/ +*******************************************/ +//AC - 0ms; +int* spiralOrder(int** matrix, int rSize, int cSize) +{ + int count = 0; + int size = rSize*cSize; + int *arr = (int*)malloc(sizeof(int)*size); + int rmin=0, rmax=rSize-1; + int cmin=0, cmax=cSize-1; + while(count < size) + { + for(int c = cmin; c <= cmax; c++) //from left to right including the last; + arr[count++] = matrix[rmin][c]; + if(count == size) break; //only one row; + for(int r = rmin+1; r <= rmax; r++) //from top to bottom including the last; + arr[count++] = matrix[r][cmax]; + if(count == size) break; //only one column; + for(int c = cmax-1; c >= cmin; c--) //from right to left including the last; + arr[count++] = matrix[rmax][c]; + for(int r = rmax-1; r > rmin; r--) //from bottom to top excluding the last; + arr[count++] = matrix[r][cmin]; + rmin++; rmax--; cmin++; cmax--; + } + return arr; +} diff --git a/LuoSonglei/week-93/SpiralMatrix2.c b/LuoSonglei/week-93/SpiralMatrix2.c new file mode 100644 index 0000000..0e8adcc --- /dev/null +++ b/LuoSonglei/week-93/SpiralMatrix2.c @@ -0,0 +1,32 @@ +/******************************************* +Author : LHearen +E-mail : LHearen@126.com +Time : 2016-02-26 09:09 +Description : +Source : https://leetcode.com/problems/spiral-matrix-ii/ +*******************************************/ +//AC - 0ms; +int** generateMatrix(int n) +{ + int size = n*n; + int count = 1; + int** matrix = (int**)malloc(sizeof(int*)*n); + for(int i = 0; i < n; i++) + matrix[i] = (int*)malloc(sizeof(int)*n); + int rmin=0, rmax=n-1; + int cmin=0, cmax=n-1; + while(count <= size) + { + for(int c = cmin; c <= cmax; c++) //from right to left including the last; + matrix[rmin][c] = count++; + if(count > size) break; + for(int r = rmin+1; r <= rmax; r++) //from top to bottom including the last; + matrix[r][cmax] = count++; + for(int c = cmax-1; c >= cmin; c--) //from left to right including the last; + matrix[rmax][c] = count++; + for(int r = rmax-1; r > rmin; r--) //from bottom to top including the last; + matrix[r][cmin] = count++; + rmin++; rmax--; cmin++; cmax--; + } + return matrix; +} diff --git a/LuoSonglei/week-93/SubstringWithConcatenationOfAllWords.c b/LuoSonglei/week-93/SubstringWithConcatenationOfAllWords.c new file mode 100644 index 0000000..033e6eb --- /dev/null +++ b/LuoSonglei/week-93/SubstringWithConcatenationOfAllWords.c @@ -0,0 +1,11 @@ +/******************************************* +Author : LHearen +E-mail : LHearen@126.com +Time : 2016-02-25 10:44 +Description : +Source : https://leetcode.com/problems/substring-with-concatenation-of-all-words/ +*******************************************/ +int* findSubstring(char* s, char** words, int size, int* returnSize) +{ + +} diff --git a/LuoSonglei/week-94/138-CopyListWithRandomPointer.c b/LuoSonglei/week-94/138-CopyListWithRandomPointer.c new file mode 100644 index 0000000..2370321 --- /dev/null +++ b/LuoSonglei/week-94/138-CopyListWithRandomPointer.c @@ -0,0 +1,66 @@ +/******************************************* +Author : LHearen +E-mail : LHearen@126.com +Time : 2016-03-06 17:01 +Description : A linked list is given such that each node contains an additional random pointer which could point to any node in the list or null. + +Return a deep copy of the list. +Source : https://leetcode.com/problems/copy-list-with-random-pointer/ +*******************************************/ +#include +struct RandomListNode +{ + int label; + struct RandomListNode *next; + struct RandomListNode *random; +}; + +struct Mapper +{ + struct RandomListNode *key; + struct RandomListNode *value; +}; + +struct RandomListNode *nodeMaker(struct RandomListNode *node) +{ + struct RandomListNode *t = (struct RandomListNode*)malloc(sizeof(struct RandomListNode)); + t->label = node->label; + t->next = node->next; + t->random = node->random; + return t; +} +struct RandomListNode *copyRandomList(struct RandomListNode *head) +{ + if(!head) return NULL; + struct RandomListNode *newHead = nodeMaker(head); + struct RandomListNode *t = newHead; + struct RandomListNode *p = head; + struct Mapper *dict = (struct Mapper*)malloc(sizeof(struct Mapper)); + int size = 0; + while(p) //doing the complete copy but the random will be further handled; + { + struct RandomListNode *t0 = nodeMaker(p); + size++; + dict = (struct Mapper*)realloc(dict, sizeof(struct Mapper)*size); //mapping for later random pointer; + dict[size-1].key = p; + dict[size-1].value = t0; + t->next = t0; + p = p->next; + t = t->next; + } + p = newHead->next; + while(p) + { + for(int i = 0; i < size; i++) + { + if(!p->random) break; + if(dict[i].key == p->random) + { + p->random = dict[i].value; + break; + } + } + p = p->next; + } + return newHead->next; +} diff --git a/LuoSonglei/week-94/138-CopyListWithRandomPointerOptimized.c b/LuoSonglei/week-94/138-CopyListWithRandomPointerOptimized.c new file mode 100644 index 0000000..e43d06a --- /dev/null +++ b/LuoSonglei/week-94/138-CopyListWithRandomPointerOptimized.c @@ -0,0 +1,90 @@ +/******************************************* +Author : LHearen +E-mail : LHearen@126.com +Time : 2016-03-06 20:41 +Description : A linked list is given such that each node contains an additional random pointer which could point to any node in the list or null. + +Return a deep copy of the list. +Source : https://leetcode.com/problems/copy-list-with-random-pointer/ +*******************************************/ +#include +struct RandomListNode +{ + int label; + struct RandomListNode *next; + struct RandomListNode *random; +}; + +struct RandomListNode* copyRandomList0(struct RandomListNode *head) +{ + if(!head) return NULL; + struct RandomListNode *newHead=NULL, *oldNode=head, *newNode=NULL, *preNewNode=NULL; + while(oldNode) //copy the node and place the new node just after the original one; + { + newNode = (struct RandomListNode*)malloc(sizeof(struct RandomListNode)); + newNode->next = oldNode->next; + newNode->label = oldNode->label; + newNode->random = NULL; + oldNode->next = newNode; + oldNode = oldNode->next->next; + } + oldNode = head; + while(oldNode) //using the adjacent attribute to find the random pointer; + { + if(oldNode->random) + oldNode->next->random = oldNode->random->next; + oldNode = oldNode->next->next; + } + + newHead = head->next; + oldNode = head; + while(oldNode) //splitting the two merged list into two independent ones restoring the original list; + { + newNode = oldNode->next; + oldNode->next = newNode->next; + if(preNewNode) + preNewNode->next = newNode; + preNewNode = newNode; + oldNode = oldNode->next; + } + return newHead; +} + +struct RandomListNode* copyRandomList(struct RandomListNode *head) +{ + if(!head) return NULL; + struct RandomListNode *newHead=NULL, *oldNode=head, *newNode=NULL; + while(oldNode) //copy the node and place the new node just after the original one; + { + newNode = (struct RandomListNode*)malloc(sizeof(struct RandomListNode)); + newNode->next = oldNode->next; + newNode->label = oldNode->label; + newNode->random = NULL; + oldNode->next = newNode; + oldNode = oldNode->next->next; + } + oldNode = head; + while(oldNode) //using the adjacent attribute to find the random pointer; + { + if(oldNode->random) + oldNode->next->random = oldNode->random->next; + oldNode = oldNode->next->next; + } + + newHead = head->next; + newNode = head->next; + oldNode = head; + while(oldNode) //splitting the two merged list into two independent ones restoring the original list; + { + oldNode->next = oldNode->next->next; + if(oldNode->next == NULL) + { + newNode->next = NULL; + break; + } + newNode = newNode->next->next; + newNode = newNode->next; + oldNode = oldNode->next; + } + return newHead; +} diff --git a/LuoSonglei/week-94/AddAndSearchWord.c b/LuoSonglei/week-94/AddAndSearchWord.c new file mode 100644 index 0000000..d1534ca --- /dev/null +++ b/LuoSonglei/week-94/AddAndSearchWord.c @@ -0,0 +1,72 @@ +/******************************************* +Author : LHearen +E-mail : LHearen@126.com +Time : 2016-03-02 18:23 +Description : +Source : https://leetcode.com/problems/add-and-search-word-data-structure-design/ +*******************************************/ +#include +#define SIZE 26 + +struct WordDictionary +{ + bool isWord; //determine whether a word exists in the path; + struct WordDictionary **children; +}; + +struct WordDictionary* nodeMaker() +{ + struct WordDictionary *t = (struct WordDictionary*)malloc(sizeof(struct WordDictionary)); + t->isWord = false; + int space = sizeof(struct WordDictionary*)*SIZE; + t->children = (struct WordDictionary**)malloc(space); + memset(t->children, 0, space); + return t; +} +struct WordDictionary* wordDictionaryCreate() +{ + return nodeMaker(); +} + +void addWord(struct WordDictionary* dict, char* word) +{ + struct WordDictionary *cur = dict; + for(int i = 0; word[i]; i++) + { + if(!(cur->children[word[i]-'a'])) + cur->children[word[i]-'a'] = nodeMaker(); + cur = cur->children[word[i]-'a']; + } + cur->isWord = true; //set the flag for the existence of the word in the current path; +} + +//Runtime Error - unkonwn! - pointer of an array -> children; +// The term comes from "retrieval" and the originator, Edward Fredkin, pronounced it "tree." However, "trey" is the more common pronounciation. "Try" is rare and considered incorrect. +//https://leetcode.com/discuss/39022/80ms-clear-c-code-with-detailed-explanations +//https://en.wikipedia.org/wiki/Trie +//AC - 40ms; +bool search(struct WordDictionary* root, char* word) +{ + struct WordDictionary *cur = root; + for(int i = 0; word[i]; i++) + { + if(!cur) return false; //the path is interrupted; + if(word[i]!='.') //track the path down; + cur = cur->children[word[i]-'a']; + else if(word[i]=='.') //while there is dot, the possible paths can be all; + { + for(int j = 0; j < SIZE; j++) //try every possible path; + if(search(cur->children[j], word+i+1)) + return true; + return false; //all possible paths have failed; + } + } + return cur&&cur->isWord; //the last checking; +} + + +void wordDictionaryFree(struct WordDictionary *dict) +{ + free(dict->children); + free(dict); +} diff --git a/LuoSonglei/week-94/BasicCalculator.c b/LuoSonglei/week-94/BasicCalculator.c new file mode 100644 index 0000000..5924ed8 --- /dev/null +++ b/LuoSonglei/week-94/BasicCalculator.c @@ -0,0 +1,47 @@ +/******************************************* +Author : LHearen +E-mail : LHearen@126.com +Time : 2016-02-29 14:41 +Description : +Source : https://leetcode.com/problems/basic-calculator/ +*******************************************/ +#include +//AC - 4ms; +int calculate(char* s) +{ + int* signs = (int*)malloc(sizeof(int)); //used to store the signs before opening bracket; + int top = -1; + signs[++top] = 1; + int sign = 1; + int num = 0; + int ret = 0; //used to store the result; + while(*s) + { + if(*s>='0' && *s<='9') //collect the number between non-digits; + { + num = 10*num + *s - '0'; + } + else if(*s=='+' || *s=='-') //add the previous number and reset sign; + { + ret += signs[top]*sign*num; + num = 0; + sign = (*s=='+'? 1 : -1); + } + else if(*s == '(') //store the sign before opening bracket; + { + signs = (int*)realloc(signs, sizeof(int)*(top+2)); + signs[top+1] = sign*signs[top]; //to avoid evaluation sequence problem, moving top++ to another statement; + top++; + sign = 1; + } + else if(*s == ')') //add the previous number and delete a sign for this pair of brackets; + { + ret += signs[top--]*sign*num; + num = 0; + } + s++; + } + if(num) //if there is still number left; + ret += signs[top]*sign*num; + return ret; +} diff --git a/LuoSonglei/week-94/BitwiseANDOfNumbersRange.c b/LuoSonglei/week-94/BitwiseANDOfNumbersRange.c new file mode 100644 index 0000000..6b9f91f --- /dev/null +++ b/LuoSonglei/week-94/BitwiseANDOfNumbersRange.c @@ -0,0 +1,20 @@ +/******************************************* +Author : LHearen +E-mail : LHearen@126.com +Time : 2016-03-04 14:00 +Description : Given a range [m, n] where 0 <= m <= n <= 2147483647, return the bitwise AND of all numbers in this range, inclusive. + +For example, given the range [5, 7], you should return 4. +Source : https://leetcode.com/problems/bitwise-and-of-numbers-range/ +*******************************************/ +int rangeBitwiseAnd(int m, int n) +{ + int count = 0; + while(m != n) //until the left identical bits, all the right will be cancelled by increments from m to n;; + { + m >>= 1; + n >>= 1; + count++; + } + return m << count; +} diff --git a/LuoSonglei/week-94/BulbSwitcher.c b/LuoSonglei/week-94/BulbSwitcher.c new file mode 100644 index 0000000..8a9af83 --- /dev/null +++ b/LuoSonglei/week-94/BulbSwitcher.c @@ -0,0 +1,35 @@ +/******************************************* +Author : LHearen +E-mail : LHearen@126.com +Time : 2016-02-29 16:29 +Description : +Source : https://leetcode.com/problems/bulb-switcher/ +*******************************************/ +#include +//TLE; +int bulbSwitch0(int n) +{ + bool *lights = (bool*)malloc(sizeof(bool)*n); + memset(lights, 0, sizeof(bool)*n); + for(int i = 0; i < n; i++) + { + int k = i; + while(k < n) + { + lights[k] = !lights[k]; + k += i+1; + } + } + int count = 0; + for(int i = 0; i < n; i++) + if(lights[i]) + count++; + return count; +} + +//AC - 0ms; +//https://leetcode.com/discuss/89449/the-simplest-and-most-efficient-solution-in-well-explained +int bulbSwitch(int n) +{ + return sqrt(n); +} diff --git a/LuoSonglei/week-94/CloneGraph.c b/LuoSonglei/week-94/CloneGraph.c new file mode 100644 index 0000000..1b24121 --- /dev/null +++ b/LuoSonglei/week-94/CloneGraph.c @@ -0,0 +1,99 @@ +/******************************************* +Author : LHearen +E-mail : LHearen@126.com +Time : 2016-03-04 15:02 +Description : Clone an undirected graph. Each node in the graph contains a label and a list of its neighbors. +Source : https://leetcode.com/problems/clone-graph/ +*******************************************/ +#include +#include +#define NEIGHBORS_MAX_SIZE 100 +struct UndirectedGraphNode +{ + int label; + struct UndirectedGraphNode *neighbors[NEIGHBORS_MAX_SIZE]; + int neighborsCount; +}; + +struct Mapper +{ + struct UndirectedGraphNode *key; + struct UndirectedGraphNode *value; + struct Mapper *next; +}; + +bool push(struct Mapper* head, struct UndirectedGraphNode* key, struct UndirectedGraphNode* value) +{ + struct Mapper* p = head; + while(p->next) + { + if(p->key == key) + return false; + p = p->next; + } + p->next = (struct Mapper*)malloc(sizeof(struct Mapper)); + p = p->next; + p->key = key; + p->value = value; + return true; +} + +struct UndirectedGraphNode* pop(struct Mapper* head, struct UndirectedGraphNode* key) +{ + while(head) + { + if(head->key == key) return head->value; + head = head->next; + } + return NULL; +} + +struct UndirectedGraphNode* copy(struct UndirectedGraphNode* node) +{ + struct UndirectedGraphNode *t = (struct UndirectedGraphNode*)malloc(sizeof(struct UndirectedGraphNode)); + t->label = node->label; + int count = node->neighborsCount; + t->neighborsCount = count; + for(int i = 0; i < count; i++) + t->neighbors[i] = node->neighbors[i]; + return t; +} + +struct UndirectedGraphNode* cloneGraph(struct UndirectedGraphNode* graph) +{ + if(!graph) return NULL; + struct UndirectedGraphNode *root = copy(graph); + struct Mapper *head = (struct Mapper*)malloc(sizeof(struct Mapper)); + head->next = NULL; + head->key = 0; + push(head, graph, root); + struct UndirectedGraphNode **stack = (struct UndirectedGraphNode**)malloc(sizeof(struct UndirectedGraphNode*)); //recording the address of the original graph; + int size = 0; + stack[size++] = graph; + while(size) + { + struct UndirectedGraphNode *cur = stack[--size]; + printf("size: %d\tcurrent label: %d\t neighborsCount: %d\n", size, cur->label, cur->neighborsCount); + for(int i = 0; i < cur->neighborsCount; i++) + { + struct Mapper *p = head; + printf("inside map\n"); + while(p) + { + printf("key address: %ld\tvalue: %ld\n", p->key, p->value); + p = p->next; + } + printf("address of neighbor: %ld, pop: %d\n", cur->neighbors[i], pop(head, cur->neighbors[i])); + if(!pop(head, cur->neighbors[i])) //not visited; + { + stack = (struct UndirectedGraphNode**)realloc(stack, sizeof(struct UndirectedGraphNode*)*(size+2)); + stack[size++] = cur->neighbors[i]; + struct UndirectedGraphNode *cCur = pop(head, cur); + struct UndirectedGraphNode *cNeighbor = copy(cur->neighbors[i]); + cCur->neighbors[i] = cNeighbor; + push(head, cur->neighbors[i], cNeighbor); + } + } + } + return root; +} diff --git a/LuoSonglei/week-94/Combinations.c b/LuoSonglei/week-94/Combinations.c new file mode 100644 index 0000000..72bf653 --- /dev/null +++ b/LuoSonglei/week-94/Combinations.c @@ -0,0 +1,44 @@ +/******************************************* +Author : LHearen +E-mail : LHearen@126.com +Time : 2016-03-03 15:01 +Description : +Source : https://leetcode.com/problems/combinations/ +*******************************************/ +void traverse(int* nums, int size, int begin, int k, int* stack, int top, int*** arr, int** colSize, int* returnSize) +{ + if(top+1==k) + { + *returnSize += 1; + *colSize = (int*)realloc(*colSize, sizeof(int)*(*returnSize)); + (*colSize)[*returnSize-1] = k; + *arr = (int**)realloc(*arr, sizeof(int*)*(*returnSize)); + (*arr)[*returnSize-1] = (int*)malloc(sizeof(int)*k); + for(int i = 0; i < k; i++) + (*arr)[*returnSize-1][i] = stack[i]; + return ; + } + for(int i = begin; i < size; i++) + { + stack[top+1] = nums[i]; + traverse(nums, size, i+1, k, stack, top+1, arr, colSize, returnSize); + } +} + +//AC - 4ms; +int** combine(int n, int k, int** colSize, int* returnSize) +{ + int *nums = (int*)malloc(sizeof(int)*n); + for(int i = 0; i < n; i++) + nums[i] = i+1; + int *stack = (int*)malloc(sizeof(int)*k); + int top = -1; + *returnSize = 0; + int **arr = (int**)malloc(sizeof(int*)); + for(int i = 0; i <= n-k; i++) + { + stack[top+1] = nums[i]; + traverse(nums, n, i+1, k, stack, top+1, &arr, colSize, returnSize); + } + return arr; +} diff --git a/LuoSonglei/week-94/CourseSchedule.c b/LuoSonglei/week-94/CourseSchedule.c new file mode 100644 index 0000000..2eeffc9 --- /dev/null +++ b/LuoSonglei/week-94/CourseSchedule.c @@ -0,0 +1,58 @@ +/******************************************* +Author : LHearen +E-mail : LHearen@126.com +Time : 2016-03-04 20:02 +Description : There are a total of n courses you have to take, labeled from 0 to n - 1. + +Some courses may have prerequisites, for example to take course 0 you have to first take course 1, which is expressed as a pair: [0,1] + +Given the total number of courses and a list of prerequisite pairs, is it possible for you to finish all courses? + +For example: + +2, [[1,0]] +There are a total of 2 courses to take. To take course 1 you should have finished course 0. So it is possible. + +2, [[1,0],[0,1]] +There are a total of 2 courses to take. To take course 1 you should have finished course 0, and to take course 0 you should also have finished course 1. So it is impossible. + +Note: +The input prerequisites is a graph represented by a list of edges, not adjacency matrices. +Source : https://leetcode.com/problems/course-schedule/ +*******************************************/ +#include +void traverse(int start, int** graph, int* colSize, int* visited, bool* isCycle) +{ + if(visited[start] == 1) { *isCycle = true; return ; } + visited[start] = 1; + for(int i = 0; i < colSize[start]; i++) + { + traverse(graph[start][i], graph, colSize, visited, isCycle); + if(*isCycle) return ; + } + visited[start] = 2; +} +bool canFinish(int courses, int** prerequisites, int rSize, int cSize) +{ + int space = sizeof(int)*courses; + int* colSize = (int*)malloc(space); //count of edges of a certain node; + memset(colSize, 0, space); + int** graph = (int**)malloc(sizeof(int*)*courses); //constructing the graph; + for(int i = 0; i < courses; i++) + graph[i] = (int*)malloc(sizeof(int)*2); + for(int r = 0; r < rSize; r++) + { + int num = prerequisites[r][1]; //the head of the edge; + colSize[num]++; + graph[num][colSize[num]-1] = prerequisites[r][0]; + } + int *visited = (int*)malloc(space); + memset(visited, 0, space); + bool isCycle = false; + for(int i = 0; i < courses; i++) + { + if(isCycle) return false; + if(visited[i] == 0) traverse(i, graph, colSize, visited, &isCycle); + } + return !isCycle; +} diff --git a/LuoSonglei/week-94/CourseSchedule2.c b/LuoSonglei/week-94/CourseSchedule2.c new file mode 100644 index 0000000..f0cdf5d --- /dev/null +++ b/LuoSonglei/week-94/CourseSchedule2.c @@ -0,0 +1,69 @@ +/******************************************* +Author : LHearen +E-mail : LHearen@126.com +Time : 2016-03-04 21:47 +Description : There are a total of n courses you have to take, labeled from 0 to n - 1. + +Some courses may have prerequisites, for example to take course 0 you have to first take course 1, which is expressed as a pair: [0,1] + +Given the total number of courses and a list of prerequisite pairs, return the ordering of courses you should take to finish all courses. + +There may be multiple correct orders, you just need to return one of them. If it is impossible to finish all courses, return an empty array. + +For example: + +2, [[1,0]] +There are a total of 2 courses to take. To take course 1 you should have finished course 0. So the correct course order is [0,1] + +4, [[1,0],[2,0],[3,1],[3,2]] +There are a total of 4 courses to take. To take course 3 you should have finished both courses 1 and 2. Both courses 1 and 2 should be taken after you finished course 0. So one correct course order is [0,1,2,3]. Another correct ordering is[0,2,1,3]. + +Note: +The input prerequisites is a graph represented by a list of edges, not adjacency matrices. +Source : https://leetcode.com/problems/course-schedule-ii/ +*******************************************/ +#include +void traverse(int start, int courses, int** graph, int* colSize, int* visited, int* arr, int *returnSize) +{ + printf("start: %d\tcourses: %d\treturnSize: %d\n", start, courses, *returnSize); + if(*returnSize == courses) return ; + if(visited[start] == 1) return ; + visited[start] = 1; + arr[++(*returnSize)] = start; + for(int i = 0; i < colSize[start]; i++) + traverse(graph[start][i], courses, graph, colSize, visited, arr, returnSize); + visited[start] = 0; +} + +int* findOrder(int courses, int** prerequisites, int rSize, int cSize, int* returnSize) +{ + int* colSize = (int*)malloc(sizeof(int)*courses); + memset(colSize, 0, sizeof(int)*courses); + int** graph = (int**)malloc(sizeof(int*)*courses); + for(int i = 0; i < courses; i++) + graph[i] = (int*)malloc(sizeof(int)*2); + printf("allocating for graph done\n"); + for(int r = 0; r < rSize; r++) + { + int num = prerequisites[r][1]; + colSize[num]++; + graph[num][colSize[num]-1] = prerequisites[r][0]; + } + for(int i = 0; i < courses; i++) + { + for(int j = 0; j < colSize[i]; j++) + printf("%d\t", graph[i][j]); + printf("\n"); + } + int *arr = (int*)malloc(sizeof(int)*courses); + *returnSize = 0; + bool* visited = (bool*)malloc(sizeof(bool)*courses); + memset(visited, 0, sizeof(int)*courses); + for(int i = 0; i < courses; i++) + { + arr[*returnSize] = i; + traverse(i, courses, graph, colSize, visited, arr, returnSize); + if(*returnSize == courses) return arr; + } + return NULL; +} diff --git a/LuoSonglei/week-94/Fraction2RecurringDecimal.c b/LuoSonglei/week-94/Fraction2RecurringDecimal.c new file mode 100644 index 0000000..8d2a1bd --- /dev/null +++ b/LuoSonglei/week-94/Fraction2RecurringDecimal.c @@ -0,0 +1,91 @@ +/******************************************* +Author : LHearen +E-mail : LHearen@126.com +Time : 2016-03-01 22:42 +Description : +Source : https://leetcode.com/problems/fraction-to-recurring-decimal/ +*******************************************/ +#include +#define LEN 10000 +struct MyListNode +{ + long long key; + int val; + struct MyListNode *next; +}; + +void push(struct MyListNode* head, long long key, int val) +{ + struct MyListNode *p = head; + while(p->next) + p = p->next; + struct MyListNode *t = (struct MyListNode*)malloc(sizeof(struct MyListNode)); + t->key = key; + t->val = val; + p->next = t; +} + +int pop(struct MyListNode* head, long long key) +{ + struct MyListNode *p = head->next; + while(p) + { + if(p->key == key) + return p->val; + p = p->next; + } + return 0; +} + +//AC - 4ms; +char* fractionToDecimal(int n, int d) +{ + if(n == 0) return "0"; + char *s = (char*)malloc(sizeof(char)*LEN); + int index = 0; + if((n<0 && d>0) || (n>0 && d<0)) s[index++] = '-'; //get the sign part; + long long numerator = (n==INT_MIN)? -1*(long long)n : abs(n); //get the positive format of numerator; + long long denominator = (d==INT_MIN)? -1*(long long)d : abs(d); //get the positive format of denominator; + long long integer = numerator/denominator; //collecting the integer part; + if(integer == 0) + s[index++] = '0'; + else + { + char *t = (char*)malloc(sizeof(char)*LEN); //used to store the integer part in reverse order; + int index0 = 0; + while(integer) + { + t[index0++] = integer%10+'0'; + integer /= 10; + } + for(int i = index0-1; i > -1; i--) //reverse it again, then s will store the integer part in normal sequence; + s[index++] = t[i]; + } + long long remainder = numerator%denominator; //get the remainder by mod operator; + if(remainder == 0) + { + s[index] = '\0'; + return s; + } + s[index++] = '.'; //there are decimals; + struct MyListNode *head = (struct MyListNode*)malloc(sizeof(struct MyListNode)); //used to store the remainder digit index in string for recurring; + while(remainder) + { + int pre = pop(head, remainder); + if(pre) //check if this digit has already occurred, if so, add brackets; + { + for(int i = index; i > pre; i--) + s[i] = s[i-1]; + index++; + s[pre] = '('; + s[index++] = ')'; + break; + } + push(head, remainder, index); + remainder *= 10; //imitating division process here, retrieving the high decimal digit; + s[index++] = remainder/denominator+'0'; + remainder %= denominator; + } + s[index] = '\0'; + return s; +} diff --git a/LuoSonglei/week-94/GenerateParentheses.c b/LuoSonglei/week-94/GenerateParentheses.c new file mode 100644 index 0000000..329d4e8 --- /dev/null +++ b/LuoSonglei/week-94/GenerateParentheses.c @@ -0,0 +1,45 @@ +/******************************************* +Author : LHearen +E-mail : LHearen@126.com +Time : 2016-03-03 20:55 +Description : +Source : https://leetcode.com/problems/generate-parentheses/ +*******************************************/ +#include +void traverse(char*** arr, int* returnSize, char* stack, int top, int leftCount, int rightCount) +{ + if(!leftCount && !rightCount) + { + *returnSize += 1; + *arr = (char**)realloc(*arr, sizeof(char*)*(*returnSize)); + (*arr)[*returnSize-1] = (char*)malloc(sizeof(char)*(top+2)); + for(int i = 0; i <= top; i++) + (*arr)[*returnSize-1][i] = stack[i]; + (*arr)[*returnSize-1][top+1] = '\0'; + return ; + } + if(leftCount) + { + stack[top+1] = '('; + traverse(arr, returnSize, stack, top+1, leftCount-1, rightCount); + } + if(rightCount > leftCount) //always close the opening brackets; + { + stack[top+1] = ')'; + traverse(arr, returnSize, stack, top+1, leftCount, rightCount-1); + } +} + +//AC - 0ms; +char** generateParenthesis(int n, int* returnSize) +{ + if(!n) return NULL; + char **arr = (char**)malloc(sizeof(char*)); + *returnSize = 0; + char* stack = (char*)malloc(sizeof(char)*2*n); + int top = -1; + int leftCount = n; + int rightCount = n; + traverse(&arr, returnSize, stack, top, leftCount, rightCount); + return arr; +} diff --git a/LuoSonglei/week-94/GrayCode.c b/LuoSonglei/week-94/GrayCode.c new file mode 100644 index 0000000..8a15431 --- /dev/null +++ b/LuoSonglei/week-94/GrayCode.c @@ -0,0 +1,22 @@ +/******************************************* +Author : LHearen +E-mail : LHearen@126.com +Time : 2016-03-03 19:53 +Description : +Source : https://leetcode.com/problems/gray-code/ +*******************************************/ +//AC - 0ms; +//convert a unsigned binary number to reflected binary Gray Code (num >> 1) ^ num; +int grayCode(int n, int* returnSize) +{ + *returnSize = 0; + int *arr = (int*)malloc(sizeof(int)); + n = 1<>1); + } + return arr; +} diff --git a/LuoSonglei/week-94/ImplementTriePrefixTree.c b/LuoSonglei/week-94/ImplementTriePrefixTree.c new file mode 100644 index 0000000..8a85e25 --- /dev/null +++ b/LuoSonglei/week-94/ImplementTriePrefixTree.c @@ -0,0 +1,70 @@ +/******************************************* +Author : LHearen +E-mail : LHearen@126.com +Time : 2016-03-03 10:12 +Description : +Source : https://leetcode.com/problems/implement-trie-prefix-tree/ +*******************************************/ +#include +#include +#define LEN 26 +struct TrieNode +{ + bool isWord; + struct TrieNode **children; +}; + +struct TrieNode* nodeMaker() +{ + struct TrieNode *t = (struct TrieNode*)malloc(sizeof(struct TrieNode)); + t->isWord = false; + int space = sizeof(struct TrieNode*)*LEN; + t->children = (struct TrieNode**)malloc(space); + memset(t->children, 0, space); + return t; +} +struct TrieNode* trieCreate() +{ + return nodeMaker(); +} + +void insert(struct TrieNode *root, char *word) +{ + for(int i = 0; word[i]; i++) + { + int index = word[i]-'a'; + if(!(root->children[index])) //when there is no such child, create one; + root->children[index] = nodeMaker(); + root = root->children[index]; + } + root->isWord = true; //label this child as the leaf of the word; +} + +struct TrieNode *findLeaf(struct TrieNode *root, char *word) +{ + for(int i = 0; word[i]; i++) //following the word to traverse the tree; + { + root = root->children[word[i]-'a']; + if(!root) return false; //there is no corresponding child node; + } + return root; //at the end of the traversal, return the last node; +} + +//AC - 36ms; +bool search(struct TrieNode *root, char *word) +{ + root = findLeaf(root, word); + return root&&root->isWord; //check whether the node exists and it's the leaf of a word; +} + +bool startsWith(struct TrieNode *root, char *prefix) +{ + root = findLeaf(root, word); + return root; //check whether the node is valid; +} + +void trieFree(struct TrieNode *root) +{ + free(root->children); + free(root); +} diff --git a/LuoSonglei/week-94/Integer2EnglishWords.c b/LuoSonglei/week-94/Integer2EnglishWords.c new file mode 100644 index 0000000..e2f51db --- /dev/null +++ b/LuoSonglei/week-94/Integer2EnglishWords.c @@ -0,0 +1,62 @@ +/******************************************* +Author : LHearen +E-mail : LHearen@126.com +Time : 2016-02-29 20:54 +Description : +Source : https://leetcode.com/problems/integer-to-english-words/ +*******************************************/ +#define LEN 100 +const *units[] = {"Billion", "Million", "Thousand", "Hundred"}; +const int unitsN[] = {1000000000, 1000000, 1000, 100}; +const *tens[] = {"Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety"}; +const int tensN[] = {20, 30, 40, 50, 60, 70, 80, 90}; +const *specials[] = {"One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen"}; +const specialsN[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19}; +void helper(int* num, char* s) +{ + for(int i = 0; i < sizeof(unitsN)/sizeof(int); i++) //only this part can be handled for several times; + { + if(*num >= unitsN[i]) + { + int t = *num/unitsN[i]; + helper(&t, s); //get number of this unit; + strcat(s, " "); + strcat(s, units[i]); + *num %= unitsN[i]; + helper(num, s); //get all after this unit; + return ; + } + } + for(int i = sizeof(tensN)/sizeof(int)-1; i > -1; i--) //only be handled once for each number; + { + if(*num >= tensN[i]) + { + int t = *num - tensN[i]; + if(*s) //in case that the number is just this, avoid preceding white space; + strcat(s, " "); + strcat(s, tens[i]); + *num -= tensN[i]; + break; + } + } + for(int i = sizeof(specialsN)/sizeof(int)-1; i > -1; i--) //only be handled once for each number; + { + if(*num == specialsN[i]) + { + if(*s) //in case that the number is just this, avoid preceding white space; + strcat(s, " "); + strcat(s, specials[i]); + break; + } + } +} + +//AC - 4ms; +char* numberToWords(int num) +{ + if(!num) return "Zero"; //special case handled first, prevent messing the whole structure; + char* s = (char*)malloc(sizeof(char)*LEN); + *s = '\0'; //to use strcat normally; + helper(&num, s); //using pointer to record the modified num for latter use; + return s; +} diff --git a/LuoSonglei/week-94/Integer2Roman.c b/LuoSonglei/week-94/Integer2Roman.c new file mode 100644 index 0000000..4e84ffe --- /dev/null +++ b/LuoSonglei/week-94/Integer2Roman.c @@ -0,0 +1,129 @@ +/******************************************* +Author : LHearen +E-mail : LHearen@126.com +Time : 2016-02-29 12:23 +Description : +Source : https://leetcode.com/problems/integer-to-roman/ +*******************************************/ +#include +//AC - 28ms; +char* intToRoman0(int num) +{ + if(num<1 || num>3999) return NULL; + int index = 0; + char* s = (char*)malloc(sizeof(char)*100); + while(num >= 1000) + { + s[index++] = 'M'; + num -= 1000; + } + if(num >= 900) + { + s[index++] = 'C'; + s[index++] = 'M'; + num -= 900; + } + if(num >= 500) + { + s[index++] = 'D'; + num -= 500; + } + if(num >= 400) + { + s[index++] = 'C'; + s[index++] = 'D'; + num -= 400; + } + while(num >= 100) + { + s[index++] = 'C'; + num -= 100; + } + if(num >= 90) + { + s[index++] = 'X'; + s[index++] = 'C'; + num -= 90; + } + if(num >= 50) + { + s[index++] = 'L'; + num -= 50; + } + if(num >= 40) + { + s[index++] = 'X'; + s[index++] = 'L'; + num -= 40; + } + while(num >= 10) + { + s[index++] = 'X'; + num -= 10; + } + if(num >= 9) + { + s[index++] = 'I'; + s[index++] = 'X'; + num -= 9; + } + if(num >= 5) + { + s[index++] = 'V'; + num -= 5; + } + if(num >= 4) + { + s[index++] = 'I'; + s[index++] = 'V'; + num -= 4; + } + while(num) + { + s[index++] = 'I'; + num--; + } + s[index] = '\0'; + return s; +} + +//AC - 28ms; +//how to define an array of strings in C; +char* intToRoman1(int num) +{ + char *table[] = {"M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"}; + int units[] = {1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1}; + int index = 0; + char *s = (char*)malloc(sizeof(char)*20); + for(int i = 0; i < sizeof(units)/sizeof(int); i++) + { + while(num >= units[i]) + { + if(i%2) //the integrated numerals are in odd position in table; + { + s[index++] = table[i][0]; + s[index++] = table[i][1]; + } + else s[index++] = table[i][0]; + num -= units[i]; + } + } + s[index] = '\0'; + return s; +} + +//AC - 20ms; +char* intToRoman(int num) +{ + char* M[] = {"", "M", "MM", "MMM"}; + char* C[] = {"", "C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM"}; + char* X[] = {"", "X", "XX", "XXX", "XL", "L", "LX", "LXX", "LXXX", "XC"}; + char* I[] = {"", "I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX"}; + char* s = (char*)malloc(sizeof(char)*20); + *s = '\0'; + strcat(s, M[num/1000]); + strcat(s, C[(num%1000)/100]); + strcat(s, X[(num%100)/10]); + strcat(s, I[(num%10)]); + return s; +} diff --git a/LuoSonglei/week-94/LetterCombinationsOfPhoneNumber.c b/LuoSonglei/week-94/LetterCombinationsOfPhoneNumber.c new file mode 100644 index 0000000..c453ed0 --- /dev/null +++ b/LuoSonglei/week-94/LetterCombinationsOfPhoneNumber.c @@ -0,0 +1,45 @@ +/******************************************* +Author : LHearen +E-mail : LHearen@126.com +Time : 2016-03-03 20:40 +Description : +Source : https://leetcode.com/problems/letter-combinations-of-a-phone-number/ +*******************************************/ +#include +const char *map[] = {"", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"}; +void traverse(char* digits, int size, char* stack, int top, char*** arr, int *returnSize) +{ + if(!*digits) + { + *returnSize += 1; + *arr = (char**)realloc(*arr, sizeof(char*)*(*returnSize)); + (*arr)[*returnSize-1] = (char*)malloc(sizeof(char)*(size+1)); + for(int i = 0; i < size; i++) + (*arr)[*returnSize-1][i] = stack[i]; + (*arr)[*returnSize-1][size] = '\0'; + return ; + } + int index = *digits-'1'; + for(int i = 0; i < strlen(map[index]); i++) + { + stack[top+1] = map[index][i]; + traverse(digits+1, size, stack, top+1, arr, returnSize); + } +} +//AC - 0ms; +char** letterCombinations(char* digits, int* returnSize) +{ + if(!*digits) return NULL; + char **arr = (char**)malloc(sizeof(char*)); + *returnSize = 0; + int len = strlen(digits); + char *stack = (char*)malloc(sizeof(char)*len); + int top = -1; + int index = *digits-'1'; + for(int i = 0; i < strlen(map[index]); i++) + { + stack[top+1] = map[index][i]; + traverse(digits+1, len, stack, top+1, &arr, returnSize); + } + return arr; +} diff --git a/LuoSonglei/week-94/LongestIncreasingPathInMatrix.c b/LuoSonglei/week-94/LongestIncreasingPathInMatrix.c new file mode 100644 index 0000000..8717c76 --- /dev/null +++ b/LuoSonglei/week-94/LongestIncreasingPathInMatrix.c @@ -0,0 +1,114 @@ +/******************************************* +Author : LHearen +E-mail : LHearen@126.com +Time : 2016-03-05 09:36 +Description : Given an integer matrix, find the length of the longest increasing path. + +From each cell, you can either move to four directions: left, right, up or down. You may NOT move diagonally or move outside of the boundary (i.e. wrap-around is not allowed). + +Example 1: + +nums = [ +[9,9,4], +[6,6,8], +[2,1,1] + +] +Return 4 +The longest increasing path is [1, 2, 6, 9]. + +Example 2: + +nums = [ +[3,4,5], +[3,2,6], +[2,2,1] + +] +Return 4 +The longest increasing path is [3, 4, 5, 6]. Moving diagonally is not allowed. +Source : https://leetcode.com/problems/longest-increasing-path-in-a-matrix/ +*******************************************/ +#include +const int Directions[][2] = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}}; +bool inRange(int r, int c, int rSize, int cSize) +{ + return r>=0 && r=0 && c matrix[r-1][c]) + { + t = traverse(r-1, c, rSize, cSize, matrix, maxes)+1; + if(t > max) + max = t; + } + if(inRange(r+1, c, rSize, cSize) && cur > matrix[r+1][c]) + { + t = traverse(r+1, c, rSize, cSize, matrix, maxes)+1; + if(t > max) + max = t; + } + if(inRange(r, c-1, rSize, cSize) && cur > matrix[r][c-1]) + { + t = traverse(r, c-1, rSize, cSize, matrix, maxes)+1; + if(t > max) + max = t; + } + if(inRange(r, c+1, rSize, cSize) && cur > matrix[r][c+1]) + { + t = traverse(r, c+1, rSize, cSize, matrix, maxes)+1; + if(t > max) + max = t; + } + return maxes[r][c] = max; +} + +int traverse0(int r, int c, int rSize, int cSize, int** matrix, int** maxes) +{ + if(!inRange(r, c, rSize, cSize)) return 0; + if(maxes[r][c] != -1) return maxes[r][c]; + int cur = matrix[r][c]; + int max = 1; //as long as it's valid, it will be at least 1; + int t = 0; + for(int i = 0; i < 4; i++) //check the cells around; + { + int r0 = r+Directions[i][0]; + int c0 = c+Directions[i][1]; + if(inRange(r0, c0, rSize, cSize) && cur > matrix[r0][c0]) + { + t = traverse(r0, c0, rSize, cSize, matrix, maxes)+1; + if(t > max) + max = t; + } + } + return maxes[r][c] = max;//update the current cell; +} + +int longestIncreasingPath(int** matrix, int rSize, int cSize) +{ + int **maxes = (int**)malloc(sizeof(int*)*rSize); + for(int i = 0; i < rSize; i++) //initialize the maxes states matrix; + { + maxes[i] = (int*)malloc(sizeof(int)*cSize); + for(int j = 0; j < cSize; j++) + maxes[i][j] = -1; + } + int max = 0; + for(int r = 0; r < rSize; r++) //try to start the traversal from each cell; + { + for(int c = 0; c < cSize; c++) + { + int t = traverse(r, c, rSize, cSize, matrix, maxes); + if(t > max) + max = t; + } + } + return max; +} diff --git a/LuoSonglei/week-94/MaxProductOfWordLengths.c b/LuoSonglei/week-94/MaxProductOfWordLengths.c new file mode 100644 index 0000000..fe0b51e --- /dev/null +++ b/LuoSonglei/week-94/MaxProductOfWordLengths.c @@ -0,0 +1,45 @@ +/******************************************* +Author : LHearen +E-mail : LHearen@126.com +Time : 2016-03-04 13:26 +Description : Given a string array words, find the maximum value of length(word[i]) * length(word[j]) where the two words do not share common letters. You may assume that each word will contain only lower case letters. If no such two words exist, return 0. + +Example 1: +Given ["abcw", "baz", "foo", "bar", "xtfn", "abcdef"] +Return 16 +The two words can be "abcw", "xtfn". + +Example 2: +Given ["a", "ab", "abc", "d", "cd", "bcd", "abcd"] +Return 4 +The two words can be "ab", "cd". + +Example 3: +Given ["a", "aa", "aaa", "aaaa"] +Return 0 +No such pair of words. +Source : https://leetcode.com/problems/maximum-product-of-word-lengths/ +*******************************************/ +//AC - 40ms; +int maxProduct(char** words, int wSize) +{ + int space = sizeof(int)*wSize; //since we are going to use this value several times, store it; + int *lens = (int*)malloc(space); + for(int i = 0; i < wSize; i++) //pre-store the lengths for all words; + lens[i] = strlen(words[i]); + int *flags = (int*)malloc(space); + memset(flags, 0, space); + for(int i = 0; i < wSize; i++) //retrieve the bit-flag from word; + for(int j = 0; words[i][j]; j++) + flags[i] |= 1<<(words[i][j]-'a'); + int max = 0; + for(int i = 0; i < wSize; i++) //traversing each pair of two different words; + for(int j = i+1; j < wSize; j++) + if(!(flags[i] & flags[j])) + { + int t = lens[i]*lens[j]; + if(t > max) + max = t; + } + return max; +} diff --git a/LuoSonglei/week-94/MinHeightTrees.c b/LuoSonglei/week-94/MinHeightTrees.c new file mode 100644 index 0000000..6fadcb9 --- /dev/null +++ b/LuoSonglei/week-94/MinHeightTrees.c @@ -0,0 +1,82 @@ +/******************************************* +Author : LHearen +E-mail : LHearen@126.com +Time : 2016-03-05 21:47 +Description : For a undirected graph with tree characteristics, we can choose any node as the root. The result graph is then a rooted tree. Among all possible rooted trees, those with minimum height are called minimum height trees (MHTs). Given such a graph, write a function to find all the MHTs and return a list of their root labels. + +Format +The graph contains n nodes which are labeled from 0 to n - 1. You will be given the number n and a list of undirected edges (each edge is a pair of labels). + +You can assume that no duplicate edges will appear in edges. Since all edges are undirected, [0, 1] is the same as [1, 0] and thus will not appear together in edges. + +Example 1: + +Given n = 4, edges = [[1, 0], [1, 2], [1, 3]] + +0 +| +1 +/ \ +2 3 +return [1] +Source : https://leetcode.com/problems/minimum-height-trees/ +*******************************************/ +int* findMinHeightTrees(int n, int** edges, int rSize, int cSize, int* returnSize) +{ + int* arr = (int*)malloc(sizeof(int)*n); + *returnSize = 0; + if(n == 1) //corner case; + { + *returnSize += 1; + arr[*returnSize-1] = 0; + return arr; + } + int** graph = (int**)malloc(sizeof(int*)*n); //constructing the graph as a DAG - Directed Acyclic Graph; + for(int i = 0; i < n; i++) + graph[i] = (int*)malloc(sizeof(int)); + int* colSizes = (int*)malloc(sizeof(int)*n); + memset(colSizes, 0, sizeof(int)*n); + for(int i = 0; i < rSize; i++) //constructing the graph in edges list format; + { + int begin = edges[i][0]; + int end = edges[i][1]; + colSizes[begin]++; + graph[begin] = (int*)realloc(graph[begin], sizeof(int)*colSizes[begin]); //dynamically allocate the space - just use the required space, nothing more; + graph[begin][colSizes[begin]-1] = end; + colSizes[end]++; + graph[end] = (int*)realloc(graph[end], sizeof(int)*colSizes[end]); + graph[end][colSizes[end]-1] = begin; + } + int* degrees = (int*)malloc(sizeof(int)*n); + for(int i = 0; i < n; i++) //collecting the bottom leaves; + { + degrees[i] = colSizes[i]; //copy the degrees; + if(colSizes[i] == 1) + { + *returnSize += 1; + arr[*returnSize-1] = i; + } + } + int count = n; //record the vertexes left; + int* nextLevel = (int*)malloc(sizeof(int)*n); //used with arr imitating queue operations; + int next = 0; + while(count > 2) + { + for(int i = 0; i < *returnSize; i++) + { + int end = arr[i]; + count--; //remove the leaf then the vertexes left should be decremented; + for(int k = 0; k < colSizes[end]; k++) //decrement related vertexes in degrees; + { + int begin = graph[end][k]; + degrees[begin]--; + if(degrees[begin] == 1) //when the degree of the connected vertex is 1 which means it turns leaf now, collect it for next level; + nextLevel[next++] = graph[end][k]; + } + } + *returnSize = next; //update next, returnSize, arr and nextLevel for next round; + next = 0; + int *t=arr; arr=nextLevel; nextLevel=t; + } + return arr; +} diff --git a/LuoSonglei/week-94/MinHeightTrees0.c b/LuoSonglei/week-94/MinHeightTrees0.c new file mode 100644 index 0000000..233327d --- /dev/null +++ b/LuoSonglei/week-94/MinHeightTrees0.c @@ -0,0 +1,93 @@ +/******************************************* +Author : LHearen +E-mail : LHearen@126.com +Time : 2016-03-05 21:47 +Description : For a undirected graph with tree characteristics, we can choose any node as the root. The result graph is then a rooted tree. Among all possible rooted trees, those with minimum height are called minimum height trees (MHTs). Given such a graph, write a function to find all the MHTs and return a list of their root labels. + +Format +The graph contains n nodes which are labeled from 0 to n - 1. You will be given the number n and a list of undirected edges (each edge is a pair of labels). + +You can assume that no duplicate edges will appear in edges. Since all edges are undirected, [0, 1] is the same as [1, 0] and thus will not appear together in edges. + +Example 1: + +Given n = 4, edges = [[1, 0], [1, 2], [1, 3]] + +0 +| +1 +/ \ +2 3 +return [1] +Source : https://leetcode.com/problems/minimum-height-trees/ +*******************************************/ +int* findMinHeightTrees(int n, int** edges, int rSize, int cSize, int* returnSize) +{ + int* arr = (int*)malloc(sizeof(int)*n); + *returnSize = 0; + if(n == 1) + { + *returnSize += 1; + arr[*returnSize-1] = 0; + return arr; + } + int** graph = (int**)malloc(sizeof(int*)*n); //constructing the graph as a DAG - Directed Acyclic Graph; + for(int i = 0; i < n; i++) + graph[i] = (int*)malloc(sizeof(int)); + int* colSizes = (int*)malloc(sizeof(int)*n); + memset(colSizes, 0, sizeof(int)*n); + for(int i = 0; i < rSize; i++) + { + int begin = edges[i][0]; + int end = edges[i][1]; + colSizes[begin]++; + graph[begin] = (int*)realloc(graph[begin], sizeof(int)*colSizes[begin]); //dynamically allocate the space - just use the required space, nothing more; + graph[begin][colSizes[begin]-1] = end; + colSizes[end]++; + graph[end] = (int*)realloc(graph[end], sizeof(int)*colSizes[end]); + graph[end][colSizes[end]-1] = begin; + } + for(int i = 0; i < n; i++) //collecting the bottom leaves; + { + if(colSizes[i] == 1) + { + *returnSize += 1; + arr[*returnSize-1] = i; + } + } + int* nextLevel = (int*)malloc(sizeof(int)*n); //traversing in a bottom-up way; + int next = 0; + while(*returnSize) //there is more; + { + for(int i = 0; i < *returnSize; i++) + { + int end = arr[i]; + for(int j = 0; j < n; j++) //remove it from its connected vertexes; + { + for(int k = 0; k < colSizes[j]; k++) //searching it in node j checking whether they are connected; + { + if(graph[j][k] == end) //connected then remove it from node j; + { + int h = k+1; + while(h < colSizes[j]) //remove it; + { + graph[j][h-1] = graph[j][h]; + h++; + } + colSizes[j]--; + if(colSizes[j] == 1) //if now node j becomes a leaf itself, add it to the nextLevel; + { + next++; + nextLevel[next-1] = j; + } + break; + } + } + } + } + if(!next) return arr; //no next level any more then arr collected all the top-level and return it; + *returnSize = next; //prepare for the next level traversal; + next = 0; + int *t = arr; arr=nextLevel; nextLevel=t; + } +} diff --git a/LuoSonglei/week-94/MultiplyStrings.c b/LuoSonglei/week-94/MultiplyStrings.c new file mode 100644 index 0000000..c2b8506 --- /dev/null +++ b/LuoSonglei/week-94/MultiplyStrings.c @@ -0,0 +1,33 @@ +/******************************************* +Author : LHearen +E-mail : LHearen@126.com +Time : 2016-03-01 08:56 +Description : +Source : https://leetcode.com/problems/multiply-strings/ +*******************************************/ +//AC - 4ms; +char* multiply(char* num1, char* num2) +{ + if(*num1=='0' || *num2=='0') return "0"; + int len1 = strlen(num1); + int len2 = strlen(num2); + int len = len1+len2; + int *arr = (int*)malloc(sizeof(int)*len); //the number of digits of the result - len is the top; + memset(arr, 0, sizeof(int)*len); //this is critical; + for(int i=len1-1; i > -1; i--) + for(int j=len2-1; j > -1; j--) + arr[i+j+1] += (num1[i]-'0')*(num2[j]-'0'); //collect result of each position; + for(int i=len-1; i > 0; i--) //restore the carry for each position and get the final result; + { + arr[i-1] += arr[i]/10; + arr[i] %= 10; + } + char *s = (char*)malloc(sizeof(char)*(len+1)); //converting the digits result to string; + int index = 0; + int i = 0; + if(arr[i]==0) i++; //in case the zero position has no carry, if it does, ignore it; + while(i < len) + s[index++] = arr[i++]+'0'; + s[index] = '\0'; + return s; +} diff --git a/LuoSonglei/week-94/NumberOfDigitOne.c b/LuoSonglei/week-94/NumberOfDigitOne.c new file mode 100644 index 0000000..d336d9a --- /dev/null +++ b/LuoSonglei/week-94/NumberOfDigitOne.c @@ -0,0 +1,21 @@ +/******************************************* +Author : LHearen +E-mail : LHearen@126.com +Time : 2016-03-01 16:20 +Description : +Source : https://leetcode.com/problems/number-of-digit-one/ +*******************************************/ +//AC - 0ms; +//https://leetcode.com/discuss/44281/4-lines-o-log-n-c-java-python +int countDigitOne(int n) +{ + if(n < 10) return 0; + long long count = 0; + for(long long m = 1; m <= n; m *= 10) + { + int a = n/m; + int b = n%m; + count += (a+8)/10*m+(a%10==1)*(b+1); //0, 1 and >=2 should be treated differently when we are counting for each unit; + } + return count; +} diff --git a/LuoSonglei/week-94/NumberOfIslands.c b/LuoSonglei/week-94/NumberOfIslands.c new file mode 100644 index 0000000..cd4d5c9 --- /dev/null +++ b/LuoSonglei/week-94/NumberOfIslands.c @@ -0,0 +1,98 @@ +/******************************************* +Author : LHearen +E-mail : LHearen@126.com +Time : 2016-03-05 10:41 +Description : Given a 2d grid map of '1's (land) and '0's (water), count the number of islands. An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. You may assume all four edges of the grid are all surrounded by water. + +Example 1: + +11110 +11010 +11000 +00000 +Answer: 1 + +Example 2: + +11000 +11000 +00100 +00011 +Answer: 3 + +Source : https://leetcode.com/problems/number-of-islands/ +*******************************************/ +#include +const int Directions[][2] = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}}; +bool inRange(int r, int c, int rSize, int cSize) +{ + return r>=0 && r=0 && c0 && grid[r-1][c]=='1') //since we are just moving upwards, just checking row's validity is enough; + traverse(r-1, c, rSize, cSize, grid); + if(c>0 && grid[r][c-1]=='1') + traverse(r, c-1, rSize, cSize, grid); + if(r +void traverse(char* s, int len, int begin, char** stack, int top, char**** arrs, int** colSizes, int* returnSize) +{ + if(begin == len) //there is nothing left, collect the strings of a set; + { + *returnSize += 1; + *colSizes = (int*)realloc(*colSizes, sizeof(int)*(*returnSize)); + int size = top+1; + (*colSizes)[*returnSize-1] = size; + *arrs = (char***)realloc(*arrs, sizeof(char**)*(*returnSize)); + (*arrs)[*returnSize-1] = (char**)malloc(sizeof(char*)*size); + for(int i = 0; i < size; i++) + (*arrs)[*returnSize-1][i] = stack[i]; + return ; + } + for(int i = begin; i < len; i++) //check each string that begin with s[begin]; + { + int l=begin, r=i; + while(l= r) //it's a palindrome; + { + int size = i-begin+1; + char *t = (char*)malloc(sizeof(char)*(size+1)); + *t = '\0'; + strncat(t, s+begin, size); + stack[top+1] = t; + traverse(s, len, i+1, stack, top+1, arrs, colSizes, returnSize); //collect the left; + } + } +} + +//AC - 8ms; +char*** partition(char* s, int** colSizes, int* returnSize) +{ + if(!*s) return NULL; + int len = strlen(s); + *returnSize = 0; + *colSizes = (char*)malloc(sizeof(char)); + char*** arrs = (char***)malloc(sizeof(char**)); + char** stack = (char**)malloc(sizeof(char*)*len); + int top = -1; + traverse(s, strlen(s), 0, stack, top, &arrs, colSizes, returnSize); + return arrs; +} diff --git a/LuoSonglei/week-94/ReconstructItinerary.c b/LuoSonglei/week-94/ReconstructItinerary.c new file mode 100644 index 0000000..3e01ada --- /dev/null +++ b/LuoSonglei/week-94/ReconstructItinerary.c @@ -0,0 +1,128 @@ +/******************************************* +Author : LHearen +E-mail : LHearen@126.com +Time : 2016-03-05 11:28 +Description : Given a list of airline tickets represented by pairs of departure and arrival airports [from, to], reconstruct the itinerary in order. All of the tickets belong to a man who departs from JFK. Thus, the itinerary must begin with JFK. + +Note: +If there are multiple valid itineraries, you should return the itinerary that has the smallest lexical order when read as a single string. For example, the itinerary ["JFK", "LGA"] has a smaller lexical order than ["JFK", "LGB"]. +All airports are represented by three capital letters (IATA code). +You may assume all tickets form at least one valid itinerary. +Example 1: +tickets = [["MUC", "LHR"], ["JFK", "MUC"], ["SFO", "SJC"], ["LHR", "SFO"]] +Return ["JFK", "MUC", "LHR", "SFO", "SJC"]. +Example 2: +tickets = [["JFK","SFO"],["JFK","ATL"],["SFO","ATL"],["ATL","JFK"],["ATL","SFO"]] +Return ["JFK","ATL","JFK","SFO","ATL","SFO"]. +Another possible reconstruction is ["JFK","SFO","ATL","JFK","ATL","SFO"]. But it is larger in lexical order. +Source : https://leetcode.com/problems/reconstruct-itinerary/ +*******************************************/ +#include +struct Mapper +{ + char *key; + char **values; + int size; +}; + +void insert(struct Mapper*** dict, int* size, char* key, char* value) +{ + for(int i = 0; i < *size; i++) + { + if(!strcmp((*dict)[i]->key, key)) + { + struct Mapper *t = (*dict)[i]; + t->size += 1; + t->values = (char**)realloc(t->values, sizeof(char*)*(t->size)); + int j = t->size-2; + while(strcmp(t->values[j], value) == 1) + { + t->values[j+1] = t->values[j]; + j--; + } + t->values[j] = value; + return ; + } + } + *size += 1; + *dict = (struct Mapper**)realloc(*dict, sizeof(struct Mapper*)*(*size)); + struct Mapper *t = (struct Mapper*)malloc(sizeof(struct Mapper)); + t->key = key; + t->values = (char**)malloc(sizeof(char*)); + t->values[0] = value; + t->size = 1; + (*dict)[*size-1] = t; +} + +void traverse(struct Mapper *start, struct Mapper** dict, int size, char** stack, int* returnSize, int tCount) +{ + printf("\n\n"); + printf("collected: \n"); + for(int j = 0; j < *returnSize; j++) + printf("%s -> ", stack[j]); + printf("current: %s\treturnSize: %d\n", start->key, *returnSize); + if(*returnSize == tCount) return ; + *returnSize += 1; + stack[*returnSize-1] = start->key; + if(*returnSize == tCount) return ; + for(int i = 0; i < start->size; i++) + { + int t = *returnSize; + struct Mapper *next = NULL; + for(int j = 0; j < size; j++) + if(!strcmp(dict[j]->key, start->values[i])) + next = dict[j]; + if(!next) return ; + traverse(next, dict, size, stack, returnSize, tCount); + if(*returnSize == tCount) return ; + *returnSize = t; + } +} +char** findItinerary(char*** tickets, int rSize, int cSize, int* returnSize) +{ + int count = 0; + struct Mapper **dict = (struct Mapper**)malloc(sizeof(struct Mapper*)); + for(int i = 0; i < rSize; i++) //constructing graph in edges list; + insert(&dict, &count, tickets[i][0], tickets[i][1]); + char** tt = (char**)malloc(sizeof(char*)*2*rSize); + int tCount = 0; + for(int i = 0; i < rSize; i++) + { + int j = 0; + while(j < tCount) + { + if(!strcmp(tickets[i][0], tt[j])) + break; + j++; + } + if(j == tCount) + tt[tCount++] = tickets[i][0]; + j = 0; + while(j < tCount) + { + if(!strcmp(tickets[i][1], tt[j])) + break; + j++; + } + if(j == tCount) + tt[tCount++] = tickets[i][1]; + } + printf("tCount: %d\n", tCount); + for(int i = 0; i < count; i++) + { + printf("key: %s\t --> ", dict[i]->key); + for(int j = 0; j < dict[i]->size; j++) + printf("\t%s", dict[i]->values[j]); + printf("\n"); + } + char** stack = (char**)malloc(sizeof(char*)*count); + for(int i = 0; i < count; i++) + { + *returnSize = 0; + traverse(dict[i], dict, count, stack, returnSize, tCount); + for(int j = 0; j < *returnSize; j++) + printf("%s -> ", stack[j]); + if(*returnSize == tCount) return stack; + } + return NULL; +} diff --git a/LuoSonglei/week-94/RemoveInvalidParentheses.c b/LuoSonglei/week-94/RemoveInvalidParentheses.c new file mode 100644 index 0000000..e9ecb9d --- /dev/null +++ b/LuoSonglei/week-94/RemoveInvalidParentheses.c @@ -0,0 +1,87 @@ +/******************************************* +Author : LHearen +E-mail : LHearen@126.com +Time : 2016-03-05 20:48 +Description : Remove the minimum number of invalid parentheses in order to make the input string valid. Return all possible results. + +Note: The input string may contain letters other than the parentheses ( and ). + +Examples: +"()())()" -> ["()()()", "(())()"] +"(a)())()" -> ["(a)()()", "(a())()"] +")(" -> [""]")" +Source : https://leetcode.com/problems/remove-invalid-parentheses/ +*******************************************/ +void traverse(char* s, int len, int start, int left, int right, int pair, char* stack, int top, char*** arr, int *returnSize) +{ + if(start == len) + { + if(!left && !right && !pair) + { + int size = top+1; + char *t = (char*)malloc(sizeof(char)*(size+1)); + for(int i = 0; i < size; i++) + t[i] = stack[i]; + t[size] = '\0'; + int i = 0; + while(i < *returnSize) //remove duplicates; + { + if(!strcmp(t, (*arr)[i])) + break; + i++; + } + if(i == *returnSize) //add a bran-new string; + { + *returnSize += 1; + *arr = (char**)realloc(*arr, sizeof(char*)*(*returnSize)); + (*arr)[*returnSize-1] = t; + } + } + return ; + } + char c = s[start]; + if(c == '(') + { + if(left) //try to remove it; + traverse(s, len, start+1, left-1, right, pair, stack, top, arr, returnSize); + stack[top+1] = c; //try to add it as a pair; + traverse(s, len, start+1, left, right, pair+1, stack, top+1, arr, returnSize); + } + else if(c == ')') + { + if(right) //try to remove it; + traverse(s, len, start+1, left, right-1, pair, stack, top, arr, returnSize); + if(pair) //try to use it as the other half of a pair; + { + stack[top+1] = c; + traverse(s, len, start+1, left, right, pair-1, stack, top+1, arr, returnSize); + } + } + else //just collect since it's not brackets; + { + stack[top+1] = c; + traverse(s, len, start+1, left, right, pair, stack, top+1, arr, returnSize); + } +} + +//AC - 0ms; +char** removeInvalidParentheses(char* s, int* returnSize) +{ + char** arr = (char**)malloc(sizeof(char*)); + *returnSize = 0; + int left=0, right=0; + for(int i = 0; s[i]; i++) //find out how many opening and closing brackets should be removed; + { + if(s[i] == '(') left++; + else if(s[i] == ')') + { + if(left) left--; + else right++; + } + } + int len = strlen(s); + char *stack = (char*)malloc(sizeof(char)*len); + int top = -1; + traverse(s, len, 0, left, right, 0, stack, top, &arr, returnSize); + return arr; +} diff --git a/LuoSonglei/week-94/SudokuSolver.c b/LuoSonglei/week-94/SudokuSolver.c new file mode 100644 index 0000000..ea52584 --- /dev/null +++ b/LuoSonglei/week-94/SudokuSolver.c @@ -0,0 +1,37 @@ +/******************************************* +Author : LHearen +E-mail : LHearen@126.com +Time : 2016-03-04 09:20 +Description : +Source : https://leetcode.com/problems/sudoku-solver/?sort=votes +*******************************************/ +#include +bool check(char** board, int r, int c, char a) //check it in row, column and the sub three-dimension cube; +{ + for(int i = 0; i < 9; i++) if(board[r][i]==a || board[i][c]==a) return false; + int r0=r-r%3, c0=c-c%3; //get the start row and column of the sub cube; + for(int i = 0; i < 3; i++) + for(int j = 0; j < 3; j++) + if(board[r0+i][c0+j] == a) return false; + return true; +} +bool solver(char** board, int r, int c) //check and try it from left to right and then downwards; +{ + if(r == 9) return true; //now till the end and nothing wrong so far, so return true; + if(c == 9) return solver(board, r+1, 0); //till the end of the current row and then downwards; + if(board[r][c] != '.') return solver(board, r, c+1); //already taken just move to the next; + for(char a = '1'; a <= '9'; a++) //try each possible candidate; + { + if(check(board, r, c, a)) //check its validity; + { + board[r][c] = a; //set it then and just move to the next; + if(solver(board, r, c+1)) return true; //if it's solvable then just return true; + board[r][c] = '.'; //restore it for easier checking in the next round; + } + } + return false; //nothing works around then return false; +} +void solveSudoku(char** board, int rSize, int cSize) +{ + solver(board, 0, 0); //start from the top-left position to the bottom right end; +} diff --git a/LuoSonglei/week-94/SuperUglyNumber.c b/LuoSonglei/week-94/SuperUglyNumber.c new file mode 100644 index 0000000..030a491 --- /dev/null +++ b/LuoSonglei/week-94/SuperUglyNumber.c @@ -0,0 +1,30 @@ +/******************************************* +Author : LHearen +E-mail : LHearen@126.com +Time : 2016-03-01 19:06 +Description : +Source : https://leetcode.com/problems/super-ugly-number/ +*******************************************/ +#include +//AC - 40ms; +int nthSuperUglyNumber(int n, int* primes, int size) +{ + int *uglies = (int*)malloc(sizeof(int)*n); + uglies[0] = 1; //the first SuperUgly; + int *indexes = (int*)malloc(sizeof(int)*size); + memset(indexes, 0, sizeof(int)*size); //all pointing to the first SuperUgly first; + for(int i = 1; i < n; i++) //you will never know how big n can be; + uglies[i] = INT_MAX; + for(int i = 1; i < n; i++) + { + for(int j = 0; j < size; j++) //search for the smallest that can be retrieved from primes and former SuperUgly numbers; + { + int t = uglies[indexes[j]]*primes[j]; + if(uglies[i] < t) + uglies[i] = t; + } + for(int j = 0; j < size; j++) //make sure there will be no duplicate, so that we can find the (i+1)th; + indexes[j] += (uglies[i]==uglies[indexes[j]]*primes[j]); + } + return uglies[n-1]; +} diff --git a/LuoSonglei/week-94/ValidNumber.c b/LuoSonglei/week-94/ValidNumber.c new file mode 100644 index 0000000..fecc6ec --- /dev/null +++ b/LuoSonglei/week-94/ValidNumber.c @@ -0,0 +1,80 @@ +/******************************************* +Author : LHearen +E-mail : LHearen@126.com +Time : 2016-03-02 11:12 +Description : +Source : https://leetcode.com/problems/valid-number/ +*******************************************/ +/* + * .1 -> true; + * 07 -> true; + * 09 -> true; + * 3. -> true; + * 0000 -> true; + * 10e300 -> true; + * 10e-300 -> true; + * 10e+300 -> true; + * 10000000000.0000 -> true; + * + * e -> false; + * 0e -> false; + * 0e+ -> false; + * 6ee9 -> false; + * ..2 -> false; + * ++2 -> false; + * - -> false; + * + -> false; + * -> false; + * . -> false; + * e3 -> false; + * 3e 3 -> false; + * 10E20 -> false; + * 0xf and 0xF -> false; + */ +#include +bool isSign(char c) +{ + return c=='+' || c=='-'; +} + +//AC - 8ms; +bool isNumber(char* s) +{ + int index = 0; + int len = strlen(s); + int i = 0; + while(s[i] == ' ') i++; //remove the prefixing white spaces; + if(isSign(s[i])) i++; //if there is a sign in the head, remove it first - only remove the first ignoring the latter ones if there are some; + while(i < len) + s[index++] = s[i++]; + while(s[index-1] == ' ') index--; //remove the suffixing white spaces; + s[index] = '\0';//no prefixing and suffixing white spaces and preceding sign; + if(index==0) return false; //nothing here; + bool eOccurred = false; + bool signOccurred = false; + bool digitOccurred = false; + bool dotOccurred = false; + for(int i = 0; i < index; i++) //traversing and checking each character; + { + if(isdigit(s[i])) + digitOccurred = true; + else if(s[i]=='e') //e only appears once; e cannot be the first and the last also; + { + if(eOccurred || !digitOccurred || s[i+1] == '\0') return false; + eOccurred = true; + } + else if(isSign(s[i])) //since we removed the first sign(if there is), the latter sign can only occur after e; can only appear once if ignoring the first preceding one; can not be the first since we have remove one if there is; the previous character must be e; and it cannot be the last; + { + if(!eOccurred || signOccurred || (i==0 || s[i-1]!='e' || s[i+1]=='\0')) return false; + signOccurred = true; + } + else if(s[i] == '.') //dot cannot be following e; can only appear once; there must be some preceding digits if dot is the last; + { + if(eOccurred || dotOccurred || (!digitOccurred && s[i+1]=='\0')) return false; + dotOccurred = true; + } + else //white space or other characters; + return false; + } + return true; +} diff --git a/LuoSonglei/week-94/WordSearch2.c b/LuoSonglei/week-94/WordSearch2.c new file mode 100644 index 0000000..cb93842 --- /dev/null +++ b/LuoSonglei/week-94/WordSearch2.c @@ -0,0 +1,93 @@ +/******************************************* +Author : LHearen +E-mail : LHearen@126.com +Time : 2016-03-04 10:37 +Description : Given a 2D board and a list of words from the dictionary, find all words in the board. +Each word must be constructed from letters of sequentially adjacent cell, where "adjacent" cells are those horizontally or vertically neighboring. The same letter cell may not be used more than once in a word. +For example, +Given words = ["oath","pea","eat","rain"] and board = +[ + ['o','a','a','n'], + ['e','t','a','e'], + ['i','h','k','r'], + ['i','f','l','v'] +] +Return ["eat","oath"]. +Note: +You may assume that all inputs are consist of lowercase letters a-z. +Source : https://leetcode.com/problems/word-search-ii/ +*******************************************/ +#include +#define PLACEHOLDER '#' +#define SIZE 26 +struct TrieNode +{ + bool isWord; + struct TrieNode **children; +}; + +struct TrieNode* nodeMaker() +{ + struct TrieNode *t = (struct TrieNode*)malloc(sizeof(struct TrieNode)); + t->isWord = false; + int space = sizeof(struct TrieNode*)*SIZE; + t->children = (struct TrieNode**)malloc(space); + memset(t->children, 0, space); + return t; +} + +struct TrieNode* addWords(char** words, int size) +{ + struct TrieNode *root = nodeMaker(); + struct TrieNode *cur; + for(int i = 0; i < size; i++) + { + cur = root; //always start from the root; + for(int j = 0; words[i][j]; j++) + { + int index = words[i][j]-'a'; + if(!(cur->children[index])) + cur->children[index] = nodeMaker(); + cur = cur->children[index]; + } + cur->isWord = true; + } + return root; +} + +void traverse(char** board, int rSize, int cSize, int r, int c, struct TrieNode* root, char* stack, int top, char*** arr, int* returnSize) +{ + if(r<0 || c<0 || r==rSize || c==cSize || board[r][c]==PLACEHOLDER) return ; //either out of range or being taken; + char a = board[r][c]; + root = root->children[a-'a']; + if(!root) return ; + stack[++top] = a; + if(root->isWord) //hit the word, now collect it; + { + *returnSize += 1; + *arr = (char**)realloc(*arr, sizeof(char*)*(*returnSize)); + int len = top+1; + (*arr)[*returnSize-1] = (char*)malloc(sizeof(char)*(len+1)); + for(int i = 0; i < len; i++) + (*arr)[*returnSize-1][i] = stack[i]; + (*arr)[*returnSize-1][len] = '\0'; + root->isWord = false; //already taken, avoid being re-taken; + } + board[r][c] = PLACEHOLDER; //avoid being re-taken by the following four new searchings; + traverse(board, rSize, cSize, r+1, c, root, stack, top, arr, returnSize); + traverse(board, rSize, cSize, r-1, c, root, stack, top, arr, returnSize); + traverse(board, rSize, cSize, r, c+1, root, stack, top, arr, returnSize); + traverse(board, rSize, cSize, r, c-1, root, stack, top, arr, returnSize); + board[r][c] = a; //restore it always after checking each possible path; +} +char** findWords(char** board, int rSize, int cSize, char** words, int wSize, int* returnSize) +{ + struct TrieNode *root = addWords(words, wSize); + char** arr = (char**)malloc(sizeof(char*)); + char* stack = (char*)malloc(sizeof(char)*SIZE*2); + int top = -1; + for(int r = 0; r < rSize; r++) //start from all the possible cells; + for(int c = 0; c < cSize; c++) + traverse(board, rSize, cSize, r, c, root, stack, top, &arr, returnSize); + return arr; +} diff --git a/LuoSonglei/week-95/139-WordBreak.c b/LuoSonglei/week-95/139-WordBreak.c new file mode 100644 index 0000000..0c4dc08 --- /dev/null +++ b/LuoSonglei/week-95/139-WordBreak.c @@ -0,0 +1,107 @@ +/******************************************* +Author : LHearen +E-mail : LHearen@126.com +Time : 2016-03-13 10:28 +Description : Given a string s and a dictionary of words dict, determine if s can be segmented into a space-separated sequence of one or more dictionary words. + +For example, given +s = "leetcode", +dict = ["leet", "code"]. + +Return true because "leetcode" can be segmented as "leet code". +Source : https://leetcode.com/problems/word-break/ +*******************************************/ +#include +#define MIN(a, b) ((a) < (b) ? (a) : (b)) +//TLE +//"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaab" +//["a","aa","aaa","aaaa","aaaaa","aaaaaa","aaaaaaa","aaaaaaaa","aaaaaaaaa","aaaaaaaaaa"] +//Using naive DFS will result in this case, try to record the status information; + +//AC - BFS - 0ms +bool wordBreak0(char* s, char** dict, int size) +{ + int min=INT_MAX, max=0; //compare only in a limited range of length of the substring actually; + int* lens = (int*)malloc(sizeof(int)*size); //used to compare substring with words; + int lSize = 0; + for(int i = 0; i < size; i++) + { + int len = strlen(dict[i]); + lens[lSize++] = len; + if(len < min) min = len; + if(len > max) max = len; + } + int len = strlen(s); + bool* visited = (bool*)malloc(sizeof(bool)*len); //used to record whether the index visited or not; + memset(visited, 0, len*sizeof(bool)); + int* queue = (int*)malloc(sizeof(int)*len*100); //avoid parallel stacks' interdenpendency; + int begin=0, end=-1; + queue[++end] = 0; + while(end-begin > -1) + { + int start = queue[begin++]; + if(!visited[start]) //unvisited so far; + { + visited[start] = true; //label it as visited; + for(int j = min; j <= MIN(max, len-start); j++) //check different length of substringfrom the start index; + { + int i = 0; + for(; i < size; i++) + if(lens[i]==j && strncmp(dict[i], s+start, j)==0) + break; + if(i != size) + { + int next = start+j; + queue[++end] = next; + if(next == len) + return true; + } + } + } + } + return false; +} + +//AC - DFS - 0ms; +bool wordBreak(char* s, char** dict, int size) +{ + int min=INT_MAX, max=0; //compare only in a limited range of length of the substring actually; + int* lens = (int*)malloc(sizeof(int)*size); //used to compare substring with words; + int lSize = 0; + for(int i = 0; i < size; i++) + { + int len = strlen(dict[i]); + lens[lSize++] = len; + if(len < min) min = len; + if(len > max) max = len; + } + int len = strlen(s); + bool* visited = (bool*)malloc(sizeof(bool)*len); //used to record whether the index visited or not; + memset(visited, 0, len*sizeof(bool)); + int* stack = (int*)malloc(sizeof(int)*len*100); //avoid parallel stacks' interdenpendency; + int top = -1; + stack[++top] = 0; + while(top > -1) + { + int start = stack[top--]; + if(!visited[start]) //unvisited so far; + { + visited[start] = true; //label it as visited; + for(int j = min; j <= MIN(max, len-start); j++) //check different length of substringfrom the start index; + { + int i = 0; + for(; i < size; i++) + if(lens[i]==j && strncmp(dict[i], s+start, j)==0) + break; + if(i != size) + { + int next = start+j; + stack[++top] = next; + if(next == len) + return true; + } + } + } + } + return false; +} diff --git a/LuoSonglei/week-95/14-LongestCommonPrefix.c b/LuoSonglei/week-95/14-LongestCommonPrefix.c new file mode 100644 index 0000000..d3b9c64 --- /dev/null +++ b/LuoSonglei/week-95/14-LongestCommonPrefix.c @@ -0,0 +1,32 @@ +/******************************************* +Author : LHearen +E-mail : LHearen@126.com +Time : 2016-03-07 21:37 +Description : Write a function to find the longest common prefix string amongst an array of strings. +Source : https://leetcode.com/problems/longest-common-prefix/ +*******************************************/ +#include +//AC - 0ms; +char* longestCommonPrefix(char** strs, int size) +{ + if(!size) return ""; + char *s = (char*)malloc(sizeof(char)*(strlen(strs[0]+1))); + int index = 0; + for(int i = 0; strs[0][i]; i++) + { + char c = strs[0][i]; + int j = 1; + while(j < size) + { + if(strs[j][i] != c) + break; + j++; + } + if(j == size) + s[index++] = c; + else + break; + } + s[index] = '\0'; + return s; +} diff --git a/LuoSonglei/week-95/143-ReorderList.c b/LuoSonglei/week-95/143-ReorderList.c new file mode 100644 index 0000000..f263876 --- /dev/null +++ b/LuoSonglei/week-95/143-ReorderList.c @@ -0,0 +1,64 @@ +/******************************************* +Author : LHearen +E-mail : LHearen@126.com +Time : 2016-03-13 20:55 +Description : Given a singly linked list L: L0→L1→…→Ln-1→Ln, +reorder it to: L0→Ln→L1→Ln-1→L2→Ln-2→… +You must do this in-place without altering the nodes' values. +For example, +Given {1,2,3,4}, reorder it to {1,4,2,3}. +Source : https://leetcode.com/problems/reorder-list/ +*******************************************/ +struct ListNode +{ + int val; + struct ListNode *next; +}; + +#include +void reorderList(struct ListNode* head) +{ + if(!head || !head->next) return ; + struct ListNode *slow=head, *fast=head->next; + while(fast && fast->next) //split the list into two halves left part >= right part; + { + slow = slow->next; + fast = fast->next->next; + } + struct ListNode *right = slow->next; //get the right part; + slow->next = NULL; //terminate the left part; + + struct ListNode *p, *next; + struct ListNode *rightHead = (struct ListNode*)malloc(sizeof(struct ListNode)); + rightHead->next = NULL; + struct ListNode *t = rightHead; + p = right; + while(p) //reverse the right part; + { + next = p->next; + p->next = t->next; + t->next = p; + p = next; + } + + struct ListNode *newHead = (struct ListNode*)malloc(sizeof(struct ListNode)); + newHead->next = NULL; + t = newHead; + struct ListNode *left = head; + right = rightHead->next; + while(left || right) //connect the left and right one by one; + { + t->next = left; + left = left->next; //before resetting in t->next=NULL, move left to the next; + t = t->next; + t->next = NULL; + if(right) //in case of odd length; + { + t->next = right; + right = right->next; + t = t->next; + t->next = NULL; + } + } + return ; +} diff --git a/LuoSonglei/week-95/147-InsertionSortList.c b/LuoSonglei/week-95/147-InsertionSortList.c new file mode 100644 index 0000000..6589fd6 --- /dev/null +++ b/LuoSonglei/week-95/147-InsertionSortList.c @@ -0,0 +1,63 @@ +/******************************************* +Author : LHearen +E-mail : LHearen@126.com +Time : 2016-03-08 21:34 +Description : Sort a linked list using insertion sort. +Source : https://leetcode.com/problems/insertion-sort-list/ +*******************************************/ +#include +struct ListNode +{ + int val; + struct ListNode *next; +}; + +//AC - 68ms; +struct ListNode* insertionSortList0(struct ListNode* head) +{ + struct ListNode* newHead = (struct ListNode*)malloc(sizeof(struct ListNode)); + newHead->next = NULL; //in case of uncertainty; + struct ListNode *p=head, *next, *pre=newHead; + while(p) + { + next = p->next; //store the next node; + p->next = NULL; + while(pre->next && pre->next->valval) + pre = pre->next; + p->next = pre->next; //point to the next node of the current inserting position; + pre->next = p; + pre = newHead; //start over from the very beginning; + p = next; //move to the next node; + } + return newHead->next; +} + +//AC - 12ms; +struct ListNode* insertionSortList(struct ListNode* head) +{ + if(!head || !head->next) return head; //we have to handle the corner case now, since we adopted last and check head->val the first round; + struct ListNode* newHead = (struct ListNode*)malloc(sizeof(struct ListNode)); + newHead->next = NULL; //in case of uncertainty; + newHead->val = head->val-1; //to update the last for the first insertion; + struct ListNode *p=head, *next, *pre=newHead, *last=newHead; + while(p) + { + next = p->next; + p->next = NULL; + if(last->val < p->val) + { + last->next = p; + last = p; + } + else + { + while(pre->next && pre->next->valval) + pre = pre->next; + p->next = pre->next; //point to the next node of the current inserting position; + pre->next = p; + pre = newHead; //start over from the very beginning; + } + p = next; //move to the next node; + } + return newHead->next; +} diff --git a/LuoSonglei/week-95/150-EvaluateReversePolishNotation.c b/LuoSonglei/week-95/150-EvaluateReversePolishNotation.c new file mode 100644 index 0000000..e6791c2 --- /dev/null +++ b/LuoSonglei/week-95/150-EvaluateReversePolishNotation.c @@ -0,0 +1,48 @@ +/******************************************* +Author : LHearen +E-mail : LHearen@126.com +Time : 2016-03-12 20:30 +Description : Evaluate the value of an arithmetic expression in Reverse Polish Notation. + +Valid operators are +, -, *, /. Each operand may be an integer or another expression. + +Some examples: + ["2", "1", "+", "3", "*"] -> ((2 + 1) * 3) -> 9 + ["4", "13", "5", "/", "+"] -> (4 + (13 / 5)) -> 6 +Source : https://leetcode.com/problems/evaluate-reverse-polish-notation/ +*******************************************/ +#include +bool isOperator(char c) +{ + return c=='+' || c=='-' || c=='*' || c=='/'; +} +int evalRPN(char** tokens, int size) +{ + int *stack = (int*)malloc(sizeof(int)*size); + int top = -1; + int num = 0; + for(int i = 0; i < size; i++) + { + num = 0; + if(tokens[i][1]=='\0' && isOperator(tokens[i][0])) //ensure its length is 1 and the only one letter is operator; + { + int b = stack[top--]; //pop out the second operand; + int a = stack[top--]; //pop out the first operand; + if(tokens[i][0] == '+') num = a+b; + else if(tokens[i][0] == '-') num = a-b; + else if(tokens[i][0] == '*') num = a*b; + else if(tokens[i][0] == '/') num = a/b; + } + else + { + int j = 0; + if(isOperator(tokens[i][0])) j++; //there is leading sign; + int sign = tokens[i][0]=='-'? -1 : 1; //take the sign; + for(; tokens[i][j]; j++) + num = 10*num + tokens[i][j] - '0'; + num *= sign; + } + stack[++top] = num; + } + return stack[0]; +} diff --git a/LuoSonglei/week-95/151-ReverseWordsInString.c b/LuoSonglei/week-95/151-ReverseWordsInString.c new file mode 100644 index 0000000..c2d78d7 --- /dev/null +++ b/LuoSonglei/week-95/151-ReverseWordsInString.c @@ -0,0 +1,63 @@ +/******************************************* +Author : LHearen +E-mail : LHearen@126.com +Time : 2016-03-12 19:40 +Description : Given an input string, reverse the string word by word. + +For example, +Given s = "the sky is blue", +return "blue is sky the". + +Update (2015-02-12): +For C programmers: Try to solve it in-place in O(1) space. +Source : https://leetcode.com/problems/reverse-words-in-a-string/ +*******************************************/ +void reverseWords(char* s) +{ + int len = strlen(s); + int count = 0; + while(s[count] == ' ') count++; //remove the preceding white spaces; + for(int i = count; i < len+1; i++) + s[i-count] = s[i]; + len -= count; + while(s[len-1] == ' ') len--; //remove the tailing white spaces; + s[len] = '\0'; + int index = 0; + count = 0; + for(int i = 0; i < len; i++) //removing all the redundant white spaces among words; + { + if(s[i] != ' ') + { + s[index++] = s[i]; + count = 0; + } + else + { + if(!count) //only the first white space will be collected; + s[index++] = s[i]; + count++; + } + } + s[index] = '\0'; + len = index; + for(int i = 0; i < len/2; i++) + { + char c=s[i]; s[i]=s[len-i-1]; s[len-i-1]=c; + } + int begin=0, end=0; + for(int i = 0; i < len; i++) + { + if(s[i] == ' ' || i == len-1) + { + end = i; + if(i != len-1) end--; //point to the last letter of the word; + int size = end-begin+1; + for(int j = 0; j < size/2; j++) + { + char c=s[begin+j]; s[begin+j]=s[end-j]; s[end-j]=c; + } + begin = end+2; //point to the leading letter of the next word; + } + } +} + diff --git a/LuoSonglei/week-95/155-MinStack.c b/LuoSonglei/week-95/155-MinStack.c new file mode 100644 index 0000000..50142bf --- /dev/null +++ b/LuoSonglei/week-95/155-MinStack.c @@ -0,0 +1,59 @@ +/******************************************* +Author : LHearen +E-mail : LHearen@126.com +Time : 2016-03-08 12:31 +Description : Design a stack that supports push, pop, top, and retrieving the minimum element in constant time. + +push(x) -- Push element x onto stack. +pop() -- Removes the element on top of the stack. +top() -- Get the top element. +getMin() -- Retrieve the minimum element in the stack. +Source : https://leetcode.com/problems/min-stack/ +*******************************************/ +#include +typedef struct +{ + int *arr; + int count; + int *mins; + int minCount; +} MinStack; + +void minStackCreate(MinStack *stack, int maxSize) +{ + stack->arr = (int*)malloc(sizeof(int)*maxSize); + stack->mins = (int*)malloc(sizeof(int)*maxSize); //record the mins till the top of the arr; + stack->count = 0; + stack->minCount = 0; +} + +void minStackPush(MinStack *stack, int element) //push it to arr normally, but meantime check whether we should push it to mins; +{ + stack->arr[stack->count++] = element; + if(stack->minCount==0 || element<=stack->mins[stack->minCount-1]) + stack->mins[stack->minCount++] = element; +} + +void minStackPop(MinStack *stack) //pop will always pop the top -> the top of mins and arr; +{ + int top = stack->arr[stack->count-1]; + if(stack->mins[stack->minCount-1] == top) + stack->minCount--; + stack->count--; +} + +int minStackTop(MinStack *stack) //just return the top, needless to remove it; +{ + return stack->arr[stack->count-1]; +} + +int minStackGetMin(MinStack *stack) //just return the min, needless to remove it; +{ + return stack->mins[stack->minCount-1]; +} + +void minStackDestroy(MinStack *stack) +{ + free(stack->arr); + free(stack->mins); +} diff --git a/LuoSonglei/week-95/179-LargestNumber.c b/LuoSonglei/week-95/179-LargestNumber.c new file mode 100644 index 0000000..9fe35b7 --- /dev/null +++ b/LuoSonglei/week-95/179-LargestNumber.c @@ -0,0 +1,70 @@ +/******************************************* +Author : LHearen +E-mail : LHearen@126.com +Time : 2016-03-12 21:19 +Description : Given a list of non negative integers, arrange them such that they form the largest number. + +For example, given [3, 30, 34, 5, 9], the largest formed number is 9534330. + +Note: The result may be very large, so you need to return a string instead of an integer. +Source : https://leetcode.com/problems/largest-number/ +*******************************************/ +#include +#define LEN 20 +bool compare(int a, int b) //if the string a+b is bigger then the string b+a return true; +{ + char *t0 = (char*)malloc(sizeof(char)*2*LEN); + *t0 = '\0'; + strcat(t0,a); + strcat(t0, b); + char *t1 = (char*)malloc(sizeof(char)*LEN); + *t1= '\0'; + strcat(t1, b); + strcat(t1,a); + return strcmp(t0, t1)>0; //using strcmp to achieve comparing operation; +} + +char* toString(int a) //turn a int to a string; +{ + char* t = (char*)malloc(sizeof(char)*30); + int index = 0; + while(a) //collect each digit from low to high; + { + t[index++] = a%10+'0'; + a /= 10; + } + t[index] = '\0'; + for(int i = 0; i < index/2; i++) //reverse the string; + { + char c=t[i]; t[i]=t[index-i-1]; t[index-i-1]=c; + } + return t; +} + +char* largestNumber(int* nums, int size) +{ + char** arrs = (char**)malloc(sizeof(char*)*size); + for(int i = 0; i < size; i++) //turn each number to string; + { + if(nums[i] == 0) + arrs[i] = "0"; + else + arrs[i] = toString(nums[i]); + } + char* s = (char*)malloc(sizeof(char)*size*LEN); + *s = '\0'; + int max; + for(int i = 0; i < size; i++) //using selection sort to sort the number strings; + { + max = i; + for(int j = i+1; j < size; j++) //find the ith biggest number string; + if(compare(arrs[j], arrs[max])) + max = j; + char *t = arrs[i]; + arrs[i] = arrs[max]; + arrs[max] = t; + if(arrs[0][0] == '0') return "0"; //if the first letter of the first number string is 0, then the result will definitely "0", just return "0"; + strcat(s, arrs[i]); //collect the string from 0 to size-1 in descending order; + } + return s; +} diff --git a/LuoSonglei/week-95/215-KthLargestInArray.c b/LuoSonglei/week-95/215-KthLargestInArray.c new file mode 100644 index 0000000..dc5c4dc --- /dev/null +++ b/LuoSonglei/week-95/215-KthLargestInArray.c @@ -0,0 +1,65 @@ +/******************************************* +Author : LHearen +E-mail : LHearen@126.com +Time : 2016-03-07 08:24 +Description : Find the kth largest element in an unsorted array. Note that it is the kth largest element in the sorted order, not the kth distinct element. + +For example, +Given [3,2,1,5,6,4] and k = 2, return 5. + +Note: +You may assume k is always valid, 1 ≤ k ≤ array's length. +Source : https://leetcode.com/problems/kth-largest-element-in-an-array/ +*******************************************/ +#include +#include +void swap(int* p, int* q) +{ + int t=*p; *p=*q; *q=t; +} + +int partition(int* nums, int begin, int end) +{ + int l=begin, r=end; + int m = (l+r)/2; + int mid = nums[m]; + swap(nums+m, nums+l); + l++; + while(l <= r) + { + while(nums[r] > mid) r--; + while(l<=r && nums[l] k) end = position-1; + else begin = position+1; + } +} + +int main(void) +{ + int nums[] = { 3,2,1,5,6,4 }; + int k; + scanf("%d", &k); + int ret = findKthLargest(nums, sizeof(nums)/sizeof(int), k); + printf("result: %d\n", ret); + return 0; +} diff --git a/LuoSonglei/week-95/225-ImplementStackUsingQueues.c b/LuoSonglei/week-95/225-ImplementStackUsingQueues.c new file mode 100644 index 0000000..d441dc7 --- /dev/null +++ b/LuoSonglei/week-95/225-ImplementStackUsingQueues.c @@ -0,0 +1,70 @@ +/******************************************* +Author : LHearen +E-mail : LHearen@126.com +Time : 2016-03-08 08:50 +Description : Implement the following operations of a stack using queues. + +push(x) -- Push element x onto stack. +pop() -- Removes the element on top of the stack. +top() -- Get the top element. +empty() -- Return whether the stack is empty. +Notes: +You must use only standard operations of a queue -- which means only push to back, peek/pop from front, size, and is empty operations are valid. +Depending on your language, queue may not be supported natively. You may simulate a queue by using a list or deque (double-ended queue), as long as you use only standard operations of a queue. +You may assume that all operations are valid (for example, no pop or top operations will be called on an empty stack). + +Source : https://leetcode.com/problems/implement-stack-using-queues/ +*******************************************/ +#include +typedef struct +{ + int *queue0; //the major queue where all elements being stored; + int *queue1; //assistant queue for imitation; + int size; //used to record the size of queue0; + int maxSize; +} Stack; + +void stackCreate(Stack *stack, int maxSize) +{ + stack->maxSize = maxSize; + stack->size = 0; + stack->queue0 = (int*)malloc(sizeof(int)*maxSize); + stack->queue1 = (int*)malloc(sizeof(int)*maxSize); +} + +void stackPush(Stack *stack, int element) +{ + stack->queue0[stack->size++] = element; +} + +void stackPop(Stack *stack) +{ + int size = stack->size; + for(int i = 0; i < size-1; i++) //popping queue0 to queue1 all elements except for the last; + stack->queue1[i] = stack->queue0[i]; + stack->size--; //delete the last element in queue0; + for(int i = 0; i < size-1; i++) //popping queue1 back to queue0 and update stack->size; + stack->queue0[i] = stack->queue1[i]; +} + +int stackTop(Stack *stack) +{ + int size = stack->size; + for(int i = 0; i < size-1; i++) //popping queue0 to queue1 all elements except for the last; + stack->queue1[i] = stack->queue0[i]; + int ret = stack->queue0[size-1]; //pop the last from queue0; + for(int i = 0; i < size-1; i++) //popping queue1 back to queue0; + stack->queue0[i] = stack->queue1[i]; + return ret; +} + +bool stackEmpty(Stack *stack) +{ + return stack->size == 0; +} + +void stackDestroy(Stack *stack) +{ + free(stack->queue0); + free(stack->queue1); +} diff --git a/LuoSonglei/week-95/227-BasicCalculator2.c b/LuoSonglei/week-95/227-BasicCalculator2.c new file mode 100644 index 0000000..62e7d1b --- /dev/null +++ b/LuoSonglei/week-95/227-BasicCalculator2.c @@ -0,0 +1,89 @@ +/******************************************* +Author : LHearen +E-mail : LHearen@126.com +Time : 2016-03-10 14:01 +Description : Implement a basic calculator to evaluate a simple expression string. + +The expression string contains only non-negative integers, +, -, *, / operators and empty spaces . The integer division should truncate toward zero. + +You may assume that the given expression is always valid. + +Some examples: +"3+2*2" = 7 +" 3/2 " = 1 +" 3+5 / 2 " = 5 +Source : https://leetcode.com/problems/basic-calculator-ii/ +*******************************************/ +#include +int calculate0(char* s) +{ + bool d = false; + int len = strlen(s); + int ret=0, sign=1, num=0, pre=0; + for(int i = 0; i < len+1; i++) + { + if(isdigit(s[i])) + num = 10*num+s[i]-'0'; + else if(' ' != s[i]) + { + if(d) //update the current number since the previous operator is '/'; + { + num = pre/num; + d = !d; //reset d flag; + } + if(s[i] == '/') + { + d = true; //set d flag; + pre = num*sign; //update previous number; + sign = 1; //reset sign to its default value; + } + else if(s[i] == '*') //store the current number to sign; + sign *= num; + else + { + ret += sign*num; //collect the result before previous operator; + sign = (s[i]=='+')? 1 : -1; //reset sign ignoring the last character since we've done with it already; + } + num = 0; //reset number for next collecting; + } + } + return ret; +} + +int calculate(char* s) +{ + int len = strlen(s); + int* stack = (int*)malloc(sizeof(int)*len/2); //actually passed, weird; + int index = 0; + char sign = '+'; + int num = 0; + int t = 0; + for(int i = 0; i < len+1; i++) //the last character will be '\0', used to collect the last number; + { + if(isdigit(s[i])) + num = 10*num+s[i]-'0'; + else if(' ' != s[i]) //avoid white spaces; + { + if(sign == '-') //the previous operator; + stack[index++] = -1*num; + else if(sign == '+') + stack[index++] = num; + else if(sign == '*') + { + t = stack[--index]*num; + stack[index++] = t; + } + else if(sign == '/') + { + t = stack[--index]/num; + stack[index++] = t; + } + sign = s[i]; + num = 0; + } + } + int ret = 0; //sum them up; + for(int i = 0; i < index; i++) + ret += stack[i]; + return ret; +} diff --git a/LuoSonglei/week-95/232-ImplementQueueUsingStack.c b/LuoSonglei/week-95/232-ImplementQueueUsingStack.c new file mode 100644 index 0000000..f943132 --- /dev/null +++ b/LuoSonglei/week-95/232-ImplementQueueUsingStack.c @@ -0,0 +1,65 @@ +/******************************************* +Author : LHearen +E-mail : LHearen@126.com +Time : 2016-03-08 07:55 +Description : Implement the following operations of a queue using stacks. + +push(x) -- Push element x to the back of queue. +pop() -- Removes the element from in front of queue. +peek() -- Get the front element. +empty() -- Return whether the queue is empty. +Notes: +You must use only standard operations of a stack -- which means only push to top, peek/pop from top, size, and is empty operations are valid. +Depending on your language, stack may not be supported natively. You may simulate a stack by using a list or deque (double-ended queue), as long as you use only standard operations of a stack. +You may assume that all operations are valid (for example, no pop or peek operations will be called on an empty queue). +Source : https://leetcode.com/problems/implement-queue-using-stacks/ +*******************************************/ +#include +typedef struct //using deque to imitate the two stacks operation avoid extra O(N) space wasting; +{ + int *stack; + int begin; //begin -> point to the exact first front element; + int end; //end -> point to the next element of the last element to be easily indicate the empty case; + int maxSize; +} Queue; + +void queueCreate(Queue *queue, int maxSize) +{ + queue->stack = (int*)malloc(sizeof(int)*maxSize); + queue->begin = 0; + queue->end = 0; + queue->maxSize = maxSize; //record the maxSize for checking; +} + +void queuePush(Queue *queue, int element) +{ + if(queue->end == queue->maxSize) //reach its valid end, we have to rearrange the stack; + { + for(int i = queue->begin; i < queue->end; i++) + queue->stack[i-queue->begin] = queue->stack[i]; + queue->begin = 0; + queue->end -= queue->begin; + } + queue->stack[queue->end++] = element; +} + +void queuePop(Queue *queue) +{ + queue->begin++; +} + +int queuePeek(Queue *queue) +{ + return queue->stack[queue->begin]; +} + +bool queueEmpty(Queue *queue) +{ + return queue->begin == queue->end; +} + +void queueDestroy(Queue *queue) +{ + free(queue->stack); + /*free(queue); this part cannot be executed*/ +} diff --git a/LuoSonglei/week-95/239-SlidingWindowMaximum.c b/LuoSonglei/week-95/239-SlidingWindowMaximum.c new file mode 100644 index 0000000..13b14af --- /dev/null +++ b/LuoSonglei/week-95/239-SlidingWindowMaximum.c @@ -0,0 +1,48 @@ +/******************************************* +Author : LHearen +E-mail : LHearen@126.com +Time : 2016-03-11 22:47 +Description : Given an array nums, there is a sliding window of size k which is moving from the very left of the array to the very right. You can only see the k numbers in the window. Each time the sliding window moves right by one position. + +For example, +Given nums = [1,3,-1,-3,5,3,6,7], and k = 3. + +Window position Max +--------------- ----- +[1 3 -1] -3 5 3 6 7 3 +1 [3 -1 -3] 5 3 6 7 3 +1 3 [-1 -3 5] 3 6 7 5 +1 3 -1 [-3 5 3] 6 7 5 +1 3 -1 -3 [5 3 6] 7 6 +1 3 -1 -3 5 [3 6 7] 7 +Therefore, return the max sliding window as [3,3,5,5,6,7]. + +Note: +You may assume k is always valid, ie: 1 ≤ k ≤ input array's size for non-empty array. + +Follow up: +Could you solve it in linear time? +Source : https://leetcode.com/problems/sliding-window-maximum/ +*******************************************/ +//AC - 40ms; +int* maxSlidingWindow(int* nums, int size, int k, int* returnSize) +{ + *returnSize = 0; + int* arr = (int*)malloc(sizeof(int)*(size-k+1)); + int* queue = (int*)malloc(sizeof(int)*size); + int begin=0, end=-1; + for(int i = 0; i < size; i++) + { + if(end-begin>-1 && queue[begin]==i-k) + begin++; + while(end-begin>-1 && nums[queue[end]]= k-1) + { + *returnSize += 1; + arr[*returnSize-1] = nums[queue[begin]]; + } + } + return arr; +} diff --git a/LuoSonglei/week-95/24-SwapNodesPairs.c b/LuoSonglei/week-95/24-SwapNodesPairs.c new file mode 100644 index 0000000..b1eed71 --- /dev/null +++ b/LuoSonglei/week-95/24-SwapNodesPairs.c @@ -0,0 +1,37 @@ +/******************************************* +Author : LHearen +E-mail : LHearen@126.com +Time : 2016-03-07 21:51 +Description : Given a linked list, swap every two adjacent nodes and return its head. + +For example, +Given 1->2->3->4, you should return the list as 2->1->4->3. + +Your algorithm should use only constant space. You may not modify the values in the list, only nodes itself can be changed. +Source : https://leetcode.com/problems/swap-nodes-in-pairs/ +*******************************************/ +struct ListNode +{ + int val; + struct ListNode *next; +}; + +//AC - 0ms; +struct ListNode* swapPairs(struct ListNode* head) +{ + if(!head || !head->next) return head; + struct ListNode *t = (struct ListNode*)malloc(sizeof(struct ListNode)); + t->next = head; + struct ListNode *pre=t, *cur=head, *next=head->next; + while(cur && cur->next) + { + next = cur->next->next; + pre->next = cur->next; + cur->next->next = cur; + cur->next = next; + pre = pre->next->next; + cur = next; + + } + return t->next; +} diff --git a/LuoSonglei/week-95/241-DifferentWaysToAddParentheses.c b/LuoSonglei/week-95/241-DifferentWaysToAddParentheses.c new file mode 100644 index 0000000..bc6bfe6 --- /dev/null +++ b/LuoSonglei/week-95/241-DifferentWaysToAddParentheses.c @@ -0,0 +1,71 @@ +/******************************************* +Author : LHearen +E-mail : LHearen@126.com +Time : 2016-03-08 14:45 +Description : Given a string of numbers and operators, return all possible results from computing all the different possible ways to group numbers and operators. The valid operators are +, - and *. + + +Example 1 +Input: "2-1-1". + +((2-1)-1) = 0 +(2-(1-1)) = 2 +Output: [0, 2] + + +Example 2 +Input: "2*3-4*5" + +(2*(3-(4*5))) = -34 +((2*3)-(4*5)) = -14 +((2*(3-4))*5) = -10 +(2*((3-4)*5)) = -10 +(((2*3)-4)*5) = 10 +Output: [-34, -14, -10, -10, 10] +Hint: there are just valid strings will be provided. +Source : https://leetcode.com/problems/different-ways-to-add-parentheses/ +*******************************************/ +#include +int* compute(char* s, int len, int* size) +{ + int *arr = (int*)malloc(sizeof(int)); + *size = 0; + int *arr0, *arr1; //prepared for storing the array of different results from left and right side of a operator; + int size0=0, size1=0; //used to cooperate with arr0 and arr1 respectively; + for(int i = 0; i < len; i++) + { + if(!isdigit(s[i])) + { + arr0 = compute(s, i, &size0); //compute the left part of the string and store it in arr0; + arr1 = compute(s+i+1, len-i-1, &size1); //compute the right part; + for(int j = 0; j < size0; j++) + { + for(int k = 0; k < size1; k++) + { + switch(s[i]) + { + case '-': arr[*size] = arr0[j]-arr1[k]; break; + case '+': arr[*size] = arr0[j]+arr1[k]; break; + case '*': arr[*size] = arr0[j]*arr1[k]; break; + default: break; + } + *size += 1; + arr = (int*)realloc(arr, sizeof(int)*(*size+1)); //dynamically allocate space for arr; + }//end of arr1 + }//end of arr0; + } + } + if(*size == 0) //there is no operator in s[0] - s[len-1], so just collect the number; + { + int t = 0; + for(int i = 0; i < len; i++) + t = 10*t + (s[i]-'0'); + arr[*size] = t; + *size += 1; + } + return arr; +} +int* diffWaysToCompute(char* s, int* returnSize) +{ + return compute(s, strlen(s), returnSize); +} diff --git a/LuoSonglei/week-95/282-ExpressionAddOperators.c b/LuoSonglei/week-95/282-ExpressionAddOperators.c new file mode 100644 index 0000000..9f3bc91 --- /dev/null +++ b/LuoSonglei/week-95/282-ExpressionAddOperators.c @@ -0,0 +1,78 @@ +/******************************************* +Author : LHearen +E-mail : LHearen@126.com +Time : 2016-03-12 08:00 +Description : Given a string that contains only digits 0-9 and a target value, return all possibilities to add binary operators (not unary) +, -, or * between the digits so they evaluate to the target value. + +Examples: +"123", 6 -> ["1+2+3", "1*2*3"] +"232", 8 -> ["2*3+2", "2+3*2"] +"105", 5 -> ["1*0+5","10-5"] +"00", 0 -> ["0+0", "0-0", "0*0"] +"3456237490", 9191 -> [] +Source : https://leetcode.com/problems/expression-add-operators/ +*******************************************/ +#include +#include +#include +void helper(char* num, int len, int start, int target, long long sum, long long pre, char* stack, int top, char*** arr, int* returnSize) +{ + if(start == len) //end of the string; + { + if(target == sum) //check whether it's valid; + { + stack[++top] = '\0'; //terminate the string; + *returnSize += 1; + *arr = (char**)realloc(*arr, sizeof(char*)*(*returnSize)); + (*arr)[*returnSize-1] = (char*)malloc(sizeof(char)*(top+1)); + for(int i = 0; i <= top; i++) + (*arr)[*returnSize-1][i] = stack[i]; + } + return ; + } + long long val = 0; //in case of INT_MAX or INT_MIN; + int index = top+1; //record the index for the operator; + for(int i = start; i < len; i++) + { + val = 10*val + num[i] - '0'; //collect the number; + if(start == 0) //if it's the first number, no operator should be added; + { + stack[top+1] = num[i]; + helper(num, len, i+1, target, val, val, stack, top+1, arr, returnSize); + } + else + { + stack[top+2] = num[i]; + stack[index] = '-'; //get the sum directly by sum-val and record -1*val as pre in case the next operator is '*'; + helper(num, len, i+1, target, sum-val, -1*val, stack, top+2, arr, returnSize); + stack[index] = '+'; //store val as pre in case the next operator is '*'; + helper(num, len, i+1, target, sum+val, val, stack, top+2, arr, returnSize); + stack[index] = '*'; //we have to delete the pre first and then add the product of pre and var and then store pre*val in case the next operator is '*'; + helper(num, len, i+1, target, sum-pre+pre*val, pre*val, stack, top+2, arr, returnSize); + } + if(num[start] == '0') break; //no number starts with 0; + top++; + } +} +char** addOperators(char* num, int target, int* returnSize) +{ + char** arr = (char**)malloc(sizeof(char*)); + *returnSize = 0; + int len = strlen(num); + if(len == 0) return arr; + char* stack = (char*)malloc(sizeof(char)*2*len); + int top = -1; + helper(num, len, 0, target, 0, 0, stack, top, &arr, returnSize); + return arr; +} + +int main(int argc, char *argv[]) +{ + char *s = "123"; + int target = 6; + int size = 0; + char** arr = addOperators(s, target, &size); + for(int i = 0; i < size; i++) + printf("%s\n", arr[i]); + return 0; +} diff --git a/LuoSonglei/week-95/282-ExpressionAddOperators1.c b/LuoSonglei/week-95/282-ExpressionAddOperators1.c new file mode 100644 index 0000000..c8dd8ec --- /dev/null +++ b/LuoSonglei/week-95/282-ExpressionAddOperators1.c @@ -0,0 +1,78 @@ +/******************************************* +Author : LHearen +E-mail : LHearen@126.com +Time : 2016-03-12 08:00 +Description : Given a string that contains only digits 0-9 and a target value, return all possibilities to add binary operators (not unary) +, -, or * between the digits so they evaluate to the target value. + +Examples: +"123", 6 -> ["1+2+3", "1*2*3"] +"232", 8 -> ["2*3+2", "2+3*2"] +"105", 5 -> ["1*0+5","10-5"] +"00", 0 -> ["0+0", "0-0", "0*0"] +"3456237490", 9191 -> [] +Source : https://leetcode.com/problems/expression-add-operators/ +*******************************************/ +#include +#include +#include +void helper(char* num, int len, int start, int target, long long sum, long long pre, char* stack, int top, char*** arr, int* returnSize) +{ + if(start == len) //end of the string; + { + if(target == sum+pre) //add sum and pre to check whether it's valid, since pre is not added so far; + { + stack[++top] = '\0'; //terminate the string; + *returnSize += 1; + *arr = (char**)realloc(*arr, sizeof(char*)*(*returnSize)); + (*arr)[*returnSize-1] = (char*)malloc(sizeof(char)*(top+1)); + for(int i = 0; i <= top; i++) + (*arr)[*returnSize-1][i] = stack[i]; + } + return ; + } + long long val = 0; //in case of INT_MAX or INT_MIN; + int index = top+1; //record the index for the operator; + for(int i = start; i < len; i++) + { + val = 10*val + num[i] - '0'; //collect the number; + if(start == 0) //if it's the first number, no operator should be added; + { + stack[top+1] = num[i]; + helper(num, len, i+1, target, 0, val, stack, top+1, arr, returnSize); + } + else + { + stack[top+2] = num[i]; + stack[index] = '-'; //get the sum directly by sum+val since we will store -1*val for subtraction and record -1*val as pre in case the next operator is '*'; + helper(num, len, i+1, target, sum+pre, -1*val, stack, top+2, arr, returnSize); + stack[index] = '+'; //store val as pre in case the next operator is '*'; + helper(num, len, i+1, target, sum+pre, val, stack, top+2, arr, returnSize); + stack[index] = '*'; //save the product of pre and val for next round; + helper(num, len, i+1, target, sum, pre*val, stack, top+2, arr, returnSize); + } + if(num[start] == '0') break; //no number starts with 0; + top++; + } +} +char** addOperators(char* num, int target, int* returnSize) +{ + char** arr = (char**)malloc(sizeof(char*)); + *returnSize = 0; + int len = strlen(num); + if(len == 0) return arr; + char* stack = (char*)malloc(sizeof(char)*2*len); + int top = -1; + helper(num, len, 0, target, 0, 0, stack, top, &arr, returnSize); + return arr; +} + +int main(int argc, char *argv[]) +{ + char *s = "123"; + int target = 6; + int size = 0; + char** arr = addOperators(s, target, &size); + for(int i = 0; i < size; i++) + printf("%s\n", arr[i]); + return 0; +} diff --git a/LuoSonglei/week-95/295-FindMedianFromDataStream.c b/LuoSonglei/week-95/295-FindMedianFromDataStream.c new file mode 100644 index 0000000..320a422 --- /dev/null +++ b/LuoSonglei/week-95/295-FindMedianFromDataStream.c @@ -0,0 +1,80 @@ +/******************************************* +Author : LHearen +E-mail : LHearen@126.com +Time : 2016-03-10 08:52 +Description : Median is the middle value in an ordered integer list. If the size of the list is even, there is no middle value. So the median is the mean of the two middle value. + +Examples: +[2,3,4] , the median is 3 + +[2,3], the median is (2 + 3) / 2 = 2.5 + +Design a data structure that supports the following two operations: + +void addNum(int num) - Add a integer number from the data stream to the data structure. +double findMedian() - Return the median of all elements so far. +For example: + +add(1) +add(2) +findMedian() -> 1.5 +add(3) +findMedian() -> 2 +Source : https://leetcode.com/problems/find-median-from-data-stream/ +*******************************************/ +#include +#include +struct MedianFinder +{ + int* arr; + int size; +}; + +struct MedianFinder* MedianFinderCreate() +{ + struct MedianFinder *t = (struct MedianFinder*)malloc(sizeof(struct MedianFinder)); + t->arr = (int*)malloc(sizeof(int)); + t->size = 0; + return t; +} + +void addNum(struct MedianFinder *mf, int num) +{ + mf->size += 1; + mf->arr = (int*)realloc(mf->arr, (sizeof(int)*mf->size)); + if(num > mf->arr[mf->size-2]) + { + mf->arr[mf->size-1] = num; + return ; + } + int j = mf->size-2; + while(j>-1 && mf->arr[j]>num) + { + mf->arr[j+1] = mf->arr[j]; + j--; + } + mf->arr[j+1] = num; +} + +//AC - 656ms; +double findMedian(struct MedianFinder* mf) +{ + if(mf->size%2) + return mf->arr[mf->size/2]; + return (mf->arr[mf->size/2-1]+mf->arr[mf->size/2])/2.0; +} + +void MedianFinderFree(struct MedianFinder* mf) +{ + +} + +int main(int argc, char *argv[]) +{ + struct MedianFinder *t = MedianFinderCreate(); + addNum(t, 2); + printf("%f\n", findMedian(t)); + addNum(t, 3); + printf("%f\n", findMedian(t)); + return 0; +} diff --git a/LuoSonglei/week-95/297-SerializeAndDeserializeBinaryTree.c b/LuoSonglei/week-95/297-SerializeAndDeserializeBinaryTree.c new file mode 100644 index 0000000..a4d07e6 --- /dev/null +++ b/LuoSonglei/week-95/297-SerializeAndDeserializeBinaryTree.c @@ -0,0 +1,120 @@ +/******************************************* +Author : LHearen +E-mail : LHearen@126.com +Time : 2016-03-11 15:06 +Description : Serialization is the process of converting a data structure or object into a sequence of bits so that it can be stored in a file or memory buffer, or transmitted across a network connection link to be reconstructed later in the same or another computer environment. + +Design an algorithm to serialize and deserialize a binary tree. There is no restriction on how your serialization/deserialization algorithm should work. You just need to ensure that a binary tree can be serialized to a string and this string can be deserialized to the original tree structure. + +For example, you may serialize the following tree + +1 +/ \ +2 3 + / \ + 4 5 + as "[1,2,3,null,null,4,5]", just the same as how LeetCode OJ serializes a binary tree. You do not necessarily need to follow this format, so please be creative and come up with different approaches yourself. +Note: Do not use class member/global/static variables to store states. Your serialize and deserialize algorithms should be stateless. + + +Source : https://leetcode.com/problems/serialize-and-deserialize-binary-tree/ +*******************************************/ +#include +#define LEN 10000 +struct TreeNode +{ + int val; + struct TreeNode *left, *right; +}; + +char* serialize(struct TreeNode* root) +{ + if(!root) return "X,"; + char *t = (char*)malloc(sizeof(char)*LEN); + int size = 0; + int val = root->val; + while(val) //collect the string and convert it number in reverse order; + { + t[size++] = val%10 + '0'; + val /= 10; + } + for(int i = 0; i < size/2; i++) //since it's reversed, then reverse it again to make it normal; + { + char c = t[size-i-1]; t[size-i-1]=t[i]; t[i]=c; + } + t[size++] = ','; //add splitter; + t[size] = '\0'; //terminate the string; + char *left = serialize(root->left); //collect left and right children; + char *right = serialize(root->right); + int leftSize = strlen(left); + int rightSize = strlen(right); + t = (char*)realloc(t, sizeof(char)*(size+leftSize+rightSize+2)); + strcat(t, left); + strcat(t, right); + return t; +} + +char** split(char* s, int* size) //split a string by ','; +{ + char** arr = (char**)malloc(sizeof(char*)); + *size = 0; + char* t = (char*)malloc(sizeof(char)*30); + int index = 0; + for(int i = 0; s[i]; i++) + { + if(s[i] != ',') + t[index++] = s[i]; + else + { + t[index] = '\0'; + *size += 1; + arr = (char**)realloc(arr, sizeof(char*)*(*size)); + arr[*size-1] = t; + t = (char*)malloc(sizeof(char)*30); + index = 0; + } + } + return arr; +} + +struct TreeNode* helper0(char*** arr) //using the pointer of the array to move it for recursion; +{ + if(strcmp(**arr, "X") == 0) return NULL; + int num = 0; + for(int i = 0; (**arr)[i]; i++) + num = 10*num + (**arr)[i]-'0'; + struct TreeNode* root = (struct TreeNode*)malloc(sizeof(struct TreeNode)); + root->val = num; + *arr += 1; //move to skip the current number; + root->left = helper(arr); + *arr += 1; //skip the left number; + root->right = helper(arr); + return root; +} +struct TreeNode* deserialize0(char *s) +{ + int size = 0; + char** arr = split(s, &size); + return helper(&arr); +} + +struct TreeNode* helper(char** s) +{ + if(**s == 'X') return NULL; + int num = 0; + int count = 0; + while(**s != ',') //collect number and meantime skip the current number; + num = 10*num + *((*s)++) - '0'; + *s += 1; //skip the comma ','; + struct TreeNode *root = (struct TreeNode*)malloc(sizeof(struct TreeNode)); + root->val = num; + root->left = helper(s); + while((*(*s)++) != ','); //skip the left value; + root->right = helper(s); + retrn root; +} + +struct TreeNode* deserialize(char* s) +{ + return helper(&s); +} diff --git a/LuoSonglei/week-95/306-AdditiveNumber.c b/LuoSonglei/week-95/306-AdditiveNumber.c new file mode 100644 index 0000000..79f3ea1 --- /dev/null +++ b/LuoSonglei/week-95/306-AdditiveNumber.c @@ -0,0 +1,62 @@ +/******************************************* +Author : LHearen +E-mail : LHearen@126.com +Time : 2016-03-11 08:41 +Description : Additive number is a string whose digits can form additive sequence. + +A valid additive sequence should contain at least three numbers. Except for the first two numbers, each subsequent number in the sequence must be the sum of the preceding two. + +For example: +"112358" is an additive number because the digits can form an additive sequence: 1, 1, 2, 3, 5, 8. + +1 + 1 = 2, 1 + 2 = 3, 2 + 3 = 5, 3 + 5 = 8 +"199100199" is also an additive number, the additive sequence is: 1, 99, 100, 199. +1 + 99 = 100, 99 + 100 = 199 +Note: Numbers in the additive sequence cannot have leading zeros, so sequence 1, 2, 03 or 1, 02, 3 is invalid. + +Given a string containing only digits '0'-'9', write a function to determine if it's an additive number. + +Follow up: +How would you handle overflow for very large input integers? +Source : https://leetcode.com/problems/additive-number/ +*******************************************/ +#include +char* addString(char* s1, int len1, char* s2, int len2) +{ + int sum = 0; + char* t = (char*)malloc(sizeof(char)*(len1+len2)); + int index = 0; + int carry = 0; + while(len1>0 || len2>0) //add them from the end to the begin, but the t will collect them in reverse direction;; + { + sum = carry + (len1>0? s1[len1---1]-'0':0) + (len2>0? s2[len2---1]-'0':0); + t[index++] = sum%10+'0'; + carry = sum/10; + } + if(carry) //if there is a last carry, collect it; + t[index++] = carry+'0'; + for(int i = 0; i < index/2; i++) //reverse t; + { + char c=t[i]; t[i]=t[index-i-1]; t[index-i-1]=c; + } + t[index] = '\0'; //terminate the string; + return t; +} +bool isValid(char* s1, int len1, char* s2, int len2, char* s3, int len3) +{ + if(*s1=='0' && len1>1) return false; //handle corner cases; + if(*s2=='0' && len2>1) return false; + if(len3 == 0) return true; //nothing left to compare, so far so good just return true; + char* t = addString(s1, len1, s2, len2); + int len = strlen(t); + return strncmp(t, s3, len)==0 && isValid(s2, len2, t, len, s3+len, len3-len); //if the current round is valid then check the next round till the end; +} + +bool isAdditiveNumber(char* s) +{ + int len = strlen(s); + for(int i = 1; i <= len/2; i++) + for(int j = 1; j <= (len-i)/2; j++) //there should always be some left for the third part, the sum; + if(isValid(s, i, s+i, j, s+i+j, len-i-j)) return true; + return false; //no combination works; +} diff --git a/LuoSonglei/week-95/324-WiggleSort2.c b/LuoSonglei/week-95/324-WiggleSort2.c new file mode 100644 index 0000000..47b703d --- /dev/null +++ b/LuoSonglei/week-95/324-WiggleSort2.c @@ -0,0 +1,62 @@ +/******************************************* +Author : LHearen +E-mail : LHearen@126.com +Time : 2016-03-09 14:52 +Description : Given an unsorted array nums, reorder it such that nums[0] < nums[1] > nums[2] < nums[3].... + +Example: +(1) Given nums = [1, 5, 1, 1, 6, 4], one possible answer is [1, 4, 1, 5, 1, 6]. +(2) Given nums = [1, 3, 2, 2, 3, 1], one possible answer is [2, 3, 1, 3, 1, 2]. + +Note: +You may assume all input has valid answer. + +Follow Up: +Can you do it in O(n) time and/or in-place with O(1) extra space? +Source : https://leetcode.com/problems/wiggle-sort-ii/ +*******************************************/ +void swap(int* p, int* q) +{ + int t=*p; *p=*q; *q=t; +} + +void sort(int* nums, int begin, int end) +{ + int l=begin, r=end; + int v = nums[l+(r-l)/2]; + while(l <= r) + { + while(nums[l] < v) l++; + while(nums[r] > v) r--; + if(l <= r) + { + swap(nums+l, nums+r); + l++; r--; + } + } + if(begin < r) + sort(nums, begin, r); + if(l < end) + sort(nums, l, end); +} + +//AC - 40ms; +//https://leetcode.com/discuss/76965/3-lines-python-with-explanation-proof +void wiggleSort(int* nums, int size) +{ + sort(nums, 0, size-1); //using quick sort to sort the array first; + int *arr = (int*)malloc(sizeof(int)*size); + for(int i = 0; i < size; i++) + arr[i] = nums[i]; + int small= 0; //the first of smallers; + int big = (size-1)/2+1; //the first of biggers; + int index = size-1; //start to fill in reverse direction: from right to left; + if(size%2 == 0) //if the size is even then the last should be indexed by odd size-1, so place the bigger one in odd position size-1; + nums[index--] = arr[big++]; + while(index > -1) + { + nums[index--] = arr[small++]; + if(index > -1) //in case of "underflow"; + nums[index--] = arr[big++]; + } +} diff --git a/LuoSonglei/week-95/331-VerityPreorderSerializationOfABinaryTree.c b/LuoSonglei/week-95/331-VerityPreorderSerializationOfABinaryTree.c new file mode 100644 index 0000000..c8f8b48 --- /dev/null +++ b/LuoSonglei/week-95/331-VerityPreorderSerializationOfABinaryTree.c @@ -0,0 +1,102 @@ +/******************************************* +Author : LHearen +E-mail : LHearen@126.com +Time : 2016-03-08 20:29 +Description : One way to serialize a binary tree is to use pre-order traversal. When we encounter a non-null node, we record the node's value. If it is a null node, we record using a sentinel value such as #. + + _9_ + / \ + 3 2 + / \ / \ +4 1 # 6 +/ \ / \ / \ +# # # # # # +For example, the above binary tree can be serialized to the string "9,3,4,#,#,1,#,#,2,#,6,#,#", where # represents a null node. + +Given a string of comma separated values, verify whether it is a correct preorder traversal serialization of a binary tree. Find an algorithm without reconstructing the tree. + +Each comma separated value in the string must be either an integer or a character '#' representing null pointer. + +You may assume that the input format is always valid, for example it could never contain two consecutive commas such as "1,,3". + +Example 1: +"9,3,4,#,#,1,#,#,2,#,6,#,#" +Return true + +Example 2: +"1,#" +Return false + +Example 3: +"9,#,#,1" +Return false +Source : https://leetcode.com/problems/verify-preorder-serialization-of-a-binary-tree/ +*******************************************/ +#include +char** split(char* s, int* size) +{ + char** arr = (char**)malloc(sizeof(char*)); + char *t = (char*)malloc(sizeof(char)*30); + int index = 0; + for(int i = 0; i < strlen(s)+1; i++) + { + if(s[i]==',' || s[i]=='\0') + { + if(s[i]==',' || s[i]=='\0') + { + t[index] = '\0'; + *size += 1; + arr = (char**)realloc(arr, sizeof(char*)*(*size)); + arr[*size-1] = t; + } + index = 0; + t = (char*)malloc(sizeof(char)*30); + } + else + { + t[index++] = s[i]; + } + } + return arr; +} + +//AC - 8ms; +//https://leetcode.com/discuss/83825/simple-python-solution-using-stack-with-explanation +//https://leetcode.com/discuss/84073/straight-forward-c-solution-with-explanation +bool isValidSerialization0(char* preorder) +{ + int size = 1; + char** arr = split(preorder, &size); + int difference = 0; + for(int i = 1; i < size; i++) + { + if(strcmp(arr[i], "#") == 0) //it's null; + difference++; + else //it's null cannot have not-null children; + difference--; + if(difference>1 || (difference==1&&i!=size-1)) return false; + } + if(difference < 1) return false; + return true; +} + +//AC - 0ms; +bool isValidSerialization(char* preorder) +{ + int difference = 0; + int size = strlen(preorder); + for(int i = 1; i <= size; i++) + { + if(preorder[i]==',' || preorder[i]=='\0') + { + if(preorder[i-1] == '#') //null; + difference++; + else //not null; + difference--; + } + if(difference > 1) return false; //surpass more than 1, return false directly; + if(difference==1 && i!=size) return false; //not end of the string but it reaches difference 1 already, terminate the checking directly; + } + if(difference < 1) return false; //after traversing the difference should be exactly one; + return true; +} diff --git a/LuoSonglei/week-95/334-IncreasingTripletSubsequence.c b/LuoSonglei/week-95/334-IncreasingTripletSubsequence.c new file mode 100644 index 0000000..f0dc034 --- /dev/null +++ b/LuoSonglei/week-95/334-IncreasingTripletSubsequence.c @@ -0,0 +1,35 @@ +/******************************************* +Author : LHearen +E-mail : LHearen@126.com +Time : 2016-03-08 16:38 +Description : Given an unsorted array return whether an increasing subsequence of length 3 exists or not in the array. + +Formally the function should: +Return true if there exists i, j, k +such that arr[i] < arr[j] < arr[k] given 0 ≤ i < j < k ≤ n-1 else return false. +Your algorithm should run in O(n) time complexity and O(1) space complexity. + +Examples: +Given [1, 2, 3, 4, 5], +return true. + +Given [5, 4, 3, 2, 1], +return false. +Source : https://leetcode.com/problems/increasing-triplet-subsequence/ +*******************************************/ +#include +//AC - 4ms; +bool increasingTriplet(int* nums, int size) +{ + int first = INT_MAX; + int second = INT_MAX; + for(int i = 0; i < size; i++) + { + if(nums[i] <= first) + first = nums[i]; + else if(nums[i] <= second) + second = nums[i]; + else return true; + } + return false; +} diff --git a/LuoSonglei/week-95/337-HouseRobber3.c b/LuoSonglei/week-95/337-HouseRobber3.c new file mode 100644 index 0000000..fbf1462 --- /dev/null +++ b/LuoSonglei/week-95/337-HouseRobber3.c @@ -0,0 +1,51 @@ +/******************************************* +Author : LHearen +E-mail : LHearen@126.com +Time : 2016-03-13 08:45 +Description : The thief has found himself a new place for his thievery again. There is only one entrance to this area, called the "root." Besides the root, each house has one and only one parent house. After a tour, the smart thief realized that "all houses in this place forms a binary tree". It will automatically contact the police if two directly-linked houses were broken into on the same night. + +Determine the maximum amount of money the thief can rob tonight without alerting the police. + +Example 1: + 3 +/ \ +2 3 +\ \ + 3 1 +Maximum amount of money the thief can rob = 3 + 3 + 1 = 7. +Example 2: +3 +/ \ +4 5 +/ \ \ +1 3 1 +Maximum amount of money the thief can rob = 4 + 5 = 9. +Source : https://leetcode.com/problems/house-robber-iii/ +*******************************************/ +struct TreeNode +{ + int val; + struct TreeNode *left, *right; +}; + +#define MAX(a, b) ((a) > (b) ? (a) : (b)) +void traverse(struct TreeNode* root, int* maxWithRoot, int* maxWithoutRoot) +{ + int lMaxWithRoot=0, lMaxWithoutRoot=0; + int rMaxWithRoot=0, rMaxWithoutRoot=0; + if(root) + { + traverse(root->left, &lMaxWithRoot, &lMaxWithoutRoot); + traverse(root->right, &rMaxWithRoot, &rMaxWithoutRoot); + *maxWithRoot = lMaxWithoutRoot+rMaxWithoutRoot+root->val; //if we take root, then the next adjacent children cannot be taken; + *maxWithoutRoot = MAX(lMaxWithRoot, lMaxWithoutRoot)+MAX(rMaxWithRoot, rMaxWithoutRoot); //since we do not take the root, then whatever might be greater is what we want; + } +} + +int rob(struct TreeNode *root) +{ + int maxWithRoot = 0; + int maxWithoutRoot = 0; + traverse(root, &maxWithRoot, &maxWithoutRoot); + return MAX(maxWithRoot, maxWithoutRoot); +} diff --git a/LuoSonglei/week-95/38-CountAndSay.c b/LuoSonglei/week-95/38-CountAndSay.c new file mode 100644 index 0000000..fa8bece --- /dev/null +++ b/LuoSonglei/week-95/38-CountAndSay.c @@ -0,0 +1,51 @@ +/******************************************* +Author : LHearen +E-mail : LHearen@126.com +Time : 2016-03-07 14:19 +Description : The count-and-say sequence is the sequence of integers beginning as follows: +1, 11, 21, 1211, 111221, ... + +1 is read off as "one 1" or 11. +11 is read off as "two 1s" or 21. +21 is read off as "one 2, then one 1" or 1211. +Given an integer n, generate the nth sequence. + +Note: The sequence of integers will be represented as a string. +Source : https://leetcode.com/problems/count-and-say/ +*******************************************/ +//AC - 0ms; +char* countAndSay(int n) +{ + if(n < 2) return "1"; //both 0 and 1 will return "1"; + n--; + char *s = (char*)malloc(sizeof(char)*2); //prepare the first "1" as a start-up; + s[0] = '1'; + s[1] = '\0'; + char *t = (char*)malloc(sizeof(char)); //used to store the next; + while(n) + { + char cur = s[0]; + int count = 0; //count the frequency for each consecutive digit; + int tSize = 0; //record the index in t; + for(int i = 0; i < strlen(s)+1; i++) //move till \0 of the string; + { + if(cur != s[i]) //if not equal, we collect the count and the digit in letter-format; + { + tSize += 2; //count + digit -> two positions will be taken; + t = (char*)realloc(t, sizeof(char)*(tSize+1)); + t[tSize-2] = count+'0'; + t[tSize-1] = cur; + t[tSize] = '\0'; + cur = s[i]; //update cur with the current new letter s[i]; + count = 1; //count the current letter once; + } + else + { + count++; //count the cur; + } + } + char *t0=t; t=s; s=t0; //exchange the string for next; + n--; //decrement the times left; + } + return s; +} diff --git a/LuoSonglei/week-95/49-GroupAnagrams.c b/LuoSonglei/week-95/49-GroupAnagrams.c new file mode 100644 index 0000000..8213eb9 --- /dev/null +++ b/LuoSonglei/week-95/49-GroupAnagrams.c @@ -0,0 +1,60 @@ +/******************************************* +Author : LHearen +E-mail : LHearen@126.com +Time : 2016-03-06 21:32 +Description : Given an array of strings, group anagrams together. +For example, given: ["eat", "tea", "tan", "ate", "nat", "bat"], +Return: +[ +["ate", "eat","tea"], +["nat","tan"], +["bat"] +] +Note: +For the return value, each inner list's elements must follow the lexicographic order. +All inputs will be in lower-case. +Source : https://leetcode.com/problems/anagrams/ +*******************************************/ +#include +void sort(char* s, int begin, int end, (int)(*p)(void)) +{ + int l=begin, r=end; + char c = s[(r+l)/2]; + while(l <= r) + { + while(s[l] < c) l++; + while(s[r] > c) r--; + if(l <= r) + { + char t=s[l]; s[l]=s[r]; s[r]=t; + l++; r--; + } + } + if(begin < r) + sort(s, begin, r); + if(l < end) + sort(s, l, end); +} + +char*** groupAnagrams(char** strs, int size, int** colSizes, int* returnSize) +{ + if(!size) return NULL; + *returnSize = 0; + *colSizes = (int*)malloc(sizeof(int)*size); + char*** arr = (char***)malloc(sizeof(char**)); + int *bits = (int*)malloc(sizeof(int)*size); + memset(bits, 0, sizeof(int)*size); + for(int i = 0; i < size; i++) + { + for(int j = 0; strs[i][j]; j++) + bits[i] |= 1<<(strs[i][j]-'a'); + } + + for(int i = 0; i < size; i++) + { + int j = 0; + while(j < *returnSize) + { + } + } +} diff --git a/LuoSonglei/week-95/49-GroupAnagrams.cpp b/LuoSonglei/week-95/49-GroupAnagrams.cpp new file mode 100644 index 0000000..3a40953 --- /dev/null +++ b/LuoSonglei/week-95/49-GroupAnagrams.cpp @@ -0,0 +1,44 @@ +/******************************************* +Author : LHearen +E-mail : LHearen@126.com +Time : 2016-03-07 13:51 +Description : Given an array of strings, group anagrams together. + +For example, given: ["eat", "tea", "tan", "ate", "nat", "bat"], +Return: + +[ +["ate", "eat","tea"], +["nat","tan"], +["bat"] + +] +Note: +For the return value, each inner list's elements must follow the lexicographic order. +All inputs will be in lower-case. +Source : https://leetcode.com/problems/anagrams/ +*******************************************/ +#include +class Solution +{ + public: + //AC - 64ms; + vector> groupAnagrams(vector& strs) + { + unordered_map> map; + for(auto s: strs) + { + string t(s); + sort(t.begin(), t.end()); + map[t].push_back(s); + } + vector> result(map.size()); + int i = 0; + for(auto iter=map.begin(); iter!=map.end(); ++iter, ++i) + { + result[i].swap(iter->second); + sort(result[i].begin(), result[i].end()); + } + return result; + } +}; diff --git a/LuoSonglei/week-95/5-LongestPalindromeSubstring.c b/LuoSonglei/week-95/5-LongestPalindromeSubstring.c new file mode 100644 index 0000000..5e8549d --- /dev/null +++ b/LuoSonglei/week-95/5-LongestPalindromeSubstring.c @@ -0,0 +1,80 @@ +/******************************************* +Author : LHearen +E-mail : LHearen@126.com +Time : 2016-03-13 16:30 +Description : Given a string S, find the longest palindromic substring in S. You may assume that the maximum length of S is 1000, and there exists one unique longest palindromic substring. +Source : https://leetcode.com/problems/longest-palindromic-substring/ +*******************************************/ +void check(char* s, int len, int l, int r, int* start, int* maxLen) +{ + while(l>-1 && r *maxLen) + { + *maxLen = len0; + *start = l+1; + } +} + +//AC - 20ms; +char* longestPalindrome0(char* s) +{ + int len = strlen(s); + if(len < 2) return s; + int start = 0; + int maxLen = 0; + for(int i = 0; i < len-1; i++) + { + check(s, len, i, i, &start, &maxLen); + check(s, len, i, i+1, &start, &maxLen); + } + char* t = (char*)malloc(sizeof(char)*(maxLen+1)); + memcpy(t, s+start, sizeof(char)*maxLen); + t[maxLen] = '\0'; + return t; +} + +//AC - 12ms; +char* longestPalindrome1(char* s) +{ + int len = strlen(s); + if(len < 2) return s; + int start = 0; + int maxLen = 0; + for(int i = 0; i < len-1 && len-i > maxLen/2; i++) + { + check(s, len, i, i, &start, &maxLen); + check(s, len, i, i+1, &start, &maxLen); + } + char* t = (char*)malloc(sizeof(char)*(maxLen+1)); + memcpy(t, s+start, sizeof(char)*maxLen); + t[maxLen] = '\0'; + return t; +} + + +//AC - 0ms; +char* longestPalindrome(char* s) +{ + int len = strlen(s); + if(len < 2) return s; + int start=0, maxLen=0; + int l=0, r=0; + for(int i = 0; imaxLen/2;) + { + l = r = i; + while(r now there will no even or odd length palindrome problem; + i = r+1; //move to the next non-duplicate for a new start; + while(l>0 && r maxLen) + { + maxLen = len0; + start = l; + } + } + char* t = (char*)malloc(sizeof(char)*(maxLen+1)); + memcpy(t, s+start, sizeof(char)*maxLen); + t[maxLen] = '\0'; + return t; +} diff --git a/LuoSonglei/week-95/82-RemoveDuplicatesFromSortedList.c b/LuoSonglei/week-95/82-RemoveDuplicatesFromSortedList.c new file mode 100644 index 0000000..599d58c --- /dev/null +++ b/LuoSonglei/week-95/82-RemoveDuplicatesFromSortedList.c @@ -0,0 +1,39 @@ +/******************************************* +Author : LHearen +E-mail : LHearen@126.com +Time : 2016-03-07 16:04 +Description : Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list. + +For example, +Given 1->2->3->3->4->4->5, return 1->2->5. +Given 1->1->1->2->3, return 2->3.j +Source : https://leetcode.com/problems/remove-duplicates-from-sorted-list-ii/ +*******************************************/ +#include +struct ListNode +{ + int val; + struct ListNode *next; +}; + +//AC - 4ms; +struct ListNode *deleteDuplicates(struct ListNode* head) +{ + if(!head || !head->next) return head; //needless to handle; + struct ListNode *newHead = (struct ListNode*)malloc(sizeof(struct ListNode)); //we need a head node for more convenient handling needless to consider the first node separately now ^^; + newHead->next = head; + struct ListNode *pre=newHead, *cur=head; + int preVal = head->val-1; //record the previous value of the current node, the default value should affect the first node collecting - so we set it different from head->val; + while(cur) + { + if(cur->val!=preVal && (!cur->next||cur->next->val!=cur->val)) //only when both the previous value and the next are not equal to the current one - by the way, the next node is null will definitely considered unequal, we can then collect it; + { + pre->next = cur; + pre = pre->next; + } + preVal = cur->val; + cur = cur->next; + } + pre->next = NULL; //terminate the list; + return newHead->next; +} diff --git a/LuoSonglei/week-95/92-ReverseLinkedList2.c b/LuoSonglei/week-95/92-ReverseLinkedList2.c new file mode 100644 index 0000000..8645d74 --- /dev/null +++ b/LuoSonglei/week-95/92-ReverseLinkedList2.c @@ -0,0 +1,57 @@ +/******************************************* +Author : LHearen +E-mail : LHearen@126.com +Time : 2016-03-07 14:43 +Description : Reverse a linked list from position m to n. Do it in-place and in one-pass. + +For example: +Given 1->2->3->4->5->NULL, m = 2 and n = 4, + +return 1->4->3->2->5->NULL. + +Note: +Given m, n satisfy the following condition: +1 ≤ m ≤ n ≤ length of list. +Source : https://leetcode.com/problems/reverse-linked-list-ii/ +*******************************************/ +#include +struct ListNode +{ + int val; + struct ListNode *next; +}; + +//AC - 0ms; +struct ListNode* reverseBetween(struct ListNode* head, int m, int n) +{ + if(!head || !head->next || n==m) return head; //corner cases; + int count = 0; + struct ListNode *newHead = (struct ListNode*)malloc(sizeof(struct ListNode)); //allocate a new node as the 'head'; + newHead->next = head; + struct ListNode *start=NULL, *pre=NULL, *next=NULL,*p = newHead; + while(p) //till the (m-1)th node of the list; + { + if(count == m-1) + { + start = p; //record the (m-1)th node; + break; + } + p = p->next; + count++; + } + pre = start->next; //start to reverse, record the pre for being pointed to by p; + p = pre->next; //record the next node of p in case of losing it; + while(p) + { + if(count == n-1) //till the nth node of the list; + break; + next = p->next; //record the next of the p; + p->next = pre; //reverse -> connect the p to its previous node; + pre = p; //update pre and p; + p = next; + count++; + } + start->next->next = next; //connect the mth to the (n+1)th node; + start->next = pre; //connect (m-1)th to the nth; + return newHead->next; //return the m-to-n-reversed list; +} diff --git a/LuoSonglei/week-96/146-LRUCache.c b/LuoSonglei/week-96/146-LRUCache.c new file mode 100644 index 0000000..9c9698f --- /dev/null +++ b/LuoSonglei/week-96/146-LRUCache.c @@ -0,0 +1,93 @@ +/******************************************* +Author : LHearen +E-mail : LHearen@126.com +Time : 2016-03-14 12:41 +Description : Design and implement a data structure for Least Recently Used (LRU) cache. It should support the following operations: get and set. +get(key) - Get the value (will always be positive) of the key if the key exists in the cache, otherwise return -1. +set(key, value) - Set or insert the value if the key is not already present. When the cache reached its capacity, it should invalidate the least recently used item before inserting a new item. +Source : https://leetcode.com/problems/lru-cache/ +*******************************************/ +#include +struct MyListNode +{ + int key; + int val; + struct MyListNode *next, *previous; +}; +struct Cache +{ + struct MyListNode **map; + struct MyListNode *head, *tail; + int maxSize; + int currentSize; +} cache; + +void deleteNode(struct MyListNode* p) +{ + p->previous->next = p->next; + p->next->previous = p->previous; +} + +void insertAfterHead(struct MyListNode *t) +{ + t->next = cache.head->next; + t->previous = cache.head; + cache.head->next->previous = t; + cache.head->next = t; +} + +void lruCacheInit(int capacity) +{ + cache.head = (struct MyListNode*)malloc(sizeof(struct MyListNode)); + cache.tail = (struct MyListNode*)malloc(sizeof(struct MyListNode)); + cache.head->previous = NULL; + cache.head->next = cache.tail; + cache.tail->previous = cache.head; + cache.tail->next = NULL; + cache.maxSize = capacity; + cache.currentSize = 0; + cache.map = (struct MyListNode**)malloc(sizeof(struct MyListNode*)*10000); + memset(cache.map, 0, sizeof(struct MyListNode*)*10000); +} + +void lruCacheFree() +{ +} + +int lruCacheGet(int key) +{ + struct MyListNode *p = cache.map[key]; + if(!p) return -1; + deleteNode(p); + insertAfterHead(p); + return p->val; +} + +void lruCacheSet(int key, int value) +{ + struct MyListNode *p = cache.map[key]; + if(p) + { + p->val = value; + deleteNode(p); + insertAfterHead(p); + } + else + { + struct MyListNode* t = (struct MyListNode*)malloc(sizeof(struct MyListNode)); + t->key = key; + t->val = value; + cache.map[key] = t; + if(cache.currentSize < cache.maxSize) + { + cache.currentSize++; + } + else + { + cache.map[cache.tail->previous->key] = NULL; + cache.tail->previous->previous->next = cache.tail; + cache.tail->previous = cache.tail->previous->previous; + } + insertAfterHead(t); + } +} diff --git a/LuoSonglei/week-96/164-MaxGap.c b/LuoSonglei/week-96/164-MaxGap.c new file mode 100644 index 0000000..c46d682 --- /dev/null +++ b/LuoSonglei/week-96/164-MaxGap.c @@ -0,0 +1,91 @@ +/******************************************* +Author : LHearen +E-mail : LHearen@126.com +Time : 2016-03-13 09:39 +Description : Given an unsorted array, find the maximum difference between the successive elements in its sorted form. +Try to solve it in linear time/space. +Return 0 if the array contains less than 2 elements. +You may assume all elements in the array are non-negative integers and fit in the 32-bit signed integer range. +Source : https://leetcode.com/problems/maximum-gap/ +*******************************************/ +#define MIN(a, b) ((a) < (b) ? (a) : (b)) +#define MAX(a, b) ((a) > (b) ? (a) : (b)) +void sort(int* nums, int begin, int end) +{ + int l=begin, r=end; + int v = nums[l+(r-l)/2]; + while(l <= r) + { + while(nums[l] < v) l++; + while(nums[r] > v) r--; + if(l <= r) + { + int t = nums[l]; + nums[l] = nums[r]; + nums[r] = t; + l++; r--; + } + } + if(begin < r) + sort(nums, begin, r); + if(l < end) + sort(nums, l, end); +} + +//AC - 8ms; +int maximumGap0(int* nums, int size) +{ + sort(nums, 0, size-1); + int max = 0; + for(int i = 1; i < size; i++) + if(nums[i]-nums[i-1] > max) + max = nums[i]-nums[i-1]; + return max; + +} + +#include + +int maximumGap(int* nums, int size) +{ + if(size < 2) return 0; + int min=INT_MAX, max=0; + for(int i = 0; i < size; i++) + { + if(nums[i] < min) min = nums[i]; + if(nums[i] > max) max = nums[i]; + } + if(min == max) return 0; //some corner cases; + if(min+1 == max) return 1; + if(size == 2) return max-min; + int gap = (max-min)/(size-1)+1; //make later index searching process easier but actually there will be also (max-min)/(size-1) numbers in each bucket; + int** buckets = (int**)malloc(sizeof(int*)*size); //only store the min and max in the bucket; + for(int i = 0; i < size; i++) + { + buckets[i] = (int*)malloc(sizeof(int)*2); + buckets[i][0] = -1; + buckets[i][1] = 0; + } + for(int i = 0; i < size; i++) //[min+k*gap, min+(k+1)*gap); + { + int k = (nums[i]-min)/gap; //get the index of the bucket; + if(nums[i] > buckets[k][1]) //the greatest in the bucket; + buckets[k][1] = nums[i]; + if(buckets[k][0]==-1 || nums[i] end) //move to the next bucket that has numbers since we initialize bucket with -1 and 0; + { + end = buckets[i][0]; //the end of the gap; + if(end-start > maxGap) + maxGap = end-start; + start = buckets[i][1]; //move to the next start; + } + } + return maxGap; +} diff --git a/LuoSonglei/week-96/218-TheSkylineProblem.c b/LuoSonglei/week-96/218-TheSkylineProblem.c new file mode 100644 index 0000000..2a54b40 --- /dev/null +++ b/LuoSonglei/week-96/218-TheSkylineProblem.c @@ -0,0 +1,29 @@ +/******************************************* +Author : LHearen +E-mail : LHearen@126.com +Time : 2016-03-12 15:49 +Description : A city's skyline is the outer contour of the silhouette formed by all the buildings in that city when viewed from a distance. Now suppose you are given the locations and height of all the buildings as shown on a cityscape photo (Figure A), write a program to output the skyline formed by these buildings collectively (Figure B). + + Buildings Skyline Contour + The geometric information of each building is represented by a triplet of integers [Li, Ri, Hi], where Li and Ri are the x coordinates of the left and right edge of the ith building, respectively, and Hi is its height. It is guaranteed that 0 ≤ Li, Ri ≤ INT_MAX, 0 < Hi ≤ INT_MAX, and Ri - Li > 0. You may assume all buildings are perfect rectangles grounded on an absolutely flat surface at height 0. + + For instance, the dimensions of all buildings in Figure A are recorded as: [ [2 9 10], [3 7 15], [5 12 12], [15 20 10], [19 24 8] ] . + + The output is a list of "key points" (red dots in Figure B) in the format of [ [x1,y1], [x2, y2], [x3, y3], ... ] that uniquely defines a skyline. A key point is the left endpoint of a horizontal line segment. Note that the last key point, where the rightmost building ends, is merely used to mark the termination of the skyline, and always has zero height. Also, the ground in between any two adjacent buildings should be considered part of the skyline contour. + + For instance, the skyline in Figure B should be represented as:[ [2 10], [3 15], [7 12], [12 0], [15 10], [20 8], [24, 0] ]. + +Notes: + +The number of buildings in any input list is guaranteed to be in the range [0, 10000]. +The input list is already sorted in ascending order by the left x position Li. +The output list must be sorted by the x position. +There must be no consecutive horizontal lines of equal height in the output skyline. For instance, [...[2 3], [4 5], [7 5], [11 5], [12 7]...] is not acceptable; the three lines of height 5 should be merged into one in the final output as such: [...[2 3], [4 5], [12 7], ...] +Source : https://leetcode.com/problems/the-skyline-problem/ +*******************************************/ +//https://briangordon.github.io/2014/08/the-skyline-problem.html +//http://www.geeksforgeeks.org/divide-and-conquer-set-7-the-skyline-problem/ +int** getSkyline(int** buildings, int rSize, int cSize, int* returnSize) +{ + +} diff --git a/LuoSonglei/week-96/25-ReverseNodesInK-Group.c b/LuoSonglei/week-96/25-ReverseNodesInK-Group.c new file mode 100644 index 0000000..45d4a11 --- /dev/null +++ b/LuoSonglei/week-96/25-ReverseNodesInK-Group.c @@ -0,0 +1,67 @@ +/******************************************* +Author : LHearen +E-mail : LHearen@126.com +Time : 2016-03-14 11:03 +Description : Given a linked list, reverse the nodes of a linked list k at a time and return its modified list. +If the number of nodes is not a multiple of k then left-out nodes in the end should remain as it is. +You may not alter the values in the nodes, only nodes itself may be changed. +Only constant memory is allowed. +For example, +Given this linked list: 1->2->3->4->5 +For k = 2, you should return: 2->1->4->3->5 +For k = 3, you should return: 3->2->1->4->5 +Source : https://leetcode.com/problems/reverse-nodes-in-k-group/ +*******************************************/ +#include +struct ListNode +{ + int val; + struct ListNode *next; +}; +struct ListNode* reverseList(struct ListNode* head) //reverse a linked list by insertion mode; +{ + struct ListNode *newHead = (struct ListNode*)malloc(sizeof(struct ListNode)); + newHead->next = NULL; + struct ListNode *t = newHead; + struct ListNode *p=head, *next; + while(p) + { + next = p->next; //store the next pointer; + p->next = t->next; //insert p just after the head pointer; + t->next = p; //connect p; + p = next; //move to the next; + } + return newHead->next; +} + + +//AC - 8ms; +struct ListNode* reverseKGroup(struct ListNode* head, int k) +{ + struct ListNode *newHead = (struct ListNode*)malloc(sizeof(struct ListNode)); + newHead->next = NULL; + struct ListNode *t=newHead, *last; + struct ListNode *p = head, *next, *start; + while(p) + { + start = p; //store the start for reversal; + last = start; //after reversal, the start will be the last; + int count = k-1; //move forward k-1 times to get the group of length k; + while(count && p) + { + p = p->next; + count--; + } + if(!p) //reached the end before the end of the group, directly connect it without reversal; + { + t->next = start; + break; + } + next = p->next; //store the next; + p->next = NULL; //terminate the current group; + t->next = reverseList(start); //reverse the group; + p = next; + t = last; //move t to the last of the collecting list; + } + return newHead->next; //using a head node will always make the list operations much simpler; +} diff --git a/LuoSonglei/week-96/307-RangeSumQuery.c b/LuoSonglei/week-96/307-RangeSumQuery.c new file mode 100644 index 0000000..ee3ad73 --- /dev/null +++ b/LuoSonglei/week-96/307-RangeSumQuery.c @@ -0,0 +1,82 @@ +/******************************************* +Author : LHearen +E-mail : LHearen@126.com +Time : 2016-03-09 16:38 +Description : Given an integer array nums, find the sum of the elements between indices i and j (i ≤ j), inclusive. + +The update(i, val) function modifies nums by updating the element at index i to val. +Example: +Given nums = [1, 3, 5] + +sumRange(0, 2) -> 9 +update(1, 2) +sumRange(0, 2) -> 8 +Note: +The array is only modifiable by the update function. +You may assume the number of calls to update and sumRange function is distributed evenly. +Source : https://leetcode.com/problems/range-sum-query-mutable/ +Reference : http://www.geeksforgeeks.org/binary-indexed-tree-or-fenwick-tree-2/ +*******************************************/ +#include +struct NumArray +{ + int *nums, *sums; + int size; +}; + +//partial sums are stored in numArray->sums; +//index of sums are 1 more than that in nums; +void updateElement(struct NumArray* numArray, int i, int val) +{ + i++; + while(i <= numArray->size) + { + numArray->sums[i] += val; + i += (i & -i); //move to its parent i UpdateView; + } +} + +struct NumArray* NumArrayCreate(int *nums, int size) +{ + struct NumArray *t = (struct NumArray*)malloc(sizeof(struct NumArray)); + t->nums = (int*)malloc(sizeof(int)*size); + memcpy(t->nums, nums, sizeof(int)*size); + t->size = size; + t->sums = (int*)malloc(sizeof(int)*(size+1)); + memset(t->sums, 0, sizeof(int)*(size+1)); + for(int i = 0; i <= size; i++) + updateElement(t, i, nums[i]); + return t; +} + +void update(struct NumArray* numArray, int i, int val) +{ + int d = val-numArray->nums[i]; + numArray->nums[i] = val; + updateElement(numArray, i, d); +} + +//partial sums are stored in numArray->sums; +//index of sums are 1 more than that in nums; +int getSum(struct NumArray* numArray, int i) +{ + int sum = 0; + i++; + while(i > 0) + { + sum += numArray->sums[i]; + i -= (i & -i); //move to its parent in getSumView; + } + return sum; +} +int sumRange(struct NumArray* numArray, int i, int j) +{ + return getSum(numArray, j)-getSum(numArray, i-1); +} + +void NumArrayFree(struct NumArray* numArray) +{ + free(numArray->nums); + free(numArray->sums); + free(numArray); +} diff --git a/LuoSonglei/week-96/307-RangeSumQuery1.c b/LuoSonglei/week-96/307-RangeSumQuery1.c new file mode 100644 index 0000000..ee3ad73 --- /dev/null +++ b/LuoSonglei/week-96/307-RangeSumQuery1.c @@ -0,0 +1,82 @@ +/******************************************* +Author : LHearen +E-mail : LHearen@126.com +Time : 2016-03-09 16:38 +Description : Given an integer array nums, find the sum of the elements between indices i and j (i ≤ j), inclusive. + +The update(i, val) function modifies nums by updating the element at index i to val. +Example: +Given nums = [1, 3, 5] + +sumRange(0, 2) -> 9 +update(1, 2) +sumRange(0, 2) -> 8 +Note: +The array is only modifiable by the update function. +You may assume the number of calls to update and sumRange function is distributed evenly. +Source : https://leetcode.com/problems/range-sum-query-mutable/ +Reference : http://www.geeksforgeeks.org/binary-indexed-tree-or-fenwick-tree-2/ +*******************************************/ +#include +struct NumArray +{ + int *nums, *sums; + int size; +}; + +//partial sums are stored in numArray->sums; +//index of sums are 1 more than that in nums; +void updateElement(struct NumArray* numArray, int i, int val) +{ + i++; + while(i <= numArray->size) + { + numArray->sums[i] += val; + i += (i & -i); //move to its parent i UpdateView; + } +} + +struct NumArray* NumArrayCreate(int *nums, int size) +{ + struct NumArray *t = (struct NumArray*)malloc(sizeof(struct NumArray)); + t->nums = (int*)malloc(sizeof(int)*size); + memcpy(t->nums, nums, sizeof(int)*size); + t->size = size; + t->sums = (int*)malloc(sizeof(int)*(size+1)); + memset(t->sums, 0, sizeof(int)*(size+1)); + for(int i = 0; i <= size; i++) + updateElement(t, i, nums[i]); + return t; +} + +void update(struct NumArray* numArray, int i, int val) +{ + int d = val-numArray->nums[i]; + numArray->nums[i] = val; + updateElement(numArray, i, d); +} + +//partial sums are stored in numArray->sums; +//index of sums are 1 more than that in nums; +int getSum(struct NumArray* numArray, int i) +{ + int sum = 0; + i++; + while(i > 0) + { + sum += numArray->sums[i]; + i -= (i & -i); //move to its parent in getSumView; + } + return sum; +} +int sumRange(struct NumArray* numArray, int i, int j) +{ + return getSum(numArray, j)-getSum(numArray, i-1); +} + +void NumArrayFree(struct NumArray* numArray) +{ + free(numArray->nums); + free(numArray->sums); + free(numArray); +} diff --git a/LuoSonglei/week-96/336-PalindromePairs.c b/LuoSonglei/week-96/336-PalindromePairs.c new file mode 100644 index 0000000..e0e6663 --- /dev/null +++ b/LuoSonglei/week-96/336-PalindromePairs.c @@ -0,0 +1,56 @@ +/******************************************* +Author : LHearen +E-mail : LHearen@126.com +Time : 2016-03-10 08:02 +Description : Given a list of unique words. Find all pairs of indices (i, j) in the given list, so that the concatenation of the two words, i.e. words[i] + words[j] is a palindrome. + +Example 1: +Given words = ["bat", "tab", "cat"] +Return [[0, 1], [1, 0]] +The palindromes are ["battab", "tabbat"] +Example 2: +Given words = ["abcd", "dcba", "lls", "s", "sssll"] +Return [[0, 1], [1, 0], [3, 2], [2, 4]] +The palindromes are ["dcbaabcd", "abcddcba", "slls", "llssssll"] +Source : https://leetcode.com/problems/palindrome-pairs/ +*******************************************/ +//TLE; +int** palindromePairs(char** words, int wSize, int** colSizes, int* returnSize) +{ + int **pairs = (int**)malloc(sizeof(int*)); + *colSizes = (int*)malloc(sizeof(int)); + int maxLen = 0; + int *lens = (int*)malloc(sizeof(int)*wSize); + for(int i = 0; i < wSize; i++) + { + lens[i] = strlen(words[i]); + if(lens[i] > maxLen) + maxLen = lens[i]; + } + char *t = (char*)malloc(sizeof(char)*(2*maxLen+1)); + for(int i = 0; i < wSize; i++) + { + for(int j = 0; j < wSize; j++) + { + if(i == j) continue; + *t = '\0'; + strcat(t, words[i]); + strcat(t, words[j]); + int k = 0; + int len = lens[i]+lens[j]; + while(k maxWidth) break; + len += strlen(words[index])+1; + index++; + } + char* t = (char*)malloc(sizeof(char)*(maxWidth+2)); + *t = '\0'; + int spaceCount = index-start-1; + if(index==wSize || spaceCount==0) //the last line or only one word just take up the whole line -> should be left justified; + { + int j = 0; + for(int i = start; i < index; i++) //left justified; + { + for(int k = 0; k < strlen(words[i]); k++) + t[j++] = words[i][k]; + t[j++] = ' '; + } + t[j-1] = '\0'; //remove the last redundant white space; + for(int i = j-1; i < maxWidth; i++) //fill up the left spaces with white spaces; + t[i] = ' '; + t[maxWidth] = '\0'; + } + else //normally full justification; + { + int averageSpace = (maxWidth-len)/spaceCount; //average white spaces should be filled in each slot between words; + int remainder = (maxWidth-len)%spaceCount; //the left; + for(int i = start; i < index; i++) + { + strcat(t, words[i]); + if(i < index-1) //the last word cannot be followed by white spaces; + for(int j = 0; j <= averageSpace+((i-start) +//AC - 4ms - using loop to check; +bool isPowerOfFour0(int n) +{ + int arr[] = {1, 4,16,64,256,1024,4096,16384,65536,262144,1048576,4194304, + 16777216,67108864,268435456,1073741824}; //using the OJ to get the array; + for(int i = 0; i < sizeof(arr)/sizeof(int); i++) //check whether it's one of them; + if(num == arr[i]) return true; + return false; +} + +//AC - 4ms - recursive; +bool isPowerOfFour1(int n) +{ + if(n < 1) return false; + if(n == 1) return true; + return (n&3)==0 && isPowerOfFour(n>>2); //n&3 -> n%4; +} + +//AC - 4ms - using loop; +bool isPowerOfFour2(int n) +{ + if(n < 1) return false; + if(n == 1) return true; + while(n > 1) + { + if(n%4) return false; + n /= 4; + } + return true; +} + +//AC - 4ms - adopting bit manipulation; +bool isPowerOfFour(int n) +{ + return n==1 || (n>1 && (n&-n)==n && (n&0x2aaaaaab)==0); //n&-n used to get the last bit of n -> used here to check whether it only has one 1-bit; + //n&0x2aaaaaab used to make sure the 1-bit lies in the right position - power of four; +} diff --git a/LuoSonglei/week-97/343-IntegerBreak.c b/LuoSonglei/week-97/343-IntegerBreak.c new file mode 100644 index 0000000..f09d531 --- /dev/null +++ b/LuoSonglei/week-97/343-IntegerBreak.c @@ -0,0 +1,44 @@ +/******************************************* +Author : LHearen +E-mail : LHearen@126.com +Time : Tue, 24 May 2016 20:21 CST +Description : Given a positive integer n, break it into the sum of at least two positive integers and maximize the product of those integers. Return the maximum product you can get. +For example, given n = 2, return 1 (2 = 1 + 1); given n = 10, return 36 (10 = 3 + 3 + 4). +Note: you may assume that n is not less than 2. +Source : https://leetcode.com/problems/integer-break/ +*******************************************/ +//AC - 0ms - DP; +#define MAX(a, b) ((a) > (b) ? (a) : (b)) +int integerBreak0(int n) +{ + int *arr = (int*)malloc(sizeof(int)*(n+1)); //used to store the max product of the index; + arr[2]=1, arr[3]=2, arr[4]=4; //corner cases; + for(int i = 5; i <= n; i++) + { + int max = 0; + for(int j = 2; j < i-1; j++) + { + int t = MAX(j, arr[j])*MAX(i-j, arr[i-j]); //select the value itself or the its product value; + if(t > max) max = t; + } + arr[i] = max; + } + return arr[n]; +} + +//AC - 0ms - mathematical solution; +//only 2 or 3 will be used to make the product bigger; +//elements bigger than them can be splitted further to make bigger; +//meantime 3*3 > 2*2*2 so we should get as many 3 as possible; +int integerBreak(int n) +{ + if(n == 2) return 1; + if(n == 3) return 2; + int ret = 1; + while(n > 4) + { + ret *= 3; + n -= 3; + } + return ret*n; +} diff --git a/LuoSonglei/week-97/345-ReverseVowelsOfAString.c b/LuoSonglei/week-97/345-ReverseVowelsOfAString.c new file mode 100644 index 0000000..f7b5547 --- /dev/null +++ b/LuoSonglei/week-97/345-ReverseVowelsOfAString.c @@ -0,0 +1,33 @@ +/******************************************* +Author : LHearen +E-mail : LHearen@126.com +Time : Tue, 24 May 2016 19:58 CST +Description : Write a function that takes a string as input and reverse only the vowels of a string. +Example 1: +Given s = "hello", return "holle". +Example 2: +Given s = "leetcode", return "leotcede". +Source : https://leetcode.com/problems/reverse-vowels-of-a-string/ +*******************************************/ +#include +//AC - 4ms; +bool isVowel(char a) +{ + char c = tolower(a); + return c=='a' || c=='e' || c=='i' || c=='o' || c=='u'; +} +char* reverseVowels(char* s) { + int len = strlen(s); + int l=0, r=len-1; + while(l < r) + { + while(l-1 && !isVowel(s[r])) r--; + if(l-1 && l < r) + { + char t=s[l]; s[l]=s[r]; s[r]=t; + l++, r--; + } + } + return s; +} diff --git a/LuoSonglei/week-97/347-TopkFrequentElements.c b/LuoSonglei/week-97/347-TopkFrequentElements.c new file mode 100644 index 0000000..d655f09 --- /dev/null +++ b/LuoSonglei/week-97/347-TopkFrequentElements.c @@ -0,0 +1,60 @@ +/******************************************* +Author : LHearen +E-mail : LHearen@126.com +Time : Tue, 31 May 2016 08:54 CST +Description : Given a non-empty array of integers, return the k most frequent elements. +For example, +Given [1,1,1,2,2,3] and k = 2, return [1,2]. +Note: +You may assume k is always valid, 1 ≤ k ≤ number of unique elements. +Your algorithm's time complexity must be better than O(n log n), where n is the array's size. +Source : https://leetcode.com/problems/top-k-frequent-elements/ +*******************************************/ +void swap(int* p, int* q) +{ + int t=*p; *p=*q; *q=t; +} + +//Sort the array nums and keep its indexes along with it; +void sort(int* nums, int* indexes, int begin, int end) +{ + int l=begin, r=end; + int v = nums[l+(r-l)/2]; + while(l <= r) + { + while(nums[l] < v) l++; + while(nums[r] > v) r--; + if(l <= r) + { + swap(indexes+l, indexes+r); + swap(nums+l++, nums+r--); + } + } + if(begin < r) + sort(nums, indexes, begin, r); + if(l < end) + sort(nums, indexes, l, end); +} + +//AC - 24ms; +int* topKFrequent(int* nums, int size, int k, int* returnSize) +{ + int* indexes = (int*)malloc(sizeof(int)*size); + int* arr = (int*)malloc(sizeof(int)*size); //used to count and also be used as return array; + sort(nums, arr, 0, size-1); //arr here is used for parameter position-taker, nothing more; + int top = -1; + for(int i = 0; i < size; i++) //count elements, recording its first index and frequency; + { + if(top==-1 || nums[indexes[top]]!=nums[i]) + { + indexes[++top] = i; + arr[top] = 1; + } + else arr[top]++; + } + sort(arr, indexes, 0, top); //make the frequency array arr in ascending order; + for(int i = 0; i < k; i++) //collect the first k most frequent elements; + arr[i] = nums[indexes[top-i]]; + *returnSize = k; + return arr; +} diff --git a/LuoSonglei/week-97/349-IntersectionOfTwoArrays.c b/LuoSonglei/week-97/349-IntersectionOfTwoArrays.c new file mode 100644 index 0000000..2729d42 --- /dev/null +++ b/LuoSonglei/week-97/349-IntersectionOfTwoArrays.c @@ -0,0 +1,86 @@ +/******************************************* +Author : LHearen +E-mail : LHearen@126.com +Time : Tue, 24 May 2016 20:49 CST +Description : Given two arrays, write a function to compute their intersection. +Example: +Given nums1 = [1, 2, 2, 1], nums2 = [2, 2], return [2]. +Note: +Each element in the result must be unique. +The result can be in any order. +Source : https://leetcode.com/problems/intersection-of-two-arrays/ +*******************************************/ +//AC - 12ms; +#define MIN(a, b) ((a) < (b) ? (a) : (b)) +int* intersection0(int* nums1, int size1, int* nums2, int size2, int* returnSize) +{ + int size = MIN(size1, size2); + int *arr = (int*)malloc(sizeof(int)*(size)); + int top = -1; + for(int i = 0; i < size1; i++) //check each element in nums1; + { + int j = 0; + for(; j < size2; j++) //check whether the nums[i] in array nums2; + if(nums1[i] == nums2[j]) break; + if(j < size2) + { + j = 0; + for(; j <= top; j++) //avoid duplicate; + if(arr[j] == arr[i]) break; + if(j > top) + arr[++top] = arr[i]; + } + } + *returnSize = top+1; + return arr; +} + +void swap(int* p, int* q) +{ + int t=*p; *p=*q; *q=t; +} + +//Quick sort; +void sort(int* nums, int begin, int end) +{ + int l = begin, r = end; + int v = nums[l+(r-l)/2]; + while(l <= r) + { + while(nums[l] < v) l++; + while(nums[r] > v) r--; + if(l <= r) + { + swap(nums+l, nums+r); + l++, r--; + } + } + if(begin < r) + sort(nums, begin, r); + if(l < end) + sort(nums, l, end); +} + +//AC - 4ms - using two pointers; +int* intersection(int* nums1, int size1, int* nums2, int size2, int* returnSize) +{ + sort(nums1, 0, size1-1); + sort(nums2, 0, size2-1); + int size = MIN(size1, size2); + int* arr = (int*)malloc(sizeof(int)*size); //the size of the result will at most be size; + int top = -1; + int p1=0, p2=0; + while(p1 nums2[p2]) p2++; + else if(nums1[p1] < nums2[p2]) p1++; + else //only collect the equal one; + { + if(top==-1 || arr[top]!=nums1[p1]) //avoid duplicates; + arr[++top] = nums1[p1]; + p1++, p2++; + } + } + *returnSize = top+1; + return arr; +} diff --git a/LuoSonglei/week-97/350-IntersectionOfTwoArrays2.c b/LuoSonglei/week-97/350-IntersectionOfTwoArrays2.c new file mode 100644 index 0000000..4243255 --- /dev/null +++ b/LuoSonglei/week-97/350-IntersectionOfTwoArrays2.c @@ -0,0 +1,63 @@ +/******************************************* +Author : LHearen +E-mail : LHearen@126.com +Time : Tue, 31 May 2016 07:55 CST +Description : Given two arrays, write a function to compute their intersection. +Example: +Given nums1 = [1, 2, 2, 1], nums2 = [2, 2], return [2, 2]. + +Note: +Each element in the result should appear as many times as it shows in both arrays. +The result can be in any order. +Follow up: +What if the given array is already sorted? How would you optimize your algorithm? +What if nums1's size is small compared to num2's size? Which algorithm is better? +What if elements of nums2 are stored on disk, and the memory is limited such that you cannot load all elements into the memory at once? +Source : https://leetcode.com/problems/intersection-of-two-arrays-ii/ +*******************************************/ +void swap(int* p, int* q) +{ + int t=*p; *p=*q; *q=t; +} + +//Quick sort; +void sort(int* nums, int begin, int end) +{ + int l = begin, r = end; + int v = nums[l+(r-l)/2]; + while(l <= r) + { + while(nums[l] < v) l++; + while(nums[r] > v) r--; + if(l <= r) + { + swap(nums+l, nums+r); + l++, r--; + } + } + if(begin < r) + sort(nums, begin, r); + if(l < end) + sort(nums, l, end); +} + +//AC - 4ms; +int* intersect(int* nums1, int size1, int* nums2, int size2, int* returnSize) +{ + int size = size1>size2? size2:size1; + int* arr = (int*)malloc(sizeof(int)*size); + int top = -1; + int i=0, j=0; + while(i nums2[j]) j++; + else + { + arr[++top] = nums1[i]; + i++, j++; + } + } + *returnSize = top+1; + return arr; +} diff --git a/Schedule of AlgorithmHackers' b/Schedule of AlgorithmHackers' index 7509817..13eb30e 100644 --- a/Schedule of AlgorithmHackers' +++ b/Schedule of AlgorithmHackers' @@ -1,3 +1,98 @@ +################################################################### +ISCAS14 - AlgorithmHackers - week12 +Tue Mar 22 11:24:15 CST 2016 +1. 陈晓旭 +Add and Search Word - Data structure design +https://leetcode.com/problems/add-and-search-word-data-structure-design/ +2. 罗松磊 +Wiggle Sort II +https://leetcode.com/problems/wiggle-sort-ii/ +3. 郑莹莹 +Range Sum Query - Mutable +https://leetcode.com/problems/range-sum-query-mutable/ +4. 邬登峰 +LRU Cache +https://leetcode.com/problems/lru-cache/ +5. 王子勇 +Maximum Gap +https://leetcode.com/problems/maximum-gap/ + +################################################################### +ISCAS14 - AlgorithmHackers - week11 +Wed Mar 16 13:57:27 CST 2016 +1. 梁建华 +Reverse Nodes in k-Group +https://leetcode.com/problems/reverse-nodes-in-k-group/ +2. 倪嘉志 +The Skyline Problem +https://leetcode.com/problems/the-skyline-problem/ +3. 段世凯 +Palindrome Pairs +https://leetcode.com/problems/palindrome-pairs/ +4. 徐培兴 +Course Schedule II +https://leetcode.com/problems/course-schedule-ii/ +5. 崔光范 +Clone Graph +https://leetcode.com/problems/clone-graph/ + +################################################################### +ISCAS14 - AlgorithmHackers - week10 +Tue Mar 8 19:32:29 CST 2016 +1. 倪嘉志 +Maximal Square +https://leetcode.com/problems/maximal-square/ +2. 罗松磊 +Single Number II +https://leetcode.com/problems/single-number-ii/ +3. 燕东 +Decode Ways +https://leetcode.com/problems/decode-ways/ +4. 佘艺 +Word Break II +https://leetcode.com/problems/word-break-ii/ +5. 刘财政 +Create Maximum Number +https://leetcode.com/problems/create-maximum-number/ + +################################################################### +ISCAS14 - AlgorithmHackers - week9 +Mon Feb 29 19:11:20 CST 2016 +1. 郑莹莹 +Count Primes +https://leetcode.com/problems/count-primes/ +2. 徐培兴 +Basic Calculator +https://leetcode.com/problems/basic-calculator/ +3. 邬登峰 +Bulb Switcher +https://leetcode.com/problems/bulb-switcher/ +4. 王子勇 +Multiply Strings +https://leetcode.com/problems/multiply-strings/ +5. 唐弘胤 +Fraction to Recurring Decimal +https://leetcode.com/problems/fraction-to-recurring-decimal/ + +################################################################### +ISCAS14 - AlgorithmHackers - week8 +Mon Jan 18 21:01:54 CST 2016 +1. 崔艳玲 +Distinct Subsequences +https://leetcode.com/problems/distinct-subsequences/ +2. 唐弘胤 +House Robber +https://leetcode.com/problems/house-robber/ +3. 燕东 +Ugly Number II +https://leetcode.com/problems/ugly-number-ii/ +4. 罗松磊 +Unique Paths II +https://leetcode.com/problems/unique-paths-ii/ +5. 倪嘉志 +Unique Binary Search Trees +https://leetcode.com/problems/unique-binary-search-trees/ + ################################################################### ISCAS14 - AlgorithmHackers - week7 Mon Jan 11 21:18:42 CST 2016 diff --git a/SheYi/2016-01-10-week6/UniqueBinarySearchTreesII.java b/SheYi/2016-01-10-week6/UniqueBinarySearchTreesII.java new file mode 100644 index 0000000..cfb3a4d --- /dev/null +++ b/SheYi/2016-01-10-week6/UniqueBinarySearchTreesII.java @@ -0,0 +1,165 @@ +package algorithm; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +public class UniqueBinarySearchTreesII { + /* public List generateTrees(int n) { + List nodelist=new ArrayList(); + HashMap s=new HashMap(); + TreeNode temp=null; + for(int i=1;i s,TreeNode curNode,TreeNode preNode,List rlist,TreeNode r){ + if(k==n){ + TreeNode temp=copyTree(r); + rlist.add(temp); + // s.clear(); + }else{ + List c=new ArrayList(); + if(!c.isEmpty()) c.clear(); + construct_candidate(n,0,curNode,preNode,s,c); + for(int i=0;i cur,List c){ + if(pre==null) pre=new TreeNode(n+1); + if(type==0){ + for(int i=1;ii) + c.add(i); + } + }else if(type==1){ + for(int i=pre.val+1;i generateTrees(int n) { + if(n<1) return new ArrayList(); + else + return recur(1,n); + } + + public List recur(int begin,int end){ + List rlist=new ArrayList(); + if(begin>end){ + rlist.add(null); + return rlist; + }else{ + for(int k=begin;k<=end;k++){ + List left=recur(begin,k-1); //������ + List right=recur(k+1,end); //������ + for(int i=0;i rlist=u.generateTrees(3); + for(int i=0;icurmax) + curmax=nums[i]+i; + if(curmax>=nums.length-1){ + return count+1; + } + if(i>=premax){ + count++; + premax=curmax; + } + } + return count; + } + + public static void main(String [] args){ + JumpGameII j=new JumpGameII(); + int[] nums={1,1,1,1}; + int r=j.jump(nums); + System.out.println("result="+r); + } +} diff --git a/SheYi/2016-01-17-week7/Permutations.java b/SheYi/2016-01-17-week7/Permutations.java new file mode 100644 index 0000000..f6012e4 --- /dev/null +++ b/SheYi/2016-01-17-week7/Permutations.java @@ -0,0 +1,129 @@ +package week7; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +//I AC 7ms +public class Permutations { + //I AC 7ms ���ݷ� ����ȥѡ�������Ԫ�� �����е�Ԫ�ض������� ����⵽�˵�n�㣨nΪ����Ԫ�صĸ���������õ�һ��⣬���Ż��� + //ȥ����һ��� ��⵽ÿһ�� �͸��ݵ�ǰ�������⵱ǰ�����п�ѡ��ֵ +/* public List> permute(int[] nums) { + List> rlist=new ArrayList>(); + List cur=new ArrayList(); + if(rlist==null) return rlist; + traceback(0,nums,cur,rlist); + return rlist; + } + + public void traceback(int k,int[] nums,List cur,List> rlist){ + if(k==nums.length){ + List temp=new ArrayList(cur); + rlist.add(temp); + }else{ + k++; + List c=new ArrayList(); + int count=construct_candidate(nums,cur,c); + for(int i=0;i cur,List c){ + int length=nums.length; + for(int i=0;i> permuteUnique(int[] nums) { + List> rlist=new ArrayList>(); + HashMap map=new HashMap(); + List cur=new ArrayList(); + if(nums.length<1) return rlist; + //��ʼ��hashmap + for(int i=0;i map,List cur,List> rlist){ + if(k==nums.length){ + ArrayList temp=new ArrayList(cur); + rlist.add(temp); + }else{ + k++; + List c=new ArrayList(); + int count=construct_candidate(map,c); + for(int i=0;i map){ + if(type==0){//��map���Ƴ���Ԫ�� + Integer value= map.get(element); + if(null==value) return ; + else if(value.equals(1)){ + map.remove(element); + } + else if(value>1){ + map.put(element, value-1); + } + }else if(type==1) {//����Ԫ�ص�map�� + Integer value=map.get(element); + if(null==value){ + map.put(element, 1); + }else{ + map.put(element, value+1); + } + } + + } + + public int construct_candidate(HashMap map,List r){ + Iterator it=map.entrySet().iterator(); + while(it.hasNext()){ + Map.Entry entry=(Map.Entry)it.next(); + r.add((Integer)entry.getKey()); + } + return r.size(); + } + + public static void main(String [] args){ + int[] nums={1,1,2,2}; + Permutations p=new Permutations(); + List> list=p.permuteUnique(nums); + System.out.println("["); + for(int i=0;i 0 && builder.charAt(i) != builder.charAt(j)) + j = next[j - 1]; //��������ƥ�䣬Ѱ����һ���γ���ƥ�� + if(builder.charAt(i)==builder.charAt(j)) + j++; + next[i]=j; + } + return next[next.length - 1]; + } + + public static void main(String [] args){ + ShortestPalindrome p=new ShortestPalindrome(); + String s="a"; + String r=p.shortestPalindrome(s); + System.out.println("r="+r); + } +} diff --git a/SheYi/2016-01-24-week8/DistinctSubsequences.java b/SheYi/2016-01-24-week8/DistinctSubsequences.java new file mode 100644 index 0000000..e03e754 --- /dev/null +++ b/SheYi/2016-01-24-week8/DistinctSubsequences.java @@ -0,0 +1,36 @@ +package week8; + +public class DistinctSubsequences { + public int numDistinct(String s, String t) { + int sLength=s.length(); + int tLength=t.length(); + if(s.equals(t)) return 1; + if(sLength==0||tLength==0) return 0; + int[][] d=new int[sLength][tLength]; + int count=0; + for(int i=0;i dp[i - 2] + nums[i]: + dp[i] = dp[i - 1] + else: + dp[i] = dp[i - 2] + nums[i] + return dp[len(nums) - 1] + +if __name__ == "__main__": + solution = Solution() + print solution.rob([2, 1, 1, 1]) \ No newline at end of file diff --git a/TangHongyin/ugly_number_ii.py b/TangHongyin/ugly_number_ii.py new file mode 100644 index 0000000..f199055 --- /dev/null +++ b/TangHongyin/ugly_number_ii.py @@ -0,0 +1,18 @@ +def nthUglyNumber(self, n): + + ugly = [1] * n + i2 = i3 = i5 = -1 + x = v2 = v3 = v5 = 1 + for k in xrange(n): + x = min(v2, v3, v5) + ugly[k] = x + if x == v2: + i2 += 1 + v2 = ugly[i2] * 2 + if x == v3: + i3 += 1 + v3 = ugly[i3] * 3 + if x == v5: + i5 += 1 + v5 = ugly[i5] * 5 + return x \ No newline at end of file diff --git a/TangHongyin/unique_binary_search_trees.py b/TangHongyin/unique_binary_search_trees.py new file mode 100644 index 0000000..1155232 --- /dev/null +++ b/TangHongyin/unique_binary_search_trees.py @@ -0,0 +1,15 @@ +class Solution(object): + def numTrees(self, n): + """ + :type n: int + :rtype: int + """ + dp = [0] * (n + 1) + dp[0], dp[1] = 1, 1 + for i in range(2, n + 1): + for j in range(0, i): + dp[i] += dp[j] * dp[i - 1 - j] + return dp[n] +if __name__ == '__main__': + solution = Solution() + print solution.numTrees(4) \ No newline at end of file diff --git a/TangHongyin/unique_paths_ii.py b/TangHongyin/unique_paths_ii.py new file mode 100644 index 0000000..91190a0 --- /dev/null +++ b/TangHongyin/unique_paths_ii.py @@ -0,0 +1,25 @@ +class Solution(object): + def uniquePathsWithObstacles(self, obstacleGrid): + """ + :type obstacleGrid: List[List[int]] + :rtype: int + """ + if len(obstacleGrid) == 0 or obstacleGrid is None: + return 1 + dp = [[0] * len(obstacleGrid[i]) for i in range(len(obstacleGrid))] + for i in range(len(obstacleGrid)): + for j in range(len(obstacleGrid[i])): + if obstacleGrid[i][j] == 1: + dp[i][j] = 0 + continue + if i == 0: + if j == 0: + dp[i][j] = 1 + else: + dp[i][j] = dp[i][j - 1] + else: + if j == 0: + dp[i][j] = dp[i - 1][j] + else: + dp[i][j] = dp[i - 1][j] + dp[i][j - 1] + return dp[len(obstacleGrid) - 1][len(obstacleGrid[0]) - 1] diff --git a/wudengfeng/95.txt b/WuDengFeng/95.txt similarity index 100% rename from wudengfeng/95.txt rename to WuDengFeng/95.txt diff --git a/WuDengFeng/stock3.txt b/WuDengFeng/stock3.txt new file mode 100644 index 0000000..7ae1fe6 --- /dev/null +++ b/WuDengFeng/stock3.txt @@ -0,0 +1,33 @@ +public class Solution { + public int maxProfit(int[] prices) { + if(prices.length == 0) return 0; + int ans = 0; + int n = prices.length; + + int opt[] = new int[n]; + opt[0] = 0; + int low = prices[0]; + int curAns = 0; + for(int i = 1; i=0; i--){ + if(prices[i] > high) high = prices[i]; + else if(curAns < high - prices[i]) curAns = high - prices[i]; + optReverse[i] = curAns; + } + + for(int i=0; iheight) { + return false; + } + if (y<0||y>width) { + return false; + } + if ('O' == board[x][y]) { + board[x][y] = 'K'; + return true; + } + return false; + } + public static void main(String[] args) { +// // TODO Auto-generated method stub +// char[][] bb = {{'X','K','X','K','X','K'}, +// {'O','O','O','X','O','X'}, +// {'X','O','X','O','O','X'}, +// {'O','X','O','X','O','X'}}; +// new SurroundedRegions130().solve(bb); +// Map m = new HashMap<>(); +// m.hashCode(); +// Integer a = 1; +// Integer b = 1; +// System.out.println(a==b); +// a = new Integer(1); +// b = new Integer(1); +// System.out.println(a==b); +// System.out.println(a.equals(b)); +// a = new Integer('1'); +// b = new Integer(1); +// System.out.println(a==b); +// Integer a = 1; +// Integer b = 1; +// a = Integer.valueOf(1); +// b = Integer.valueOf("1"); +// System.out.println(a==b); + for(int i = 0;i<78 ;i++){ + System.out.println(""); + } + } + +} diff --git a/XuPershing/WordLadder127.java b/XuPershing/WordLadder127.java new file mode 100644 index 0000000..401405c --- /dev/null +++ b/XuPershing/WordLadder127.java @@ -0,0 +1,35 @@ + +public class WordLadder127 { + /** + * @param beginWord + * @param endWord + * @param wordList + * @return + * @author xpxstar@gmail.com + * @2015��12��28�� + * Given two words (beginWord and endWord), and a dictionary's word list, find the length of shortest transformation sequence from beginWord to endWord, such that: +Only one letter can be changed at a time +Each intermediate word must exist in the word list +For example, + +Given: +beginWord = "hit" +endWord = "cog" +wordList = ["hot","dot","dog","lot","log"] +As one shortest transformation is "hit" -> "hot" -> "dot" -> "dog" -> "cog", +return its length 5. + +Note: +Return 0 if there is no such transformation sequence. +All words have the same length. +All words contain only lowercase alphabetic characters + */ + public int ladderLength(String beginWord, String endWord, Set wordList) { + + } + public static void main(String[] args) { + // TODO Auto-generated method stub + + } + +} diff --git a/XuPershing/week7/BSTree.java b/XuPershing/week7/BSTree.java new file mode 100644 index 0000000..caa98c8 --- /dev/null +++ b/XuPershing/week7/BSTree.java @@ -0,0 +1,60 @@ +package week7; + +public class BSTree { + public TreeNode root; + public class TreeNode{ + int val; + int children; + TreeNode left; + TreeNode right; + public TreeNode(int x) {val = x;children = 0;} + public TreeNode(TreeNode l,TreeNode r) {left = l;right = r;} + } + //ƫ���BST��children ��ʾ��ǰ�ڵ�ĺ������� + /** + * @param value + * @return ���رȵ�ǰֵС��Ԫ�ظ����� + * @author xpxstar@gmail.com + * @2016��1��12�� + * ʱ�临�Ӷ�O(lgN) + */ + public int addNode(int value){ + int num = 0; + if(this.root == null){ + this.root = new TreeNode(value); + return num; + } + TreeNode parent = null, node = root; + while(node != null){ + parent = node; + node.children++; + if(value > node.val){ + num+= node.left == null?1:node.left.children+2; + node = node.right; + }else{ + node = node.left; + } + } + /* Have found the new node's position. Insert it into the tree. */ + if(value > parent.val) + parent.right = new TreeNode(value); + else + parent.left = new TreeNode(value); + + return num; + } + + public static void main(String[] args) { + BSTree tree = new BSTree(); + tree.addNode(25); + tree.addNode(1); + tree.addNode(65); + tree.addNode(9); + tree.addNode(41); + tree.addNode(8); + System.out.println(tree.addNode(0)); + + + } + +} diff --git a/XuPershing/week7/BestTimeTradeStock121.java b/XuPershing/week7/BestTimeTradeStock121.java new file mode 100644 index 0000000..3feaecf --- /dev/null +++ b/XuPershing/week7/BestTimeTradeStock121.java @@ -0,0 +1,89 @@ +package week7; + +import java.util.HashMap; +import java.util.Map; + +public class BestTimeTradeStock121 { + + /** + * @param prices + * @return + * @author xpxstar@gmail.com + * @2016��1��14�� + * Say you have an array for which the ith element is the price of a given stock on day i. + +If you were only permitted to complete at most one transaction (ie, buy one and sell one share of the stock), +design an algorithm to find the maximum profit. + */ + public int maxProfitI(int[] prices) { + if (prices.length<2) { + return 0; + } + int min = prices[0],profit = 0,tmp; + for (int i = 1; i < prices.length; i++) { + if (min > prices[i]) { + min = prices[i]; + }else { + tmp = prices[i]-min; + profit = tmp>profit?tmp:profit; + } + } + return profit; + } + /** + * @param prices + * @return + * @author xpxstar@gmail.com + * @2016��1��14�� + * Say you have an array for which the ith element is the price of a given stock on day i. + +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). +ע�⣬����Ĺ�Ʊ���ܶ���1����*/ + public int maxProfitII(int[] prices) { + if (prices.length<2) { + return 0; + } + int min = prices[0],smin = prices[0],profit = 0,sprofit = 0,tmp; + for (int i = 1; i < prices.length; i++) { + if (min > prices[i]) { + min = prices[i]; + }else { + tmp = prices[i]-min; + if(tmp>profit){ + sprofit = profit; + profit = tmp; + } + } + } + return profit; + } + /** + * @param prices + * @return + * @author xpxstar@gmail.com + * @2016��1��14�� + * Say you have an array for which the ith element is the price of a given stock on day i. + +Design an algorithm to find the maximum profit. You may complete at most two transactions. + +Note: +You may not engage in multiple transactions at the same time +(ie, you must sell the stock before you buy again). + */ + public int maxProfitIII(int[] prices) { + int total = 0; + for (int i=prices.length-1; i > 0; i++) { + if (prices[i+1]>prices[i]) total += prices[i+1]-prices[i]; + } + + return total; + } + public static void main(String[] args){ + BestTimeTradeStock121 bt = new BestTimeTradeStock121(); + int[] p = {4,2,8,1,5,6}; + System.out.println(bt.maxProfitII(p)); + } +} diff --git a/XuPershing/week7/CountRangeSum327.java b/XuPershing/week7/CountRangeSum327.java new file mode 100644 index 0000000..e7ecce9 --- /dev/null +++ b/XuPershing/week7/CountRangeSum327.java @@ -0,0 +1,138 @@ +package week7; + +public class CountRangeSum327 { + public TreeNode root; + public class TreeNode{ + long val; + int children; + TreeNode left; + TreeNode right; + public TreeNode(long x) {val = x;children = 0;} + public TreeNode(TreeNode l,TreeNode r) {left = l;right = r;} + } + //ƫ���BST��children ��ʾ��ǰ�ڵ�ĺ������� + /** + * @param value + * @return ���رȵ�ǰֵС��Ԫ�ظ����� + * @author xpxstar@gmail.com + * @2016��1��12�� + * ʱ�临�Ӷ�O(lgN) + */ + public void addNode(long value){ + if(this.root == null){ + this.root = new TreeNode(value); + return; + } + TreeNode parent = null, node = root; + while(node != null){ + parent = node; + node.children++; + if(value > node.val){ + node = node.right; + } + else{ + node = node.left; + } + } + if(value > parent.val) + parent.right = new TreeNode(value); + else + parent.left = new TreeNode(value); + } + /** + * @param bottom + * @param top + * @return + * @author xpxstar@gmail.com + * @2016��1��18�� + * ���Ҹ��������޷�Χ�ڵ��� + * �����ұ�����С�ĸ��� + * ���ұ����޸ߵĸ��� + * �������飬ʱ�临�Ӷ���O(lgN) + */ + public int searchBetween(long bottom,long top){ + /* ˼·���Ѿ�������BST + * ��ô�ұ�bottomС�ĸ���ʱ��ֻҪ�жϵ�ǰ�ڵ��Ƿ��bottomС�� + * ����ǣ�˵����ǰ�ڵ��Լ���ǰ�ڵ�����Ӷ�����bottomС������Ҳ����Ҫ���ϵ�ǰ�ڵ㡢��ǰ�ڵ�����������Լ��������ĺ��Ӹ��� + * ��Ȼ�������ǰ�ڵ�û����������ֻ��Ҫ�������ϵ�ǰ�ڵ���С� + * �����ǰ�ڵ�Ҫ����ô���������������� + * + */ + int num = 0; + TreeNode node = root; + while(node != null){ + if(bottom > node.val){ + num+= node.left == null?1:node.left.children+2; + node = node.right; + }else{ + node = node.left; + } + } + node = root; + while(node != null){ + if(top < node.val){ + num+= node.right == null?1:node.right.children+2; + node = node.left; + }else{ + node = node.right; + } + } + return num; + } + /** + * @param nums + * @param lower + * @param upper + * @return + * @author xpxstar@gmail.com + * @2016��1��12�� + * Given an integer array nums, return the number of range sums that lie in [lower, upper] inclusive. +Range sum S(i, j) is defined as the sum of the elements in nums between indices i and j (i �� j), inclusive. + +Note: +A naive algorithm of O(n2) is trivial. You MUST do better than that. + +Example: +Given nums = [-2, 5, -1], lower = -2, upper = 2, +Return 3. +The three ranges are : [0, 0], [2, 2], [0, 2] and their respective sums are: -2, -1, 2. + */ + public int countRangeSum(int[] nums, int lower, int upper) { + /*˼·������ת������sum[i],��0~i��������ͣ���ôij������ i~j�ĺ�(������i)�Ϳ��Ա�ʾΪsum[j]-sum[i]�� + * ������������õ���sum[j],���֪����jǰ���ijsum[i]������ lower <=sum[j]-sum[i] <= upper + * Ҳ����˵��jǰ�����sum[i] ���ڵ��� sum[j]-upper ��С�ڵ���sum[j]-lower �����ҵ���i~j(������i)�ĺͷ��Ϸ�Χ�� + * ��BST �÷���Count315��ͬ�� + */ + int size = nums.length; + if (1>size) { + return size; + } + int count = 0; + long sum = 0; + for(int i = 0;i=lower && sum <= upper) { + count++; + } + } + } + return count; + } + public static void main(String[] args) { + CountRangeSum327 cr = new CountRangeSum327(); + int[] nums = {2147483647,-2147483648,-1,0}; + System.out.println(cr.countRangeSum(nums, -1, 0)); + } +} diff --git a/XuPershing/week7/CountRightSmaller315.java b/XuPershing/week7/CountRightSmaller315.java new file mode 100644 index 0000000..ff1db41 --- /dev/null +++ b/XuPershing/week7/CountRightSmaller315.java @@ -0,0 +1,88 @@ +package week7; + +import java.util.LinkedList; +import java.util.List; + +public class CountRightSmaller315 { + public TreeNode root; + public class TreeNode{ + int val; + int children; + TreeNode left; + TreeNode right; + public TreeNode(int x) {val = x;children = 0;} + } + //ƫ���BST��children ��ʾ��ǰ�ڵ�ĺ������� + /** + * @param value + * @return ���ر��²�����С��Ԫ�ظ��� + * @author xpxstar@gmail.com + * @2016��1��12�� + * ʱ�临�Ӷ�O(lgN) + */ + public int addNode(int value){ + int num = 0; + if(this.root == null){ + this.root = new TreeNode(value); + return num; + } + TreeNode parent = null, node = root; + while(node != null){ + parent = node; + node.children++; + if(value > node.val){ + num+= node.left == null?1:node.left.children+2; + node = node.right; + }else{ + node = node.left; + } + } + /* Have found the new node's position. Insert it into the tree. */ + if(value > parent.val) + parent.right = new TreeNode(value); + else + parent.left = new TreeNode(value); + + return num; + } + + /** + * @param nums + * @return + * @author xpxstar@gmail.com + * @2016��1��12�� + * You are given an integer array nums and you have to return a new counts array. The counts array has the property where counts[i] is the number of smaller elements to the right of nums[i]. + +Example: + +Given nums = [5, 2, 6, 1] + +To the right of 5 there are 2 smaller elements (2 and 1). +To the right of 2 there is only 1 smaller element (1). +To the right of 6 there is 1 smaller element (1). +To the right of 1 there is 0 smaller element. +Return the array [2, 1, 1, 0]. + */ + public List countSmaller(int[] nums) { + /*˼·������BST����Ŀ������log(N)��ʱ����Ѱ�ҵ�����֪��С�����ĸ����� + * Ϊ�ˣ���BST�������޸ģ�1)BST�����ظ�����ƫ��ģ�����ȵ��������������� + * 2)����children ��¼��ǰ�ڵ�ĺ��Ӹ��� + * ����������������ʱ���жϵ�·���Ͻ��к��Ӹ������£����ң�ÿ�����Ҳ���ʱ���ۼƵ�ǰ�����������ĺ�����Ŀ������ǰ��֧��Ŀ��С�ĸ����� + * �ҵ��²�������ͬʱҲ����Ŀ����С�ĸ������������ + */ + LinkedList result = new LinkedList(); + if (0> nums.length) { + return result; + } + for (int i = nums.length-1; i > -1; i--) { + result.addFirst(addNode(nums[i])); + } + return result; + } + public static void main(String[] args) { + int[] nums = {26,78,27,100,33,67,90,23,66,5,38,7,35,23,52,22,83,32,78,9,21,84,66,65}; + CountRightSmaller315 cr = new CountRightSmaller315(); + System.out.println(cr.countSmaller(nums)); + } + +} diff --git a/XuPershing/week7/Permutation47.java b/XuPershing/week7/Permutation47.java new file mode 100644 index 0000000..7c79af2 --- /dev/null +++ b/XuPershing/week7/Permutation47.java @@ -0,0 +1,70 @@ +package week7; + +import java.util.ArrayList; +import java.util.LinkedList; +import java.util.List; + +import javax.annotation.Generated; + +/** + * @author xpxstar@gmail.com + * + * 2016��1��13�� + */ +public class Permutation47 { + + /** + * @param nums + * @return + * @author xpxstar@gmail.com + * @2016��1��13�� + * Given a collection of distinct numbers, return all possible permutations. + +For example, +[1,2,3] have the following permutations: +[1,2,3], [1,3,2], [2,1,3], [2,3,1], [3,1,2], and [3,2,1]. + */ + List> result = new LinkedList(); + public List> permute(int[] nums) { + for (int i = 0; i < nums.length; i++) { + List tmp = + } + } + private void findNext(int[] nums,int[] store,int level){ + if (level == nums.length) { + return; + } + + for (int i = 0;i> permuteUnique(int[] nums) { + + } + + + public static void main(String[] args) { + // TODO Auto-generated method stub + + } + +} diff --git a/XuPershing/week7/ShortestPalindrome214.java b/XuPershing/week7/ShortestPalindrome214.java new file mode 100644 index 0000000..771e565 --- /dev/null +++ b/XuPershing/week7/ShortestPalindrome214.java @@ -0,0 +1,60 @@ +package week7; + +public class ShortestPalindrome214 { + /** + * @param s + * @return + * @author xpxstar@gmail.com + * @2016��1��14�� + * Given a string S, you are allowed to convert it to a palindrome by adding characters in front of it. Find and return the shortest palindrome you can find by performing this transformation. + +For example: + +Given "aacecaaa", return "aaacecaaa". + +Given "abcd", return "dcbabcd". + */ + public String shortestPalindrome(String s) { + if (s.length()<2) { + return s; + } + StringBuffer sb = new StringBuffer(s.length()); + int left = 0,right = s.length()-1; + int lastHead = 0; + int head = 0; + boolean second = true; + while (left < right) { + if (s.charAt(0) == s.charAt(right) && second) { + head = lastHead; + lastHead = right; + second = false; + } + if (s.charAt(left) == s.charAt(right)){ + right--; + left++; + }else { + if (second) { + left = 0; + right--; + }else { + left = 1; + right = lastHead-1; + + } + second = true; + } + } + left = head == 0?lastHead:head; + right = s.length()-left; + for (int i = s.length()-1; i > left; i--) { + sb.append(s.charAt(i)); + } + sb.append(s); + return sb.toString(); + } + public static void main(String[] args) { + ShortestPalindrome214 sp = new ShortestPalindrome214(); + System.out.println(sp.shortestPalindrome("baaaab")); + } + +} diff --git a/XuPershing/week8/DistinctSubsequences115.java b/XuPershing/week8/DistinctSubsequences115.java new file mode 100644 index 0000000..780a341 --- /dev/null +++ b/XuPershing/week8/DistinctSubsequences115.java @@ -0,0 +1,111 @@ +package week8; + +import java.util.HashMap; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; + +public class DistinctSubsequences115 { + public static boolean isHappy(int n) { + Set set= new HashSet<>(); + set.add(n); + while(n!=1){ + System.out.println(n); + n = sumSquare(n); + if(set.contains(n)){ + return false; + } + set.add(n); + } + return true; + } + public static int sumSquare(int n){ + int sum = 0,tmp=0; + while(n != 0){ + tmp = n%10; + sum+=tmp*tmp; + n/=10; + } + return sum; + } + public static void main(String[] args) { + // TODO Auto-generated method stub + Map num = new HashMap<>(); + num.put(1,"One"); + num.put(2,"Two"); + num.put(3,"Three"); + num.put(4,"Four"); + num.put(5,"Five"); + num.put(6,"Six"); + num.put(7,"Seven"); + num.put(8,"Eight"); + num.put(9,"Nine"); + num.put(10,"Ten"); + num.put(11,"Eleven"); + num.put(12,"Twelve"); + num.put(13,"Thirteen"); + num.put(14,"Fourteen"); + num.put(15,"Fifteen"); + num.put(16,"Sixteen"); + num.put(17,"Seventeen"); + num.put(18,"Eighteen"); + num.put(19,"Nineteen"); + num.put(20,"Twenty"); + num.put(30,"Thirty"); + num.put(40,"Forty"); + num.put(50,"Fifty"); + num.put(60,"Sixty"); + num.put(70,"Seventy"); + num.put(80,"Eighty"); + num.put(90,"Ninety"); + num.put(100,"Hundred"); + String[] dd = {" Thousand"," Million"," Billion"}; + String result = ""; + int n = 12000678,i=0,tmp; + while(n!=0){ + tmp = n%1000; + if (tmp == 0) { + n = n/1000; + i++; + continue; + } + String sub = ""; + while(tmp!=0){ + + if (tmp<21) { + sub +=num.get(tmp); + break; + }else if(tmp > 99){ + sub+=num.get(tmp/100)+" "+num.get(100); + tmp = tmp%100; + if (tmp == 0) { + break; + } + }else { + sub +=" "+num.get((tmp/10)*10); + tmp = tmp%10; + if (tmp == 0) { + break; + }else + sub+=" "; + } + } + if (n/1000 > 0) { + + if("".equals(sub)) + sub = dd[i]; + else { + sub = dd[i]+" "+sub; + } + i++; + + } + result = sub+result; + sub=""; + n = n/1000; + } + System.out.println(result); + } + + +} diff --git a/XuPershing/week8/HouseRobber198.java b/XuPershing/week8/HouseRobber198.java new file mode 100644 index 0000000..4c14662 --- /dev/null +++ b/XuPershing/week8/HouseRobber198.java @@ -0,0 +1,82 @@ +package week8; + +public class HouseRobber198 { + /** + * @param nums + * @return + * @author xpxstar@gmail.com + * @2016��1��21�� + * You are a professional robber planning to rob houses along a street. + * Each house has a certain amount of money stashed, + * the only constraint stopping you from robbing each of them is that + * adjacent houses have security system connected and it will automatically contact the police + * if two adjacent houses were broken into on the same night. + +Given a list of non-negative integers representing the amount of money of each house, determine the maximum amount of money you can rob tonight without alerting the police. + */ + public int rob(int[] nums) { + if (nums.length < 1) { + return 0; + } + int size = nums.length; + int back0 =nums[0], back1 = 0,back2 = 0,tmp; + for(int i = 1;i < size;i++){ + tmp = back0; + if (back2 > back1) { + back0 = back2+nums[i]; + }else { + back0 = back1+nums[i]; + } + back2 = back1; + back1 = tmp; + } + if (back1>back0) { + back0 = back1; + } + return back0; + + } + /** + * @param nums + * @return + * @author xpxstar@gmail.com + * @2016��1��21�� + * After robbing those houses on that street, the thief has found himself a new place for his thievery so that + * he will not get too much attention. This time, all houses at this place are arranged in a circle. + * That means the first house is the neighbor of the last one. + * Meanwhile, the security system for these houses remain the same as for those in the previous street. + +Given a list of non-negative integers representing the amount of money of each house, determine the maximum amount of money you can rob tonight without alerting the police. + */ + public int robII(int[] nums) { + if (nums.length < 1) { + return 0; + } + int size = nums.length; + int back0 =nums[0], back1 = 0,back2 = 0,tmp; + + for(int i = 1;i < size;i++){ + tmp = back0; + if (back2 > back1) { + back0 = back2+nums[i]; + }else { + back0 = back1+nums[i]; + } + back2 = back1; + back1 = tmp; + } + if (back1>back0) { + back0 = back1; + } + + return back0; + + } + public static void main(String[] args) { + // TODO Auto-generated method stub + int[] nums = {1,2,3,5,7,6}; + HouseRobber198 hr = new HouseRobber198(); + System.out.println(hr.rob(nums)); + } + +} diff --git a/XuPershing/week8/UglyNumber263.java b/XuPershing/week8/UglyNumber263.java new file mode 100644 index 0000000..2b5152c --- /dev/null +++ b/XuPershing/week8/UglyNumber263.java @@ -0,0 +1,75 @@ +package week8; + +import java.util.ArrayList; +import java.util.LinkedList; + +public class UglyNumber263 { + /** + * @param num + * @return + * @author xpxstar@gmail.com + * @2016��1��21�� + * Write a program to check whether a given number is an ugly number. + +Ugly numbers are positive numbers whose prime factors only include 2, 3, 5. For example, 6, 8 are ugly while 14 is not ugly since it includes another prime factor 7. + +Note that 1 is typically treated as an ugly number. + */ + public boolean isUgly(int num) { + if(num == 0) + return false; + while (num%2 ==0) { + num = num>>1; + } + while (num%3 ==0) { + num = num/3; + } + while (num%5 == 0) { + num = num/5; + } + return num == 1; + } + /** + * @param n + * @return + * @author xpxstar@gmail.com + * @2016��1��25�� + * return the n-th ugly number which 1 is the first one + */ + public int uglyII(int n) { + if (n<2) { + return 1; + } + ArrayList> ll = new ArrayList<>(3); + for (int i = 0; i < 3; i++) { + ll.add(new LinkedList()); + } + int result = 1,index; + for (int i = 1; i < n; i++) { + ll.get(0).add(result*2); + ll.get(1).add(result*3); + ll.get(2).add(result*5); + index = 0; + if (i == 38) { + System.out.println(' '); + } + for (int j = 1; j < 3; j++) { + if (ll.get(index).getFirst() >= ll.get(j).getFirst()) { + if (ll.get(index).getFirst().equals(ll.get(j).getFirst())) { + ll.get(index).removeFirst(); + } + index = j; + } + } + result = ll.get(index).removeFirst(); + System.out.println(result); + } + return result; + } + public static void main(String[] args) { + // TODO Auto-generated method stub + UglyNumber263 un = new UglyNumber263(); + System.out.println(un.uglyII(40)); + } + +} diff --git a/XuPershing/week8/UniquePaths62.java b/XuPershing/week8/UniquePaths62.java new file mode 100644 index 0000000..d1ab3a7 --- /dev/null +++ b/XuPershing/week8/UniquePaths62.java @@ -0,0 +1,85 @@ +package week8; + +public class UniquePaths62 { + /** + * @param m + * @param n + * @return + * @author xpxstar@gmail.com + * @2016��1��21�� + * A robot is located at the top-left corner of a m x n grid (marked 'Start' in the diagram below). + +The robot can only move either down or right at any point in time. The robot is trying to reach the bottom-right corner of the grid (marked 'Finish' in the diagram below). + +How many possible unique paths are there? + */ + public int uniquePaths(int m, int n) { + /*˼·��������Ҫô����Ҫô���ң��ܹ���m-1�����º�n-1�����ң� + * ������n-1�����ҵĹ����У���������ѡ��ij�գ�����m-1�����µĹ��̡� + * �����ܵĴ�����A(m-1,m+n-2)/(m-1)! + * + */ + int up = n+m-2; + int small = m>n?n:m; + long result=1; + for(int i = 1 ;i < small;i++){ + result*=up--; + result/=i; + } + return (int)result; + } + /** + * @param m + * @param n + * @return + * @author xpxstar@gmail.com + * @2016��1��22�� + * + */ + public int uniquePathsII(int[][] obstacleGrid) { + /*˼·����̬�滮��pp[i][j]��ʾ���ýڵ��·������������ϰ�����ֵ0 + * ��ôpp[i][j]��·����Ȼ����pp[i-1][j]��pp[i][j-1],������·���ĺͣ���Ϊ����û�н����·���� + * + * + */ + int m = obstacleGrid.length; + if (m<1) { + return 1; + } + int n = obstacleGrid[0].length; + int[][] pp = new int[m][n]; + boolean stuck = false; + for (int i = 0; i < m; i++) { + stuck = stuck || obstacleGrid[i][0]==1; + pp[i][0] = stuck?0:1; + } + stuck = false; + for (int i = 0; i < n; i++) { + stuck = stuck || obstacleGrid[0][i]==1; + pp[0][i] = stuck?0:1; + } + for(int i = 1; i < m; i++){ + for (int j = 1; j < n; j++) { + if (1== obstacleGrid[i][j]) { + pp[i][j] = 0; + }else{ + pp[i][j] = pp[i-1][j]+pp[i][j-1]; + } + } + } + + return pp[m-1][n-1]; + } + public static void main(String[] args) { + // TODO Auto-generated method stub + UniquePaths62 up = new UniquePaths62(); + int[][] test = { + {0,0,0,1,0}, + {0,1,0,0,0}, + {1,0,1,0,0}, + {0,0,0,0,0} + }; + System.out.println(up.uniquePathsII(test)); + } + +} diff --git a/XuPershing/week9/BasicCalculator224.java b/XuPershing/week9/BasicCalculator224.java new file mode 100644 index 0000000..5799aa1 --- /dev/null +++ b/XuPershing/week9/BasicCalculator224.java @@ -0,0 +1,71 @@ +package week9; + + +public class BasicCalculator224 { + public static int position = 0; + public static int calculate(String s){ + /*˼·����Ӧ�жϣ�����ǡ�(��,��ʾһ���µ�����ʽ���͵ݹ顣�����)����ʾ��ǰ����ʽ���� + * �ؼ��㣺��λ��ʱ����ȡ�� + * ʱ�临�Ӷ���O(n) + */ + int sum = 0,tmp; + boolean plus = true; + while (position < s.length()) { + switch (s.charAt(position)) { + case ' ': + position++; + break; + case '+': + position++; + plus = true; + break; + case '-': + plus = false; + position++; + break; + case '(': + position++; + sum+=plus?calculate(s):-calculate(s); + break; + case ')': + position++; + return sum; + default: + tmp = s.charAt(position)-48; + while(position+1 < s.length() && s.charAt(position+1) >47 &&s.charAt(position+1) <58){ + position++; + tmp = tmp*10+s.charAt(position)-48; + } + sum+=plus?tmp:-tmp; + position++; + break; + } + } + return sum; + } + public static int simpleCalculate(char s[],int start,int end){ + int sum = 0,tmp; + boolean plus = true; + while(start< end){ + if (s[start] == '+') { + plus = true; + }else if (s[start] == '-') { + plus = false; + }else { + tmp = s[start]-48; + while(start+1 < end && s[start+1] != '+'&&s[start+1] != '-'){ + start++; + tmp = tmp*10+s[start]-48; + } + sum+=plus?tmp:-tmp; + } + start++; + } + return sum; + } + public static void main(String[] args) { + // TODO Auto-generated method stub + System.out.println(calculate("(8-((12-4)-3+(32 - 2)) )")); + } + +} diff --git a/XuPershing/week9/BulbSwitcher319.java b/XuPershing/week9/BulbSwitcher319.java new file mode 100644 index 0000000..f7518ce --- /dev/null +++ b/XuPershing/week9/BulbSwitcher319.java @@ -0,0 +1,29 @@ +package week9; + +public class BulbSwitcher319 { + public static int bulbSwitch(int n) { + return (int)Math.sqrt(n); + } + public static int countFactor(int n){ + if (n == 1) { + return 0; + } + int f = 2,opf = n,c = 0; + while(f0){ + int1[ii] = Integer.valueOf(num1.substring(i-4,i)); + i-=4;ii++; + } + int1[ii] = Integer.valueOf(num1.substring(0,i)); + i=l2;ii=0; + while(i-4>0){ + int2[ii] = Integer.valueOf(num2.substring(i-4,i)); + i-=4;ii++; + } + int2[ii] = Integer.valueOf(num2.substring(0,i)); + int tmp = 0; + for (int j = 0; j < s1+s2; j++) { + for(int k = 0;k<=j&&k= 0; j--) { + String aa = String.valueOf(result[j]); + for (int k = 0; k < 4-aa.length(); k++) { + sb.append('0'); + } + sb.append(aa); + } + return sb.toString(); + } + public static void main(String[] args) { + // TODO Auto-generated method stub + System.out.println(multiply("140","721")); + } + +} diff --git a/Zhengyingying/src/com/zyy/week11/_303_RangeSumQueryImmutable.java b/Zhengyingying/src/com/zyy/week11/_303_RangeSumQueryImmutable.java new file mode 100644 index 0000000..a79428c --- /dev/null +++ b/Zhengyingying/src/com/zyy/week11/_303_RangeSumQueryImmutable.java @@ -0,0 +1,31 @@ +package com.zyy.week11; + +/** + * + * @author ZYY 计算nums中从i到j的数组中元素之和,但会多次调用。 + * + */ +public class _303_RangeSumQueryImmutable { + private int[] nums; + + public _303_RangeSumQueryImmutable(int[] nums) { + for (int i = 1; i < nums.length; i++) { + nums[i] = nums[i] + nums[i - 1]; + } + this.nums = nums; + } + + public int _303_RangeSumQueryImmutable(int i, int j) { + if (i == 0) + return nums[j]; + else + return nums[j] - nums[i - 1]; + } + + public static void main(String[] args) { + int[] nums = new int[] { -2, 0, 3, -5, 2, -1 }; + _303_RangeSumQueryImmutable rsqi = new _303_RangeSumQueryImmutable(nums); + int sum = rsqi._303_RangeSumQueryImmutable(0,5); + System.out.println(sum); + } +} diff --git a/Zhengyingying/src/com/zyy/week11/_307_RangeSumQueryMutable.java b/Zhengyingying/src/com/zyy/week11/_307_RangeSumQueryMutable.java new file mode 100644 index 0000000..2fa48e4 --- /dev/null +++ b/Zhengyingying/src/com/zyy/week11/_307_RangeSumQueryMutable.java @@ -0,0 +1,83 @@ +package com.zyy.week11; + +public class _307_RangeSumQueryMutable { + // 9.57% + class SegmentTreeNode { + // 记录分段的起始位置 + int start, end; + SegmentTreeNode left, right; + int sum; + + // 初始化 + SegmentTreeNode(int start, int end) { + this.start = start; + this.end = end; + this.left = null; + this.right = null; + this.sum = 0; + } + } + + SegmentTreeNode root = null; + + public _307_RangeSumQueryMutable(int[] nums) { + root = buildTree(nums, 0, nums.length - 1); + } + + private SegmentTreeNode buildTree(int[] nums, int start, int end) { + if (start > end) + return null; + // 初始化一个节点 + SegmentTreeNode ret = new SegmentTreeNode(start, end); + if (start == end) + ret.sum = nums[start]; + else { + int mid = start + (end - start) / 2; + ret.left = buildTree(nums, start, mid); + ret.right = buildTree(nums, mid + 1, end); + ret.sum = ret.left.sum + ret.right.sum; + } + return ret; + + } + + void update(int i, int val) { + update(root, i, val); + } + + // 更新需要先找到这个点的位置,采用二分搜索 + private void update(SegmentTreeNode node, int index, int val) { + // 只有这一个节点,更新值 + if (node.start == node.end) + node.sum = val; + else { + int mid = node.start + (node.end - node.start) / 2; + if (index <= mid) + update(node.left, index, val); + else + update(node.right, index, val); + // 需要更新当前节点的sum值 + node.sum = node.left.sum + node.right.sum; + } + } + + public int sumRange(int i, int j) { + return sumRange(root, i, j); + } + + private int sumRange(SegmentTreeNode node, int start, int end) { + if (node.start == start && node.end == end) + return node.sum; + else { + int mid = node.start + (node.end - node.start) / 2; + if (end <= mid) { + return sumRange(node.left, start, end); + } else if (start >= mid + 1) { + return sumRange(node.right, start, end); + } else + return sumRange(node.left, start, mid) + + sumRange(node.right, mid + 1, end); + } + + } +} diff --git a/Zhengyingying/src/com/zyy/week11/_307_RangeSumQueryMutable_1.java b/Zhengyingying/src/com/zyy/week11/_307_RangeSumQueryMutable_1.java new file mode 100644 index 0000000..d29a4be --- /dev/null +++ b/Zhengyingying/src/com/zyy/week11/_307_RangeSumQueryMutable_1.java @@ -0,0 +1,47 @@ +package com.zyy.week11; + +//75.38% 7ms +public class _307_RangeSumQueryMutable_1 { + // 使用树状数组 + private int[] BIT; + private int[] nums; + private int n; + + public _307_RangeSumQueryMutable_1(int[] nums) { + this.n = nums.length; + this.BIT = new int[n + 1]; + this.nums = nums; + for (int i = 0; i < n; i++) { + init(i, nums[i]); + } + } + + private void init(int pos, int val) { + pos++; + while (pos <= n) { + BIT[pos] += val; + pos += pos & -pos; + } + } + + void update(int i, int val) { + int discard = val - nums[i]; + nums[i] = val; + init(i, discard); + } + + int getSum(int i) { + i++; + int sum = 0; + while (i > 0) { + sum += BIT[i]; + i -= i & -i; + } + return sum; + } + + public int sumRange(int i, int j) { + return getSum(j) - getSum(i - 1); + } + +} diff --git a/Zhengyingying/src/com/zyy/week6/PopulatingNextRightPointersinEachNodeI.java b/Zhengyingying/src/com/zyy/week6/PopulatingNextRightPointersinEachNodeI.java index bbca5df..7f72523 100644 --- a/Zhengyingying/src/com/zyy/week6/PopulatingNextRightPointersinEachNodeI.java +++ b/Zhengyingying/src/com/zyy/week6/PopulatingNextRightPointersinEachNodeI.java @@ -3,8 +3,19 @@ import java.util.LinkedList; import java.util.Queue; +/** + * + * @author zyy + * + * 问题描述: 将一个完全二叉树的同一层上的节点用next连接起来 + * + * 注意事项: 使用固定的空间,因此谨慎使用队列,会影响效率。 + * + * 解题思路: 使用递归 + * + */ public class PopulatingNextRightPointersinEachNodeI { - //AC : 5ms 9.71% + // AC : 5ms 9.71% // 广度优先搜索BFS public void connect(TreeLinkNode root) { if (root == null) @@ -20,16 +31,27 @@ public void connect(TreeLinkNode root) { list.add(node.right); levelNum--; if (levelNum == 0) { - node.next = null; levelNum = list.size(); } else { node.next = list.peek(); } } } - - //深度优先搜索DFS + + // 迭代 + // 两次遍历 public void connect1(TreeLinkNode root) { - + TreeLinkNode level_start = root; + while (level_start != null) { + TreeLinkNode cur = level_start; + while (cur != null) { + if (cur.left != null) + cur.left.next = cur.right; + if (cur.right != null && cur.next != null) + cur.right.next = cur.next.left; + cur = cur.next; + } + level_start = level_start.left; + } } } diff --git a/Zhengyingying/src/com/zyy/week7/JumpGame.java b/Zhengyingying/src/com/zyy/week7/JumpGame.java new file mode 100644 index 0000000..d5f8d41 --- /dev/null +++ b/Zhengyingying/src/com/zyy/week7/JumpGame.java @@ -0,0 +1,62 @@ +package com.zyy.week7; + +/** + * + * @author zyy 问题描述:给定一个非负整数的数组,数组中的每个元素存放的是能够jump的最大距离,判断是否可以从第一个位置jump到最后一个位置。 + * + * + */ +public class JumpGame { + + //2ms + public boolean canJump3(int[] nums) { + int n = nums.length; + if (n == 0 || n == 1) { + return true; + } + int maxstep = nums[0]; + for (int i = 1; i < n; i++) { + if (maxstep == 0) + return false; + maxstep--; + if (maxstep < nums[i]) { + maxstep = nums[i]; + } + if (maxstep + i >= n - 1) { + return true; + } + } + return false; + } + + //3ms + public boolean canJump2(int[] nums) { + int i = 0, n = nums.length; + for (int reach = 0; i < n && i <= reach; ++i) + reach = Math.max(i + nums[i], reach); + return i == n; + } + + // 30.8% 3ms + public boolean canJump1(int[] nums) { + int dis = 0; + for (int i = 0; i <= dis; i++) { + dis = Math.max(dis, i + nums[i]); + if (dis >= nums.length - 1) { + return true; + } + } + return false; + } + + // 从前往后 3ms 29.1% + public boolean canJump(int[] nums) { + int max = 0; + for (int i = 0; i < nums.length; i++) { + if (i > max) + return false; + max = Math.max(nums[i] + i, max); + } + return true; + } +} diff --git a/Zhengyingying/src/com/zyy/week7/JumpGameII.java b/Zhengyingying/src/com/zyy/week7/JumpGameII.java new file mode 100644 index 0000000..30f6cfd --- /dev/null +++ b/Zhengyingying/src/com/zyy/week7/JumpGameII.java @@ -0,0 +1,44 @@ +package com.zyy.week7; + +public class JumpGameII { + + // 3ms + public int jump1(int[] nums) { + int n = nums.length; + if (n < 2) + return 0; + int level = 0, currentMax = 0, i = 0, nextMax = 0; + + while (currentMax - i + 1 > 0) { // nodes count of current level>0 + level++; + for (; i <= currentMax; i++) { // traverse current level , and + // update the max reach of next + // level + nextMax = Math.max(nextMax, nums[i] + i); + if (nextMax >= n - 1) + return level; // if last element is in level+1, then the min + // jump=level + } + currentMax = nextMax; + } + return 0; + } + + // 3ms + // 仍然使用贪心算法,需记录当前所能到达的最远距离、上一跳所能到达的最远距离、当前跳数 + public int jump(int[] nums) { + int ret = 0;// 当前跳数 + int last = 0; // 上一跳可达最远距离 + int cur = 0;// 当前一跳可达最远距离 + for (int i = 0; i < nums.length; i++) { + // 需要进行下次跳,需要更新last和当前执行的跳数 + if (i > last) { + last = cur; + ++ret; + } + // 记录当前可达的最远点 + cur = Math.max(cur, nums[i] + i); + } + return ret; + } +} diff --git a/Zhengyingying/src/com/zyy/week7/explanation b/Zhengyingying/src/com/zyy/week7/explanation new file mode 100644 index 0000000..d44aca5 --- /dev/null +++ b/Zhengyingying/src/com/zyy/week7/explanation @@ -0,0 +1,67 @@ +--- +title: 45. Jump Game II +author: Zheng Yingying +time: 2016-01-17 +leetcodeUrl: https://leetcode.com/problems/jump-game-ii/ +description: "给定一个非负整数数组,从数组的第一个索引开始,数组中的元素代表可以跳跃的最大长度,求到达最后一个元素的最短跳跃数。" +categories: +-week7 +tags: +-Array +-Greedy +--- + +###解题思路 + 性质: + 如果i是从i-1跳一步到达的,那i位置的最少跳数是 = +1; + 如果i是从i-2或是之前跳到的,则有 = + 即有 >= . + 利用贪心算法,每次求取当前阶段的最优解,最终得到最后的结果。 + 目标函数:max(cur,i+A[i])//求局部最优解 +####方案一 + 时间复杂度:O(n) + 空间复杂度:O(1) +```java +public int jump(int[] nums) { + int ret = 0;// 当前跳数 + int last = 0; // 上一跳可达最远距离 :ret + int cur = 0;// 当前一跳可达最远距离 :ret + 1 + for (int i = 0; i < nums.length; i++) { + // 需要进行下次跳,需要更新last和当前执行的跳数 + // i 不仅是数组下标, 还是已经到达的距离 + if (i > last) { + last = cur; + ++ret; + } + // 记录当前可达的最远点,保证每次以尽可能大的步伐往后跳 + cur = Math.max(cur, nums[i] + i); + } + return ret; + } +``` +####方案二 + 把问题转换成BFS问题。 + 第i层节点是指那些可以通过i-1步跳跃到达的节点。 + 例如:2 3 1 1 4, 可以看成 2 || 3 1 || 1 4 +```java +public int jump1(int[] nums) { + int n = nums.length; + if (n < 2) + return 0; + int level = 0, currentMax = 0, i = 0, nextMax = 0; + + // 当前层的节点数目>0 + while (currentMax - i + 1 > 0) { + level++; + // 遍历当前层,求局部最优解 + for (; i <= currentMax; i++) { + nextMax = Math.max(nextMax, nums[i] + i);、 + //如果最后一个元素在level+1层,则最小的跳跃数就是level + if (nextMax >= n - 1) + return level; + } + currentMax = nextMax; + } + return 0; + } +``` diff --git a/Zhengyingying/src/com/zyy/week9/_204_CountPrimes.java b/Zhengyingying/src/com/zyy/week9/_204_CountPrimes.java new file mode 100644 index 0000000..9700d46 --- /dev/null +++ b/Zhengyingying/src/com/zyy/week9/_204_CountPrimes.java @@ -0,0 +1,86 @@ +package com.zyy.week9; + +/** + * + * @author ZYY 统计小于非负整数n的素数的数目 素数:除了1和它本身不能被其他数整除 + * + */ +public class _204_CountPrimes { + // 超时 + public int countPrimes(int n) { + int result = 0; + for (int i = 0; i < n; i++) { + if (isPrimes(i)) + result++; + } + return result; + } + + // 判断是不是素数 + private boolean isPrimes(int n) { + if (n <= 1) + return false; + if (n == 2) + return true; + int edge = (int) Math.sqrt(n); + for (int i = 2; i <= edge; i++) { + if (n % i == 0) + return false; + } + return true; + } + + // Sieve of Eratosthenes:找质数的算法 + //40ms 24% + public int countPrimes1(int n) { + // 使用一个长度为n的数组记录每个数的状态 + boolean[] primes = new boolean[n]; + // 初始化数组primes + for (int i = 2; i < n; i++) { + primes[i] = true; + } + // 按照倍数方式将数组中的合数置为false + for (int i = 2; i * i < n; i++) { + if (!primes[i]) + continue; + for (int j = i * i; j < n; j += i) { + primes[j] = false; + } + } + // 统计素数个数 + int count = 0; + for (int i = 2; i < n; i++) { + if (primes[i]) + count++; + } + return count; + } + + // Sieve of Eratosthenes:找质数的算法 + // 32ms(43%) + public int countPrimes2(int n) { + // 使用一个长度为n的数组记录每个数的状态 + boolean[] primes = new boolean[n]; + // 初始化数组primes + for (int i = 2; i < n; i++) { + primes[i] = true; + } + // 统计素数个数 + int count = 0; + // 按照倍数方式将数组中的合数置为false + for (int i = 2; i < n; i++) { + if (primes[i]) { + count++; + for (int j = 2; i * j < n; j++) { + primes[i * j] = false; + } + } + } + return count; + } + + public static void main(String[] args) { + _204_CountPrimes cp = new _204_CountPrimes(); + System.out.println(cp.countPrimes2(1500)); + } +} diff --git a/Zhengyingying/src/com/zyy/week9/_319_BulbSwitcher.java b/Zhengyingying/src/com/zyy/week9/_319_BulbSwitcher.java new file mode 100644 index 0000000..7c51d78 --- /dev/null +++ b/Zhengyingying/src/com/zyy/week9/_319_BulbSwitcher.java @@ -0,0 +1,14 @@ +package com.zyy.week9; +/**\ + * + * @author ZYY + * 这是一道智力题 + * 第i次变动第i个位置以及i的倍数的位置的灯的开关, + * 统计最后开着的灯的数目 + * + */ +public class _319_BulbSwitcher { + public int bulbSwitch(int n) { + return (int) Math.sqrt(n); + } +} diff --git a/Zhengyingying/src/com/zyy/week9/_43_MultiplyStrings.java b/Zhengyingying/src/com/zyy/week9/_43_MultiplyStrings.java new file mode 100644 index 0000000..595ec8d --- /dev/null +++ b/Zhengyingying/src/com/zyy/week9/_43_MultiplyStrings.java @@ -0,0 +1,32 @@ +package com.zyy.week9; + +/** + * + * @author ZYY 计算两个数的乘积,用字符串表示,且两个数可以任意大 + * + */ +public class _43_MultiplyStrings { + //9ms 72.73% + public String multiply(String num1, String num2) { + int n1 = num1.length(); + int n2 = num2.length(); + int[] pos = new int[n1 + n2]; + for (int i = n1 - 1; i >= 0; i--) { + for (int j = n2 - 1; j >= 0; j--) { + int multi = (num1.charAt(i) - '0') * (num2.charAt(j) - '0'); + int po1 = i + j, po2 = i + j + 1; + int num = multi + pos[po2]; + // 十位 + pos[po1] += num / 10; + // 个位 + pos[po2] = num % 10; + } + } + StringBuilder sb = new StringBuilder(); + for (int k : pos) { + if (!(sb.length() == 0 && k == 0)) + sb.append(k); + } + return sb.length() == 0 ? "0" : sb.toString(); + } +} diff --git a/nijiazhi/week_10/_091_DecodeWays.java b/nijiazhi/week_10/_091_DecodeWays.java new file mode 100644 index 0000000..4be99f5 --- /dev/null +++ b/nijiazhi/week_10/_091_DecodeWays.java @@ -0,0 +1,84 @@ +package leetcode_njz; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + + +public class _091_DecodeWays { + + /* + * 初始思想 --- 回溯法,按照1个、2个去匹配 + */ + public static int numDecodings(String s) { + if(s==null || s.length()==0) return 0; + + List rs = new ArrayList(); + dfs(0,rs,s); + return rs.size(); + } + + + private static void dfs(int cur, List rs, String s) { + if(cur<0) return; + if(cur==s.length()) { + rs.add(1); + return; + } + + //处理1位情况 + int cur_val = Integer.valueOf(s.substring(cur,cur+1)); + if(cur_val>0 && cur_val<10) + dfs(cur+1, rs, s); + + //处理2位情况 + if(cur < s.length()-1){ + int pre_val = Integer.valueOf(s.substring(cur,cur+2)); + if(pre_val>=10 && pre_val<= 26) + dfs(cur+2, rs, s); + } + + } + + + /* + * dp思想 --- 来源于回溯法,在回溯的过程中,做了很多次重复计算 + * dp[i]代表当前的匹配方法数目,也是考虑两种情况 + */ + public static int numDecodings_1(String s) { + if(s==null || s.length()==0) return 0; + + int[] dp = new int[s.length()]; + //dp[0] + if(Integer.valueOf(s.substring(0,1))>0 && Integer.valueOf(s.substring(0,1))<10) + dp[0] = 1; + if(s.length() == 1) return dp[0]; + + //dp[1] + if(Integer.valueOf(s.substring(1,2))>0 && Integer.valueOf(s.substring(1,2))<10) + dp[1] += dp[0]; + if(Integer.valueOf(s.substring(0,2))>=10 && Integer.valueOf(s.substring(0,2))<=26) + dp[1] += 1; + + for(int i=2; i0 && cur_val<10) + dp[i] += dp[i-1]; + int pre_val = Integer.valueOf(s.substring(i-1,i+1)); + if(pre_val>=10 && pre_val<= 26) + dp[i] += dp[i-2]; + } + return dp[s.length()-1]; + } + + public static void main(String[] args) { + String s = "10"; + int rs = numDecodings(s); + System.out.println(rs); + + int rs1 = numDecodings_1(s); + System.out.println(rs1); + } + +} diff --git a/nijiazhi/week_10/_137_SingleNumber2.java b/nijiazhi/week_10/_137_SingleNumber2.java new file mode 100644 index 0000000..bee9418 --- /dev/null +++ b/nijiazhi/week_10/_137_SingleNumber2.java @@ -0,0 +1,66 @@ +package leetcode_njz; + +// 除了一个数,其他的都出现3次 +public class _137_SingleNumber2 { + + /* + * 通用的方法---还可以计算出现2次、3次的情况 + * + * 用一个int[32]记录每一位出现的次数, + * 两个for循环,其中一个是32次循环,常数次循环。 + */ + public static int singleNumber1(int[] nums) { + if(nums == null || nums.length == 0) + return 0; + + int[] flag = new int[32]; + int rs = 0; + for(int i=0; i<32; i++){ + for(int j=0; j>i) & 1; + flag[i] += tmp; + } +// flag[i] %= 3; + rs += (flag[i]%3)<>i) & 1; + flag[i] += tmp; + } + rs += (flag[i]%3)< wordBreak(String s, Set wordDict) { + List rs = new ArrayList(); + if(wordDict.contains(s)) rs.add(s+" "); + + /* + * 问题在于map,其中不应该存放boolean型,不然直接根据判断就跳出了 + * map应该存放当前字符串所能构成的所有答案 --- (不含有初始串) + */ + HashMap> map = new HashMap<>(); + dfs(s, wordDict, map); + return map.get(s); + } + + + private static List dfs(String s2, Set wordDict, HashMap> map) { + if(map.containsKey(s2)) return map.get(s2); + + List rs = new ArrayList(); + if(s2.equals("")) return rs; + + for(int i=1; i<=s2.length(); i++){ + String pre = s2.substring(0,i); + String append = s2.substring(i); + + boolean f1 = wordDict.contains(pre); + if(!f1) continue; + + List tmp; + if(map.containsKey(append)){ + tmp = map.get(append); + }else{ + tmp = dfs(append, wordDict, map); + } + + //注意条件 --- append.isEmpty() + if(tmp.size() == 0 && append.isEmpty()) + rs.add(pre); + for(int k=0; k wordBreak2(String s, Set wordDict) { + List rs = new ArrayList(); + if(wordDict.contains(s)) rs.add(s+" "); + HashMap> map = new HashMap<>(); + dfs2(s, wordDict, map); + return map.get(s); + } + + + private static List dfs2(String s2, Set wordDict, HashMap> map) { + if(map.containsKey(s2)) return map.get(s2); + + List rs = new ArrayList(); + if(s2.equals("")) + return rs; + + for(int i=1; i<=s2.length(); i++){ + String pre = s2.substring(0,i); + String append = s2.substring(i); + + boolean f1 = wordDict.contains(pre); + if(!f1) continue; + + List tmp = dfs2(append, wordDict, map); + + if(tmp.size()==0 && append.equals("")){ + rs.add(pre); + } + + for(int k=0; k wordDict = new HashSet<>(); + for(int i=0; i rs2 = wordBreak2(s,wordDict); +// System.out.println(rs2); + + List rs = wordBreak(s,wordDict); + System.out.println(rs); + } + +} diff --git a/nijiazhi/week_10/_221_MaximalSquare.java b/nijiazhi/week_10/_221_MaximalSquare.java new file mode 100644 index 0000000..ab821a7 --- /dev/null +++ b/nijiazhi/week_10/_221_MaximalSquare.java @@ -0,0 +1,101 @@ +package leetcode_njz; + +public class _221_MaximalSquare { + + /* + * 暴力解 --- 穷举所有以matrix[i][j]为左上角的正方形 + * You are here! Your runtime beats 0.41% of java submissions. + */ + public static int maximalSquare(char[][] matrix) { + if(matrix==null || matrix.length==0) return 0; + int row = matrix.length; + int col = matrix[0].length; + + int maxArea = 0; + for(int i=0; i=0 && j-1>=0) + diag = dp[i-1][j-1]; + + int left = 0; + if(j-1 >= 0) + left = dp[i][j-1]; + + int up = 0; + if(i-1 >= 0) + up= dp[i-1][j]; + + int min = getMin(diag,left,up); + dp[i][j] = min+1; + if(maxLen < dp[i][j]) + maxLen = dp[i][j]; + } + } + + return maxLen*maxLen; + } + + private static int getMin(int diag, int left, int up) { + int min = Math.min(diag, left); + min = Math.min(min, up); + return min; + } + + public static void main(String[] args) { + char[][] matrix = { + {'1','0' ,'1' ,'0' ,'0'}, + {'1' ,'0' ,'1' ,'1' ,'1'}, + {'1' ,'1' ,'1' ,'1' ,'1'}, + {'1' ,'0' ,'0' ,'1' ,'0'}, + }; + + int rs = maximalSquare(matrix); + System.out.println(rs); + + int rs1 = maximalSquare1(matrix); + System.out.println(rs1); + } + +} diff --git a/nijiazhi/week_10/_321_CreateMaximumNumber.java b/nijiazhi/week_10/_321_CreateMaximumNumber.java new file mode 100644 index 0000000..8fbb0d1 --- /dev/null +++ b/nijiazhi/week_10/_321_CreateMaximumNumber.java @@ -0,0 +1,127 @@ +package leetcode_njz; + +import java.util.Arrays; +import java.util.LinkedList; +import java.util.List; + +public class _321_CreateMaximumNumber { + + /* + * You are here! Your runtime beats 2.53% of java submissions + */ + public static int[] maxNumber(int[] nums1, int[] nums2, int k) { + if(k==0) return null; + if(nums1==null) return nums2; + if(nums2==null) return nums1; + if(nums1.length==0) return nums2; + if(nums2.length==0) return nums1; + + int len1 = nums1.length; + int len2 = nums2.length; + String maxRs = ""; + + for(int k1=0; k1<=k; k1++){ + int k2 = k - k1; + int[] n1 = new int[k1]; + int[] n2 = new int[k2]; + + if(len1= k1 && cnt1 < k1){ + int maxIndex = index1; + int endIndex = len1-k1+cnt1; + if(endIndex < maxIndex) break; + + for(int i= index1+1; i<=endIndex; i++) + maxIndex = (nums1[maxIndex] < nums1[i])? i: maxIndex; + n1[cnt1] = nums1[maxIndex]; + index1 = maxIndex+1; + cnt1++; + } + + int cnt2 = 0; + int index2 = 0; + while(len2 >= k2 && cnt2 < k2){ + int maxIndex = index2; + int endIndex = len2-k2+cnt2; + if(endIndex < maxIndex) break; + + for(int i=index2+1; i<=endIndex; i++) + maxIndex = (nums2[maxIndex] < nums2[i])?i :maxIndex; + n2[cnt2] = nums2[maxIndex]; + index2 = maxIndex+1; + cnt2++; + } + + //整理n1和n2 + String tmp = getMax(n1, n2); + if(maxRs.compareTo(tmp) < 1) + maxRs = tmp; + } + + char[] s = maxRs.toCharArray(); + int[] rs = new int[k]; + for(int i=0; i n2[j]){ + rs += n1[i++]; + }else if(n1[i] < n2[j]){ + rs += n2[j++]; + }else if(n1[i] == n2[j]){ + int tmp1 = i+1; + int tmp2 = j+1; + while(tmp1 n2[tmp2-1]){ + rs += n1[i++]; + }else if(n1[tmp1-1] < n2[tmp2-1]){ + rs += n2[j++]; + }else if(tmp1 == l1) { + rs += n2[j++]; + }else if(tmp2 == l2) { + rs += n1[i++]; + } + + } + } + + while(i < l1) + rs += n1[i++]; + while(j < l2) + rs += n2[j++]; + return rs; + + } + + public static void main(String[] args) { +// int[] nums1 = {3, 4, 6, 5}; +// int[] nums2 = {9, 1, 2, 5, 8, 3}; + + int[] nums1 = {6, 7}; + int[] nums2 = {6, 0, 4}; + +// int[] nums1 = {5, 6, 8}; +// int[] nums2 = {6, 4, 0}; + + int k = 5; + + int[] rs = maxNumber(nums1, nums2, k); + for(int i=0; i