提交 2850c153 编写于 作者: L liu13

20190117

上级 cd5790db
......@@ -5,7 +5,7 @@ package code;
* 难度:Medium
* 分类:Array, Tree, Depth-first Search
* 思路:通过递归的方式,找左节点和右节点
* Tips:思路记一下,自己想不起来
* Tips:思路记一下,自己想不起来。递归的方法,每次把inorder数组分为两半,设置一个pre_index,每次根据pre_index建立节点,向下递归。
*/
public class lc105 {
public static class TreeNode {
......
package code;
/*
* 322. Coin Change
* 题意:不同面额零钱组合成总值,用的零钱数最少
* 难度:Medium
* 分类:Dynamic Programming
* 思路:和lc279一样的思路,注意下没解的情况
* Tips:不用Set, 加一个dp[0]=0,可以直接递归出结果
*/
import java.util.Arrays;
import java.util.HashSet;
public class lc322 {
public static void main(String[] args) {
System.out.println(coinChange(new int[]{2}, 3));
}
public static int coinChange(int[] coins, int amount) {
if(amount==0) return 0;
int[] dp = new int[amount];
Arrays.fill(dp, Integer.MAX_VALUE);
HashSet<Integer> s = new HashSet();
for (int i = 0; i < coins.length ; i++) {
s.add(coins[i]);
}
for (int i = 0; i < amount ; i++) {
if(s.contains(i+1))
dp[i] = 1;
else{
for (int j = 0; j < coins.length ; j++) {
if( i+1-coins[j]>0 && dp[i - coins[j]]!=Integer.MAX_VALUE ) { // 注意子结构没解的情况
dp[i] = Math.min(dp[i - coins[j]] + 1, dp[i]);
}
}
}
}
return dp[amount-1]==Integer.MAX_VALUE ? -1 : dp[amount-1]; //没解返回-1
}
}
package code;
import java.util.HashMap;
/*
* 337. House Robber III
* 题意:该节点被抢了,那么下层节点不能被抢
* 难度:Medium
* 分类:Tree, Depth-first Search
* 思路:递归和dp。真的经典,树的递归与dp。
* Tips:https://leetcode.com/problems/house-robber-iii/discuss/79330/Step-by-step-tackling-of-the-problem
* 解答给了三种方法,递归,记忆递归,dp
* 多理解一下树的dp,核心是返回数组而不是一个数字
*/
public class lc337 {
public class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) { val = x; }
}
public int rob(TreeNode root) {
return helper(root, new HashMap());
}
public int helper(TreeNode root, HashMap<TreeNode, Integer> mem){
if(root==null)
return 0;
if(mem.containsKey(root)) //用mem去记忆一下资情况的结果,防止重复计算
return mem.get(root);
int val =0;
if(root.left!=null){
val += helper(root.left.left, mem);
val += helper(root.left.right, mem);
}
if(root.right!=null){
val += helper(root.right.left, mem);
val += helper(root.right.right, mem);
}
int res = Math.max(root.val+val, helper(root.left, mem)+helper(root.right, mem));
mem.put(root, res);
return res;
}
public int rob2(TreeNode root) {
return Math.max(helper2(root)[0], helper2(root)[1]);
}
public int[] helper2(TreeNode root){
int[] res = new int[2];
if(root==null) return res;
int[] left = helper2(root.left);
int[] right = helper2(root.right);
res[0] = root.val + left[1] + right[1]; // res[0] 表示该节点被抢的最大结果,下层节点不能被抢
res[1] = Math.max(left[0], left[1]) + Math.max(right[0], right[1]); // res[1] 表示该节点不抢的最大结果。注意不抢该节点,下层节点可能被抢,也可能不被抢,取大的。
return res;
}
}
package code;
/*
* 338. Counting Bits
* 题意:0~n数字上1的个数
* 难度:Medium
* 分类:Dynamic Programming, Bit Maniputation
* 思路:把前几个数的二进制写出来,就很容易看出来dp公式,前边的值+1即可
* Tips:注意细节,边界情况
*/
public class lc338 {
public static void main(String[] args) {
int[] res = countBits(0);
for (int i = 0; i < res.length ; i++) {
System.out.print(res[i]);
System.out.print(" ");
}
}
public static int[] countBits(int num) {
int[] dp = new int[num+1];
int i = 1;
while(i<=num) {
dp[i] = 1;
int max = i;
for (int j = 0; j<max && i<=num ; j++) {
dp[i] = 1 + dp[j];
i++;
}
}
return dp;
}
}
package code;
/*
* 347. Top K Frequent Elements
* 题意:找出数组中出现次数最大的k个元素
* 难度:Medium
* 分类:Hash Table, Heap
* 思路:放入hashmap计数是基本思路,后续可以用桶排序的方法,时间复杂度为O(n)。若用优先队列,则时间复杂度为nlg(k)。
* Tips:第二部巧妙的用了桶排序,避免了比较排序的复杂度
*/
import java.util.*;
public class lc347 {
public static void main(String[] args) {
int[] nums = {1,1,1,2,2,3};
int k = 2;
System.out.println(topKFrequent(nums,2));
}
public static List<Integer> topKFrequent(int[] nums, int k) {
HashMap<Integer, Integer> hm = new HashMap();
TreeMap<Integer, ArrayList<Integer>> tm = new TreeMap();
List<Integer> res = new ArrayList<>();
for (int i = 0; i < nums.length ; i++) { //放入hashmap计数
hm.put(nums[i], hm.getOrDefault(nums[i], 0)+1);
}
for( int i : hm.keySet() ){ //key,value反转,放入treemap
int freq = hm.get(i);
if(tm.containsKey(freq))
tm.get(freq).add(i);
else {
tm.put(freq, new ArrayList<>());
tm.get(freq).add(i);
}
}
while(res.size()<k) {
List ls = tm.pollLastEntry().getValue(); //pollLastEntry将最后一个弹出,而LastEntry只是查看
res.addAll(ls);
}
return res;
}
public List<Integer> topKFrequent2(int[] nums, int k) {
List<Integer>[] bucket = new List[nums.length + 1];
Map<Integer, Integer> frequencyMap = new HashMap<Integer, Integer>();
for (int n : nums) {
frequencyMap.put(n, frequencyMap.getOrDefault(n, 0) + 1);
}
for (int key : frequencyMap.keySet()) { //桶排序,开辟一个nums.length+1的数组,因为一个数出现次数取值为[0~nums.length]
int frequency = frequencyMap.get(key);
if (bucket[frequency] == null) {
bucket[frequency] = new ArrayList<>();
}
bucket[frequency].add(key);
}
List<Integer> res = new ArrayList<>();
for (int pos = bucket.length - 1; pos >= 0 && res.size() < k; pos--) {
if (bucket[pos] != null) {
res.addAll(bucket[pos]);
}
}
return res;
}
}
package code;
/*
* 438. Find All Anagrams in a String
* 题意:匹配相同字符组成的串
* 难度:Easy
* 分类:Hash Table
* 思路:滑动窗口,O(n)时间
* Tips:滑动窗口解法 https://leetcode.com/problems/find-all-anagrams-in-a-string/discuss/92007/Sliding-Window-algorithm-template-to-solve-all-the-Leetcode-substring-search-problem
* lc76类似
*/
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
public class lc438 {
public static void main(String[] args) {
System.out.println(findAnagrams("cbaebabacd", "abc"));
}
public static List<Integer> findAnagrams(String s, String p) {
List<Integer> ls = new ArrayList<>();
if(s.length()<p.length())
return ls;
HashMap<Character, Integer> hm = new HashMap();
for (int i = 0; i < p.length() ; i++) {
hm.put(p.charAt(i), hm.getOrDefault(p.charAt(i), 0)+1);
}
int right = 0, left = 0, count = 0;
while(right<s.length()){
char ch_r = s.charAt(right);
char ch_l = s.charAt(left);
if(hm.containsKey(ch_r)){
hm.put(ch_r, hm.getOrDefault(ch_r,0)-1);
if(hm.get(ch_r)>=0) //注意count++的条件,多余的相同字符不用++了
count++;
}
if(count==p.length())
ls.add(left);
if(right-left+1==p.length()){ //左指针需要右移
if(hm.containsKey(ch_l)){
hm.put(ch_l, hm.get(ch_l)+1);
if(hm.get(ch_l)>0) //count--的条件
count--;
}
left++;
}
right++;
}
return ls;
}
}
......@@ -93,29 +93,30 @@ Welcome to improve this project with me.*
| 236 | [Lowest Common Ancestor of a Binary Tree](https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-tree/) |Medium| [Java](./code/lc236.java)
| 238 | [Product of Array Except Self](https://leetcode.com/problems/product-of-array-except-self/) |Medium| [Java](./code/lc238.java)
| 239 | [Sliding Window Maximum](https://leetcode.com/problems/sliding-window-maximum/) | Hard | [Java](./code/lc239.java)
| 240 | [Search a 2D Matrix II](https://leetcode.com/problems/search-a-2d-matrix-ii/) |Medium| [Java]
| 279 | [Perfect Squares](https://leetcode.com/problems/perfect-squares/) |Medium| [Java]
| 283 | [Move Zeroes](https://leetcode.com/problems/move-zeroes/)| Easy | [Java]
| 287 | [Find the Duplicate Number](https://leetcode.com/problems/find-the-duplicate-number/) | Hard | [Java]
| 240 | [Search a 2D Matrix II](https://leetcode.com/problems/search-a-2d-matrix-ii/) |Medium| [Java](./code/lc240.java)
| 279 | [Perfect Squares](https://leetcode.com/problems/perfect-squares/) |Medium| [Java](./code/lc279.java)
| 283 | [Move Zeroes](https://leetcode.com/problems/move-zeroes/)| Easy | [Java](./code/lc283.java)
| 287 | [Find the Duplicate Number](https://leetcode.com/problems/find-the-duplicate-number/) | Hard | [Java](./code/lc287.java)
| 297 | [Serialize and Deserialize Binary Tree](https://leetcode.com/problems/serialize-and-deserialize-binary-tree/) | Hard | [Java](./code/lc297.java)
| 300 | [Longest Increasing Subsequence](https://leetcode.com/problems/longest-increasing-subsequence/) |Medium| [Java]
| 309 | [Best Time to Buy and Sell Stock with Cooldown](https://leetcode.com/problems/best-time-to-buy-and-sell-stock-with-cooldown/) |Medium| [Java]
| 312 | [Burst Balloons](https://leetcode.com/problems/burst-balloons/) | Hard | [Java]
| 322 | [Coin Change](https://leetcode.com/problems/coin-change/)|Medium| [Java]
| 337 | [House Robber III](https://leetcode.com/problems/house-robber-iii/) |Medium| [Java]
| 338 | [Counting Bits](https://leetcode.com/problems/counting-bits/) |Medium| [Java]
| 347 | [Top K Frequent Elements](https://leetcode.com/problems/top-k-frequent-elements/) |Medium| [Java]
| 300 | [Longest Increasing Subsequence](https://leetcode.com/problems/longest-increasing-subsequence/) |Medium| [Java](./code/lc300.java)
| 301 | [Remove Invalid Parentheses](https://leetcode.com/problems/remove-invalid-parentheses/) |Hard| [Java](./code/lc301.java)
| 309 | [Best Time to Buy and Sell Stock with Cooldown](https://leetcode.com/problems/best-time-to-buy-and-sell-stock-with-cooldown/) |Medium| [Java](./code/lc309.java)
| 312 | [Burst Balloons](https://leetcode.com/problems/burst-balloons/) | Hard | [Java](./code/lc312.java)
| 322 | [Coin Change](https://leetcode.com/problems/coin-change/)|Medium| [Java](./code/lc322.java)
| 337 | [House Robber III](https://leetcode.com/problems/house-robber-iii/) |Medium| [Java](./code/lc337.java)
| 338 | [Counting Bits](https://leetcode.com/problems/counting-bits/) |Medium| [Java](./code/lc338.java)
| 347 | [Top K Frequent Elements](https://leetcode.com/problems/top-k-frequent-elements/) |Medium| [Java](./code/lc347.java)
| 394 | [Decode String](https://leetcode.com/problems/decode-string/) |Medium| [Java]
| 406 | [Queue Reconstruction by Height](https://leetcode.com/problems/queue-reconstruction-by-height/) |Medium| [Java]
| 416 | [Partition Equal Subset Sum](https://leetcode.com/problems/partition-equal-subset-sum/) |Medium| [Java]
| 437 | [Path Sum III](https://leetcode.com/problems/path-sum-iii/) | Easy |[Java]
| 438 | [Find All Anagrams in a String](https://leetcode.com/problems/find-all-anagrams-in-a-string/) | Easy |[Java]
| 438 | [Find All Anagrams in a String](https://leetcode.com/problems/find-all-anagrams-in-a-string/) | Easy |[Java](./code/lc438.java)
| 448 | [Find All Numbers Disappeared in an Array](https://leetcode.com/problems/find-all-numbers-disappeared-in-an-array/) | Easy | [Java]
| 461 | [Hamming Distance](https://leetcode.com/problems/hamming-distance/) | Easy |[Java]
| 494 | [Target Sum](https://leetcode.com/problems/target-sum/) |Medium|[Java]
| 538 | [Convert BST to Greater Tree](https://leetcode.com/problems/convert-bst-to-greater-tree/description/) | Easy |[Java]
| 543 | [Diameter of Binary Tree](https://leetcode.com/problems/diameter-of-binary-tree/description/) | Easy | [Java]
| 560 | [Subarray Sum Equals K](https://leetcode.com/problems/subarray-sum-equals-k) |Medium| [Java]
| 560 | [Subarray Sum Equals K](https://leetcode.com/problems/subarray-sum-equals-k) |Medium| [Java](./code/lc560.java)
| 572 | [Subtree of Another Tree](https://leetcode.com/problems/subtree-of-another-tree/description/) | Easy | [Java]
| 581 | [Shortest Unsorted Continuous Subarray](https://leetcode.com/problems/shortest-unsorted-continuous-subarray/description/) | Easy | [Java]
| 617 | [Merge Two Binary Trees](https://leetcode.com/problems/merge-two-binary-trees/description/) | Easy | [Java]
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册