├── .gitignore
├── Android-Advance.iml
├── README.md
├── README2.md
├── algorithm
├── .gitignore
├── BinaryTreeAllPaths.java
├── BinaryTreePath.java
├── CompleteBinaryTree.java
├── FindTopK.java
├── HeapSort.java
├── IsHaveCircle.java
├── MergeSort.java
├── OrderBinaryTree.java
├── PrintLastK.java
├── QuickSort.java
├── ReverseNode.java
├── Singleton.java
├── TwoThreadPrintNumber.java
├── TwoThreadPrintNumberV2.java
├── leetcode
│ ├── l100
│ │ └── SameTree.java
│ ├── l101
│ │ └── SymmetricTree.java
│ ├── l102
│ │ └── BinaryTreeLevelOrderTraversal.java
│ ├── l103
│ │ └── BinaryTreeZigzagLevelOrderTraversal.java
│ ├── l104
│ │ └── MaximumDepthOfBinaryTree.java
│ ├── l1071
│ │ └── GreatestCommonDivisorOfStrings.java
│ ├── l11
│ │ └── ContainerWithMostWater.java
│ ├── l110
│ │ └── BalancedBinaryTree.java
│ ├── l1137
│ │ └── NThTribonacciNumber.java
│ ├── l1161
│ │ └── MaximumLevelSumOfABinaryTree.java
│ ├── l124
│ │ └── BinaryTreeMaximumPathSum.java
│ ├── l131
│ │ └── PalindromePartitioning.java
│ ├── l1372
│ │ └── LongestZigzagPathInABinaryTree.java
│ ├── l141
│ │ └── LinkedListCycle.java
│ ├── l142
│ │ └── LinkedListCycleII.java
│ ├── l143
│ │ └── ReorderList.java
│ ├── l1431
│ │ └── KidsWithTheGreatestNumberOfCandies.java
│ ├── l144
│ │ └── BinaryTreePreorderTraversal.java
│ ├── l1448
│ │ └── CountGoodNodesInBinaryTree.java
│ ├── l145
│ │ └── BinaryTreePostorderTraversal.java
│ ├── l15
│ │ └── Sum3.java
│ ├── l151
│ │ └── ReverseWordsInAString.java
│ ├── l153
│ │ └── FindMinimumInRotatedSortedArray.java
│ ├── l162
│ │ └── FindPeakElement.java
│ ├── l167
│ │ └── TwoSumIIInput.java
│ ├── l17
│ │ └── LetterCombinationsOfAPhoneNumber.java
│ ├── l1768
│ │ └── MergeStringsAlternately.java
│ ├── l19
│ │ └── RemoveNthNodeFromEndOfList.java
│ ├── l198
│ │ └── HouseRobber.java
│ ├── l199
│ │ └── BinaryTreeRightSideView.java
│ ├── l206
│ │ └── ReverseLinkedList.java
│ ├── l209
│ │ └── MinimumSizeSubArraySum.java
│ ├── l2095
│ │ └── DeleteTheMiddleNodeOfALinkedList.java
│ ├── l216
│ │ └── CombinationSumIII.java
│ ├── l22
│ │ └── GenerateParentheses.java
│ ├── l235
│ │ └── LowestCommonAncestorOfABinarySearchTree.java
│ ├── l236
│ │ └── LowestCommonAncestorOfABinaryTree.java
│ ├── l237
│ │ └── DeleteNodeInALinkedList.java
│ ├── l25
│ │ └── ReverseNodesInKGroup.java
│ ├── l3
│ │ └── LongestSubStringWithoutRepeatingCharacters.java
│ ├── l300
│ │ └── LongestIncreasingSubsequence.java
│ ├── l328
│ │ └── OddEvenLinkedList.java
│ ├── l33
│ │ └── SearchInRotatedSortedArray.java
│ ├── l34
│ │ └── FindFirstAndLastPositionOfElementInSortedArray.java
│ ├── l345
│ │ └── ReverseVowelsOfAString.java
│ ├── l42
│ │ └── TrappingRainWater.java
│ ├── l437
│ │ └── PathSumIII.java
│ ├── l450
│ │ └── DeleteNodeInABST.java
│ ├── l46
│ │ └── Permutations.java
│ ├── l494
│ │ └── TargetSum.java
│ ├── l513
│ │ └── FindBottomLeftTreeValue.java
│ ├── l605
│ │ └── CanPlaceFlowers.java
│ ├── l700
│ │ └── SearchInABinarySearchTree.java
│ ├── l713
│ │ └── SubArrayProductLessThanK.java
│ ├── l746
│ │ └── MinCostClimbingStairs.java
│ ├── l77
│ │ └── Combinations.java
│ ├── l78
│ │ └── Subsets.java
│ ├── l790
│ │ └── DominoAndTrominoTiling.java
│ ├── l82
│ │ └── RemoveDuplicatedFromSortListsII.java
│ ├── l83
│ │ └── RemoveDuplicatedFromSortLists.java
│ ├── l872
│ │ └── LeafSimilarTrees.java
│ ├── l876
│ │ └── MiddleOfTheLinkedList.java
│ ├── l92
│ │ └── ReverseLinkedListII.java
│ ├── l94
│ │ └── BinaryTreeInorderTraversal.java
│ └── l98
│ │ └── ValidateBinarySearchTree.java
├── nowcoder
│ ├── JZ1.java
│ ├── JZ10.java
│ ├── JZ11.java
│ ├── JZ12.java
│ ├── JZ13.java
│ ├── JZ14.java
│ ├── JZ15.java
│ ├── JZ16.java
│ ├── JZ17.java
│ ├── JZ18.java
│ ├── JZ19.java
│ ├── JZ2.java
│ ├── JZ20.java
│ ├── JZ21.java
│ ├── JZ22.java
│ ├── JZ23.java
│ ├── JZ24.java
│ ├── JZ25.java
│ ├── JZ26.java
│ ├── JZ27.java
│ ├── JZ28.java
│ ├── JZ29.java
│ ├── JZ3.java
│ ├── JZ30.java
│ ├── JZ31.java
│ ├── JZ32.java
│ ├── JZ33.java
│ ├── JZ34.java
│ ├── JZ35.java
│ ├── JZ36.java
│ ├── JZ37.java
│ ├── JZ38.java
│ ├── JZ39.java
│ ├── JZ4.java
│ ├── JZ40.java
│ ├── JZ41.java
│ ├── JZ42.java
│ ├── JZ43.java
│ ├── JZ44.java
│ ├── JZ45.java
│ ├── JZ46.java
│ ├── JZ47.java
│ ├── JZ48.java
│ ├── JZ49.java
│ ├── JZ5.java
│ ├── JZ6.java
│ ├── JZ68.java
│ ├── JZ7.java
│ ├── JZ8.java
│ └── JZ9.java
└── practice
│ └── Permutation.java
├── img
└── advance.jpeg
└── java
└── Java内存模型以及GC原理.md
/.gitignore:
--------------------------------------------------------------------------------
1 | algorithm/out/*
2 | algorithm/out/production
3 | algorithm/out/production/algorithm
4 | /out
5 | .DS_Store
6 | .idea
--------------------------------------------------------------------------------
/Android-Advance.iml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Android-Advance
2 |
3 | 一个用来记录自己平时工作、生活过程中遇到与解决的问题,学习和收获的知识的库,主要是Android相关,也会包含一些编程相关的基础知识。
4 |
5 | ## 面试基础算法题
6 |
7 | ### 排序
8 |
9 | 1. [快排](/algorithm/QuickSort.java)
10 | 1. [堆排](/algorithm/HeapSort.java)
11 | 1. [归并排序](/algorithm/MergeSort.java)
12 | 1. [M个元素中找出前N大的元素](/algorithm/FindTopK.java)
13 |
14 | ### 链表
15 |
16 | 1. [判断单链表是否有环](/algorithm/IsHaveCircle.java)
17 | 1. [判断单链表是否有环并且找到有环的那个节点](/algorithm/IsHaveCircleAndMeetWhere.java)
18 | 1. [反转一个单链表](/algorithm/ReverseNode.java)
19 | 1. [单链表输出倒数第k个元素](/algorithm/PrintLastK.java)
20 |
21 | ### 二叉树
22 |
23 | 1. [二叉树给出根节点和目标节点,找出从根节点到目标节点的路径](/algorithm/BinaryTreePath.java)
24 | 1. [如何判断一颗二叉树是完全二叉树](/algorithm/BinaryTreeCheckCompletion.java)
25 | 1. [二叉树的三种遍历方式递归非递归](/algorithm/OrderBinaryTree.java)
26 | 1. [二叉树层次遍历](/algorithm/BinaryTreeLevelOrder.java)
27 |
28 |
29 | ## Java
30 |
31 | ### JVM基础
32 |
33 | 1. [如何判断对象是否可以GC](/java/Java内存模型以及GC原理.md)
34 | 1. [GC的时候垃圾回收器是怎样工作的](/java/Java内存模型以及GC原理.md)
35 | 1. GC Root 对象有哪些
36 | 1. 类加载机制,双亲委派模型原理
37 |
38 | ### Java基础
39 |
40 | 1. final关键字可以修饰哪些,作用分别是什么
41 | 1. volatile可以修饰哪些,作用分别是什么
42 | 1. Synchronized可以修饰哪些,作用分别是什么
43 | 1. 四种引用类型
44 | 1. 内部类分为哪些
45 | 1. HashMap实现原理
46 | 1. 什么是注解,注解的原理,利用注解可以干什么
47 |
48 |
49 | ### 设计模式
50 |
51 | 1. 单例模式
52 | 1. 生产者消费者模式
53 | 1. 代理模式
54 | 1. 工厂模式
55 | 1. 建造者模式
56 |
57 | ## Android
58 |
59 | ### Android基础
60 |
61 | 1. Activity的生命周期
62 | 1. Fragment生命周期
63 | 1. Context类相关内容
64 | 1. MVC,MVP,MVVM异同
65 | 1. LifeCycle的应用
66 | 1. RecyclerView的缓存原理
67 | 1. [妙用ConstraintLayout的Circular positioning](https://www.jianshu.com/p/7f111f0bdbd0)
68 |
69 | ### Android事件传递
70 |
71 | 1. [【透镜系列】看穿 > 触摸事件分发 >](https://juejin.im/post/5c3c8538f265da6142741d63)
72 | 1. [【透镜系列】看穿 > NestedScrolling 机制 >](https://juejin.im/post/5c3c8d2ae51d4552475fcef7)
73 |
74 | ### 好用的ViewGroup
75 |
76 | 1. [Android 弹性布局 FlexboxLayout了解一下](https://juejin.im/post/5b1ceaf8f265da6e3423bc6b)
77 |
78 | ### Handler相关
79 |
80 | 1. [你知道android的MessageQueue.IdleHandler吗?](https://blog.csdn.net/tencent_bugly/article/details/78395717)
81 |
82 | ### Android源码解析
83 |
84 | 1. [RecyclerView缓存机制(咋复用?)](https://juejin.im/post/5c696ba9e51d457f136d24ff)
85 |
86 | ### 开源框架
87 |
88 | 1. RxJava原理
89 | 1. Retrofit2原理
90 | 1. OkHttp原理
91 | 1. LeakCanary原理
92 | 1. Glide的原理
93 |
94 |
95 | ### 插件化
96 |
97 | ### Hook相关
98 |
99 | 1. [Android Hook 神器——XPosed入门](https://juejin.im/entry/55e97c42ddb2dd0023d1b96f)
100 |
101 | ### 性能分析相关
102 |
103 | 1. [Android性能优化第(五)篇---Allaction Tracing追踪内存分配的轨迹](https://www.jianshu.com/p/d9e426c10581)
104 |
105 |
106 | ### Gradle相关
107 |
108 | 1. [Android Studio3.0中dependencies依赖](https://blog.csdn.net/silenceoo/article/details/78735687)
109 |
110 |
111 | ## Kotlin相关
112 |
113 | 1. [区别Kotlin中的object和companion object关键字](http://liuqingwen.me/blog/2017/06/20/object-vs-companion-object-in-kotlin/)
114 | 1. [Kotlin中的with函数](https://www.jianshu.com/p/272372acc00c)
115 |
116 |
117 |
118 | ## JNI相关
119 |
120 | ### 环境搭建
121 |
122 | 1. [NDK开发入门终极教程](https://juejin.im/post/5c3b01016fb9a049f81984bb)
123 |
124 |
125 |
126 | ### JNI基础入门
127 | 1. [手把手教你如何在Android下进行JNI开发(入门)](https://juejin.im/post/5c05d0776fb9a049ca371cb6)
128 |
129 |
130 |
131 |
132 |
133 |
134 |
135 |
136 |
137 |
138 |
139 |
140 |
141 |
142 |
143 |
144 |
145 |
146 |
147 |
148 |
149 |
150 |
--------------------------------------------------------------------------------
/README2.md:
--------------------------------------------------------------------------------
1 | # Android-Advance
2 |
3 | 安卓系统以及进阶教程
4 |
5 | 撰写这个工程,有两个目的。
6 |
7 | 1. 帮助那些想系统完善Android体系的人,有一个资料
8 | 2. 做一个知识库,丰富自己的眼界,提升自己的能力
9 |
10 | 不断挑战突破自己,即使是咸鱼,也要做最咸的那一条。技术要日有精进,要沿着目标一步一步的走过去。定一个小目标吧,半年内,加入BAT TMD这类的公司。
11 |
12 | - [最全的BAT大厂面试题整理](https://www.jianshu.com/p/c70989bd5f29)
13 |
14 | ## 算法
15 |
16 | 1. [判断单链表是否有环,并且找到相交点](/algorithm/IsHaveCircle.java)
17 | 2. [逆转链表](/algorithm/ReverseNode.java)
18 | 3. [反转一颗二叉树](/algorithm/ReverseNode.j)
19 | 4. 单链表输出倒数第k个元素
20 | 5. [100万个数据找出100个最大的](/algorithm/FindTopK.java)
21 | 6. 快排,堆排,归并排序
22 | - [QuickSort](/algorithm/QuickSort.java)
23 | - [MergeSort](/algorithm/MergeSort.java)
24 | - [HeapSort](/algorithm/HeapSort.java)
25 | 7. 判断一颗二叉树是完全二叉树
26 | 8. [分析一下常见的排序算法的稳定性](https://www.cnblogs.com/tigerson/p/7156648.html)
27 | 9. [二叉树给出根节点和目标节点,找出从根节点到目标节点的路径]()
28 | 10. [一个文件中有100万个整数,由空格分开,在程序中判断用户输入的整数是否在此文件中。说出最优的方法]()
29 | 11. [N*N的方格纸,里面有多少个正方形]()
30 | 12. [时针走一圈,时针分针重合几次]()
31 | 13. [求1000以内的水仙花数以及40亿以内的水仙花数]()
32 | 14. [两个不重复的数组集合中,这两个集合都是海量数据,内存中放不下,怎么求共同的元素?]()
33 | 15. [子串包含问题(KMP 算法)写代码实现]()
34 | 16. [Leetcode 动态规划】 买卖股票 I II III IV 冷却,共5题](https://blog.csdn.net/dr_unknown/article/details/51939121)
35 |
36 | 17. LRU算法
37 | 18. 数组存水
38 | 19. 两个有序数组找第k大的数
39 | 20. 字符串动态规划
40 | 21. 二分查找的变形
41 | 22. 最少4个点,最多9个点,一个点经过一次,类似手机解锁,一共有多少种可能
42 | 23. 之字形输出二叉树
43 | 24. 如何判断一个二叉树是否为完全二叉树
44 | 25. leetcode11 , leetcode42
45 | 26. 给一个字符串和单词列表,判断字符串能不能由这些单词组成
46 | 27. 二叉树最小公共祖先
47 | 28. 一棵树里最远的两个节点间的距离
48 | 29. 链表交叉判断
49 | 30. 手写后序遍历非递归代码
50 | 31. 数组中搜索子数组
51 |
52 | 了解相关的TextureView吗?
53 | HashMap的结构是怎样的,怎么存value,遇到相同的hash值的key,其value又怎么存。
54 | String str = new String("123") 创建了几个对象,都存在哪
55 | 解释IOC AOP都是什么
56 |
57 |
58 | ## JVM基础
59 |
60 | 1. Java GC简介
61 | - [Java GC系列(1):Java垃圾回收简介](http://www.importnew.com/13504.html)
62 | - [Java GC系列(2):Java垃圾回收是如何工作的?](http://www.importnew.com/13493.html)
63 | - [Java GC系列(3):垃圾回收器种类](http://www.importnew.com/13827.html)
64 | - [Java GC系列(4):垃圾回收监视和分析](http://www.importnew.com/13838.html)
65 |
66 |
67 | 2. 操作系统如何管理内存的
68 |
69 | 3. 自旋锁和互斥锁的区别
70 |
71 |
72 | ## Java基础
73 |
74 | 1. Java的final关键字的作用
75 | - [浅析Java中的final关键字](http://www.importnew.com/18586.html)
76 | 2. volatile 的作用,为什么会出现变量读取不一致的情况, synchronized 的区别
77 | - [你真的了解volatile关键字吗?](http://www.importnew.com/24082.html)
78 | 3. Java 中的 Error、 Exception 的区别
79 | - [谈一谈Java中的Error和Exception](https://blog.csdn.net/goodlixueyong/article/details/47122487)
80 | 4. ArrayList 如何删除重复的元素或者指定的元素
81 | 5. Java 异常简介
82 | 6. Java 中内部类为什么可以访问外部类
83 | 7. Java 泛型
84 | - [Java泛型详解](http://www.importnew.com/24029.html)
85 | 8. equals 和 hashcode 的关系
86 | - [ Java中==和equals的区别](http://blog.csdn.net/tiantiandjava/article/details/46988461)
87 | 9. Hashmap 的源码和实现方式
88 | - [从源码角度认识ArrayList,LinkedList与HashMap](https://www.jianshu.com/p/f174d49b391c)
89 | 10. ArrayList 和 LinkedList 的区别?造成区别的原因是什么,为什么删查的复杂度不同
90 | 12. Java GC 了解过没有,如何判断一个对象是否可以被GC
91 | 13. Java 线程同步了解不,同步方法在不同的实例之间是否仍然保持同步,有没有什么隐患
92 | 14. Java 类加载机制了解不,双亲委派原理
93 | 15. 四种引用类型的概念
94 | - [四种引用类型的概念](https://www.cnblogs.com/theo/p/6443493.html)
95 | 16. [Java内部类详解](https://www.cnblogs.com/dolphin0520/p/3811445.html)
96 | 17. ["=="、equals和hashCode有什么区别](http://blog.csdn.net/dove_knowledge/article/details/71027170)
97 | 18. [Java 8 种数据类型 字节大小,int 4个字节,boolean几个字节](http://blog.csdn.net/never_cxb/article/details/47204485)
98 | 19. [java面试题之int和Integer的区别
99 | ](https://www.cnblogs.com/guodongdidi/p/6953217.html)
100 | 20. [final、finally、finalize修饰符的区别](http://blog.csdn.net/javagoingon/article/details/27965381)
101 | 21. [finalize()方法](http://blog.csdn.net/u013366812/article/details/52046678)
102 | 22. [常见编码方式](http://kxjhlele.iteye.com/blog/333211)
103 | 23. [常见数据结构与算法整理总结(上)](https://www.jianshu.com/p/230e6fde9c75)
104 | 24. [常见数据结构与算法整理总结(下)](https://www.jianshu.com/p/42f81846c0fb)
105 | 25. [Android List,Set,Map集合安全 集合区别 并发集合类性能分析](http://blog.csdn.net/whb20081815/article/details/70291412)
106 | 26. [Java中Synchronized的用法](https://blog.csdn.net/luoweifu/article/details/46613015)
107 | 27. [Java内部类详解](http://www.cnblogs.com/dolphin0520/p/3811445.html)
108 | 28. [ArrayList 概述](https://www.cnblogs.com/kuoAT/p/6771653.html)
109 | 29. [HashMap 和 HashTable 到底哪不同 ?](http://www.importnew.com/24822.html
110 | 30. [ConcurrentHashMap总结](http://www.importnew.com/22007.html)
111 |
112 |
113 |
114 | ## 常见的设计模式
115 |
116 | 1. 单利模式
117 | 2. [单例的双重检验的实现方式](/algorithm/Singleton.java)
118 | 3. 生产者消费者模式
119 | 4. 建造者模式
120 | - [建造者模式](http://blog.csdn.net/carson_ho/article/details/54910597)
121 | - [建造者模式](http://www.runoob.com/design-pattern/builder-pattern.html)
122 |
123 | ## 计算机网络
124 |
125 | 1. Tcp 三次握手和四次挥手
126 | - [TCP的三次握手与四次挥手](https://blog.csdn.net/qzcsu/article/details/72861891)
127 | 2. 浏览器输入地址到返回结果发生了什么
128 | 3. Tcp 是如何保证可靠性传输的
129 | 4. Tcp/IP 协议几层
130 | 5. 如何设计在 UDP 上层保证 UDP 的可靠性传输
131 |
132 |
133 | ## 操作系统
134 |
135 | 1. 进程间通信有哪些方法
136 | 2. 进程和线程的区别
137 |
138 |
139 | ## Android相关
140 |
141 | ### 事件传递相关
142 |
143 | - [从另一个思路来学习安卓事件分发机制](https://mp.weixin.qq.com/s/djFXsrocOfpn9eSlvRNp2w)
144 | - [深入了解View的事件分发过程](https://juejin.im/post/58c8257661ff4b005dabab9d)
145 |
146 | ### 事件总线处理
147 |
148 | - [自定义消息订阅框架NotificationBus](http://www.wanandroid.com/blog/show/2422)
149 |
150 |
151 | 1. 布局优化的过程
152 | - [Android性能优化之布局优化](https://www.cnblogs.com/hoolay/p/6248514.html)
153 | - [Android性能优化系列之布局优化](http://blog.csdn.net/u012124438/article/details/54564659)
154 | - [ Android 性能优化之布局优化](http://blog.csdn.net/u014608640/article/details/52511329)
155 | 2. 性能优化有哪方面
156 | - [Android性能优化的方面](https://www.jianshu.com/p/4d6c38e1f5b8)
157 | 3. 什么是MVP模式
158 | 4. Activity启动过程
159 | 5. Activity生命周期什么时候调用
160 | - [横竖屏切换对Activity生命周期的影响](http://blog.csdn.net/hzw19920329/article/details/51345971)
161 | 6. 热更新技术简介
162 | 7. 避免OOM的方法
163 | 8. 自行设计一个图片加载库的思路
164 | 9. 布局优化的过程,为什么要进行过度绘制的优化
165 | 10. APK里面包含哪写东西,打包过程是什么样的
166 | 11. Handler 机制描述
167 | 12. Android 事件分发过程
168 | 13. HashMap 的实现过程
169 | 14. 断点上传如何设计
170 | 15. 生成的 apk 文件,解压后会有什么目录
171 | - [apk包解压缩后的文件结构](http://blog.csdn.net/qu213/article/details/9629883)
172 | 16. 讲讲 Gradle 语法、生命周期
173 | 17. ListView 和 RecycleView 的比较
174 | - [ViewHolder重用机制理解(解决图片错乱和闪烁问题)](http://blog.csdn.net/xyq046463/article/details/51800095?locationNum=3)
175 | - [ListView中convertView和viewHolder](https://www.cnblogs.com/yuhanghzsd/p/5595532.html)
176 | 18. 网络框架用了哪些,讲讲使用的框架的原理
177 | 19. 事件分发机制
178 | 20. 注解的优缺点
179 | - [ 注解机制及其原理](http://blog.csdn.net/wangyangzhizhou/article/details/51698638)
180 | 21. Activity和Fragment的生命周期,Home和Back键的生命周期
181 | - [Fragment 生命周期的详情](https://www.cnblogs.com/fajieyefu/p/6092465.html)
182 | 22. 写Service的两种实现方式和生命周期
183 | 23. 静态同步方法和非静态同步方法的区别
184 | - [Synchronized同步静态方法和非静态方法总结](http://blog.csdn.net/u010842515/article/details/65443084)
185 | 24. Android 多进程如何实现
186 | 25. 子线程更新UI的方式
187 | - [Android子线程中更新UI的3种方法](http://gqdy365.iteye.com/blog/2112471)
188 | 26. Handler 的实现机制,画图讲解
189 | 27. 安卓内存泄露检测以及解决方案
190 | 28. 讲讲线程池
191 | 29. 如果加快 Gradle 的编译速度
192 | - [加快gradle的编译速度总结-亲身经历](https://www.jianshu.com/p/200d55b4d40a)
193 | 30. Android 事件分发机制了解不
194 | 31. Android 绘制过程,onMeasure 的原理,解决了什么问题
195 | 32. LeakCanary核心原理
196 | - [LeakCanary核心原理源码浅析](http://blog.csdn.net/cloud_huan/article/details/53081120)
197 | - [LeakCanary 内存泄露监测原理研究](https://www.jianshu.com/p/5ee6b471970e)
198 | 33. 序列化Serializable与Parcelable原理与区别
199 | - [序列化Serializable与Parcelable原理与区别](https://www.jianshu.com/p/2939e11b5ecb)
200 | 34. - [Android SurfaceView入门学习](https://www.jianshu.com/p/15060fc9ef18)
201 | 35. - [Android四大组件:BroadcastReceiver史上最全面解析](https://www.jianshu.com/p/ca3d87a4cdf3)
202 | 36. - [Android APP启动时出现白屏或者黑屏怎么办?](https://www.jianshu.com/p/09b876b865ac)
203 | 37. - [Android Starting Window(Preview Window)](http://www.cnblogs.com/angeldevil/p/3801209.html)
204 | 38. app运行中的crash崩溃异常日志收集
205 | - [app运行中的crash崩溃异常日志收集](http://blog.csdn.net/qq_17387361/article/details/52688998)
206 | - [ 安卓APP崩溃(crash)后重新启动,捕获全局异常重启APP](http://blog.csdn.net/jiaweihaoku/article/details/78053403)
207 | 39. - [Android 屏幕适配:最全面的解决方案](https://www.jianshu.com/p/ec5a1a30694b)
208 | 40. - [Java NIO](http://blog.csdn.net/u011277123/article/details/71158564)
209 | 41. - [理解java的三大特性之多态](https://www.cnblogs.com/chenssy/p/3372798.html)
210 | 42. - [Java中多态的一些简单理解](https://www.cnblogs.com/wl0000-03/p/5964881.html)
211 | 43. - [Java中重载和重写的区别](http://blog.csdn.net/zhu_apollo/article/details/1852542)
212 | 44. - [接口和抽象类的联系和区别](http://blog.csdn.net/chengqiuming/article/details/70139323)
213 | 45. - [抽象类和接口的区别](http://blog.csdn.net/Hhc0917/article/details/54755001)
214 | 46. - [HTTP协议(二)header标头说明](https://www.cnblogs.com/lxg0/p/http.html)
215 | 47. - [泛型通配符extends与super的区别](https://www.cnblogs.com/yepei/p/6591289.html)
216 | 48. - [Java 中如何序列化一个对象](https://www.cnblogs.com/ScarecrowAnBird/p/7800785.html)
217 | 49. - [Java基础之—反射](http://blog.csdn.net/sinat_38259539/article/details/71799078)
218 | 50. - [深入浅出Java注解](https://zhuanlan.zhihu.com/p/21410338?refer=zmywly8866)
219 | 51. - [什么是依赖注入](http://blog.csdn.net/taijianyu/article/details/2338311/)
220 | 52. - [为什么String要设计成不可变的](http://blog.csdn.net/renfufei/article/details/16808775)
221 | 53. - [Java中的深拷贝和浅拷贝](http://blog.csdn.net/chjttony/article/details/7477346)
222 | 54. - [实现线程同步的几种方式](http://blog.csdn.net/small_lee/article/details/51453019)
223 | 55. - [HttpClient、HttpURLConnection、OKHttp和Volley优缺点和性能对比,如何选择?](http://blog.csdn.net/langtop/article/details/77972855)
224 | 56. - [Android 如何判断当前线程是否是主线程](http://blog.csdn.net/clevergump/article/details/50995612)
225 | 57. - [ Android Context完全解析,你所不知道的Context的各种细节](http://blog.csdn.net/guolin_blog/article/details/47028975)
226 | 58. - [GC Root 对象有哪些](http://blog.csdn.net/yaozhifeng123456/article/details/48375115)
227 | 59. - [获取Activity栈,判断当前Activity位置](http://blog.csdn.net/ffengz/article/details/74937311)
228 | 60. - [2种判断(获取)栈顶activity的方法](http://blog.csdn.net/u014620028/article/details/56835374)
229 | 61. - [Android查看activity所在任务栈](http://blog.csdn.net/bin622/article/details/76861009)
230 | 62. - [你必须弄懂的Intent Filter匹配规则](http://blog.csdn.net/mynameishuangshuai/article/details/51673273)
231 | 63. - [Android中为什么主线程不会因为Looper.loop()里的死循环卡死?](https://www.zhihu.com/question/34652589/answer/59578531)
232 | 64. - [两个Fragment之间如何传递数据](https://www.cnblogs.com/graphics/p/5151547.html)
233 | 65. - [本地广播和全局广播有什么差别]()
234 | 66. - [AlertDialog,popupWindow,Activity区别]()
235 | 67. - [自定义View如何考虑机型适配]()
236 | 68. - [SpareArray原理]()
237 | 69. - [SP是进程同步的吗?有什么方法做到同步?
238 | 70. - [View刷新机制]()
239 | 71. - [View绘制流程]()
240 | 72. - [AsyncTask原理及不足]()
241 | 73. - [如果在onStop的时候做了网络请求,onResume的时候怎么恢复?]()
242 | 74. - [下拉状态栏是不是影响activity的生命周期]()
243 | 75. - [ViewPager使用细节,如何设置成每次只初始化当前的Fragment,其他的不初始化?]()
244 | 76. - [微信主页面的实现方式]()
245 | 77. - [WebSocket与socket的区别]()
246 | 78. - [视频加密传输]()
247 | 79. - [App 是如何沙箱化,为什么要这么做?]()
248 | 80. - [权限管理系统(底层的权限是如何进行 grant 的)
249 | 81. - [Android中SurfaceView使用详解](https://blog.csdn.net/android_cmos/article/details/68955134)
250 | 82. - [Android 操作SQLite基本用法
251 | ](https://www.cnblogs.com/foxy/p/7725010.html)
252 | 83. - [从源码看invalidate和requestLayout的区别](https://blog.csdn.net/litefish/article/details/52859300)
253 | 84. - [Android高效加载大图、多图解决方案,有效避免程序OOM](https://blog.csdn.net/guolin_blog/article/details/9316683)
254 | 85. - [深入探究Glide的缓存机制](https://blog.csdn.net/guolin_blog/article/details/54895665)
255 | 86. - [浅谈RecyclerView性能问题 滑动卡顿 界面闪动](https://blog.csdn.net/seven25/article/details/78094255?utm_source=debugrun&utm_medium=referral)
256 | 87. - [RecyclerView的卡顿优化(一)
257 | ](https://blog.csdn.net/likuan0214/article/details/51899400)
258 | 88. - [RecyclerView 卡顿优化(二)](https://blog.csdn.net/likuan0214/article/details/51911873)
259 |
260 |
261 |
262 | ## 面经
263 |
264 | 1. - [阿里面试题总结](https://www.nowcoder.com/discuss/5949?type=0&order=0&pos=319&page=14)
265 |
--------------------------------------------------------------------------------
/algorithm/.gitignore:
--------------------------------------------------------------------------------
1 | .idea
2 | algorithm.iml
--------------------------------------------------------------------------------
/algorithm/BinaryTreeAllPaths.java:
--------------------------------------------------------------------------------
1 | package algorithm;
2 |
3 |
4 | import java.util.ArrayList;
5 | import java.util.List;
6 |
7 | public class BinaryTreeAllPaths {
8 |
9 | static class Node {
10 | int val;
11 | Node left;
12 | Node right;
13 | }
14 |
15 |
16 | static List> paths = new ArrayList<>();
17 |
18 | public static void getAllPath(Node head, List path) {
19 | if (head == null) {
20 | return;
21 | }
22 | if (head.left == null && head.right == null) {
23 | paths.add(path);
24 | }else {
25 | if (head.left != null) {
26 | List copyPath = new ArrayList<>(path);
27 | copyPath.add(head.left.val);
28 | getAllPath(head.left, copyPath);
29 | }
30 | if (head.right != null) {
31 | List copyPath = new ArrayList<>(path);
32 | copyPath.add(head.right.val);
33 | getAllPath(head.right, copyPath);
34 | }
35 | }
36 | }
37 |
38 | public static void main(String[] args) {
39 | Node node1 = new Node();
40 | node1.val = 1;
41 | Node node2 = new Node();
42 | node2.val = 2;
43 | Node node3 = new Node();
44 | node3.val = 3;
45 | Node node4 = new Node();
46 | node4.val = 4;
47 | Node node5 = new Node();
48 | node5.val = 5;
49 |
50 | node1.left = node2;
51 | node1.right = node3;
52 |
53 | node2.left = node4;
54 | node2.right = node5;
55 |
56 |
57 | List path = new ArrayList<>();
58 | path.add(1);
59 | getAllPath(node1, path);
60 | System.out.println(paths.size());
61 |
62 | for (int i = 0; i < paths.size(); i++) {
63 | for (int j = 0; j < paths.get(i).size(); j++) {
64 | System.out.print(paths.get(i).get(j) + "\t");
65 | }
66 | System.out.println();
67 | }
68 | }
69 |
70 |
71 | }
72 |
--------------------------------------------------------------------------------
/algorithm/BinaryTreePath.java:
--------------------------------------------------------------------------------
1 | package algorithm;
2 |
3 | import java.util.ArrayList;
4 | import java.util.List;
5 |
6 | /**
7 | * 寻找二叉树根节点到数上任意节点的路径
8 | */
9 | public class BinaryTreePath {
10 |
11 | static class TreeNode {
12 | TreeNode left;
13 | TreeNode right;
14 | int val;
15 |
16 | public TreeNode(int value) {
17 | this.val = value;
18 | }
19 | }
20 |
21 | private static boolean getPathFromRoot(TreeNode root, TreeNode target, List list) {
22 | if (root == null || target == null) {
23 | return false;
24 | }
25 | list.add(root.val);
26 |
27 | if (root.val == target.val) {
28 | return true;
29 | }
30 |
31 | if (getPathFromRoot(root.left, target, list)){
32 | return true;
33 | }
34 |
35 | if (getPathFromRoot(root.right, target, list)){
36 | return true;
37 | }
38 | list.remove((Integer) root.val);
39 | return false;
40 | }
41 |
42 | public static void main(String[] args) {
43 | TreeNode n1 = new TreeNode(1);
44 | TreeNode n2 = new TreeNode(2);
45 | TreeNode n3 = new TreeNode(3);
46 | TreeNode n4 = new TreeNode(4);
47 | TreeNode n5 = new TreeNode(5);
48 | n1.left = n2;
49 | n1.right = n3;
50 | n2.left = n4;
51 | n2.right = n5;
52 | ArrayList list = new ArrayList<>();
53 | getPathFromRoot(n1, n5, list);
54 | for (int i = 0; i < list.size(); i++) {
55 | System.out.println(list.get(i));
56 | }
57 | }
58 |
59 | }
60 |
--------------------------------------------------------------------------------
/algorithm/CompleteBinaryTree.java:
--------------------------------------------------------------------------------
1 | package algorithm;
2 |
3 | import java.util.LinkedList;
4 |
5 | public class CompleteBinaryTree {
6 |
7 | static class Node {
8 | Node left;
9 | Node right;
10 | int value;
11 |
12 | public Node(int value) {
13 | this.value = value;
14 | }
15 | }
16 |
17 | /**
18 | * 思想:首先利用的是层次遍历,两个判断条件
19 | * 1. 如果一个结点有右子树就一定要有左子树
20 | * 2. 如果已经出现了叶子结点,那么之后的所有结点都应该是叶子结点
21 | */
22 | private static boolean isCompleteBinaryTree(Node node) {
23 | if (node == null){
24 | return false;
25 | }
26 | LinkedList queue = new LinkedList<>();
27 | queue.add(node);
28 | boolean alreadyHaveLeafNode = false;
29 |
30 | while (queue.size() != 0){
31 | Node temp = queue.pop();
32 | if (temp.left == null && temp.right == null){
33 | alreadyHaveLeafNode = true;
34 | }
35 | if (alreadyHaveLeafNode && (temp.left != null || temp.right != null)){
36 | return false;
37 | }
38 | if (temp.left == null && temp.right != null){
39 | return false;
40 | }
41 | if (temp.left != null){
42 | queue.add(temp.left);
43 | }
44 | if (temp.right != null){
45 | queue.add(temp.right);
46 | }
47 | }
48 | return true;
49 | }
50 |
51 | public static void main(String[] args) {
52 | Node n1 = new Node(1);
53 | Node n2 = new Node(2);
54 | Node n3 = new Node(3);
55 | Node n4 = new Node(4);
56 | Node n5 = new Node(5);
57 | n1.left = n2;
58 | n1.right = n3;
59 | n2.left = n4;
60 | n2.right = n5;
61 | System.out.println(isCompleteBinaryTree(n1));
62 | }
63 | }
64 |
--------------------------------------------------------------------------------
/algorithm/FindTopK.java:
--------------------------------------------------------------------------------
1 | package algorithm;
2 |
3 | import java.util.Arrays;
4 |
5 | public class FindTopK {
6 |
7 |
8 | public static int[] getMinKNumsByHeap(int[] arr, int k) {
9 | if (k < 1 || k > arr.length) {
10 | return arr;
11 | }
12 | int[] heap = new int[k];
13 | for (int i = 0; i < k; i++) {
14 | heapInsert(heap, arr[i], i);
15 | }
16 | for (int i = k; i < arr.length; i++) {
17 | if (arr[i] < heap[0]) {
18 | heap[0] = arr[i];
19 | heapify(heap, 0, k);
20 | }
21 | }
22 | return heap;
23 | }
24 |
25 | private static void heapInsert(int[] heap, int value, int index) {
26 | heap[index] = value;
27 | while (index != 0) {
28 | int parent = (index - 1) / 2;
29 | if (heap[parent] < heap[index]) {
30 | swap(heap, parent, index);
31 | index = parent;
32 | } else {
33 | break;
34 | }
35 | }
36 | }
37 |
38 | private static void heapify(int[] heap, int index, int heapSize) {
39 | int left = index * 2 + 1;
40 | int right = index * 2 + 2;
41 | int largest = index;
42 | while (left < heapSize) {
43 | if (heap[left] > heap[index]) {
44 | largest = left;
45 | }
46 | if (right < heapSize && heap[right] > heap[largest]) {
47 | largest = right;
48 | }
49 | if (largest != index) {
50 | swap(heap, largest, index);
51 | } else {
52 | break;
53 | }
54 | index = largest;
55 | left = index * 2 + 1;
56 | right = index * 2 + 2;
57 | }
58 | }
59 |
60 | private static void swap(int[] heap, int parent, int index) {
61 | int tmp = heap[index];
62 | heap[index] = heap[parent];
63 | heap[parent] = tmp;
64 | }
65 |
66 |
67 | public static void main(String[] args) {
68 | int[] a = {1, 3, 6, 4, 7, 5, 0};
69 | System.out.println(Arrays.toString(getMinKNumsByHeap(a, 2)));
70 | }
71 |
72 | }
73 |
--------------------------------------------------------------------------------
/algorithm/HeapSort.java:
--------------------------------------------------------------------------------
1 | import java.util.ArrayList;
2 | import java.util.Arrays;
3 |
4 | public class HeapSort {
5 |
6 |
7 | public static void main(String[] args) {
8 | int[] arr = {4, 5, 1, 6, 2, 7, 3, 8};
9 | sort(arr);
10 | System.out.println(Arrays.toString(arr));
11 | }
12 |
13 | public static void sort(int[] arr) {
14 | for (int i = arr.length / 2 - 1; i >= 0; i--) {
15 | adjustHeap(arr, i, arr.length);
16 | }
17 | for (int i = arr.length - 1; i >= 0; i--) {
18 | swap(arr, 0, i);
19 | adjustHeap(arr, 0, i);
20 | }
21 | }
22 |
23 | public static void adjustHeap(int[] arr, int i, int length) {
24 | int temp = arr[i];
25 | for (int k = i * 2 + 1; k + 1 <= length; k = k * 2 + 1) {
26 | if (k + 1 < length && arr[k] < arr[k + 1]) {
27 | k++;
28 | }
29 | if (arr[k] > temp) {
30 | arr[i] = arr[k];
31 | i = k;
32 | } else {
33 | break;
34 | }
35 | }
36 | arr[i] = temp;
37 | }
38 |
39 | public static void swap(int[] arr, int a, int b) {
40 | int temp = arr[a];
41 | arr[a] = arr[b];
42 | arr[b] = temp;
43 | }
44 |
45 |
46 | }
47 |
--------------------------------------------------------------------------------
/algorithm/IsHaveCircle.java:
--------------------------------------------------------------------------------
1 | package algorithm;
2 |
3 | public class IsHaveCircle {
4 |
5 | static class Node {
6 | Node next;
7 | int value;
8 |
9 | public Node(int value) {
10 | this.value = value;
11 | }
12 | }
13 |
14 | public static int isHaveCircleAndMeetWhere(Node head) {
15 | if (head == null || head.next == null) {
16 | return -1;
17 | }
18 | Node a = head;
19 | Node b = head;
20 | while (b.next.next != null) {
21 | a = a.next;
22 | b = b.next.next;
23 |
24 | if (a == b) {
25 | Node c = head;
26 | while (c != a) {
27 | a = a.next;
28 | c = c.next;
29 | }
30 | return c.value;
31 | }
32 | a = a.next;
33 | b = b.next.next;
34 | }
35 | return -1;
36 | }
37 |
38 | public static void main(String[] args) {
39 | Node n1 = new Node(1);
40 | Node n2 = new Node(2);
41 | Node n3 = new Node(3);
42 | Node n4 = new Node(4);
43 | Node n5 = new Node(5);
44 | Node n6 = new Node(6);
45 |
46 | n1.next = n2;
47 | n2.next = n3;
48 | n3.next = n4;
49 | n4.next = n5;
50 | n5.next = n6;
51 | n6.next = n4;
52 |
53 | System.out.println(isHaveCircleAndMeetWhere(n1));
54 | }
55 |
56 | }
57 |
--------------------------------------------------------------------------------
/algorithm/MergeSort.java:
--------------------------------------------------------------------------------
1 | public class MergeSort {
2 |
3 | private static void merge(int[] arr, int[] temp, int left, int mid, int right) {
4 | int i = left;
5 | int j = mid + 1;
6 | int t = 0;
7 | while (i <= mid && j <= right) {
8 | if (arr[i] < arr[j]) {
9 | temp[t++] = arr[i++];
10 | } else {
11 | temp[t++] = arr[j++];
12 | }
13 | }
14 | while (i <= mid) {
15 | temp[t++] = arr[i++];
16 | }
17 | while (j <= right) {
18 | temp[t++] = arr[j++];
19 | }
20 | t = 0;
21 | while (left <= right) {
22 | arr[left++] = temp[t++];
23 | }
24 | }
25 |
26 | private static void sort(int[] arr, int l, int r, int[] temp) {
27 | if (l < r) {
28 | int mid = (l + r) / 2;
29 | sort(arr, l, mid, temp);
30 | sort(arr, mid + 1, r, temp);
31 | merge(arr, temp, l, mid, r);
32 | }
33 | }
34 |
35 | public static void main(String[] args) {
36 | int[] arr = {8, 5, 7, 6, 2, 1, 3};
37 | sort(arr, 0, arr.length - 1, new int[arr.length]);
38 | for (int temp : arr) {
39 | System.out.println(temp + " ");
40 | }
41 | }
42 |
43 |
44 | }
45 |
--------------------------------------------------------------------------------
/algorithm/OrderBinaryTree.java:
--------------------------------------------------------------------------------
1 | package algorithm;
2 |
3 | import java.util.Stack;
4 |
5 | public class OrderBinaryTree {
6 |
7 | static class TreeNode {
8 | TreeNode left;
9 | TreeNode right;
10 | int val;
11 |
12 | public TreeNode(int value) {
13 | this.val = value;
14 | }
15 | }
16 |
17 | private static void preOrder(TreeNode root) {
18 | if (root != null) {
19 | System.out.print(root.val + " ");
20 | preOrder(root.left);
21 | preOrder(root.right);
22 | }
23 | }
24 |
25 | /**
26 | * 1
27 | * 2 3
28 | * 4 5
29 | */
30 | private static void preOrder1(TreeNode root) {
31 | Stack stack = new Stack<>();
32 | TreeNode p = root;
33 | while (p != null || stack.size() > 0) {
34 | while (p != null) {
35 | System.out.println(p.val);
36 | stack.push(p);
37 | p = p.left;
38 | }
39 | TreeNode treeNode = stack.pop();
40 | if (treeNode != null) {
41 | p = treeNode.right;
42 | }
43 | }
44 | }
45 |
46 | private static void inOrder(TreeNode root) {
47 | if (root != null) {
48 | inOrder(root.left);
49 | System.out.print(root.val + " ");
50 | inOrder(root.right);
51 | }
52 | }
53 |
54 | private static void inOrder1(TreeNode root) {
55 | Stack stack = new Stack();
56 | TreeNode p = root;
57 | while (p != null || !stack.empty()) {
58 | while (p != null) {
59 | stack.push(p);
60 | p = p.left;
61 | }
62 | if (!stack.empty()) {
63 | TreeNode temp = stack.pop();
64 | System.out.print(temp + " ");
65 | p = temp.right;
66 | }
67 | }
68 | }
69 |
70 | private static void postOrder(TreeNode root) {
71 | if (root != null) {
72 | postOrder(root.left);
73 | postOrder(root.right);
74 | System.out.print(root.val + " ");
75 | }
76 | }
77 | /**
78 | * 1
79 | * 2 3
80 | * 4 5
81 | */
82 | private static void postOrder1(TreeNode root) {
83 | if (root == null) {
84 | return;
85 | }
86 | Stack stack = new Stack<>();
87 | TreeNode cur, pre = null;
88 |
89 | stack.push(root);
90 |
91 | while (!stack.isEmpty()) {
92 | cur = stack.peek();
93 | if ((cur.left == null && cur.right == null) || (pre != null && (cur.left == pre || cur.right == pre))) {
94 | TreeNode temp = stack.pop();
95 | System.out.println(temp.val);
96 | pre = temp;
97 | } else {
98 | if (cur.right != null) {
99 | stack.push(cur.right);
100 | }
101 | if (cur.left != null) {
102 | stack.push(cur.left);
103 | }
104 | }
105 | }
106 | }
107 |
108 | public static void main(String[] args) {
109 | TreeNode node1 = new TreeNode(1);
110 | TreeNode node2 = new TreeNode(2);
111 | TreeNode node3 = new TreeNode(3);
112 | TreeNode node4 = new TreeNode(4);
113 | TreeNode node5 = new TreeNode(5);
114 |
115 | node1.left = node2;
116 | node1.right = node3;
117 | node2.left = node4;
118 | node2.right = node5;
119 |
120 | postOrder1(node1);
121 | }
122 |
123 | }
124 |
--------------------------------------------------------------------------------
/algorithm/PrintLastK.java:
--------------------------------------------------------------------------------
1 | package algorithm;
2 |
3 | public class PrintLastK {
4 |
5 | static class Node {
6 | Node next;
7 | int value;
8 |
9 | public Node(int value) {
10 | this.value = value;
11 | }
12 | }
13 |
14 | private static int findLastK(Node node, int k) {
15 | if (node == null) {
16 | return -1;
17 | }
18 | Node fastPointer = node;
19 | Node slowPointer = node;
20 |
21 | for (int i = 0; i < k; i++) {
22 | fastPointer = fastPointer.next;
23 | }
24 |
25 | while (fastPointer != null) {
26 | fastPointer = fastPointer.next;
27 | slowPointer = slowPointer.next;
28 | }
29 | return slowPointer.value;
30 | }
31 |
32 |
33 | public static void main(String[] args) {
34 | Node n1 = new Node(1);
35 | Node n2 = new Node(2);
36 | Node n3 = new Node(3);
37 | Node n4 = new Node(4);
38 | Node n5 = new Node(5);
39 | Node n6 = new Node(6);
40 |
41 | n1.next = n2;
42 | n2.next = n3;
43 | n3.next = n4;
44 | n4.next = n5;
45 | n5.next = n6;
46 |
47 | System.out.println(findLastK(n1, 3));
48 | }
49 |
50 |
51 | }
52 |
--------------------------------------------------------------------------------
/algorithm/QuickSort.java:
--------------------------------------------------------------------------------
1 | package algorithm;
2 |
3 | public class QuickSort {
4 | public static void quickSort(int[] arr, int begin, int end) {
5 | if (begin < end) {
6 | int partitionIndex = partition(arr, begin, end);
7 | quickSort(arr, begin, partitionIndex - 1);
8 | quickSort(arr, partitionIndex + 1, end);
9 | }
10 | }
11 |
12 | private static int partition(int[] arr, int begin, int end) {
13 | int pivot = arr[begin];
14 | while (begin < end) {
15 | while (begin < end && arr[end] >= pivot) {
16 | end--;
17 | }
18 | arr[begin] = arr[end];
19 | while (begin < end && arr[begin] <= pivot) {
20 | begin++;
21 | }
22 | arr[end] = arr[begin];
23 | }
24 | arr[begin] = pivot;
25 | return begin;
26 | }
27 |
28 |
29 | public static void main(String[] args) {
30 | int[] arr = {8, 5, 7, 6, 2, 1, 3};
31 | quickSort(arr, 0, arr.length - 1);
32 | for (int i = 0; i < arr.length; i++) {
33 | System.out.println(arr[i] + " ");
34 | }
35 | }
36 | }
37 |
--------------------------------------------------------------------------------
/algorithm/ReverseNode.java:
--------------------------------------------------------------------------------
1 | package algorithm;
2 |
3 | public class ReverseNode {
4 |
5 | static class Node {
6 | Node next;
7 | int value;
8 |
9 | public Node(Node next, int value) {
10 | this.next = next;
11 | this.value = value;
12 | }
13 |
14 | }
15 |
16 | public static Node reverse(Node head) {
17 | if (head == null) {
18 | return null;
19 | }
20 | Node result = new Node(null, 0);
21 | Node cur = head;
22 | while (cur != null) {
23 | Node temp = cur;
24 | cur = cur.next;
25 | temp.next = result.next;
26 | result.next = temp;
27 | }
28 | return result.next;
29 | }
30 |
31 |
32 | public static void main(String[] args) {
33 | Node node1 = new Node(null, 1);
34 | Node node2 = new Node(node1, 2);
35 | Node node3 = new Node(node2, 3);
36 | Node node4 = new Node(node3, 4);
37 | Node node5 = new Node(node4, 5);
38 | print(node5);
39 | print(reverse(node5));
40 | }
41 |
42 | public static void print(Node head) {
43 | while (head != null) {
44 | System.out.print(head.value + "\t");
45 | head = head.next;
46 | }
47 | System.out.println();
48 | }
49 |
50 |
51 | }
52 |
--------------------------------------------------------------------------------
/algorithm/Singleton.java:
--------------------------------------------------------------------------------
1 | package algorithm;
2 |
3 | class Singleton {
4 |
5 | private static Singleton instance = null;
6 |
7 | private Singleton() {
8 |
9 | }
10 |
11 | public static Singleton getInstance() {
12 | if (instance == null) {
13 | synchronized (Singleton.class) {
14 | if (instance == null) {
15 | instance = new Singleton();
16 | }
17 | }
18 | }
19 | return instance;
20 | }
21 | }
22 |
--------------------------------------------------------------------------------
/algorithm/TwoThreadPrintNumber.java:
--------------------------------------------------------------------------------
1 | package algorithm;
2 |
3 | import java.util.concurrent.locks.ReentrantLock;
4 |
5 | public class TwoThreadPrintNumber {
6 |
7 | static class MyThread extends Thread {
8 |
9 | int a;
10 |
11 | public MyThread(int a){
12 | this.a = a;
13 | }
14 |
15 | static ReentrantLock lock = new ReentrantLock();
16 | static int i = 0;
17 |
18 | @Override
19 | public void run() {
20 | super.run();
21 |
22 | while (true) {
23 |
24 | lock.lock();
25 | if (i >= 10){
26 | lock.unlock();
27 | break;
28 | }
29 |
30 | if (i % 2 == a) {
31 | System.out.println(i + " " + this);
32 | i++;
33 | }
34 | lock.unlock();
35 |
36 |
37 | }
38 |
39 | }
40 | }
41 |
42 | public static void main(String[] args) {
43 | MyThread thread = new MyThread(0);
44 | MyThread thread2 = new MyThread(1);
45 | thread.start();
46 | thread2.start();
47 | }
48 |
49 | }
50 |
--------------------------------------------------------------------------------
/algorithm/TwoThreadPrintNumberV2.java:
--------------------------------------------------------------------------------
1 | package algorithm;
2 |
3 | import java.util.concurrent.Semaphore;
4 |
5 | public class TwoThreadPrintNumberV2 {
6 |
7 | private static Semaphore s1 = new Semaphore(1);
8 | private static Semaphore s2 = new Semaphore(0);
9 | private static int count = 0;
10 |
11 | private static void printABC(Semaphore currentThread, Semaphore nextThread) {
12 | for (int i = 0; i < 5; i++) {
13 | try {
14 | currentThread.acquire();
15 | System.out.println(count++ + " " + Thread.currentThread().getName());
16 | nextThread.release();
17 | } catch (InterruptedException e) {
18 | e.printStackTrace();
19 | }
20 | }
21 |
22 | }
23 |
24 | public static void main(String[] args) throws InterruptedException {
25 | new Thread(() -> printABC(s1, s2), "A").start();
26 | new Thread(() -> printABC(s2, s1), "B").start();
27 | }
28 |
29 | }
30 |
--------------------------------------------------------------------------------
/algorithm/leetcode/l100/SameTree.java:
--------------------------------------------------------------------------------
1 | package algorithm.leetcode.l100;
2 |
3 | public class SameTree {
4 |
5 | public class TreeNode {
6 | int val;
7 | TreeNode left;
8 | TreeNode right;
9 |
10 | }
11 |
12 |
13 | public boolean isSameTree(TreeNode p, TreeNode q) {
14 | if (p == null || q == null) {
15 | return p == q;
16 | }
17 | return p.val == q.val && isSameTree(p.left, q.left) && isSameTree(p.right, q.right);
18 | }
19 |
20 | }
21 |
--------------------------------------------------------------------------------
/algorithm/leetcode/l101/SymmetricTree.java:
--------------------------------------------------------------------------------
1 | package algorithm.leetcode.l101;
2 |
3 | public class SymmetricTree {
4 |
5 |
6 | public class TreeNode {
7 | int val;
8 | TreeNode left;
9 | TreeNode right;
10 | }
11 |
12 |
13 | public boolean isSymmetric(TreeNode root) {
14 | return isSymmetric(root.left, root.right);
15 | }
16 |
17 | private boolean isSymmetric(TreeNode left, TreeNode right) {
18 | if (left == null || right == null) {
19 | return left == right;
20 | }
21 | return left.val == right.val && isSymmetric(left.left, right.right) && isSymmetric(left.right, right.left);
22 | }
23 |
24 | }
25 |
--------------------------------------------------------------------------------
/algorithm/leetcode/l102/BinaryTreeLevelOrderTraversal.java:
--------------------------------------------------------------------------------
1 | package algorithm.leetcode.l102;
2 |
3 | import java.util.ArrayList;
4 | import java.util.List;
5 |
6 | public class BinaryTreeLevelOrderTraversal {
7 |
8 | public class TreeNode {
9 | int val;
10 | TreeNode left;
11 | TreeNode right;
12 | }
13 |
14 | public List> levelOrder(TreeNode root) {
15 | List> result = new ArrayList<>();
16 | if (root == null){
17 | return result;
18 | }
19 | List queue = new ArrayList<>();
20 | queue.add(root);
21 | while (queue.size() > 0) {
22 | int size = queue.size();
23 | List singleResult = new ArrayList<>();
24 | for (int i = 0; i < size; i++) {
25 | TreeNode temp = queue.remove(0);
26 | singleResult.add(temp.val);
27 | if (temp.left != null) {
28 | queue.add(temp.left);
29 | }
30 | if (temp.right != null) {
31 | queue.add(temp.right);
32 | }
33 | }
34 | result.add(singleResult);
35 | }
36 | return result;
37 | }
38 |
39 |
40 | }
41 |
--------------------------------------------------------------------------------
/algorithm/leetcode/l103/BinaryTreeZigzagLevelOrderTraversal.java:
--------------------------------------------------------------------------------
1 | package algorithm.leetcode.l103;
2 |
3 |
4 | import algorithm.leetcode.l102.BinaryTreeLevelOrderTraversal;
5 |
6 | import java.util.ArrayList;
7 | import java.util.Collections;
8 | import java.util.List;
9 |
10 | public class BinaryTreeZigzagLevelOrderTraversal {
11 |
12 | public class TreeNode {
13 | int val;
14 | TreeNode left;
15 | TreeNode right;
16 | }
17 |
18 | public List> zigzagLevelOrder(TreeNode root) {
19 | List> result = new ArrayList<>();
20 | if (root == null){
21 | return result;
22 | }
23 | List queue = new ArrayList<>();
24 | queue.add(root);
25 | boolean even = false;
26 | while (queue.size() > 0) {
27 | int size = queue.size();
28 | List singleResult = new ArrayList<>();
29 | for (int i = 0; i < size; i++) {
30 | TreeNode temp = queue.remove(0);
31 | singleResult.add(temp.val);
32 | if (temp.left != null) {
33 | queue.add(temp.left);
34 | }
35 | if (temp.right != null) {
36 | queue.add(temp.right);
37 | }
38 | }
39 | if (even){
40 | Collections.reverse(singleResult);
41 | result.add(singleResult);
42 | }else {
43 | result.add(singleResult);
44 | }
45 | even = !even;
46 |
47 | }
48 | return result;
49 | }
50 |
51 |
52 | }
53 |
--------------------------------------------------------------------------------
/algorithm/leetcode/l104/MaximumDepthOfBinaryTree.java:
--------------------------------------------------------------------------------
1 | package algorithm.leetcode.l104;
2 |
3 | public class MaximumDepthOfBinaryTree {
4 |
5 |
6 | public static class TreeNode {
7 | int val;
8 | TreeNode left;
9 | TreeNode right;
10 |
11 | TreeNode(int val) {
12 | this.val = val;
13 | }
14 | }
15 |
16 | public int maxDepth(TreeNode root) {
17 | if (root == null) {
18 | return 0;
19 | }
20 | int left = maxDepth(root.left);
21 | int right = maxDepth(root.right);
22 | return Math.max(left, right) + 1;
23 | }
24 |
25 | public static void main(String[] args) {
26 | TreeNode treeNode1 = new TreeNode(1);
27 | TreeNode treeNode2 = new TreeNode(2);
28 | TreeNode treeNode3 = new TreeNode(3);
29 | TreeNode treeNode4 = new TreeNode(4);
30 | TreeNode treeNode5 = new TreeNode(5);
31 | treeNode1.left = treeNode2;
32 | treeNode1.right = treeNode3;
33 | treeNode2.left = treeNode4;
34 | treeNode2.right = treeNode5;
35 | MaximumDepthOfBinaryTree maximumDepthOfBinaryTree = new MaximumDepthOfBinaryTree();
36 | System.out.println(maximumDepthOfBinaryTree.maxDepth(treeNode1));
37 | }
38 |
39 |
40 | }
41 |
--------------------------------------------------------------------------------
/algorithm/leetcode/l1071/GreatestCommonDivisorOfStrings.java:
--------------------------------------------------------------------------------
1 | package algorithm.leetcode.l1071;
2 |
3 | /**
4 | * ...
5 | */
6 | public class GreatestCommonDivisorOfStrings {
7 |
8 | public String gcdOfStrings(String str1, String str2) {
9 | if (!(str1 + str2).equals(str2 + str1)) {
10 | return "";
11 | }
12 | int length = gcd(str1.length(), str2.length());
13 | return str1.substring(0, length);
14 | }
15 |
16 |
17 | public int gcd(int num1, int num2) {
18 | while (num2 != 0) {
19 | int temp = num1;
20 | num1 = num2;
21 | num2 = temp % num2;
22 | }
23 | return num1;
24 | }
25 |
26 |
27 | public static void main(String[] args) {
28 | GreatestCommonDivisorOfStrings greatestCommonDivisorOfStrings = new GreatestCommonDivisorOfStrings();
29 | System.out.println(greatestCommonDivisorOfStrings.gcdOfStrings("ABCABC", "ABC"));
30 | }
31 |
32 |
33 | }
34 |
--------------------------------------------------------------------------------
/algorithm/leetcode/l11/ContainerWithMostWater.java:
--------------------------------------------------------------------------------
1 | package algorithm.leetcode.l11;
2 |
3 | public class ContainerWithMostWater {
4 |
5 | public int maxArea(int[] height) {
6 | int maxArea = 0;
7 | int left = 0;
8 | int right = height.length - 1;
9 | while (left < right) {
10 | maxArea = Math.max((right - left) * Math.min(height[left], height[right]), maxArea);
11 | if (height[left] < height[right]) {
12 | left++;
13 | } else {
14 | right--;
15 | }
16 | }
17 | return maxArea;
18 | }
19 |
20 |
21 | }
22 |
--------------------------------------------------------------------------------
/algorithm/leetcode/l110/BalancedBinaryTree.java:
--------------------------------------------------------------------------------
1 | package algorithm.leetcode.l110;
2 |
3 | public class BalancedBinaryTree {
4 |
5 |
6 | public class TreeNode {
7 | int val;
8 | TreeNode left;
9 | TreeNode right;
10 | }
11 |
12 |
13 | public boolean isBalanced(TreeNode root) {
14 | return isBalancedInternal(root) != -1;
15 | }
16 |
17 | public int isBalancedInternal(TreeNode root) {
18 | if (root == null) {
19 | return 0;
20 | }
21 | int left = isBalancedInternal(root.left);
22 | int right = isBalancedInternal(root.right);
23 | if (left == -1 || right == -1 || Math.abs(left - right) > 1) {
24 | return -1;
25 | } else {
26 | return Math.max(left, right) + 1;
27 | }
28 | }
29 |
30 |
31 | }
32 |
--------------------------------------------------------------------------------
/algorithm/leetcode/l1137/NThTribonacciNumber.java:
--------------------------------------------------------------------------------
1 | package algorithm.leetcode.l1137;
2 |
3 | public class NThTribonacciNumber {
4 |
5 | //0 1 1 2 4 8
6 | public int tribonacci(int n) {
7 | if (n <= 0) {
8 | return 0;
9 | }
10 | if (n == 1 || n == 2) {
11 | return 1;
12 | }
13 | int p = 0;
14 | int q = 1;
15 | int r = 1;
16 | int result = 0;
17 |
18 | for (int i = 2; i < n; i++) {
19 | result = p + q + r;
20 | p = q;
21 | q = r;
22 | r = result;
23 |
24 | }
25 | return result;
26 | }
27 |
28 |
29 | public static void main(String[] args) {
30 | NThTribonacciNumber tribonacci = new NThTribonacciNumber();
31 | System.out.printf(tribonacci.tribonacci(4) + "");
32 | }
33 |
34 | }
35 |
--------------------------------------------------------------------------------
/algorithm/leetcode/l1161/MaximumLevelSumOfABinaryTree.java:
--------------------------------------------------------------------------------
1 | package algorithm.leetcode.l1161;
2 |
3 | import java.util.ArrayList;
4 | import java.util.List;
5 |
6 | public class MaximumLevelSumOfABinaryTree {
7 |
8 |
9 | public static class TreeNode {
10 | int val;
11 | TreeNode left;
12 | TreeNode right;
13 |
14 | TreeNode() {
15 | }
16 |
17 | TreeNode(int val) {
18 | this.val = val;
19 | }
20 |
21 | TreeNode(int val, TreeNode left, TreeNode right) {
22 | this.val = val;
23 | this.left = left;
24 | this.right = right;
25 | }
26 | }
27 |
28 |
29 | public int maxLevelSum(TreeNode root) {
30 | if (root == null) {
31 | return 0;
32 | }
33 | List list = new ArrayList<>();
34 | list.add(root);
35 | int level = 0;
36 | int maxLevel = 1;
37 | int maxSum = Integer.MIN_VALUE;
38 | while (list.size() != 0) {
39 | int size = list.size();
40 | int sum = 0;
41 | level++;
42 | for (int i = 0; i < size; i++) {
43 | TreeNode temp = list.remove(0);
44 | if (temp.left != null) {
45 | list.add(temp.left);
46 | }
47 | if (temp.right != null) {
48 | list.add(temp.right);
49 | }
50 | sum = sum + temp.val;
51 | if (i == size - 1 && sum > maxSum) {
52 | maxSum = sum;
53 | maxLevel = level;
54 | }
55 | }
56 | }
57 | return maxLevel;
58 | }
59 |
60 | public static void main(String[] args) {
61 | TreeNode treeNode1 = new TreeNode(989);
62 | TreeNode treeNode2 = new TreeNode(10250);
63 | TreeNode treeNode3 = new TreeNode(98693);
64 | TreeNode treeNode4 = new TreeNode(-89388);
65 | TreeNode treeNode5 = new TreeNode(-32127);
66 |
67 | treeNode1.right = treeNode2;
68 | treeNode2.left = treeNode3;
69 | treeNode2.right = treeNode4;
70 | treeNode4.right = treeNode5;
71 |
72 | MaximumLevelSumOfABinaryTree maximumLevelSumOfABinaryTree = new MaximumLevelSumOfABinaryTree();
73 | System.out.println(maximumLevelSumOfABinaryTree.maxLevelSum(treeNode1));
74 |
75 |
76 | }
77 |
78 | }
79 |
--------------------------------------------------------------------------------
/algorithm/leetcode/l124/BinaryTreeMaximumPathSum.java:
--------------------------------------------------------------------------------
1 | package algorithm.leetcode.l124;
2 |
3 | public class BinaryTreeMaximumPathSum {
4 |
5 |
6 | public class TreeNode {
7 | int val;
8 | TreeNode left;
9 | TreeNode right;
10 | }
11 |
12 | private int max = Integer.MIN_VALUE;
13 |
14 | public int maxPathSum(TreeNode root) {
15 | maxPathSumInternal(root);
16 | return max;
17 | }
18 |
19 | public int maxPathSumInternal(TreeNode root) {
20 | if (root == null) {
21 | return 0;
22 | }
23 | int leftMax = Math.max(maxPathSumInternal(root.left), 0);
24 | int rightMax = Math.max(maxPathSumInternal(root.right), 0);
25 | max = Math.max(leftMax + rightMax + root.val, max);
26 | return Math.max(leftMax + root.val, rightMax + root.val);
27 | }
28 |
29 | }
30 |
--------------------------------------------------------------------------------
/algorithm/leetcode/l131/PalindromePartitioning.java:
--------------------------------------------------------------------------------
1 | package algorithm.leetcode.l131;
2 |
3 | import java.util.ArrayList;
4 | import java.util.List;
5 |
6 | public class PalindromePartitioning {
7 |
8 |
9 | private final List> ans = new ArrayList<>();
10 | private final List path = new ArrayList<>();
11 | private String s;
12 |
13 | public List> partition(String s) {
14 | this.s = s;
15 | dfs(0);
16 | return ans;
17 | }
18 |
19 | private boolean isPalindrome(int left, int right) {
20 | while (left < right)
21 | if (s.charAt(left++) != s.charAt(right--))
22 | return false;
23 | return true;
24 | }
25 |
26 | private void dfs(int i) {
27 | if (i == s.length()) {
28 | ans.add(new ArrayList<>(path));
29 | return;
30 | }
31 | for (int j = i; j < s.length(); j++) {
32 | if (isPalindrome(i, j)) {
33 | path.add(s.substring(i, j + 1));
34 | dfs(j + 1);
35 | path.remove(path.size() - 1);
36 | }
37 | }
38 | }
39 |
40 |
41 | }
42 |
--------------------------------------------------------------------------------
/algorithm/leetcode/l1372/LongestZigzagPathInABinaryTree.java:
--------------------------------------------------------------------------------
1 | package algorithm.leetcode.l1372;
2 |
3 | public class LongestZigzagPathInABinaryTree {
4 |
5 | public class TreeNode {
6 | int val;
7 | TreeNode left;
8 | TreeNode right;
9 |
10 | TreeNode() {
11 | }
12 |
13 | TreeNode(int val) {
14 | this.val = val;
15 | }
16 |
17 | TreeNode(int val, TreeNode left, TreeNode right) {
18 | this.val = val;
19 | this.left = left;
20 | this.right = right;
21 | }
22 | }
23 |
24 | private int maxLength = 0;
25 |
26 | public int longestZigZag(TreeNode root) {
27 | if (root == null) {
28 | return 0;
29 | }
30 | dfs(root, true, 0);
31 | dfs(root, false, 0);
32 | return maxLength;
33 | }
34 |
35 | public void dfs(TreeNode root, boolean left, int len) {
36 | maxLength = Math.max(maxLength, len);
37 | if (left) {
38 | if (root.left != null) {
39 | dfs(root.left, false, len + 1);
40 | }
41 | if (root.right != null) {
42 | dfs(root.right, true, 1);
43 | }
44 | } else {
45 | if (root.right != null) {
46 | dfs(root.right, true, len + 1);
47 | }
48 | if (root.left != null) {
49 | dfs(root.left, false, 1);
50 | }
51 | }
52 | }
53 |
54 |
55 | }
56 |
--------------------------------------------------------------------------------
/algorithm/leetcode/l141/LinkedListCycle.java:
--------------------------------------------------------------------------------
1 | package algorithm.leetcode.l141;
2 |
3 | public class LinkedListCycle {
4 |
5 | class ListNode {
6 | int val;
7 | ListNode next;
8 | }
9 |
10 |
11 | public boolean hasCycle(ListNode head) {
12 | ListNode slow = head;
13 | ListNode fast = head;
14 |
15 | while (fast != null && fast.next != null) {
16 | fast = fast.next.next;
17 | slow = slow.next;
18 | if (fast == slow){
19 | return true;
20 | }
21 | }
22 | return false;
23 | }
24 |
25 | }
26 |
--------------------------------------------------------------------------------
/algorithm/leetcode/l142/LinkedListCycleII.java:
--------------------------------------------------------------------------------
1 | package algorithm.leetcode.l142;
2 |
3 | import algorithm.leetcode.l141.LinkedListCycle;
4 |
5 | public class LinkedListCycleII {
6 |
7 | class ListNode {
8 | int val;
9 | ListNode next;
10 | }
11 |
12 | public ListNode detectCycle(ListNode head) {
13 | ListNode slow = head;
14 | ListNode fast = head;
15 |
16 | while (fast != null && fast.next != null) {
17 | fast = fast.next.next;
18 | slow = slow.next;
19 | if (fast == slow){
20 | while (slow != head){
21 | slow = slow.next;
22 | head = head.next;
23 | }
24 | return head;
25 | }
26 | }
27 | return null;
28 | }
29 | }
30 |
--------------------------------------------------------------------------------
/algorithm/leetcode/l143/ReorderList.java:
--------------------------------------------------------------------------------
1 | package algorithm.leetcode.l143;
2 |
3 | import java.util.List;
4 |
5 | public class ReorderList {
6 |
7 | public class ListNode {
8 | int val;
9 | ListNode next;
10 | }
11 |
12 |
13 | public void reorderList(ListNode head) {
14 | ListNode mid = middleNode(head);
15 | ListNode head2 = reverseNode(mid);
16 |
17 | while (head2.next != null){
18 | ListNode next = head.next;
19 | ListNode next2 = head2.next;
20 |
21 | head.next = head2;
22 | head2.next = next;
23 |
24 | head = next;
25 | head2 = next2;
26 | }
27 | }
28 |
29 | //链表的中间节点
30 | private ListNode middleNode(ListNode head){
31 | ListNode slow = head;
32 | ListNode fast = head;
33 |
34 | while (fast != null && fast.next != null){
35 | slow = slow.next;
36 | fast = fast.next.next;
37 | }
38 | return slow;
39 | }
40 |
41 | //反转链表
42 | private ListNode reverseNode(ListNode head){
43 | ListNode pre = null;
44 | ListNode cur = head;
45 |
46 | while (cur != null){
47 | ListNode next = cur.next;
48 | cur.next = pre;
49 | pre = cur;
50 | cur = next;
51 | }
52 | return pre;
53 | }
54 | }
55 |
--------------------------------------------------------------------------------
/algorithm/leetcode/l1431/KidsWithTheGreatestNumberOfCandies.java:
--------------------------------------------------------------------------------
1 | package algorithm.leetcode.l1431;
2 |
3 | import java.util.ArrayList;
4 | import java.util.List;
5 |
6 | public class KidsWithTheGreatestNumberOfCandies {
7 |
8 | public List kidsWithCandies(int[] candies, int extraCandies) {
9 | List results = new ArrayList<>();
10 | int currentGreatestNumber = 0;
11 | for (int i = 0; i < candies.length; i++) {
12 | currentGreatestNumber = Math.max(currentGreatestNumber, candies[i]);
13 | }
14 | for (int i = 0; i < candies.length; i++) {
15 | if (candies[i] + extraCandies < currentGreatestNumber) {
16 | results.add(false);
17 | } else {
18 | results.add(true);
19 | }
20 | }
21 | return results;
22 | }
23 |
24 |
25 | }
26 |
--------------------------------------------------------------------------------
/algorithm/leetcode/l144/BinaryTreePreorderTraversal.java:
--------------------------------------------------------------------------------
1 | package algorithm.leetcode.l144;
2 |
3 | import algorithm.OrderBinaryTree;
4 |
5 | import java.util.ArrayList;
6 | import java.util.List;
7 |
8 | public class BinaryTreePreorderTraversal {
9 |
10 |
11 | public static class TreeNode {
12 | int val;
13 | TreeNode left;
14 | TreeNode right;
15 | public TreeNode(int value) {
16 | this.val = value;
17 | }
18 | }
19 |
20 | public List preorderTraversal(TreeNode root) {
21 | List list = new ArrayList<>();
22 | TreeNode p = root;
23 | List stack = new ArrayList<>();
24 | while (p != null || stack.size() > 0) {
25 | while (p != null) {
26 | System.out.println(p.val);
27 | list.add(p.val);
28 | stack.add(p);
29 | p = p.left;
30 | }
31 | TreeNode temp = stack.remove(stack.size() - 1);
32 | if (temp != null) {
33 | p = temp.right;
34 | }
35 | }
36 | return list;
37 | }
38 |
39 | public static void main(String[] args) {
40 | TreeNode node1 = new TreeNode(1);
41 | TreeNode node2 = new TreeNode(2);
42 | TreeNode node3 = new TreeNode(3);
43 | TreeNode node4 = new TreeNode(4);
44 | TreeNode node5 = new TreeNode(5);
45 |
46 | node1.left = node2;
47 | node1.right = node3;
48 | node2.left = node4;
49 | node2.right = node5;
50 |
51 | // preorderTraversal(node1);
52 | }
53 |
54 | }
55 |
--------------------------------------------------------------------------------
/algorithm/leetcode/l1448/CountGoodNodesInBinaryTree.java:
--------------------------------------------------------------------------------
1 | package algorithm.leetcode.l1448;
2 |
3 | public class CountGoodNodesInBinaryTree {
4 |
5 | public class TreeNode {
6 | int val;
7 | TreeNode left;
8 | TreeNode right;
9 |
10 | TreeNode() {
11 | }
12 |
13 | TreeNode(int val) {
14 | this.val = val;
15 | }
16 |
17 | TreeNode(int val, TreeNode left, TreeNode right) {
18 | this.val = val;
19 | this.left = left;
20 | this.right = right;
21 | }
22 | }
23 |
24 |
25 | public int goodNodes(TreeNode root) {
26 | return dfs(root, root.val);
27 | }
28 |
29 | public int dfs(TreeNode root, int max) {
30 | if (root == null) {
31 | return 0;
32 | }
33 | int goodNum = root.val >= max ? 1 : 0;
34 | max = Math.max(max, root.val);
35 | goodNum += dfs(root.left, max);
36 | goodNum += dfs(root.right, max);
37 | return goodNum;
38 | }
39 |
40 |
41 | }
42 |
--------------------------------------------------------------------------------
/algorithm/leetcode/l145/BinaryTreePostorderTraversal.java:
--------------------------------------------------------------------------------
1 | package algorithm.leetcode.l145;
2 |
3 | import java.util.ArrayList;
4 | import java.util.List;
5 | import java.util.Stack;
6 |
7 | public class BinaryTreePostorderTraversal {
8 |
9 |
10 | public static class TreeNode {
11 | int val;
12 | TreeNode left;
13 | TreeNode right;
14 |
15 | TreeNode(int val) {
16 | this.val = val;
17 | }
18 | }
19 |
20 |
21 | public List postorderTraversal(TreeNode root) {
22 | List result = new ArrayList<>();
23 | if (root == null) {
24 | return result;
25 | }
26 | Stack stack = new Stack<>();
27 | TreeNode cur, pre = null;
28 |
29 | stack.push(root);
30 | while (!stack.isEmpty()) {
31 | cur = stack.peek();
32 | if ((cur.left == null && cur.right == null) || (pre != null && (cur.left == pre || cur.right == pre))) {
33 | TreeNode temp = stack.pop();
34 | result.add(temp.val);
35 | System.out.println(temp.val);
36 | pre = temp;
37 | } else {
38 | if (cur.right != null) {
39 | stack.push(cur.right);
40 | }
41 | if (cur.left != null) {
42 | stack.push(cur.left);
43 | }
44 | }
45 | }
46 | return result;
47 | }
48 |
49 | public static void main(String[] args) {
50 | TreeNode node1 = new TreeNode(1);
51 | TreeNode node2 = new TreeNode(2);
52 | TreeNode node3 = new TreeNode(3);
53 | TreeNode node4 = new TreeNode(4);
54 | TreeNode node5 = new TreeNode(5);
55 |
56 | node1.left = node2;
57 | node1.right = node3;
58 | node2.left = node4;
59 | node2.right = node5;
60 |
61 | BinaryTreePostorderTraversal binaryTreePostorderTraversal = new BinaryTreePostorderTraversal();
62 | binaryTreePostorderTraversal.postorderTraversal(node1);
63 |
64 | }
65 | }
66 |
--------------------------------------------------------------------------------
/algorithm/leetcode/l15/Sum3.java:
--------------------------------------------------------------------------------
1 | package algorithm.leetcode.l15;
2 |
3 | import java.util.ArrayList;
4 | import java.util.Arrays;
5 | import java.util.List;
6 |
7 | public class Sum3 {
8 |
9 | public List> threeSum(int[] nums) {
10 | Arrays.sort(nums);
11 | List> res = new ArrayList<>();
12 | for (int i = 0; i < nums.length - 2; i++) {
13 | int s = nums[i];
14 | if (i > 0 && s == nums[i - 1]) {
15 | continue;
16 | }
17 | int begin = i + 1;
18 | int end = nums.length - 1;
19 | while (begin < end) {
20 | int sum = s + nums[begin] + nums[end];
21 | if (sum > 0) {
22 | end--;
23 | } else if (sum < 0) {
24 | begin++;
25 | } else {
26 | List temp = new ArrayList<>();
27 | temp.add(s);
28 | temp.add(nums[begin]);
29 | temp.add(nums[end]);
30 | res.add(temp);
31 | begin++;
32 | while (begin < end && nums[begin] == nums[begin - 1]) {
33 | begin++;
34 | }
35 | end--;
36 | while (begin < end && nums[end] == nums[end + 1]) {
37 | end--;
38 | }
39 | }
40 | }
41 | }
42 | return res;
43 | }
44 |
45 | }
46 |
--------------------------------------------------------------------------------
/algorithm/leetcode/l151/ReverseWordsInAString.java:
--------------------------------------------------------------------------------
1 | package algorithm.leetcode.l151;
2 |
3 | public class ReverseWordsInAString {
4 |
5 |
6 | public String reverseWords(String s) {
7 | if (s == null) {
8 | return "";
9 | }
10 | char[] chars = s.toCharArray();
11 | StringBuilder stringBuilder = new StringBuilder();
12 | StringBuilder temp = new StringBuilder();
13 |
14 | int end = chars.length - 1;
15 | int begin = 0;
16 |
17 | while (chars[end] == ' ') {
18 | end--;
19 | }
20 | while (chars[begin] == ' ') {
21 | begin++;
22 | }
23 | boolean isFirstAppend = true;
24 | while (end >= begin) {
25 | if (chars[end] != ' ') {
26 | temp.insert(0, chars[end]);
27 | } else {
28 | if (temp.length() != 0) {
29 | if (!isFirstAppend) {
30 | stringBuilder.append(' ').append(temp);
31 | } else {
32 | stringBuilder.append(temp);
33 | isFirstAppend = false;
34 | }
35 | temp = new StringBuilder();
36 | }
37 | }
38 | end--;
39 | }
40 | if (stringBuilder.length() == 0) {
41 | stringBuilder.append(temp);
42 | } else {
43 | stringBuilder.append(' ').append(temp);
44 | }
45 | return stringBuilder.toString();
46 | }
47 |
48 | public static void main(String[] args) {
49 | String s = "the sky is blue";
50 | ReverseWordsInAString reverseWordsInAString = new ReverseWordsInAString();
51 | System.out.println(reverseWordsInAString.reverseWords(s));
52 | }
53 |
54 |
55 | }
56 |
--------------------------------------------------------------------------------
/algorithm/leetcode/l153/FindMinimumInRotatedSortedArray.java:
--------------------------------------------------------------------------------
1 | package algorithm.leetcode.l153;
2 |
3 | public class FindMinimumInRotatedSortedArray {
4 |
5 | public int findMin(int[] nums) {
6 | int left = -1;
7 | int right = nums.length - 1;
8 | while (left + 1 < right){
9 | int mid = (left+right)/2;
10 | if (nums[mid] < nums[nums.length -1]){
11 | right = mid;
12 | }else {
13 | left = mid;
14 | }
15 | }
16 | return nums[right];
17 | }
18 |
19 | }
20 |
--------------------------------------------------------------------------------
/algorithm/leetcode/l162/FindPeakElement.java:
--------------------------------------------------------------------------------
1 | package algorithm.leetcode.l162;
2 |
3 | public class FindPeakElement {
4 |
5 | public int findPeakElement(int[] nums) {
6 | int left = -1;
7 | int right = nums.length - 1;
8 |
9 | while (left + 1 < right) {
10 | int mid = (left + right) / 2;
11 | if (nums[mid] > nums[mid + 1]) {
12 | right = mid;
13 | } else {
14 | left = mid;
15 | }
16 | }
17 | return right;
18 | }
19 |
20 |
21 | }
22 |
--------------------------------------------------------------------------------
/algorithm/leetcode/l167/TwoSumIIInput.java:
--------------------------------------------------------------------------------
1 | package algorithm.leetcode.l167;
2 |
3 | public class TwoSumIIInput {
4 |
5 |
6 | public int[] twoSum(int[] numbers, int target) {
7 | int begin = 0;
8 | int end = numbers.length - 1;
9 |
10 | while (begin < end) {
11 | if (numbers[begin] + numbers[end] == target) {
12 | return new int[]{begin + 1, end + 1};
13 | } else if (numbers[begin] + numbers[end] < target) {
14 | begin++;
15 | } else {
16 | end--;
17 | }
18 | }
19 | return new int[2];
20 | }
21 |
22 | }
23 |
--------------------------------------------------------------------------------
/algorithm/leetcode/l17/LetterCombinationsOfAPhoneNumber.java:
--------------------------------------------------------------------------------
1 | package algorithm.leetcode.l17;
2 |
3 | import java.util.ArrayList;
4 | import java.util.List;
5 |
6 | /**
7 | * ...
8 | */
9 | public class LetterCombinationsOfAPhoneNumber {
10 |
11 | String[] mapping = new String[]{"", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
12 |
13 | List result = new ArrayList<>();
14 | private char[] digitsChars;
15 | private char[] path;
16 |
17 | public List letterCombinations(String digits) {
18 | if (digits == null || digits.length() == 0) {
19 | return new ArrayList<>();
20 | }
21 | digitsChars = digits.toCharArray();
22 | path = new char[digits.length()];
23 | dfs(0);
24 | return result;
25 | }
26 |
27 | public void dfs(int depth) {
28 | if (depth == path.length) {
29 | result.add(new String(path));
30 | return;
31 | }
32 | String s = mapping[digitsChars[depth] - '0'];
33 | char[] chars = s.toCharArray();
34 | for (int i = 0; i < chars.length; i++) {
35 | path[depth] = chars[i];
36 | dfs(depth + 1);
37 | }
38 | }
39 |
40 |
41 | public static void main(String[] args) {
42 | LetterCombinationsOfAPhoneNumber number = new LetterCombinationsOfAPhoneNumber();
43 | number.letterCombinations("23");
44 | }
45 | }
46 |
--------------------------------------------------------------------------------
/algorithm/leetcode/l1768/MergeStringsAlternately.java:
--------------------------------------------------------------------------------
1 | package algorithm.leetcode.l1768;
2 |
3 | /**
4 | * ...
5 | */
6 | public class MergeStringsAlternately {
7 |
8 | public String mergeAlternately(String word1, String word2) {
9 | StringBuilder result = new StringBuilder();
10 | int word1Length = word1.length();
11 | int word2Length = word2.length();
12 |
13 | int minLength = Math.min(word1Length, word2Length);
14 | for (int i = 0; i < minLength; i++) {
15 | result.append(word1.charAt(i));
16 | result.append(word2.charAt(i));
17 | }
18 |
19 |
20 | if (word2Length > minLength) {
21 | for (int i = minLength; i < word2Length; i++) {
22 | result.append(word2.charAt(i));
23 | }
24 | }
25 |
26 | if (word1Length > minLength) {
27 | for (int i = minLength; i < word1Length; i++) {
28 | result.append(word1.charAt(i));
29 | }
30 | }
31 |
32 | return result.toString();
33 | }
34 |
35 | public static void main(String[] args) {
36 | MergeStringsAlternately mergeStringsAlternately = new MergeStringsAlternately();
37 | System.out.println(mergeStringsAlternately.mergeAlternately("ab", "pqrs"));
38 | }
39 | }
40 |
--------------------------------------------------------------------------------
/algorithm/leetcode/l19/RemoveNthNodeFromEndOfList.java:
--------------------------------------------------------------------------------
1 | package algorithm.leetcode.l19;
2 |
3 | public class RemoveNthNodeFromEndOfList {
4 |
5 | public class ListNode {
6 | int val;
7 | ListNode next;
8 | }
9 |
10 | //1 -> 2 -> 3 -> 4 -> 5
11 | //dummy -> 1 -> 2 -> 3 -> 4 -> 5
12 | public ListNode removeNthFromEnd(ListNode head, int n) {
13 | ListNode dummy = new ListNode();
14 | dummy.next = head;
15 |
16 | ListNode right = dummy;
17 | ListNode left = dummy;
18 | for (int i = 0; i < n; i++) {
19 | right = right.next;
20 | }
21 | while (right.next != null){
22 | left = left.next;
23 | right = right.next;
24 | }
25 | left.next = left.next.next;
26 | return dummy.next;
27 | }
28 |
29 |
30 | }
31 |
--------------------------------------------------------------------------------
/algorithm/leetcode/l198/HouseRobber.java:
--------------------------------------------------------------------------------
1 | package algorithm.leetcode.l198;
2 |
3 | import java.util.Arrays;
4 |
5 | /**
6 | * ...
7 | */
8 | public class HouseRobber {
9 |
10 | public int rob(int[] nums) {
11 | int n = nums.length;
12 | int f0 = 0;
13 | int f1 = 0;
14 | for (int i = 0; i < nums.length; i++) {
15 | int newF = Math.max(f1, f0 + nums[i]);
16 | f0 = f1;
17 | f1 = newF;
18 | }
19 | return f1;
20 | }
21 |
22 |
23 | public int rob2(int[] nums) {
24 | if (nums.length == 0) {
25 | return 0;
26 | }
27 | if (nums.length == 1) {
28 | return nums[0];
29 | }
30 | if (nums.length == 2) {
31 | return Math.max(nums[0], nums[1]);
32 | }
33 |
34 | int[] dp = new int[nums.length + 1];
35 | dp[0] = 0;
36 | dp[1] = nums[0];
37 |
38 | for (int i = 2; i <= nums.length; i++) {
39 | dp[i] = Math.max(nums[i - 1] + dp[i - 2], dp[i - 1]);
40 | }
41 | return dp[nums.length];
42 | }
43 |
44 |
45 | private int[] cache = null;
46 |
47 | public int rob3(int[] nums) {
48 | cache = new int[nums.length];
49 | Arrays.fill(cache, -1);
50 | return dfs(nums.length - 1, nums);
51 | }
52 |
53 | private int dfs(int i, int[] nums) {
54 | if (i < 0) {
55 | return 0;
56 | }
57 | if (cache[i] != -1) {
58 | return cache[i];
59 | }
60 | int result = Math.max(dfs(i - 1, nums), dfs(i - 2, nums) + nums[i]);
61 | cache[i] = result;
62 | return result;
63 | }
64 |
65 | }
66 |
--------------------------------------------------------------------------------
/algorithm/leetcode/l199/BinaryTreeRightSideView.java:
--------------------------------------------------------------------------------
1 | package algorithm.leetcode.l199;
2 |
3 | import java.util.ArrayList;
4 | import java.util.List;
5 |
6 | public class BinaryTreeRightSideView {
7 |
8 | public class TreeNode {
9 | int val;
10 | TreeNode left;
11 | TreeNode right;
12 |
13 | TreeNode(int val) {
14 | this.val = val;
15 | }
16 | }
17 |
18 | public List rightSideViewV2(TreeNode root) {
19 | List res = new ArrayList<>();
20 | if (root == null) {
21 | return res;
22 | }
23 | List list = new ArrayList<>();
24 | list.add(root);
25 |
26 | while (list.size() > 0) {
27 | int size = list.size();
28 | for (int i = 0; i < size; i++) {
29 | TreeNode temp = list.remove(0);
30 | if (temp.left != null) {
31 | list.add(temp.left);
32 | }
33 | if (temp.right != null) {
34 | list.add(temp.right);
35 | }
36 | if (i == size - 1) {
37 | res.add(temp.val);
38 | }
39 | }
40 | }
41 | return res;
42 | }
43 |
44 | public List rightSideView(TreeNode root) {
45 | rightSideViewInternal(root, 0);
46 | return result;
47 | }
48 |
49 | private List result = new ArrayList<>();
50 |
51 | private void rightSideViewInternal(TreeNode root, int depth) {
52 | if (root == null) {
53 | return;
54 | }
55 | if (depth == result.size()) {
56 | result.add(root.val);
57 | }
58 | rightSideViewInternal(root.right, depth + 1);
59 | rightSideViewInternal(root.left, depth + 1);
60 | }
61 |
62 |
63 | }
64 |
--------------------------------------------------------------------------------
/algorithm/leetcode/l206/ReverseLinkedList.java:
--------------------------------------------------------------------------------
1 | package algorithm.leetcode.l206;
2 |
3 | import java.util.List;
4 |
5 | public class ReverseLinkedList {
6 |
7 | public class ListNode {
8 | int val;
9 | ListNode next;
10 |
11 | ListNode() {
12 | }
13 |
14 | ListNode(int val) {
15 | this.val = val;
16 | }
17 |
18 | ListNode(int val, ListNode next) {
19 | this.val = val;
20 | this.next = next;
21 | }
22 | }
23 |
24 |
25 | public ListNode reverseList(ListNode head) {
26 | ListNode pre = null;
27 | ListNode cur = head;
28 | while (cur != null) {
29 | ListNode next = cur.next;
30 | cur.next = pre;
31 | pre = cur;
32 | cur = next;
33 | }
34 | return pre;
35 | }
36 |
37 | }
38 |
--------------------------------------------------------------------------------
/algorithm/leetcode/l209/MinimumSizeSubArraySum.java:
--------------------------------------------------------------------------------
1 | package algorithm.leetcode.l209;
2 |
3 | /**
4 | * ...
5 | */
6 | public class MinimumSizeSubArraySum {
7 |
8 | public int minSubArrayLen(int target, int[] nums) {
9 | int length = nums.length;
10 | int min = length + 1;
11 |
12 | int left = 0;
13 | int right = 0;
14 | int currentTotal = 0;
15 |
16 | while (right < length) {
17 | currentTotal = currentTotal + nums[right];
18 | while (left <= right && currentTotal - nums[left] >= target) {
19 | currentTotal = currentTotal - nums[left];
20 | left++;
21 | }
22 | if (currentTotal >= target) {
23 | min = Math.min(min, right - left + 1);
24 | }
25 | right++;
26 | }
27 | return min == length + 1 ? 0 : min;
28 | }
29 |
30 | public static void main(String[] args) {
31 | MinimumSizeSubArraySum minimumSizeSubArraySum = new MinimumSizeSubArraySum();
32 | System.out.println(minimumSizeSubArraySum.minSubArrayLen(15, new int[]{1, 2, 3, 4, 5}));
33 | }
34 |
35 | }
36 |
--------------------------------------------------------------------------------
/algorithm/leetcode/l2095/DeleteTheMiddleNodeOfALinkedList.java:
--------------------------------------------------------------------------------
1 | package algorithm.leetcode.l2095;
2 |
3 | public class DeleteTheMiddleNodeOfALinkedList {
4 |
5 | public static class ListNode {
6 | int val;
7 | ListNode next;
8 |
9 | ListNode(int val) {
10 | this.val = val;
11 | }
12 | }
13 |
14 | public ListNode deleteMiddle(ListNode head) {
15 | if (head == null || head.next == null) {
16 | return null;
17 | }
18 | ListNode fast = head;
19 | ListNode slow = new ListNode(0);
20 | slow.next = head;
21 |
22 | while (fast.next != null) {
23 | if (fast.next.next != null) {
24 | fast = fast.next.next;
25 | } else {
26 | fast = fast.next;
27 | }
28 | slow = slow.next;
29 | }
30 | slow.next = slow.next.next;
31 | return head;
32 | }
33 |
34 | public static void main(String[] args) {
35 | ListNode l1 = new ListNode(1);
36 | ListNode l2 = new ListNode(3);
37 | ListNode l3 = new ListNode(4);
38 | ListNode l4 = new ListNode(7);
39 | ListNode l5 = new ListNode(1);
40 | ListNode l6 = new ListNode(2);
41 | ListNode l7 = new ListNode(6);
42 | l1.next = l2;
43 | l2.next = l3;
44 | l3.next = l4;
45 | l4.next = l5;
46 | l5.next = l6;
47 | l6.next = l7;
48 |
49 | // while (l1.next != null) {
50 | // System.out.println(l1.val);
51 | // l1 = l1.next;
52 | // }
53 |
54 | DeleteTheMiddleNodeOfALinkedList deleteTheMiddleNodeOfALinkedList = new DeleteTheMiddleNodeOfALinkedList();
55 | ListNode node = deleteTheMiddleNodeOfALinkedList.deleteMiddle(l1);
56 | while (node != null) {
57 | System.out.println(node.val);
58 | node = node.next;
59 | }
60 | }
61 |
62 | }
63 |
--------------------------------------------------------------------------------
/algorithm/leetcode/l216/CombinationSumIII.java:
--------------------------------------------------------------------------------
1 | package algorithm.leetcode.l216;
2 |
3 | import java.util.ArrayList;
4 | import java.util.List;
5 |
6 | public class CombinationSumIII {
7 |
8 | private List> result = new ArrayList<>();
9 | private List path = new ArrayList<>();
10 | private int k;
11 |
12 | public List> combinationSum3(int k, int n) {
13 | this.k = k;
14 | dfs(9, n);
15 | return result;
16 | }
17 |
18 | public void dfs(int i, int t) {
19 | int d = k - path.size();
20 | if (t < 0 || t > (i * 2 - d + 1) * d / 2) {
21 | return;
22 | }
23 | if (path.size() == k) {
24 | result.add(new ArrayList<>(path));
25 | return;
26 | }
27 | for (int j = i; j > d - 1; j--) {
28 | path.add(j);
29 | dfs(j - 1, t - j);
30 | path.remove(path.size() - 1);
31 | }
32 | }
33 |
34 | public static void main(String[] args) {
35 | CombinationSumIII com = new CombinationSumIII();
36 | List> result = com.combinationSum3(3, 7);
37 | System.out.println(result.size());
38 | }
39 |
40 |
41 | }
42 |
--------------------------------------------------------------------------------
/algorithm/leetcode/l22/GenerateParentheses.java:
--------------------------------------------------------------------------------
1 | package algorithm.leetcode.l22;
2 |
3 | import java.util.ArrayList;
4 | import java.util.List;
5 |
6 | public class GenerateParentheses {
7 |
8 | private int m;
9 | private int n;
10 | List result = new ArrayList<>();
11 | char[] path;
12 |
13 | public List generateParenthesis(int n) {
14 | this.m = n * 2;
15 | this.n = n;
16 | this.path = new char[m];
17 | dfs(0, 0);
18 | return result;
19 | }
20 |
21 | public void dfs(int i, int open) {
22 | if (i == m) {
23 | result.add(new String(path));
24 | return;
25 | }
26 | if (open < n) {
27 | path[i] = '(';
28 | dfs(i + 1, open + 1);
29 | }
30 | if (i - open < open) {
31 | path[i] = ')';
32 | dfs(i + 1, open);
33 | }
34 | }
35 |
36 | }
37 |
--------------------------------------------------------------------------------
/algorithm/leetcode/l235/LowestCommonAncestorOfABinarySearchTree.java:
--------------------------------------------------------------------------------
1 | package algorithm.leetcode.l235;
2 |
3 | public class LowestCommonAncestorOfABinarySearchTree {
4 |
5 | public class TreeNode {
6 | int val;
7 | TreeNode left;
8 | TreeNode right;
9 | }
10 |
11 |
12 | public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
13 | int val = root.val;
14 | if (p.val < val && q.val < val) {
15 | return lowestCommonAncestor(root.left, p, q);
16 | }
17 | if (p.val > val && q.val > val) {
18 | return lowestCommonAncestor(root.right, p, q);
19 | }
20 | return root;
21 | }
22 |
23 |
24 | }
25 |
--------------------------------------------------------------------------------
/algorithm/leetcode/l236/LowestCommonAncestorOfABinaryTree.java:
--------------------------------------------------------------------------------
1 | package algorithm.leetcode.l236;
2 |
3 | public class LowestCommonAncestorOfABinaryTree {
4 |
5 | public class TreeNode {
6 | int val;
7 | TreeNode left;
8 | TreeNode right;
9 | }
10 |
11 | public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
12 | if (root == null || root == p || root == q) {
13 | return root;
14 | }
15 | TreeNode left = lowestCommonAncestor(root.left, p, q);
16 | TreeNode right = lowestCommonAncestor(root.right, p, q);
17 | if (left != null && right != null) {
18 | return root;
19 | }
20 | if (left != null) {
21 | return left;
22 | } else {
23 | return right;
24 | }
25 | }
26 |
27 |
28 | }
29 |
--------------------------------------------------------------------------------
/algorithm/leetcode/l237/DeleteNodeInALinkedList.java:
--------------------------------------------------------------------------------
1 | package algorithm.leetcode.l237;
2 |
3 | public class DeleteNodeInALinkedList {
4 |
5 |
6 | public class ListNode {
7 | int val;
8 | ListNode next;
9 | }
10 |
11 |
12 | public void deleteNode(ListNode node) {
13 | node.val = node.next.val;
14 | node.next = node.next.next;
15 | }
16 | }
17 |
--------------------------------------------------------------------------------
/algorithm/leetcode/l25/ReverseNodesInKGroup.java:
--------------------------------------------------------------------------------
1 | package algorithm.leetcode.l25;
2 |
3 | public class ReverseNodesInKGroup {
4 |
5 |
6 | public class ListNode {
7 | int val;
8 | ListNode next;
9 | }
10 |
11 | public ListNode reverseKGroup(ListNode head, int k) {
12 | int n = 0;
13 | ListNode cur = head;
14 | while (cur != null) {
15 | n++;
16 | cur = cur.next;
17 | }
18 |
19 | ListNode dummy = new ListNode();
20 | dummy.next = head;
21 |
22 | ListNode p0 = dummy;
23 | ListNode pre = null;
24 |
25 | cur = p0.next;
26 | while (n >= k) {
27 | n = n - k;
28 | for (int i = 0; i < k; i++) {
29 | ListNode next = cur.next;
30 | cur.next = pre;
31 | pre = cur;
32 | cur = next;
33 | }
34 | ListNode next = p0.next;
35 | p0.next.next = cur;
36 | p0.next = pre;
37 | p0 = next;
38 | }
39 | return dummy.next;
40 | }
41 |
42 |
43 | }
44 |
--------------------------------------------------------------------------------
/algorithm/leetcode/l3/LongestSubStringWithoutRepeatingCharacters.java:
--------------------------------------------------------------------------------
1 | package algorithm.leetcode.l3;
2 |
3 | import java.util.HashMap;
4 | import java.util.Map;
5 |
6 | public class LongestSubStringWithoutRepeatingCharacters {
7 |
8 | public int lengthOfLongestSubstring(String s) {
9 | Map map = new HashMap<>();
10 | int left = 0;
11 | int result = 0;
12 | char[] chars = s.toCharArray();
13 |
14 | for (int right = 0; right < chars.length; right++) {
15 | map.put(chars[right], map.getOrDefault(chars[right], 0) + 1);
16 | while (map.getOrDefault(chars[right], 0) > 1) {
17 | map.put(chars[left], map.getOrDefault(chars[left], 0) - 1);
18 | left++;
19 | }
20 | result = Math.max(result, right - left + 1);
21 | }
22 | return result;
23 | }
24 |
25 |
26 | }
27 |
--------------------------------------------------------------------------------
/algorithm/leetcode/l300/LongestIncreasingSubsequence.java:
--------------------------------------------------------------------------------
1 | package algorithm.leetcode.l300;
2 |
3 | import java.util.ArrayList;
4 | import java.util.Arrays;
5 | import java.util.List;
6 |
7 | public class LongestIncreasingSubsequence {
8 |
9 | public int lengthOfLIS(int[] nums) {
10 | if (nums.length == 0) return 0;
11 | int[] dp = new int[nums.length];
12 | int res = 0;
13 | Arrays.fill(dp, 1);
14 | for (int i = 0; i < nums.length; i++) {
15 | for (int j = 0; j < i; j++) {
16 | if (nums[j] < nums[i]) dp[i] = Math.max(dp[i], dp[j] + 1);
17 | }
18 | res = Math.max(res, dp[i]);
19 | }
20 | return res;
21 | }
22 |
23 | public int lengthOfLISV2(int[] nums) {
24 | List g = new ArrayList<>();
25 | for (int x : nums) {
26 | int j = lowerBound(g, x);
27 | if (j == g.size()) g.add(x); // >=x 的 g[j] 不存在
28 | else g.set(j, x);
29 | }
30 | return g.size();
31 | }
32 |
33 | // 开区间写法
34 | private int lowerBound(List g, int target) {
35 | int left = -1, right = g.size(); // 开区间 (left, right)
36 | while (left + 1 < right) { // 区间不为空
37 | // 循环不变量:
38 | // nums[left] < target
39 | // nums[right] >= target
40 | int mid = (left + right) >>> 1;
41 | if (g.get(mid) < target)
42 | left = mid; // 范围缩小到 (mid, right)
43 | else
44 | right = mid; // 范围缩小到 (left, mid)
45 | }
46 | return right; // 或者 left+1
47 | }
48 |
49 | }
50 |
--------------------------------------------------------------------------------
/algorithm/leetcode/l328/OddEvenLinkedList.java:
--------------------------------------------------------------------------------
1 | package algorithm.leetcode.l328;
2 |
3 | public class OddEvenLinkedList {
4 |
5 | public class ListNode {
6 | int val;
7 | ListNode next;
8 |
9 | ListNode(int val) {
10 | this.val = val;
11 | }
12 | }
13 |
14 |
15 | public ListNode oddEvenList(ListNode head) {
16 | if (head == null) {
17 | return null;
18 | }
19 | ListNode oddHead = head;
20 | ListNode eventHead = head.next;
21 | ListNode even = eventHead;
22 | while (even != null && even.next != null) {
23 | oddHead.next = even.next;
24 | oddHead = oddHead.next;
25 | even.next = oddHead.next;
26 | even = even.next;
27 | }
28 | oddHead.next = eventHead;
29 | return head;
30 | }
31 |
32 | //1 -> 2 -> 3 -> 4 ->5 -> 6
33 |
34 |
35 | //eventHead = 2
36 | //odd = 1 event = 2
37 | //1 -> 3 odd = 3
38 | //2 -> 4 even = 4
39 | }
40 |
--------------------------------------------------------------------------------
/algorithm/leetcode/l33/SearchInRotatedSortedArray.java:
--------------------------------------------------------------------------------
1 | package algorithm.leetcode.l33;
2 |
3 | public class SearchInRotatedSortedArray {
4 |
5 | public int search(int[] nums, int target) {
6 | int left = -1;
7 | int right = nums.length;
8 | while (left + 1 < right) {
9 | int mid = (left + right) / 2;
10 | if (isBlue(nums, mid, target)) {
11 | right = mid;
12 | } else {
13 | left = mid;
14 | }
15 | }
16 | if (right == nums.length || nums[right] != target) {
17 | return -1;
18 | }
19 | return right;
20 | }
21 |
22 | private boolean isBlue(int[] nums, int i, int target) {
23 | int end = nums[nums.length - 1];
24 | if (nums[i] > end) {
25 | return target > end && nums[i] >= target;
26 | } else {
27 | return target > end || nums[i] >= target;
28 | }
29 | }
30 |
31 |
32 | }
33 |
--------------------------------------------------------------------------------
/algorithm/leetcode/l34/FindFirstAndLastPositionOfElementInSortedArray.java:
--------------------------------------------------------------------------------
1 | package algorithm.leetcode.l34;
2 |
3 | public class FindFirstAndLastPositionOfElementInSortedArray {
4 |
5 |
6 | private int lowerBound(int[] nums, int target) {
7 | int left = 0;
8 | int right = nums.length - 1;
9 |
10 | while (left <= right) {
11 | int mid = left + (right - left) / 2;
12 | if (nums[mid] < target) {
13 | left = mid + 1;
14 | } else {
15 | right = mid - 1;
16 | }
17 | }
18 | return left;
19 | }
20 |
21 | public int[] searchRange(int[] nums, int target) {
22 | int start = lowerBound(nums, target);
23 | if (start == nums.length || nums[start] != target) {
24 | return new int[]{-1, -1};
25 | }
26 | int end = lowerBound(nums, target + 1) - 1;
27 | return new int[]{start, end};
28 |
29 | }
30 |
31 |
32 | }
33 |
--------------------------------------------------------------------------------
/algorithm/leetcode/l345/ReverseVowelsOfAString.java:
--------------------------------------------------------------------------------
1 | package algorithm.leetcode.l345;
2 |
3 | /**
4 | * ...
5 | */
6 | public class ReverseVowelsOfAString {
7 |
8 | public String reverseVowels(String s) {
9 | if (s == null || s.equals("")) {
10 | return "";
11 | }
12 | char[] arrays = s.toCharArray();
13 | int begin = 0;
14 | int end = arrays.length - 1;
15 |
16 | while (end > begin) {
17 | while (begin <= arrays.length - 1 && !isVowels(arrays[begin]) && end >= begin) {
18 | begin++;
19 | }
20 | while (!isVowels(arrays[end]) && end >= begin) {
21 | end--;
22 | }
23 | if (begin != end && end >= begin) {
24 | char temp = arrays[begin];
25 | arrays[begin] = arrays[end];
26 | arrays[end] = temp;
27 | begin++;
28 | end--;
29 | }
30 | }
31 | return new String(arrays);
32 | }
33 |
34 | private boolean isVowels(char inputChar) {
35 | return inputChar == 'a'
36 | || inputChar == 'e'
37 | || inputChar == 'i'
38 | || inputChar == 'o'
39 | || inputChar == 'u'
40 | || inputChar == 'A'
41 | || inputChar == 'E'
42 | || inputChar == 'I'
43 | || inputChar == 'O'
44 | || inputChar == 'U';
45 | }
46 |
47 | public static void main(String[] args) {
48 | ReverseVowelsOfAString reverseVowelsOfAString = new ReverseVowelsOfAString();
49 | System.out.println(reverseVowelsOfAString.reverseVowels("a."));
50 | }
51 |
52 | }
53 |
--------------------------------------------------------------------------------
/algorithm/leetcode/l42/TrappingRainWater.java:
--------------------------------------------------------------------------------
1 | package algorithm.leetcode.l42;
2 |
3 | public class TrappingRainWater {
4 |
5 | public int trap(int[] height) {
6 | int[] prefixMax = new int[height.length];
7 | int[] suffixMax = new int[height.length];
8 | int length = height.length;
9 | prefixMax[0] = height[0];
10 | for (int i = 1; i < length; i++) {
11 | prefixMax[i] = Math.max(prefixMax[i - 1], height[i]);
12 | }
13 |
14 | suffixMax[length - 1] = height[length - 1];
15 | for (int i = length - 2; i >= 0; i--) {
16 | suffixMax[i] = Math.max(suffixMax[i + 1], height[i]);
17 | }
18 | int result = 0;
19 | for (int i = 0; i < length; i++) {
20 | result += Math.min(prefixMax[i], suffixMax[i]) - height[i];
21 | }
22 | return result;
23 | }
24 |
25 |
26 | }
27 |
--------------------------------------------------------------------------------
/algorithm/leetcode/l437/PathSumIII.java:
--------------------------------------------------------------------------------
1 | package algorithm.leetcode.l437;
2 |
3 | import java.util.HashMap;
4 | import java.util.Map;
5 |
6 | public class PathSumIII {
7 |
8 | public static class TreeNode {
9 | int val;
10 | TreeNode left;
11 | TreeNode right;
12 |
13 | TreeNode(int val) {
14 | this.val = val;
15 | }
16 | }
17 |
18 |
19 | int pathNumber;
20 |
21 | public int pathSumV2(TreeNode root, int sum) {
22 | if (root == null) return 0;
23 | sum(root, sum);
24 | pathSumV2(root.left, sum);
25 | pathSumV2(root.right, sum);
26 | return pathNumber;
27 | }
28 |
29 |
30 | public void sum(TreeNode root, long sum) {
31 | if (root == null) return;
32 | sum -= root.val;
33 | if (sum == 0) {
34 | pathNumber++;
35 | }
36 | sum(root.left, sum);
37 | sum(root.right, sum);
38 | }
39 |
40 |
41 | public int pathSum(TreeNode root, int targetSum) {
42 | Map prefixPath = new HashMap<>();
43 | prefixPath.put(0L, 1);
44 | return dfs(root, prefixPath, 0, targetSum);
45 | }
46 |
47 | public int dfs(TreeNode root, Map prefix, long curr, int targetSum) {
48 | if (root == null) {
49 | return 0;
50 | }
51 | curr = curr + root.val;
52 | int result = prefix.getOrDefault(curr - targetSum, 0);
53 | prefix.put(curr, prefix.getOrDefault(curr, 0) + 1);
54 | result += dfs(root.left, prefix, curr, targetSum);
55 | result += dfs(root.right, prefix, curr, targetSum);
56 | prefix.put(curr, prefix.getOrDefault(curr, 0) - 1);
57 | return result;
58 | }
59 |
60 |
61 | public static void main(String[] args) {
62 | TreeNode treeNode1 = new TreeNode(1);
63 | TreeNode treeNode2 = new TreeNode(2);
64 | TreeNode treeNode3 = new TreeNode(3);
65 | TreeNode treeNode4 = new TreeNode(4);
66 |
67 | treeNode3.right = treeNode4;
68 |
69 | treeNode1.left = treeNode2;
70 | treeNode1.right = treeNode3;
71 | PathSumIII pathSumIII = new PathSumIII();
72 | System.out.println(pathSumIII.pathSum(treeNode1, 7));
73 | }
74 |
75 | }
76 |
--------------------------------------------------------------------------------
/algorithm/leetcode/l450/DeleteNodeInABST.java:
--------------------------------------------------------------------------------
1 | package algorithm.leetcode.l450;
2 |
3 | public class DeleteNodeInABST {
4 | public class TreeNode {
5 | int val;
6 | TreeNode left;
7 | TreeNode right;
8 |
9 | TreeNode(int val) {
10 | this.val = val;
11 | }
12 |
13 | }
14 |
15 | public TreeNode deleteNode(TreeNode root, int key) {
16 | if (root == null) {
17 | return null;
18 | }
19 | if (key > root.val) {
20 | root.right = deleteNode(root.right, key); // 去右子树删除
21 | } else if (key < root.val) {
22 | root.left = deleteNode(root.left, key); // 去左子树删除
23 | } else { // 当前节点就是要删除的节点
24 | if (root.left == null) {
25 | return root.right; // 情况1,欲删除节点无左子
26 | } else if (root.right == null) {
27 | return root.left; // 情况2,欲删除节点无右子
28 | } else { // 情况3,欲删除节点左右子都有
29 | TreeNode node = root.right;
30 | while (node.left != null) { // 寻找欲删除节点右子树的最左节点
31 | node = node.left;
32 | }
33 | node.left = root.left; // 将欲删除节点的左子树成为其右子树的最左节点的左子树
34 | root = root.right; // 欲删除节点的右子顶替其位置,节点被删除
35 | }
36 | }
37 | return root;
38 | }
39 |
40 |
41 | }
42 |
--------------------------------------------------------------------------------
/algorithm/leetcode/l46/Permutations.java:
--------------------------------------------------------------------------------
1 | package algorithm.leetcode.l46;
2 |
3 | import java.util.ArrayList;
4 | import java.util.Arrays;
5 | import java.util.HashSet;
6 | import java.util.List;
7 |
8 | public class Permutations {
9 |
10 | private int[] nums;
11 | private List path;
12 | private boolean[] onPath;
13 | private final List> ans = new ArrayList<>();
14 |
15 | public List> permute(int[] nums) {
16 | this.nums = nums;
17 | path = Arrays.asList(new Integer[nums.length]);
18 | onPath = new boolean[nums.length];
19 | dfs(0);
20 | return ans;
21 | }
22 |
23 | private void dfs(int i) {
24 | if (i == nums.length) {
25 | ans.add(new ArrayList<>(path));
26 | return;
27 | }
28 | for (int j = 0; j < nums.length; j++) {
29 | if (!onPath[j]) {
30 | path.set(i, nums[j]);
31 | onPath[j] = true;
32 | dfs(i + 1);
33 | onPath[j] = false;
34 | }
35 | }
36 | }
37 |
38 | public static void main(String[] args) {
39 | Permutations permutations = new Permutations();
40 | permutations.permute(new int[]{1,2,3});
41 | }
42 |
43 | }
44 |
--------------------------------------------------------------------------------
/algorithm/leetcode/l494/TargetSum.java:
--------------------------------------------------------------------------------
1 | package algorithm.leetcode.l494;
2 |
3 | public class TargetSum {
4 |
5 | public int findTargetSumWays(int[] nums, int target) {
6 | for (int x : nums) {
7 | target += x;
8 | }
9 | if (target < 0 || target % 2 == 1) {
10 | return 0;
11 | }
12 | target /= 2;
13 |
14 | int n = nums.length;
15 | int[][] f = new int[n + 1][target + 1];
16 | f[0][0] = 1;
17 | for (int i = 0; i < n; ++i) {
18 | for (int c = 0; c <= target; ++c) {
19 | if (c < nums[i]) {
20 | f[i + 1][c] = f[i][c];
21 | } else {
22 | f[i + 1][c] = f[i][c] + f[i][c - nums[i]];
23 | }
24 | }
25 |
26 | }
27 |
28 | return f[n][target];
29 | }
30 |
31 | //1 2 3 4
32 | //5 6 7 8
33 | }
34 |
--------------------------------------------------------------------------------
/algorithm/leetcode/l513/FindBottomLeftTreeValue.java:
--------------------------------------------------------------------------------
1 | package algorithm.leetcode.l513;
2 |
3 | import algorithm.leetcode.l102.BinaryTreeLevelOrderTraversal;
4 |
5 | import java.util.ArrayList;
6 | import java.util.List;
7 |
8 | public class FindBottomLeftTreeValue {
9 |
10 | public class TreeNode {
11 | int val;
12 | TreeNode left;
13 | TreeNode right;
14 | }
15 |
16 | public int findBottomLeftValue(TreeNode root) {
17 | List queue = new ArrayList<>();
18 | int val = 0;
19 | queue.add(root);
20 | while (queue.size() > 0) {
21 | TreeNode temp = queue.remove(0);
22 | val = temp.val;
23 | if (temp.right != null) {
24 | queue.add(temp.right);
25 | }
26 | if (temp.left != null) {
27 | queue.add(temp.left);
28 | }
29 | }
30 | return val;
31 | }
32 | }
33 |
--------------------------------------------------------------------------------
/algorithm/leetcode/l605/CanPlaceFlowers.java:
--------------------------------------------------------------------------------
1 | package algorithm.leetcode.l605;
2 |
3 | /**
4 | * ...
5 | */
6 | public class CanPlaceFlowers {
7 | public boolean canPlaceFlowers(int[] flowerbed, int n) {
8 | for (int i = 0; i < flowerbed.length; i++) {
9 | if (flowerbed[i] == 0) {
10 | if (i + 1 < flowerbed.length) {
11 | if (flowerbed[i + 1] == 1) {
12 | continue;
13 | }
14 | }
15 | if (i - 1 >= 0) {
16 | if (flowerbed[i - 1] == 1) {
17 | continue;
18 | }
19 | }
20 | flowerbed[i] = 1;
21 | n--;
22 | }
23 | }
24 | return n <= 0;
25 | }
26 |
27 | public static void main(String[] args) {
28 | int[] input = new int[]{1, 0, 0, 0, 1};
29 | CanPlaceFlowers canPlaceFlowers = new CanPlaceFlowers();
30 | System.out.println(canPlaceFlowers.canPlaceFlowers(input, 2));
31 | }
32 | }
33 |
--------------------------------------------------------------------------------
/algorithm/leetcode/l700/SearchInABinarySearchTree.java:
--------------------------------------------------------------------------------
1 | package algorithm.leetcode.l700;
2 |
3 | public class SearchInABinarySearchTree {
4 |
5 | public class TreeNode {
6 | int val;
7 | TreeNode left;
8 | TreeNode right;
9 |
10 | TreeNode(int val) {
11 | this.val = val;
12 | }
13 | }
14 |
15 | public TreeNode searchBST(TreeNode root, int val) {
16 | if (root == null) {
17 | return null;
18 | }
19 | if (root.val == val) {
20 | return root;
21 | }
22 | if (root.val < val) {
23 | return searchBST(root.right, val);
24 | }else {
25 | return searchBST(root.left, val);
26 | }
27 | }
28 |
29 |
30 | }
31 |
--------------------------------------------------------------------------------
/algorithm/leetcode/l713/SubArrayProductLessThanK.java:
--------------------------------------------------------------------------------
1 | package algorithm.leetcode.l713;
2 |
3 | public class SubArrayProductLessThanK {
4 |
5 | public int numSubarrayProductLessThanK(int[] nums, int k) {
6 | if (k == 0 || k == 1) {
7 | return 0;
8 | }
9 | int prod = 1;
10 | int left = 0;
11 | int right = 0;
12 | int length = nums.length;
13 | int result = 0;
14 |
15 | while (right < length) {
16 | prod = prod * nums[right];
17 | while (prod >= k) {
18 | prod = prod / nums[left];
19 | left++;
20 | }
21 | result = result + right - left + 1;
22 | right++;
23 | }
24 | return result;
25 | }
26 |
27 |
28 | }
29 |
--------------------------------------------------------------------------------
/algorithm/leetcode/l746/MinCostClimbingStairs.java:
--------------------------------------------------------------------------------
1 | package algorithm.leetcode.l746;
2 |
3 | /**
4 | * ...
5 | */
6 | public class MinCostClimbingStairs {
7 |
8 | public int minCostClimbingStairs(int[] cost) {
9 | int[] dp = new int[cost.length + 1];
10 | dp[0] = 0;
11 | dp[1] = 0;
12 | for (int i = 2; i <= cost.length; i++) {
13 | dp[i] = Math.min(dp[i - 1] + cost[i - 1], dp[i - 2] + cost[i - 2]);
14 | }
15 | return dp[cost.length];
16 | }
17 |
18 | }
19 |
--------------------------------------------------------------------------------
/algorithm/leetcode/l77/Combinations.java:
--------------------------------------------------------------------------------
1 | package algorithm.leetcode.l77;
2 |
3 | import java.util.ArrayList;
4 | import java.util.List;
5 |
6 | public class Combinations {
7 |
8 | private List> result = new ArrayList<>();
9 | private List path = new ArrayList<>();
10 | private int k;
11 |
12 | public List> combine(int n, int k) {
13 | this.k = k;
14 | dfs(n);
15 | return result;
16 | }
17 |
18 | private void dfs(int n) {
19 | if (path.size() == k) {
20 | result.add(new ArrayList<>(path));
21 | return;
22 | }
23 | int d = k - path.size();
24 | for (int i = n; i >= d; i--) {
25 | path.add(i);
26 | dfs(i - 1);
27 | path.remove(path.size() - 1);
28 | }
29 | }
30 |
31 | }
32 |
--------------------------------------------------------------------------------
/algorithm/leetcode/l78/Subsets.java:
--------------------------------------------------------------------------------
1 | package algorithm.leetcode.l78;
2 |
3 | import java.util.ArrayList;
4 | import java.util.List;
5 |
6 | /**
7 | * ...
8 | */
9 | public class Subsets {
10 |
11 | public List> subsets(int[] nums) {
12 | List> result = new ArrayList<>();
13 | sub(nums, 0, result, new ArrayList<>());
14 | return result;
15 | }
16 |
17 | public void sub(int[] nums, int i, List> result, List currentList) {
18 | if (i == nums.length) {
19 | result.add(new ArrayList<>(currentList));
20 | return;
21 | }
22 | sub(nums, i + 1, result, currentList);
23 | currentList.add(nums[i]);
24 | sub(nums, i + 1, result, currentList);
25 | currentList.remove((Integer) nums[i]);
26 | }
27 |
28 | public void sub2(int[] nums, int i, List> result, List currentList) {
29 | result.add(new ArrayList<>(currentList));
30 | if (i == nums.length) {
31 | return;
32 | }
33 | for (int j = i; j < nums.length; j++) {
34 | currentList.add(nums[j]);
35 | sub2(nums, j + 1, result, currentList);
36 | currentList.remove((Integer) nums[j]);
37 | }
38 | }
39 | }
40 |
--------------------------------------------------------------------------------
/algorithm/leetcode/l790/DominoAndTrominoTiling.java:
--------------------------------------------------------------------------------
1 | package algorithm.leetcode.l790;
2 |
3 | /**
4 | * ...
5 | */
6 | public class DominoAndTrominoTiling {
7 |
8 | int MOD = (int) (1e9 + 7);
9 |
10 | public int numTilings(int n) {
11 | int[][] f = new int[n + 1][4];
12 | f[1][0] = f[1][1] = 1;
13 | for (int i = 2; i <= n; i++) {
14 | f[i][0] = f[i - 1][1];
15 | int cur = 0;
16 | for (int j = 0; j < 4; j++) cur = (cur + f[i - 1][j]) % MOD;
17 | f[i][1] = cur;
18 | f[i][2] = (f[i - 1][0] + f[i - 1][3]) % MOD;
19 | f[i][3] = (f[i - 1][0] + f[i - 1][2]) % MOD;
20 | }
21 | return f[n][1];
22 | }
23 |
24 | }
25 |
--------------------------------------------------------------------------------
/algorithm/leetcode/l82/RemoveDuplicatedFromSortListsII.java:
--------------------------------------------------------------------------------
1 | package algorithm.leetcode.l82;
2 |
3 | public class RemoveDuplicatedFromSortListsII {
4 |
5 |
6 | public class ListNode {
7 | int val;
8 | ListNode next;
9 | }
10 |
11 |
12 | public ListNode deleteDuplicates(ListNode head) {
13 | ListNode dummy = new ListNode();
14 | dummy.next = head;
15 |
16 | ListNode cur = dummy;
17 |
18 | while (cur.next != null && cur.next.next != null) {
19 | if (cur.next.val == cur.next.next.val) {
20 | int value = cur.next.val;
21 | while (cur.next != null && cur.next.val == value) {
22 | cur.next = cur.next.next;
23 | }
24 | } else {
25 | cur = cur.next;
26 | }
27 | }
28 | return dummy.next;
29 | }
30 |
31 | }
32 |
--------------------------------------------------------------------------------
/algorithm/leetcode/l83/RemoveDuplicatedFromSortLists.java:
--------------------------------------------------------------------------------
1 | package algorithm.leetcode.l83;
2 |
3 | public class RemoveDuplicatedFromSortLists {
4 |
5 |
6 | public class ListNode {
7 | int val;
8 | ListNode next;
9 | }
10 |
11 | public ListNode deleteDuplicates(ListNode head) {
12 | if (head == null) {
13 | return null;
14 | }
15 | ListNode cur = head;
16 | while (cur.next != null) {
17 | if (cur.val == cur.next.val) {
18 | cur.next = cur.next.next;
19 | } else {
20 | cur = cur.next;
21 | }
22 |
23 | }
24 | return head;
25 | }
26 |
27 |
28 | }
29 |
--------------------------------------------------------------------------------
/algorithm/leetcode/l872/LeafSimilarTrees.java:
--------------------------------------------------------------------------------
1 | package algorithm.leetcode.l872;
2 |
3 | import java.util.ArrayList;
4 | import java.util.List;
5 | import java.util.Objects;
6 |
7 | public class LeafSimilarTrees {
8 |
9 |
10 | public static class TreeNode {
11 | int val;
12 | TreeNode left;
13 | TreeNode right;
14 |
15 | TreeNode(int val) {
16 | this.val = val;
17 | }
18 |
19 | }
20 |
21 |
22 | public List preOrderBinaryTree(TreeNode root, List list) {
23 | if (root == null) {
24 | return list;
25 | }
26 | if (root.left == null && root.right == null) {
27 | list.add(root.val);
28 | }
29 | preOrderBinaryTree(root.left, list);
30 | preOrderBinaryTree(root.right, list);
31 | return list;
32 | }
33 |
34 | public boolean leafSimilar(TreeNode root1, TreeNode root2) {
35 | List list1 = preOrderBinaryTree(root1, new ArrayList<>());
36 | List list2 = preOrderBinaryTree(root2, new ArrayList<>());
37 | if (list1.size() != list2.size()) {
38 | return false;
39 | }
40 | for (int i = 0; i < list1.size(); i++) {
41 | if (!Objects.equals(list1.get(i), list2.get(i))) {
42 | return false;
43 | }
44 | }
45 | return true;
46 | }
47 |
48 | public static void main(String[] args) {
49 | TreeNode node1 = new TreeNode(1);
50 | TreeNode node2 = new TreeNode(3);
51 | TreeNode node3 = new TreeNode(2);
52 | TreeNode node4 = new TreeNode(6);
53 | TreeNode node5 = new TreeNode(5);
54 | TreeNode node6 = new TreeNode(9);
55 | TreeNode node7 = new TreeNode(8);
56 | TreeNode node8 = new TreeNode(7);
57 | TreeNode node9 = new TreeNode(4);
58 |
59 | node1.left = node2;
60 | node1.right = node3;
61 |
62 | node2.left = node4;
63 | node2.right = node5;
64 |
65 | node3.left = node6;
66 | node3.right = node7;
67 |
68 | node5.left = node8;
69 | node5.right = node9;
70 |
71 | LeafSimilarTrees leafSimilarTrees = new LeafSimilarTrees();
72 | List list = leafSimilarTrees.preOrderBinaryTree(node1, new ArrayList<>());
73 | for (int i = 0; i < list.size(); i++) {
74 | System.out.println(list.get(i));
75 | }
76 |
77 |
78 | }
79 |
80 |
81 | }
82 |
--------------------------------------------------------------------------------
/algorithm/leetcode/l876/MiddleOfTheLinkedList.java:
--------------------------------------------------------------------------------
1 | package algorithm.leetcode.l876;
2 |
3 | public class MiddleOfTheLinkedList {
4 |
5 |
6 | public class ListNode {
7 | int val;
8 | ListNode next;
9 | }
10 |
11 | public ListNode middleNode(ListNode head) {
12 | ListNode slow = head;
13 | ListNode fast = head;
14 |
15 | while(fast != null && fast.next != null){
16 | fast = fast.next.next;
17 | slow = slow.next;
18 | }
19 | return slow;
20 | }
21 |
22 |
23 | }
24 |
--------------------------------------------------------------------------------
/algorithm/leetcode/l92/ReverseLinkedListII.java:
--------------------------------------------------------------------------------
1 | package algorithm.leetcode.l92;
2 |
3 | import java.util.List;
4 |
5 | public class ReverseLinkedListII {
6 |
7 | public class ListNode {
8 | int val;
9 | ListNode next;
10 |
11 | ListNode() {
12 | }
13 |
14 | ListNode(int val) {
15 | this.val = val;
16 | }
17 |
18 | ListNode(int val, ListNode next) {
19 | this.val = val;
20 | this.next = next;
21 | }
22 | }
23 |
24 | public ListNode reverseBetween(ListNode head, int left, int right) {
25 | ListNode dummy = new ListNode();
26 | dummy.next = head;
27 |
28 | ListNode p0 = dummy;
29 | for (int i = 0; i < left - 1; i++) {
30 | p0 = p0.next;
31 | }
32 |
33 | ListNode pre = null;
34 | ListNode cur = p0.next;
35 | for (int i = 0; i < right - left + 1; i++) {
36 | ListNode next = cur.next;
37 | cur.next = pre;
38 | pre = cur;
39 | cur = next;
40 | }
41 |
42 | p0.next.next = cur;
43 | p0.next = pre;
44 | return dummy.next;
45 | }
46 |
47 |
48 | }
49 |
--------------------------------------------------------------------------------
/algorithm/leetcode/l94/BinaryTreeInorderTraversal.java:
--------------------------------------------------------------------------------
1 | package algorithm.leetcode.l94;
2 |
3 | import algorithm.leetcode.l144.BinaryTreePreorderTraversal;
4 |
5 | import java.util.ArrayList;
6 | import java.util.List;
7 | import java.util.Stack;
8 |
9 | public class BinaryTreeInorderTraversal {
10 |
11 | public static class TreeNode {
12 | int val;
13 | TreeNode left;
14 | TreeNode right;
15 |
16 | public TreeNode(int value) {
17 | this.val = value;
18 | }
19 | }
20 |
21 |
22 | public List inorderTraversal(TreeNode root) {
23 | List list = new ArrayList<>();
24 | TreeNode p = root;
25 | Stack stack = new Stack<>();
26 | while (p != null || !stack.isEmpty()) {
27 | while (p != null) {
28 | stack.push(p);
29 | p = p.left;
30 | }
31 | if (!stack.isEmpty()){
32 | TreeNode temp = stack.pop();
33 | list.add(temp.val);
34 | p = temp.right;
35 | }
36 | }
37 | return list;
38 | }
39 |
40 |
41 | }
42 |
--------------------------------------------------------------------------------
/algorithm/leetcode/l98/ValidateBinarySearchTree.java:
--------------------------------------------------------------------------------
1 | package algorithm.leetcode.l98;
2 |
3 | public class ValidateBinarySearchTree {
4 |
5 | public class TreeNode {
6 | int val;
7 | TreeNode left;
8 | TreeNode right;
9 | }
10 |
11 | public boolean isValidBST(TreeNode root) {
12 | // return isValidBSTPreOrder(root, Long.MIN_VALUE, Long.MAX_VALUE);
13 | return isValidBSTInOrder(root);
14 | }
15 |
16 | private boolean isValidBSTPreOrder(TreeNode root, long left, long right) {
17 | if (root == null) {
18 | return true;
19 | }
20 | int x = root.val;
21 | return x < right && x > left && isValidBSTPreOrder(root.left, left, x) && isValidBSTPreOrder(root.right, x, right);
22 | }
23 |
24 | private long preVal = Long.MIN_VALUE;
25 |
26 | private boolean isValidBSTInOrder(TreeNode root) {
27 | if (root == null) {
28 | return true;
29 | }
30 | if (!isValidBSTInOrder(root.left)) {
31 | return false;
32 | }
33 | if (root.val <= preVal) {
34 | return false;
35 | }
36 | preVal = root.val;
37 | return isValidBSTInOrder(root.right);
38 | }
39 |
40 | //return dfs(root)[1] != Long.MAX_VALUE;
41 | private long[] isValidBSTPostOrder(TreeNode root) {
42 | if (root == null) {
43 | return new long[]{Long.MAX_VALUE, Long.MIN_VALUE};
44 | }
45 | long[] left = isValidBSTPostOrder(root.left);
46 | long[] right = isValidBSTPostOrder(root.right);
47 | long x = root.val;
48 | // 也可以在递归完左子树之后立刻判断,如果不是二叉搜索树,就不用递归右子树了
49 | if (x <= left[1] || x >= right[0]) {
50 | return new long[]{Long.MIN_VALUE, Long.MAX_VALUE};
51 | }
52 | return new long[]{Math.min(left[0], x), Math.max(right[1], x)};
53 | }
54 |
55 |
56 | }
57 |
--------------------------------------------------------------------------------
/algorithm/nowcoder/JZ1.java:
--------------------------------------------------------------------------------
1 | package algorithm.nowcoder;
2 |
3 | /**
4 | * Jz1, https://www.nowcoder.com/practice/abc3fe2ce8e146608e868a70efebf62e?tpId=13&&tqId=11154&rp=1&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking
5 | */
6 | public class JZ1 {
7 |
8 | /**
9 | * Technique problem, if from the upper left corner the question will difficult
10 | * if from the lower left corner the question will easy, because if current number
11 | * less than target number, you only need move right,more than target number you
12 | * only need move up
13 | */
14 | public static boolean Find(int target, int[][] array) {
15 | if (array == null || array[0] == null) {
16 | return false;
17 | }
18 | int x = 0;
19 | int y = array[0].length - 1;
20 | while (x <= array.length - 1 && y >= 0) {
21 | if (array[x][y] == target) {
22 | return true;
23 | } else if (array[x][y] > target) {
24 | y--;
25 | } else {
26 | x++;
27 | }
28 | }
29 |
30 |
31 | return false;
32 | }
33 |
34 | public static void main(String[] args) {
35 | int[][] aar = new int[4][4];
36 | aar[0][0] = 1;
37 | aar[0][1] = 2;
38 | aar[0][2] = 8;
39 | aar[0][3] = 9;
40 |
41 | aar[1][0] = 2;
42 | aar[1][1] = 4;
43 | aar[1][2] = 9;
44 | aar[1][3] = 12;
45 |
46 | aar[2][0] = 4;
47 | aar[2][1] = 7;
48 | aar[2][2] = 10;
49 | aar[2][3] = 13;
50 |
51 | aar[3][0] = 6;
52 | aar[3][1] = 8;
53 | aar[3][2] = 11;
54 | aar[3][3] = 15;
55 | boolean result = Find(7, aar);
56 | System.out.println(result);
57 | }
58 | }
59 |
--------------------------------------------------------------------------------
/algorithm/nowcoder/JZ10.java:
--------------------------------------------------------------------------------
1 | package nowcoder;
2 |
3 | /**
4 | * JZ10, https://www.nowcoder.com/practice/72a5a919508a4251859fb2cfb987a0e6?tpId=13&tags=&title=&diffculty=0&judgeStatus=0&rp=1
5 | */
6 | public class JZ10 {
7 |
8 | public int RectCover(int target) {
9 | if (target <= 0) {
10 | return 0;
11 | } else if (target <= 2) {
12 | return target;
13 | } else {
14 | return RectCover(target - 1) + RectCover(target - 2);
15 | }
16 | }
17 | }
18 |
--------------------------------------------------------------------------------
/algorithm/nowcoder/JZ11.java:
--------------------------------------------------------------------------------
1 | package nowcoder;
2 |
3 | /**
4 | * JZ11, https://www.nowcoder.com/practice/8ee967e43c2c4ec193b040ea7fbb10b8?tpId=13&tags=&title=&diffculty=0&judgeStatus=0&rp=1
5 | */
6 | public class JZ11 {
7 |
8 | public static int NumberOf1(int n) {
9 | int count = 0;
10 | while (n != 0) {
11 | ++count;
12 | n = (n - 1) & n;
13 | System.out.println(n);
14 | }
15 | return count;
16 | }
17 |
18 | public static void main(String[] args) {
19 | int n = 11;
20 | System.out.println(NumberOf1(n));
21 | }
22 | }
23 |
--------------------------------------------------------------------------------
/algorithm/nowcoder/JZ12.java:
--------------------------------------------------------------------------------
1 | package nowcoder;
2 |
3 | /**
4 | * JZ12, https://www.nowcoder.com/practice/1a834e5e3e1a4b7ba251417554e07c00?tpId=13&tags=&title=&diffculty=0&judgeStatus=0&rp=1
5 | */
6 | public class JZ12 {
7 |
8 | public double Power(double base, int exponent) {
9 | double res = 1;
10 | for (int i = 0; i < Math.abs(exponent); i++) {
11 | res = base * res;
12 | }
13 | if (exponent > 0) {
14 | return res;
15 | } else {
16 | return 1 / res;
17 | }
18 |
19 | }
20 |
21 | }
22 |
--------------------------------------------------------------------------------
/algorithm/nowcoder/JZ13.java:
--------------------------------------------------------------------------------
1 | package nowcoder;
2 |
3 | public class JZ13 {
4 |
5 | public void reOrderArray(int[] array) {
6 | int length = array.length;
7 | int orderOddNumberCount = 0;
8 | for (int i = 0; i < length; i++) {
9 | if (array[i] % 2 == 1) {
10 | int j = i;
11 | while (j > orderOddNumberCount) {
12 | int temp = array[j];
13 | array[j] = array[j - 1];
14 | array[j - 1] = temp;
15 | j--;
16 | }
17 | orderOddNumberCount++;
18 | }
19 | }
20 | }
21 |
22 |
23 | public static void main(String[] args) {
24 | JZ13 jz13 = new JZ13();
25 | jz13.reOrderArray(new int[]{1, 2, 3});
26 | System.out.println(1);
27 | }
28 | }
29 |
--------------------------------------------------------------------------------
/algorithm/nowcoder/JZ14.java:
--------------------------------------------------------------------------------
1 | package nowcoder;
2 |
3 | /**
4 | * JZ14, https://www.nowcoder.com/practice/529d3ae5a407492994ad2a246518148a?tpId=13&tags=&title=&diffculty=0&judgeStatus=0&rp=1
5 | */
6 | public class JZ14 {
7 |
8 | public class ListNode {
9 | int val;
10 | ListNode next = null;
11 |
12 | ListNode(int val) {
13 | this.val = val;
14 | }
15 | }
16 |
17 | public class Solution {
18 | public ListNode FindKthToTail(ListNode head, int k) {
19 | if (head == null) {
20 | return null;
21 | }
22 | ListNode l1 = new ListNode(0);
23 | l1.next = head;
24 | ListNode result = head;
25 | for (int i = 0; i < k ; i++) {
26 | if(l1.next == null){
27 | return null;
28 | }
29 | l1 = l1.next;
30 | }
31 | while (l1.next != null) {
32 | result = result.next;
33 | l1 = l1.next;
34 | }
35 | return result;
36 | }
37 | }
38 |
39 | }
40 |
--------------------------------------------------------------------------------
/algorithm/nowcoder/JZ15.java:
--------------------------------------------------------------------------------
1 | package nowcoder;
2 |
3 | public class JZ15 {
4 | public class ListNode {
5 | int val;
6 | ListNode next = null;
7 |
8 | ListNode(int val) {
9 | this.val = val;
10 | }
11 | }
12 |
13 | public class Solution {
14 | public ListNode ReverseList(ListNode head) {
15 | ListNode l1 = head;
16 | ListNode newHead = new ListNode(0);
17 | ListNode temp = null;
18 | while (l1 != null){
19 | temp = newHead.next;
20 | newHead.next = l1;
21 | l1 = l1.next;
22 | newHead.next.next = temp;
23 | }
24 | return newHead.next;
25 | }
26 | }
27 | }
28 |
--------------------------------------------------------------------------------
/algorithm/nowcoder/JZ16.java:
--------------------------------------------------------------------------------
1 | package nowcoder;
2 |
3 | /**
4 | * JZ16, https://www.nowcoder.com/practice/d8b6b4358f774294a89de2a6ac4d9337?tpId=13&tags=&title=&diffculty=0&judgeStatus=0&rp=1
5 | */
6 | public class JZ16 {
7 |
8 | public class ListNode {
9 | int val;
10 | ListNode next = null;
11 |
12 | ListNode(int val) {
13 | this.val = val;
14 | }
15 | }
16 |
17 | public class Solution {
18 | public ListNode Merge(ListNode list1, ListNode list2) {
19 | ListNode result = new ListNode(0);
20 | ListNode cur = result;
21 | while (list1 != null && list2 != null) {
22 | if (list1.val < list2.val) {
23 | cur.next = list1;
24 | cur = cur.next;
25 | list1 = list1.next;
26 | } else {
27 | cur.next = list2;
28 | cur = cur.next;
29 | list2 = list2.next;
30 | }
31 | }
32 | if (list1 == null) {
33 | cur.next = list2;
34 | }
35 | if (list2 == null) {
36 | cur.next = list1;
37 | }
38 | return result.next;
39 | }
40 | }
41 | }
42 |
--------------------------------------------------------------------------------
/algorithm/nowcoder/JZ17.java:
--------------------------------------------------------------------------------
1 | package nowcoder;
2 |
3 | /**
4 | * JZ17, https://www.nowcoder.com/practice/6e196c44c7004d15b1610b9afca8bd88?tpId=13&tags=&title=&diffculty=0&judgeStatus=0&rp=1
5 | */
6 | public class JZ17 {
7 |
8 | public class TreeNode {
9 | int val = 0;
10 | TreeNode left = null;
11 | TreeNode right = null;
12 |
13 | public TreeNode(int val) {
14 | this.val = val;
15 | }
16 |
17 | }
18 |
19 | public boolean HasSubtree(TreeNode root1, TreeNode root2) {
20 | if (root2 == null) {
21 | return false;
22 | }
23 | return hasSubtreeInternal(root1, root2);
24 | }
25 |
26 | public boolean hasSubtreeInternal(TreeNode root1, TreeNode root2) {
27 | if (root1 == null) {
28 | return false;
29 | }
30 | if (root1.val == root2.val) {
31 | if (isSubTree(root1, root2)) {
32 | return true;
33 | }
34 | }
35 | return hasSubtreeInternal(root1.left, root2) || hasSubtreeInternal(root1.right, root2);
36 | }
37 |
38 | public boolean isSubTree(TreeNode root1, TreeNode root2) {
39 | if (root2 == null) {
40 | return true;
41 | }
42 | if (root1 == null) {
43 | return false;
44 | }
45 | if (root1.val != root2.val) {
46 | return false;
47 | }
48 | return isSubTree(root1.left, root2.left) && isSubTree(root1.right, root2.right);
49 | }
50 |
51 |
52 | }
53 |
--------------------------------------------------------------------------------
/algorithm/nowcoder/JZ18.java:
--------------------------------------------------------------------------------
1 | package nowcoder;
2 |
3 | /**
4 | * JZ18, https://www.nowcoder.com/practice/564f4c26aa584921bc75623e48ca3011?tpId=13&tags=&title=&diffculty=0&judgeStatus=0&rp=1
5 | */
6 | public class JZ18 {
7 |
8 | public class TreeNode {
9 | int val = 0;
10 | TreeNode left = null;
11 | TreeNode right = null;
12 |
13 | public TreeNode(int val) {
14 | this.val = val;
15 | }
16 | }
17 |
18 | public class Solution {
19 | public void Mirror(TreeNode root) {
20 | if (root == null) {
21 | return;
22 | }
23 | TreeNode temp = root.left;
24 | root.left = root.right;
25 | root.right = temp;
26 | Mirror(root.left);
27 | Mirror(root.right);
28 | }
29 |
30 |
31 | }
32 | }
33 |
--------------------------------------------------------------------------------
/algorithm/nowcoder/JZ19.java:
--------------------------------------------------------------------------------
1 | package algorithm.nowcoder;
2 |
3 | import java.util.ArrayList;
4 | import java.util.List;
5 |
6 | /**
7 | * JZ19, https://www.nowcoder.com/practice/9b4c81a02cd34f76be2659fa0d54342a?tpId=13&tags=&title=&diffculty=0&judgeStatus=0&rp=1
8 | */
9 | public class JZ19 {
10 |
11 | public static ArrayList printMatrix(int[][] matrix) {
12 | ArrayList result = new ArrayList<>();
13 | if (matrix == null || matrix.length == 0) {
14 | return result;
15 | }
16 | int x1 = 0;
17 | int x2 = matrix[0].length - 1;
18 |
19 | int y1 = 0;
20 | int y2 = matrix.length - 1;
21 |
22 | while (x1 <= x2 && y1 <= y2) {
23 | for (int i = x1; i <= x2; i++) {
24 | result.add(matrix[y1][i]);
25 | }
26 | for (int i = y1 + 1; i <= y2; i++) {
27 | result.add(matrix[i][x2]);
28 | }
29 | if (y1 != y2) {
30 | for (int i = x2 - 1; i >= x1; i--) {
31 | result.add(matrix[y2][i]);
32 | }
33 | }
34 | if (x1 != x2) {
35 | for (int i = y2 - 1; i >= y1 + 1; i--) {
36 | result.add(matrix[i][x1]);
37 | }
38 | }
39 | x1++;
40 | x2--;
41 | y1++;
42 | y2--;
43 | }
44 | return result;
45 | }
46 |
47 | public static void main(String[] args) {
48 | int[][] arr = new int[3][3];
49 | arr[0][0] = 1;
50 | arr[0][1] = 2;
51 | arr[0][2] = 3;
52 |
53 | arr[1][0] = 4;
54 | arr[1][1] = 5;
55 | arr[1][2] = 6;
56 |
57 | arr[2][0] = 7;
58 | arr[2][1] = 8;
59 | arr[2][2] = 9;
60 |
61 | List list = printMatrix(arr);
62 | for (int i = 0; i < list.size(); i++) {
63 | System.out.println(list.get(i));
64 | }
65 |
66 | }
67 | }
68 |
69 |
--------------------------------------------------------------------------------
/algorithm/nowcoder/JZ2.java:
--------------------------------------------------------------------------------
1 | package algorithm.nowcoder;
2 |
3 | /**
4 | * JZ2, https://www.nowcoder.com/practice/4060ac7e3e404ad1a894ef3e17650423?tpId=13&&tqId=11155&rp=1&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking
5 | */
6 | public class JZ2 {
7 |
8 | /**
9 | * easy
10 | */
11 | public static String replaceSpace(StringBuffer str) {
12 | if (str == null || str.length() == 0) {
13 | return "";
14 | }
15 | StringBuffer result = new StringBuffer();
16 | for (int i = 0; i < str.length(); i++) {
17 | if (str.charAt(i) == ' ') {
18 | result.append("%");
19 | result.append("2");
20 | result.append("0");
21 | } else {
22 | result.append(str.charAt(i));
23 | }
24 | }
25 | return result.toString();
26 | }
27 |
28 | public static void main(String[] args) {
29 | StringBuffer str = new StringBuffer("We Are Happy");
30 | String result = replaceSpace(str);
31 | System.out.println(result);
32 | }
33 |
34 | }
35 |
--------------------------------------------------------------------------------
/algorithm/nowcoder/JZ20.java:
--------------------------------------------------------------------------------
1 | package nowcoder;
2 |
3 | import java.util.ArrayList;
4 | import java.util.List;
5 |
6 | /**
7 | * JZ20, https://www.nowcoder.com/practice/4c776177d2c04c2494f2555c9fcc1e49?tpId=13&tags=&title=&diffculty=0&judgeStatus=0&rp=1
8 | */
9 | public class JZ20 {
10 |
11 | private static List list = new ArrayList<>();
12 | private static List minList = new ArrayList<>();
13 |
14 | public void push(int node) {
15 | list.add(node);
16 | if (minList.isEmpty()) {
17 | minList.add(node);
18 | } else {
19 | if (node < minList.get(minList.size() - 1)) {
20 | minList.add(node);
21 | } else {
22 | minList.add(minList.get(minList.size() - 1));
23 | }
24 | }
25 | }
26 |
27 | public void pop() {
28 | list.remove(list.size() - 1);
29 | minList.remove(minList.size() - 1);
30 | }
31 |
32 | public int top() {
33 | return list.get(list.size() - 1);
34 | }
35 |
36 | public int min() {
37 | return minList.get(list.size() - 1);
38 | }
39 |
40 | public static void main(String[] args) {
41 | JZ20 jz20 = new JZ20();
42 | jz20.push(1);
43 | System.out.println(jz20.min());
44 | jz20.push(2);
45 | jz20.push(3);
46 | System.out.println(jz20.min());
47 | jz20.pop();
48 | jz20.pop();
49 | System.out.println(jz20.min());
50 | jz20.pop();
51 | jz20.push(3100);
52 | System.out.println(jz20.min());
53 | }
54 | }
55 |
--------------------------------------------------------------------------------
/algorithm/nowcoder/JZ21.java:
--------------------------------------------------------------------------------
1 | package nowcoder;
2 |
3 | import java.util.Stack;
4 |
5 | /**
6 | * JZ21, https://www.nowcoder.com/practice/d77d11405cc7470d82554cb392585106?tpId=13&tags=&title=&diffculty=0&judgeStatus=0&rp=1
7 | */
8 | public class JZ21 {
9 | public boolean IsPopOrder(int[] pushA, int[] popA) {
10 | Stack s = new Stack();
11 | for (int i = 0, j = 0; i < pushA.length; i++) {
12 | s.push(pushA[i]);
13 | while (j < pushA.length && s.peek() == popA[j]) {
14 | s.pop();
15 | j = j + 1;
16 | }
17 | }
18 | return s.empty();
19 | }
20 | }
21 |
--------------------------------------------------------------------------------
/algorithm/nowcoder/JZ22.java:
--------------------------------------------------------------------------------
1 | package nowcoder;
2 |
3 | import java.util.ArrayList;
4 |
5 | /**
6 | * JZ22, https://www.nowcoder.com/practice/7fe2212963db4790b57431d9ed259701?tpId=13&tags=&title=&diffculty=0&judgeStatus=0&rp=1
7 | */
8 | public class JZ22 {
9 |
10 | public class TreeNode {
11 | int val = 0;
12 | TreeNode left = null;
13 | TreeNode right = null;
14 |
15 | public TreeNode(int val) {
16 | this.val = val;
17 | }
18 | }
19 |
20 | public ArrayList PrintFromTopToBottom(TreeNode root) {
21 | ArrayList arrayList = new ArrayList<>();
22 | if (root == null) {
23 | return arrayList;
24 | }
25 | ArrayList nodeArrayList = new ArrayList<>();
26 | nodeArrayList.add(root);
27 | while (nodeArrayList.size() > 0) {
28 | TreeNode tempNode = nodeArrayList.remove(0);
29 | arrayList.add(tempNode.val);
30 | if (tempNode.left != null) {
31 | nodeArrayList.add(tempNode.left);
32 | }
33 | if (tempNode.right != null) {
34 | nodeArrayList.add(tempNode.right);
35 | }
36 | }
37 | return arrayList;
38 | }
39 |
40 | }
41 |
--------------------------------------------------------------------------------
/algorithm/nowcoder/JZ23.java:
--------------------------------------------------------------------------------
1 | package nowcoder;
2 |
3 | public class JZ23 {
4 | public boolean VerifySquenceOfBST(int[] sequence) {
5 | if (sequence == null || sequence.length == 0) {
6 | return false;
7 | }
8 | return verify(sequence, 0, sequence.length - 1);
9 | }
10 |
11 | public boolean verify(int[] sequence, int begin, int root) {
12 | if (begin >= root) {
13 | return true;
14 | }
15 | int j = begin;
16 | for (int i = begin; i < root; i++) {
17 | j = i;
18 | if (sequence[i] > sequence[root]) {
19 | break;
20 | }
21 | }
22 | for (int i = j + 1; i < root; i++) {
23 | if (sequence[i] < sequence[root]) {
24 | return false;
25 | }
26 | }
27 | return verify(sequence, begin, j - 1) && verify(sequence, j, root - 1);
28 | }
29 |
30 | public static void main(String[] args) {
31 | JZ23 jz23 = new JZ23();
32 | System.out.println(jz23.VerifySquenceOfBST(new int[]{4,6,7,5}));
33 | }
34 | }
35 |
--------------------------------------------------------------------------------
/algorithm/nowcoder/JZ24.java:
--------------------------------------------------------------------------------
1 | package nowcoder;
2 |
3 | import java.util.ArrayList;
4 |
5 | public class JZ24 {
6 |
7 |
8 | public class TreeNode {
9 | int val = 0;
10 | TreeNode left = null;
11 | TreeNode right = null;
12 |
13 | public TreeNode(int val) {
14 | this.val = val;
15 |
16 | }
17 |
18 | }
19 |
20 | public class Solution {
21 | private ArrayList> result = new ArrayList>();
22 | private ArrayList list = new ArrayList<>();
23 |
24 | public ArrayList> FindPath(TreeNode root, int target) {
25 | if (root == null) return result;
26 | list.add(root.val);
27 | target -= root.val;
28 | if (target == 0 && root.left == null && root.right == null)
29 | result.add(new ArrayList(list));
30 | FindPath(root.left, target);
31 | FindPath(root.right, target);
32 | list.remove(list.size() - 1);
33 | return result;
34 | }
35 |
36 |
37 | }
38 |
39 | }
40 |
--------------------------------------------------------------------------------
/algorithm/nowcoder/JZ25.java:
--------------------------------------------------------------------------------
1 | package nowcoder;
2 |
3 | import java.util.HashMap;
4 | import java.util.Map;
5 |
6 | /**
7 | * JZ25, https://www.nowcoder.com/practice/f836b2c43afc4b35ad6adc41ec941dba?tpId=13&tags=&title=&diffculty=0&judgeStatus=0&rp=1
8 | */
9 | public class JZ25 {
10 |
11 | public class RandomListNode {
12 | int label;
13 | RandomListNode next = null;
14 | RandomListNode random = null;
15 |
16 | RandomListNode(int label) {
17 | this.label = label;
18 | }
19 | }
20 |
21 |
22 | public class Solution {
23 | public RandomListNode Clone(RandomListNode pHead) {
24 | if (pHead == null) return null;
25 | RandomListNode head = new RandomListNode(pHead.label);
26 | RandomListNode tempPHead = pHead;
27 | RandomListNode tail = head;
28 |
29 | Map map = new HashMap<>();
30 | while (pHead!= null) {
31 | map.put(pHead, new RandomListNode(pHead.label));
32 | pHead = pHead.next;
33 | }
34 | while (tempPHead != null) {
35 | tail.next = map.get(tempPHead.next);
36 | tail.random = map.get(tempPHead.random);
37 | tail = tail.next;
38 | tempPHead = tempPHead.next;
39 | }
40 |
41 | return head;
42 | }
43 | }
44 |
45 | }
46 |
--------------------------------------------------------------------------------
/algorithm/nowcoder/JZ26.java:
--------------------------------------------------------------------------------
1 | package nowcoder;
2 |
3 | import java.util.ArrayList;
4 | import java.util.List;
5 |
6 | public class JZ26 {
7 | public class TreeNode {
8 | int val = 0;
9 | TreeNode left = null;
10 | TreeNode right = null;
11 |
12 | public TreeNode(int val) {
13 | this.val = val;
14 | }
15 | }
16 |
17 | List list = new ArrayList<>();
18 |
19 | public TreeNode Convert(TreeNode pRootOfTree) {
20 | if (pRootOfTree == null) {
21 | return null;
22 | }
23 | orderTree(pRootOfTree);
24 | for (int i = 0; i < list.size(); i++) {
25 | if (i == 0) {
26 | list.get(i).left = null;
27 | if (i + 1 < list.size()) {
28 | list.get(i).right = list.get(i + 1);
29 | }
30 | } else if (i == list.size() - 1) {
31 | list.get(i).left = list.get(i - 1);
32 | list.get(i).right = null;
33 | } else {
34 | list.get(i).left = list.get(i - 1);
35 | list.get(i).right = list.get(i + 1);
36 | }
37 | }
38 | return list.get(0);
39 | }
40 |
41 | public void orderTree(TreeNode root) {
42 | if (root == null) {
43 | return;
44 | }
45 | orderTree(root.left);
46 | list.add(root);
47 | orderTree(root.right);
48 | }
49 |
50 | TreeNode pre = null;
51 |
52 | public TreeNode Convert2(TreeNode pRootOfTree) {
53 | if (pRootOfTree == null)
54 | return null;
55 | Convert2(pRootOfTree.right);
56 | if (pre != null) {
57 | pRootOfTree.right = pre;
58 | pre.left = pRootOfTree;
59 | }
60 | pre = pRootOfTree;
61 | Convert2(pRootOfTree.left);
62 | return pre;
63 | }
64 | }
65 |
--------------------------------------------------------------------------------
/algorithm/nowcoder/JZ27.java:
--------------------------------------------------------------------------------
1 | package nowcoder;
2 |
3 | import java.util.ArrayList;
4 | import java.util.Collections;
5 |
6 | public class JZ27 {
7 |
8 | public ArrayList Permutation(String str) {
9 | char[] chars = str.toCharArray();
10 | ArrayList results = new ArrayList<>();
11 | build(results, 0, chars);
12 | Collections.sort(results);
13 | return results;
14 | }
15 |
16 | private void build(ArrayList result, int i, char[] c) {
17 | if (i == c.length - 1) {
18 | result.add(new String(c));
19 | }
20 | for (int j = i; j < c.length; j++) {
21 | if (i == j || c[j] != c[i]) {
22 | swap(c, i, j);
23 | build(result, i + 1, c);
24 | swap(c, i, j);
25 | }
26 | }
27 | }
28 |
29 | private char[] swap(char[] c, int i, int j) {
30 | char g = c[i];
31 | c[i] = c[j];
32 | c[j] = g;
33 | return c;
34 | }
35 |
36 | public static void main(String[] args) {
37 | JZ27 jz27 = new JZ27();
38 | ArrayList arrayList = jz27.Permutation("abc");
39 | for (int i = 0; i < arrayList.size(); i++) {
40 | System.out.println(arrayList.get(i));
41 | }
42 | System.out.println();
43 | }
44 |
45 | }
46 |
--------------------------------------------------------------------------------
/algorithm/nowcoder/JZ28.java:
--------------------------------------------------------------------------------
1 | package nowcoder;
2 |
3 | /**
4 | * JZ28, https://www.nowcoder.com/practice/e8a1b01a2df14cb2b228b30ee6a92163?tpId=13&tags=&title=&diffculty=0&judgeStatus=0&rp=1
5 | */
6 | public class JZ28 {
7 | //[1,2,3,2,2,2,5,4,2]
8 | public int MoreThanHalfNum_Solution(int[] array) {
9 | if (array == null || array.length == 0) {
10 | return 0;
11 | }
12 | int maxNumsValue = array[0];
13 | int count = 1;
14 |
15 | for (int i = 1; i < array.length; i++) {
16 | if (array[i] == maxNumsValue) {
17 | count++;
18 | } else {
19 | if (count > 0) {
20 | count--;
21 | } else {
22 | count = 1;
23 | maxNumsValue = array[i];
24 | }
25 | }
26 | }
27 | count = 0;
28 | for (int i = 0; i < array.length; i++) {
29 | if (array[i] == maxNumsValue) {
30 | count++;
31 | }
32 | }
33 | if (count > array.length / 2) {
34 | return maxNumsValue;
35 | } else {
36 | return 0;
37 | }
38 | }
39 |
40 | }
41 |
--------------------------------------------------------------------------------
/algorithm/nowcoder/JZ29.java:
--------------------------------------------------------------------------------
1 | package nowcoder;
2 |
3 | import java.util.ArrayList;
4 |
5 | /**
6 | * JZ29, https://www.nowcoder.com/practice/6a296eb82cf844ca8539b57c23e6e9bf?tpId=13&tags=&title=&diffculty=0&judgeStatus=0&rp=1
7 | */
8 | public class JZ29 {
9 |
10 | public static void main(String[] args) {
11 | int[] arr = new int[]{4, 5, 1, 6, 2, 7, 3, 8};
12 | JZ29 jz29 = new JZ29();
13 | jz29.GetLeastNumbers_Solution(arr, 4);
14 | }
15 |
16 | public ArrayList GetLeastNumbers_Solution(int[] input, int k) {
17 | ArrayList list = new ArrayList<>();
18 | if (k > input.length) {
19 | return list;
20 | }
21 | for (int i = input.length / 2 - 1; i >= 0; i--) {
22 | adjustHeap(input, i, input.length);
23 | }
24 |
25 | for (int i = input.length - 1; i >= input.length - k; i--) {
26 | list.add(input[0]);
27 | System.out.print(input[0] + "\t");
28 | swap(input, 0, i);
29 | adjustHeap(input, 0, i);
30 | }
31 | return list;
32 | }
33 |
34 | public static void swap(int[] arr, int a, int b) {
35 | int temp = arr[a];
36 | arr[a] = arr[b];
37 | arr[b] = temp;
38 | }
39 |
40 | public static void adjustHeap(int[] arr, int i, int length) {
41 | int temp = arr[i];
42 | for (int k = i * 2 + 1; k + 1 <= length; k = k * 2 + 1) {
43 | if (k + 1 < length && arr[k] > arr[k + 1]) {
44 | k++;
45 | }
46 | if (arr[k] < temp) {
47 | arr[i] = arr[k];
48 | i = k;
49 | } else {
50 | break;
51 | }
52 | }
53 | arr[i] = temp;
54 | }
55 | }
56 |
--------------------------------------------------------------------------------
/algorithm/nowcoder/JZ3.java:
--------------------------------------------------------------------------------
1 | package algorithm.nowcoder;
2 |
3 | import java.util.ArrayList;
4 |
5 | /**
6 | * JZ3, ...
7 | */
8 | public class JZ3 {
9 |
10 | /**
11 | * easy
12 | */
13 | public static ArrayList printListFromTailToHead(ListNode listNode) {
14 | ArrayList list = new ArrayList<>();
15 | if (listNode == null) {
16 | return list;
17 | }
18 | ListNode head = new ListNode(0);
19 | ListNode temp = new ListNode(0);
20 | ListNode currentNode = new ListNode(0);
21 |
22 | while (listNode != null) {
23 | currentNode = listNode;
24 | listNode = listNode.next;
25 | head.next = currentNode;
26 | currentNode.next = temp;
27 | temp = head.next;
28 | }
29 | head = head.next;
30 | while (head.next != null) {
31 | System.out.println(head.val);
32 | list.add(head.val);
33 | head = head.next;
34 | }
35 | return list;
36 | }
37 |
38 | public static void main(String[] args) {
39 | ListNode listNode1 = new ListNode(1);
40 | ListNode listNode2 = new ListNode(2);
41 | ListNode listNode3 = new ListNode(3);
42 | ListNode listNode4 = new ListNode(4);
43 | listNode1.next = listNode2;
44 | listNode2.next = listNode3;
45 | listNode3.next = listNode4;
46 | printListFromTailToHead(listNode1);
47 | }
48 |
49 | public static class ListNode {
50 | int val;
51 | ListNode next = null;
52 |
53 | ListNode(int val) {
54 | this.val = val;
55 | }
56 | }
57 |
58 |
59 |
60 | }
61 |
--------------------------------------------------------------------------------
/algorithm/nowcoder/JZ30.java:
--------------------------------------------------------------------------------
1 | package nowcoder;
2 |
3 | public class JZ30 {
4 |
5 | public int FindGreatestSumOfSubArray(int[] array) {
6 | int maxValue = array[0];
7 | int curSumValue = 0;
8 |
9 | for (int i = 0; i < array.length; i++) {
10 | if (curSumValue + array[i] > 0) {
11 | curSumValue = curSumValue + array[i];
12 | maxValue = Math.max(maxValue, curSumValue);
13 | } else {
14 | curSumValue = 0;
15 | maxValue = Math.max(maxValue, array[i]);
16 | }
17 | }
18 | return maxValue;
19 | }
20 |
21 | public static void main(String[] args) {
22 | JZ30 jz30 = new JZ30();
23 | int result = jz30.FindGreatestSumOfSubArray(new int[]{1, -2, 3, 10, -4, 7, 2, -5});
24 | System.out.println(result);
25 | }
26 | }
27 |
--------------------------------------------------------------------------------
/algorithm/nowcoder/JZ31.java:
--------------------------------------------------------------------------------
1 | package nowcoder;
2 |
3 | public class JZ31 {
4 |
5 | public int NumberOf1Between1AndN_Solution(int n) {
6 | int count = 0;
7 | for (int i = 1; i <= n; i++) {
8 | int temp = i;
9 | while (temp > 0) {
10 | if (temp % 10 == 1) {
11 | count++;
12 | }
13 | temp = temp / 10;
14 | }
15 | }
16 | return count;
17 | }
18 |
19 | public static void main(String[] args) {
20 | //13->6
21 | JZ31 jz31 = new JZ31();
22 | System.out.println(jz31.NumberOf1Between1AndN_Solution(13));
23 |
24 |
25 | }
26 |
27 |
28 | }
29 |
--------------------------------------------------------------------------------
/algorithm/nowcoder/JZ32.java:
--------------------------------------------------------------------------------
1 | package nowcoder;
2 |
3 | /**
4 | * JZ32, https://www.nowcoder.com/practice/8fecd3f8ba334add803bf2a06af1b993?tpId=13&tags=&title=&diffculty=0&judgeStatus=0&rp=1
5 | */
6 | public class JZ32 {
7 |
8 | public String permutation(int[] numbers) {
9 | if (numbers == null || numbers.length == 0) return "";
10 | for (int i = 0; i < numbers.length; i++) {
11 | for (int j = i + 1; j < numbers.length; j++) {
12 | int sum1 = Integer.parseInt(numbers[i] + "" + numbers[j]);
13 | int sum2 = Integer.parseInt(numbers[j] + "" + numbers[i]);
14 | if (sum1 > sum2) {
15 | int temp = numbers[j];
16 | numbers[j] = numbers[i];
17 | numbers[i] = temp;
18 | }
19 | }
20 | }
21 | StringBuilder str = new StringBuilder();
22 | for (int number : numbers) str.append(number);
23 | return str.toString();
24 | }
25 |
26 | }
27 |
--------------------------------------------------------------------------------
/algorithm/nowcoder/JZ33.java:
--------------------------------------------------------------------------------
1 | package nowcoder;
2 |
3 | /**
4 | * JZ33, https://www.nowcoder.com/practice/6aa9e04fc3794f68acf8778237ba065b?tpId=13&tags=&title=&diffculty=0&judgeStatus=0&rp=1
5 | */
6 | public class JZ33 {
7 | public int GetUglyNumber_Solution(int index) {
8 | if (index == 0) {
9 | return 0;
10 | }
11 | int[] result = new int[index];
12 | result[0] = 1;
13 | int p2 = 0;
14 | int p3 = 0;
15 | int p5 = 0;
16 | for (int i = 1; i < index; i++) {
17 | result[i] = Math.min(result[p2] * 2, Math.min(result[p3] * 3, result[p5] * 5));
18 | System.out.print(result[i] + "\t");
19 | if (result[i] == result[p2] * 2) p2++;
20 | if (result[i] == result[p3] * 3) p3++;
21 | if (result[i] == result[p5] * 5) p5++;
22 | }
23 | System.out.println();
24 | return result[index - 1];
25 | }
26 |
27 | public static void main(String[] args) {
28 | JZ33 jz33 = new JZ33();
29 | System.out.println(jz33.GetUglyNumber_Solution(7));
30 | }
31 | }
32 |
--------------------------------------------------------------------------------
/algorithm/nowcoder/JZ34.java:
--------------------------------------------------------------------------------
1 | package nowcoder;
2 |
3 | import java.util.HashMap;
4 | import java.util.LinkedHashMap;
5 | import java.util.Map;
6 |
7 | /**
8 | * JZ34, https://www.nowcoder.com/practice/1c82e8cf713b4bbeb2a5b31cf5b0417c?tpId=13&tags=&title=&diffculty=0&judgeStatus=0&rp=1
9 | */
10 | public class JZ34 {
11 |
12 | public int FirstNotRepeatingChar(String str) {
13 | if (str == null || str.equals("")) {
14 | return -1;
15 | }
16 | HashMap hashMap = new LinkedHashMap<>(str.length());
17 | char[] chars = str.toCharArray();
18 | for (int i = 0; i < chars.length; i++) {
19 | if (!hashMap.containsKey(chars[i])) {
20 | hashMap.put(chars[i], 1);
21 | } else {
22 | hashMap.put(chars[i], hashMap.get(chars[i]) + 1);
23 | }
24 | }
25 | for (Map.Entry entry : hashMap.entrySet()) {
26 | if (entry.getValue() == 1) {
27 | System.out.println(entry.getKey());
28 | return str.indexOf(entry.getKey());
29 | }
30 | }
31 | return 0;
32 | }
33 |
34 | public static void main(String[] args) {
35 | JZ34 jz34 = new JZ34();
36 | System.out.println(jz34.FirstNotRepeatingChar("NXWtnzyoHoBhUJaPauJaAitLWNMlkKwDYbbigdMMaYfkVPhGZcrEwp"));
37 | }
38 |
39 | }
40 |
--------------------------------------------------------------------------------
/algorithm/nowcoder/JZ35.java:
--------------------------------------------------------------------------------
1 | package nowcoder;
2 |
3 | /**
4 | * JZ25, https://www.nowcoder.com/practice/96bd6684e04a44eb80e6a68efc0ec6c5?tpId=13&tags=&title=&diffculty=0&judgeStatus=0&rp=1
5 | */
6 | public class JZ35 {
7 | public Integer count = 0;
8 |
9 | public Integer InversePairs(int[] array) {
10 | divMerge(array, 0, array.length - 1);
11 | return count;
12 | }
13 |
14 | public void divMerge(int[] array, int left, int right) {
15 | if (left >= right) return;
16 | int middle = left + (right - left) / 2;
17 | divMerge(array, left, middle);
18 | divMerge(array, middle + 1, right);
19 |
20 | int i = left;
21 | int j = middle + 1;
22 | int[] tmp = new int[right - left + 1];
23 | int k = 0;
24 | while (i <= middle && j <= right) {
25 | if (array[i] > array[j]) {
26 | count += middle - i + 1;
27 | count %= 1000000007;
28 | tmp[k++] = array[j++];
29 | } else {
30 | tmp[k++] = array[i++];
31 | }
32 | }
33 | while (j <= right) {
34 | tmp[k++] = array[j++];
35 | }
36 | while (i <= middle) {
37 | tmp[k++] = array[i++];
38 | }
39 | for (int l = 0; l < k; l++) {
40 | array[left++] = tmp[l];
41 | }
42 | }
43 |
44 | public static void main(String[] args) {
45 | int[] arr = new int[]{3, 1, 4, 5, 2};
46 | JZ35 jz35 = new JZ35();
47 | System.out.println(jz35.InversePairs(arr));
48 | }
49 | }
50 |
--------------------------------------------------------------------------------
/algorithm/nowcoder/JZ36.java:
--------------------------------------------------------------------------------
1 | package nowcoder;
2 |
3 | import java.util.List;
4 |
5 | /**
6 | * JZ36, https://www.nowcoder.com/practice/6ab1d9a29e88450685099d45c9e31e46?tpId=13&tags=&title=&diffculty=0&judgeStatus=0&rp=1
7 | */
8 | public class JZ36 {
9 |
10 | public class ListNode {
11 | int val;
12 | ListNode next = null;
13 |
14 | ListNode(int val) {
15 | this.val = val;
16 | }
17 | }
18 |
19 | public ListNode FindFirstCommonNode(ListNode pHead1, ListNode pHead2) {
20 | ListNode h1 = pHead1;
21 | ListNode h2 = pHead2;
22 | while (h1 != h2) {
23 | h1 = h1 != null ? h1.next : pHead2;
24 | h2 = h2 != null ? h2.next : pHead1;
25 | }
26 | return h1;
27 | }
28 |
29 | }
30 |
--------------------------------------------------------------------------------
/algorithm/nowcoder/JZ37.java:
--------------------------------------------------------------------------------
1 | package nowcoder;
2 |
3 | /**
4 | * JZ37, https://www.nowcoder.com/practice/70610bf967994b22bb1c26f9ae901fa2?tpId=13&tags=&title=&diffculty=0&judgeStatus=0&rp=1
5 | */
6 | public class JZ37 {
7 |
8 | public int GetNumberOfK(int[] array, int k) {
9 | if (array == null || array.length == 0) {
10 | return 0;
11 | }
12 | int b = 0;
13 | int e = array.length;
14 | while (b < e) {
15 | int m = b + (e - b) / 2;
16 | if (array[m] < k) {
17 | b = m + 1;
18 | } else {
19 | e = m;
20 | }
21 | }
22 | int tempBegin = b;
23 | b = 0;
24 | e = array.length;
25 | while (b < e) {
26 | int m = b + (e - b) / 2;
27 | if (array[m] <= k) {
28 | b = m + 1;
29 | } else {
30 | e = m;
31 | }
32 | }
33 | return e - tempBegin;
34 | }
35 |
36 | public static void main(String[] args) {
37 | JZ37 jz37 = new JZ37();
38 | int result = jz37.GetNumberOfK(new int[]{1, 2, 3, 3, 3, 3, 4, 5}, 3);
39 | System.out.println(result);
40 | }
41 | }
42 |
--------------------------------------------------------------------------------
/algorithm/nowcoder/JZ38.java:
--------------------------------------------------------------------------------
1 | package nowcoder;
2 |
3 | /**
4 | * JZ38, https://www.nowcoder.com/practice/435fb86331474282a3499955f0a41e8b?tpId=13&tags=&title=&diffculty=0&judgeStatus=0&rp=1
5 | */
6 | public class JZ38 {
7 |
8 | public class TreeNode {
9 | int val = 0;
10 | TreeNode left = null;
11 | TreeNode right = null;
12 |
13 | public TreeNode(int val) {
14 | this.val = val;
15 | }
16 |
17 | }
18 |
19 | public int TreeDepth(TreeNode root) {
20 | if (root == null) {
21 | return 0;
22 | }
23 | int depth = TreeDepth(root.left) > TreeDepth(root.right)
24 | ? TreeDepth(root.left) + 1 : TreeDepth(root.right) + 1;
25 | return depth;
26 | }
27 |
28 | }
29 |
--------------------------------------------------------------------------------
/algorithm/nowcoder/JZ39.java:
--------------------------------------------------------------------------------
1 | package nowcoder;
2 |
3 | public class JZ39 {
4 |
5 | class TreeNode {
6 | TreeNode left;
7 | TreeNode right;
8 | int val;
9 |
10 | public TreeNode(int value) {
11 | this.val = value;
12 | }
13 | }
14 |
15 | public boolean IsBalanced_Solution(TreeNode root) {
16 | if (root == null) {
17 | return true;
18 | }
19 | if (Math.abs(treePath(root.left) - treePath(root.right)) > 1) {
20 | return false;
21 | }
22 | IsBalanced_Solution(root.left);
23 | IsBalanced_Solution(root.right);
24 | return true;
25 | }
26 |
27 | public int treePath(TreeNode root) {
28 | if (root == null) {
29 | return 0;
30 | }
31 | return treePath(root.left) > treePath(root.right) ? treePath(root.left) + 1 : treePath(root.right) + 1;
32 | }
33 |
34 | }
35 |
--------------------------------------------------------------------------------
/algorithm/nowcoder/JZ4.java:
--------------------------------------------------------------------------------
1 | package algorithm.nowcoder;
2 |
3 | /**
4 | * JZ4, https://www.nowcoder.com/practice/54275ddae22f475981afa2244dd448c6?tpId=13&&tqId=11158&rp=1&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking
5 | */
6 | public class JZ4 {
7 |
8 | public TreeNode reConstructBinaryTree(int[] pre, int[] in) {
9 | TreeNode root = reConstructBinaryTree(pre, 0, pre.length - 1, in, 0, in.length - 1);
10 | return root;
11 | }
12 |
13 | private TreeNode reConstructBinaryTree(int[] pre, int startPre, int endPre, int[] in, int startIn, int endIn) {
14 | if (startPre > endPre || startIn > endIn)
15 | return null;
16 | TreeNode root = new TreeNode(pre[startPre]);
17 | for (int i = startIn; i <= endIn; i++)
18 | if (in[i] == pre[startPre]) {
19 | root.left = reConstructBinaryTree(pre, startPre + 1, startPre + i - startIn, in, startIn, i - 1);
20 | root.right = reConstructBinaryTree(pre, i - startIn + startPre + 1, endPre, in, i + 1, endIn);
21 | break;
22 | }
23 | return root;
24 | }
25 |
26 | public static class TreeNode {
27 | int val;
28 | TreeNode left;
29 | TreeNode right;
30 |
31 | TreeNode(int x) {
32 | val = x;
33 | }
34 | }
35 | }
36 |
--------------------------------------------------------------------------------
/algorithm/nowcoder/JZ40.java:
--------------------------------------------------------------------------------
1 | package nowcoder;
2 |
3 | /**
4 | * JZ40, https://www.nowcoder.com/practice/e02fdb54d7524710a7d664d082bb7811?tpId=13&tags=&title=&diffculty=0&judgeStatus=0&rp=1
5 | */
6 | public class JZ40 {
7 | public void FindNumsAppearOnce(int[] array, int num1[], int num2[]) {
8 | if (array == null) {
9 | return;
10 | }
11 | int xor = 0;
12 | for (int temp : array) {
13 | xor = xor ^ temp;
14 | }
15 | int classify = xor & (-xor);
16 | for (int temp : array) {
17 | int condition = temp & classify;
18 | if (condition == 0) {
19 | num1[0] = num1[0] ^ temp;
20 | } else {
21 | num2[0] = num2[0] ^ temp;
22 | }
23 | }
24 | }
25 |
26 | }
27 |
--------------------------------------------------------------------------------
/algorithm/nowcoder/JZ41.java:
--------------------------------------------------------------------------------
1 | package nowcoder;
2 |
3 | import java.util.ArrayList;
4 |
5 | /**
6 | * JZ41, https://www.nowcoder.com/practice/c451a3fd84b64cb19485dad758a55ebe?tpId=13&tags=&title=&diffculty=0&judgeStatus=0&rp=1
7 | */
8 | public class JZ41 {
9 |
10 | public ArrayList> FindContinuousSequence(int sum) {
11 | ArrayList> resp = new ArrayList<>();
12 | if (sum <= 0) {
13 | return resp;
14 | }
15 | int leftP = 1;
16 | int rightP = 2;
17 | int sumVal = leftP + rightP;
18 |
19 | while (sum > rightP) {
20 | if (sumVal < sum) {
21 | rightP++;
22 | sumVal += rightP;
23 | } else if (sumVal > sum) {
24 | sumVal -= leftP;
25 | leftP++;
26 | } else {
27 | ArrayList list = new ArrayList<>();
28 | for (int i = leftP; i <= rightP; i++) {
29 | list.add(i);
30 | }
31 | resp.add(list);
32 |
33 | rightP++;
34 | sumVal += rightP;
35 | }
36 | }
37 | return resp;
38 | }
39 |
40 | public static void main(String[] args) {
41 | JZ41 jz41 = new JZ41();
42 | jz41.FindContinuousSequence(3);
43 | }
44 |
45 | }
46 |
--------------------------------------------------------------------------------
/algorithm/nowcoder/JZ42.java:
--------------------------------------------------------------------------------
1 | package nowcoder;
2 |
3 | import java.util.ArrayList;
4 |
5 | /**
6 | * JZ42, https://www.nowcoder.com/practice/390da4f7a00f44bea7c2f3d19491311b?tpId=13&tags=&title=&diffculty=0&judgeStatus=0&rp=1
7 | */
8 | public class JZ42 {
9 |
10 | public ArrayList FindNumbersWithSum(int[] array, int sum) {
11 | ArrayList list = new ArrayList();
12 | if (array == null) {
13 | return list;
14 | }
15 | int l = 0;
16 | int r = array.length - 1;
17 | while (l < r) {
18 | if (array[l] + array[r] == sum) {
19 | list.add(array[l]);
20 | list.add(array[r]);
21 | System.out.println(array[l] + " " + array[r]);
22 | return list;
23 | } else if (array[l] + array[r] > sum) {
24 | r--;
25 | } else {
26 | l++;
27 | }
28 | }
29 | return list;
30 | }
31 |
32 | public static void main(String[] args) {
33 | JZ42 jz42 = new JZ42();
34 | jz42.FindNumbersWithSum(new int[]{1, 2, 4, 7, 11, 15}, 15);
35 | }
36 | }
37 |
--------------------------------------------------------------------------------
/algorithm/nowcoder/JZ43.java:
--------------------------------------------------------------------------------
1 | package nowcoder;
2 |
3 | /**
4 | * JZ43, https://www.nowcoder.com/practice/12d959b108cb42b1ab72cef4d36af5ec?tpId=13&tags=&title=&diffculty=0&judgeStatus=0&rp=1
5 | */
6 | public class JZ43 {
7 |
8 | //"abcXYZdef",3 -> "XYZdefabc"
9 | public String LeftRotateString(String str, int n) {
10 | if (str == null || str.length() == 0) {
11 | return "";
12 | }
13 | char[] strChars = str.toCharArray();
14 | StringBuilder result = new StringBuilder();
15 | for (int i = n; i < strChars.length; i++) {
16 | result.append(strChars[i]);
17 | }
18 | for (int i = 0; i < n; i++) {
19 | result.append(strChars[i]);
20 | }
21 | return result.toString();
22 | }
23 |
24 | public static void main(String[] args) {
25 | JZ43 jz43 = new JZ43();
26 | System.out.println(jz43.LeftRotateString("abcXYZdef", 3));
27 | }
28 | }
29 |
--------------------------------------------------------------------------------
/algorithm/nowcoder/JZ44.java:
--------------------------------------------------------------------------------
1 | package nowcoder;
2 |
3 | /**
4 | * JZ44, https://www.nowcoder.com/practice/3194a4f4cf814f63919d0790578d51f3?tpId=13&tags=&title=&diffculty=0&judgeStatus=0&rp=1
5 | */
6 | public class JZ44 {
7 | public String ReverseSentence(String str) {
8 | if (str == null || str.length() == 0) {
9 | return "";
10 | }
11 | char[] arr = str.toCharArray();
12 | StringBuilder builder = new StringBuilder();
13 | StringBuilder tempBuilder = new StringBuilder();
14 | for (int i = arr.length - 1; i >= 0; i--) {
15 | if (arr[i] != ' ') {
16 | tempBuilder.insert(0, arr[i]);
17 | } else {
18 | builder.append(tempBuilder);
19 | builder.append(' ');
20 | tempBuilder = new StringBuilder();
21 | }
22 | }
23 | builder.append(tempBuilder);
24 | return builder.toString();
25 | }
26 |
27 | public static void main(String[] args) {
28 | JZ44 jz44 = new JZ44();
29 | System.out.println(jz44.ReverseSentence("nowcoder. a am I"));
30 | }
31 |
32 | }
33 |
--------------------------------------------------------------------------------
/algorithm/nowcoder/JZ45.java:
--------------------------------------------------------------------------------
1 | package nowcoder;
2 |
3 | import java.util.TreeSet;
4 |
5 | /**
6 | * JZ45, https://www.nowcoder.com/practice/762836f4d43d43ca9deb273b3de8e1f4?tpId=13&tags=&title=&diffculty=0&judgeStatus=0&rp=1
7 | */
8 | public class JZ45 {
9 | //[0,3,2,6,4]
10 | public boolean isContinuous(int[] numbers) {
11 | if (numbers.length != 5) {
12 | return false;
13 | }
14 | int num = 0;
15 | TreeSet set = new TreeSet<>();
16 | for (int i = 0; i < numbers.length; i++) {
17 | if (numbers[i] == 0) {
18 | num++;
19 | } else {
20 | set.add(numbers[i]);
21 | }
22 | }
23 | if ((num + set.size()) != 5) {
24 | return false;
25 | }
26 | if ((set.last() - set.first()) < 5) {
27 | return true;
28 | }
29 | return false;
30 | }
31 |
32 | public static void main(String[] args) {
33 | TreeSet set = new TreeSet<>();
34 | set.add(3);
35 | set.add(1);
36 | set.add(4);
37 | set.add(2);
38 | set.add(5);
39 | System.out.println(set.first());
40 | System.out.println(set.last());
41 | }
42 | }
43 |
--------------------------------------------------------------------------------
/algorithm/nowcoder/JZ46.java:
--------------------------------------------------------------------------------
1 | package nowcoder;
2 |
3 | /**
4 | * JZ46, https://www.nowcoder.com/practice/f78a359491e64a50bce2d89cff857eb6?tpId=13&tags=&title=&diffculty=0&judgeStatus=0&rp=1
5 | */
6 | public class JZ46 {
7 | public int LastRemaining_Solution(int n, int m) {
8 | if (n <= 0) return -1;
9 | int index = 0;
10 | for (int i = 2; i <= n; ++i) {
11 | index = (index + m) % i;
12 | }
13 | return index;
14 | }
15 | }
16 |
--------------------------------------------------------------------------------
/algorithm/nowcoder/JZ47.java:
--------------------------------------------------------------------------------
1 | package nowcoder;
2 |
3 | public class JZ47 {
4 |
5 | public int Sum_Solution(int n) {
6 | int sum = n;
7 | boolean ans = (n > 0) && ((sum += Sum_Solution(n - 1)) > 0);
8 | return sum;
9 | }
10 |
11 | public static void main(String[] args) {
12 | JZ47 jz47 = new JZ47();
13 | System.out.println(jz47.Sum_Solution(4));
14 | }
15 |
16 | }
17 |
--------------------------------------------------------------------------------
/algorithm/nowcoder/JZ48.java:
--------------------------------------------------------------------------------
1 | package nowcoder;
2 |
3 | public class JZ48 {
4 | public int Add(int num1, int num2) {
5 | while (num2 != 0) {
6 | int temp = num1 ^ num2;
7 | num2 = (num1 & num2) << 1;
8 | num1 = temp;
9 | }
10 | return num1;
11 | }
12 |
13 | public static void main(String[] args) {
14 | JZ48 jz47 = new JZ48();
15 | jz47.Add(2, 3);
16 | }
17 |
18 | }
19 |
--------------------------------------------------------------------------------
/algorithm/nowcoder/JZ49.java:
--------------------------------------------------------------------------------
1 | package nowcoder;
2 |
3 | public class JZ49 {
4 | //"+2147483647" -> 2147483647
5 | //"1a33"->0
6 | public int StrToInt(String str) {
7 | if (str == null || str.equals("")) {
8 | return 0;
9 | }
10 | char[] chars = str.toCharArray();
11 | for (int i = 0; i < chars.length; i++) {
12 | if (i == 0) {
13 | if (chars[i] != '+' && chars[i] != '-' && ('0' > chars[i] || '9' < chars[i])) {
14 | return 0;
15 | }
16 | } else {
17 | if ('0' > chars[i] || '9' < chars[i]) {
18 | return 0;
19 | }
20 | }
21 | }
22 | String tempStr = null;
23 | if (chars[0] == '+') {
24 | tempStr = str.substring(1, chars.length);
25 | return Integer.parseInt(tempStr);
26 | }else if (chars[0] == '-'){
27 | tempStr = str.substring(1,chars.length);
28 | return Integer.parseInt(tempStr);
29 | }else {
30 | tempStr = str;
31 | return Integer.parseInt(tempStr);
32 | }
33 | }
34 |
35 | public static void main(String[] args) {
36 | JZ49 jz49 = new JZ49();
37 | System.out.println(jz49.StrToInt("1a33"));
38 | }
39 | }
40 |
--------------------------------------------------------------------------------
/algorithm/nowcoder/JZ5.java:
--------------------------------------------------------------------------------
1 | package nowcoder;
2 |
3 | import java.util.Stack;
4 |
5 | /**
6 | * JZ5, https://www.nowcoder.com/practice/54275ddae22f475981afa2244dd448c6?tpId=13&tags=&title=&diffculty=0&judgeStatus=0&rp=1
7 | */
8 | public class JZ5 {
9 | public static class Solution {
10 | Stack stack1 = new Stack();
11 | Stack stack2 = new Stack();
12 |
13 | public void push(int node) {
14 | stack1.push(node);
15 | }
16 |
17 | public int pop() {
18 | if (stack1.isEmpty() || stack2.isEmpty()) {
19 | throw new RuntimeException("queue in empty");
20 | }
21 | if (stack2.isEmpty()) {
22 | while (stack1.size() > 0) {
23 | stack2.push(stack1.pop());
24 | }
25 | }
26 | return stack2.pop();
27 | }
28 |
29 | public static void main(String[] args) {
30 | Solution solution = new Solution();
31 | solution.push(1);
32 | solution.push(2);
33 | solution.push(3);
34 | System.out.println(solution.pop());
35 | System.out.println(solution.pop());
36 | }
37 | }
38 |
39 |
40 | }
41 |
--------------------------------------------------------------------------------
/algorithm/nowcoder/JZ6.java:
--------------------------------------------------------------------------------
1 | package nowcoder;
2 |
3 | /**
4 | * JZ6, https://www.nowcoder.com/practice/9f3231a991af4f55b95579b44b7a01ba?tpId=13&tags=&title=&diffculty=0&judgeStatus=0&rp=1
5 | */
6 | public class JZ6 {
7 |
8 | public int minNumberInRotateArray(int[] array) {
9 | if (array.length == 0) {
10 | return 0;
11 | }
12 | if (array.length == 1) {
13 | return array[0];
14 | }
15 | for (int i = 1; i < array.length; i++) {
16 | if (array[i] < array[i - 1]) {
17 | return Math.min(array[0], array[i]);
18 | }
19 | }
20 | return array[0];
21 | }
22 |
23 | public int minNumberInRotateArray2(int [] array) {
24 | int low = 0 ;
25 | int high = array.length - 1;
26 | while(low < high){
27 | int mid = low + (high - low) / 2;
28 | if(array[mid] > array[high]){
29 | low = mid + 1;
30 | }else if(array[mid] == array[high]){
31 | high = high - 1;
32 | }else{
33 | high = mid;
34 | }
35 | }
36 | return array[low];
37 | }
38 |
39 | public static void main(String[] args) {
40 | int[] arr = new int[]{
41 | 3, 4, 5, 1, 2
42 | };
43 | JZ6 jz6 = new JZ6();
44 | int result = jz6.minNumberInRotateArray(arr);
45 | System.out.println(result);
46 | }
47 | }
48 |
--------------------------------------------------------------------------------
/algorithm/nowcoder/JZ68.java:
--------------------------------------------------------------------------------
1 | package algorithm.nowcoder;
2 |
3 | import java.util.HashMap;
4 | import java.util.HashSet;
5 | import java.util.Map;
6 | import java.util.Set;
7 |
8 | public class JZ68 {
9 |
10 | public class TreeNode {
11 | int val;
12 | TreeNode left;
13 | TreeNode right;
14 |
15 | TreeNode(int x) {
16 | val = x;
17 | }
18 | }
19 |
20 |
21 | Map parent = new HashMap<>();
22 | Set visited = new HashSet<>();
23 |
24 | public void dfs(TreeNode root) {
25 | if (root.left != null) {
26 | parent.put(root.left.val, root);
27 | dfs(root.left);
28 | }
29 | if (root.right != null) {
30 | parent.put(root.right.val, root);
31 | dfs(root.right);
32 | }
33 | }
34 |
35 | public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
36 | dfs(root);
37 | while (p != null) {
38 | visited.add(p.val);
39 | p = parent.get(p.val);
40 | }
41 | while (q != null) {
42 | if (visited.contains(q.val)) {
43 | return q;
44 | }
45 | q = parent.get(q.val);
46 | }
47 | return null;
48 | }
49 |
50 | /**
51 | * ...
52 | */
53 | public TreeNode lowestCommonAncestorV2(TreeNode root, TreeNode p, TreeNode q) {
54 | if (root == null || root == p || root == q) {
55 | return root;
56 | }
57 | TreeNode left = lowestCommonAncestorV2(root.left, p, q);
58 | TreeNode right = lowestCommonAncestorV2(root.right, p, q);
59 | if (left == null) {
60 | return right;
61 | }
62 | if (right == null) {
63 | return left;
64 | }
65 | return root;
66 | }
67 |
68 | }
69 |
--------------------------------------------------------------------------------
/algorithm/nowcoder/JZ7.java:
--------------------------------------------------------------------------------
1 | package nowcoder;
2 |
3 | /**
4 | * JZ7,https://www.nowcoder.com/practice/c6c7742f5ba7442aada113136ddea0c3?tpId=13&tags=&title=&diffculty=0&judgeStatus=0&rp=1
5 | */
6 | public class JZ7 {
7 | public int Fibonacci(int n) {
8 | if(n == 1){
9 | return 1;
10 | }
11 | int a = 0;
12 | int b = 1;
13 | int result = 0;
14 | for (int i = n; i >= 2; i--) {
15 | result = a + b;
16 | a = b;
17 | b = result;
18 | }
19 | return result;
20 | }
21 |
22 | public static void main(String[] args) {
23 | JZ7 jz7 = new JZ7();
24 | int zz = jz7.Fibonacci(2);
25 | System.out.println(zz);
26 | }
27 |
28 | }
29 |
--------------------------------------------------------------------------------
/algorithm/nowcoder/JZ8.java:
--------------------------------------------------------------------------------
1 | package nowcoder;
2 |
3 | /**
4 | * JZ8 , https://www.nowcoder.com/practice/8c82a5b80378478f9484d87d1c5f12a4?tpId=13&tags=&title=&diffculty=0&judgeStatus=0&rp=1
5 | */
6 | public class JZ8 {
7 |
8 | public int JumpFloor(int target) {
9 | if (target == 1) {
10 | return 1;
11 | }
12 | if (target == 2) {
13 | return 2;
14 | }
15 | int a = 1;
16 | int b = 2;
17 |
18 | int result = 0;
19 | for (int i = 2; i < target; i++) {
20 | result = a + b;
21 | a = b;
22 | b = result;
23 | }
24 | return result;
25 | }
26 |
27 | public static void main(String[] args) {
28 | JZ8 jz8 = new JZ8();
29 | System.out.println(jz8.JumpFloor(4));
30 | }
31 | }
32 |
--------------------------------------------------------------------------------
/algorithm/nowcoder/JZ9.java:
--------------------------------------------------------------------------------
1 | package nowcoder;
2 |
3 | /**
4 | * JZ9 , https://www.nowcoder.com/practice/22243d016f6b47f2a6928b4313c85387?tpId=13&tags=&title=&diffculty=0&judgeStatus=0&rp=1
5 | */
6 | public class JZ9 {
7 |
8 | public int JumpFloorII(int target) {
9 | if (target <= 0) {
10 | return -1;
11 | } else if (target == 1) {
12 | return 1;
13 | } else {
14 | return 2 * JumpFloorII(target - 1);
15 | }
16 | }
17 |
18 |
19 | public static void main(String[] args) {
20 | JZ9 jz9 = new JZ9();
21 | System.out.println(jz9.JumpFloorII(3));
22 | }
23 | }
24 |
--------------------------------------------------------------------------------
/algorithm/practice/Permutation.java:
--------------------------------------------------------------------------------
1 | package algorithm.practice;
2 |
3 | import java.util.ArrayList;
4 |
5 | public class Permutation {
6 |
7 | public void permutation(int[] numbers) {
8 | ArrayList> result = new ArrayList<>();
9 | build(numbers, 0, result);
10 | System.out.println(result.size());
11 | for (int i = 0; i < result.size(); i++) {
12 | System.out.print(result.get(i) + " ");
13 | System.out.println();
14 | }
15 | }
16 |
17 | public void build(int[] arr, int begin, ArrayList> result) {
18 | ArrayList list = new ArrayList<>();
19 | for (int i = 0; i < arr.length; i++) {
20 | list.add(arr[i]);
21 | }
22 | result.add(list);
23 | for (int i = begin; i < arr.length; i++) {
24 | swap(arr, begin, i);
25 | build(arr, begin + 1, result);
26 | swap(arr, i, begin);
27 | }
28 | }
29 |
30 | public void swap(int array[], int a, int b) {
31 | int temp = array[a];
32 | array[a] = array[b];
33 | array[b] = temp;
34 | }
35 | }
36 |
--------------------------------------------------------------------------------
/img/advance.jpeg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/linsir6/Android-Advance/e09ff3bb230423f228dc5bceaa5c9f8ab41e143d/img/advance.jpeg
--------------------------------------------------------------------------------
/java/Java内存模型以及GC原理.md:
--------------------------------------------------------------------------------
1 | # Java GC原理
2 |
3 | ## 背景
4 |
5 | JAVA GC是可以帮助我们回收系统中无用的内存,这件事情Java内部已经替我们做了,但是这个不是我们说我们可以完全不了解GC内部原理的,因为如果我们随意使用JAVA内存,或者使用不当的话,可能会导致内存泄漏,或者系统进行频繁的GC这样会导致我们的应用卡顿,或者出现OOM的问题。本文的主要目的就是让我们更加了解内存GC的原理,编写出更加高效的代码,使我们的应用更加的稳定。
6 |
7 |
8 | ## JVM内存管理
9 |
10 | JVM内存区域
11 |
12 | 1. 方法区
13 | 所有线程共享,用于存储已经被虚拟机加载的类信息、常量、静态变量、即时编译器编译后的代码数据。方法区还有另一个名字叫做非堆,用于和Java堆进行区分,方法区一般被成为永久代,一般来说这个区域很少进行垃圾回收,其上的GC主要针对常量池的回收和已加载类的卸载。在方法区上进行GC,条件相当苛刻而且困难。
14 | 运行时常量池:用来存储编译器产生的常量和引用。
15 | 2. 堆区
16 | 被所有线程共享,在虚拟机启动的时候创建,用来存放对象实例,记录所有对象的实例都在这里分配,对于大多数应用来说,堆是虚拟机所属管理的内存中最大的一块。
17 | Java堆是垃圾收集器管理的主要区域,因此很多时候也称为GC堆,如果从内存回收的角度来看,由于现在收集器基本都是采用的分代收集算法,所以Java堆中还可以细分为新生代和老年代,新生代由三部分组成:Eden空间,From Survivor控件,To Survivor控件三部分组成。Java堆不需要连续的内存,并且可以通过动态增加内存,增加失败会抛出OutOfMemoryError异常。
18 | 3. 虚拟机栈
19 | 线程私有的,它的生命周期与线程相同
20 | 虚拟机栈描述的是Java方法执行的内存模型,每个方法被执行的时候都会同时创建一个栈帧,用于存储局部变量表,操作栈,动态链接,方法出口等信息,每一个方法被调用直至执行完成的过程,就对应着一个栈帧在虚拟机栈中从入栈到出栈的过程。
21 | 局部变量表存放了从编译期可知的各种基本数据类型(boolean,byte,char,short,int,float,long,double),
22 | 4. 本地方法栈
23 | 与虚拟机栈非常相似,区别是虚拟机栈为虚拟机执行的Java方法,也就是字节码服务,而本地方法栈则是为虚拟机使用到的Native方法服务。虚拟机规范中对本地方法栈中的方法使用的语言、使用方式与数据结构并没有强制规定,因此具体的虚拟机可以自由实现它。甚至有的虚拟机(譬如Sun HotSpot 虚拟机)直接就把本地方法栈和虚拟机栈合二为一。
24 | 5. 程序计数器
25 | 线程私有,它的生命周期与线程的生命周期相同
26 | 可以看作是当前线程所执行的字节码的信号指示器
27 | 如果正在执行的是一个Java方法,这个计数器记录的是正在执行虚拟机字节码指令的地址,如果正在执行的是Native方法,这个计数器的值则为空
28 | 程序计数器所占用的空间大小不会随着程序执行而发生改变,所以这个区域是不会发生OutOfMemoryError
29 |
30 | ## GC的查找算法
31 |
32 | **引用计数发** 为每个对象,添加引用计数器,每被引用一次,计数器便加一,失去引用计数器就减一,在计数器在一段时间都为0的时候,便可以将它回收了。不过可能产生相互引用的情况,就会导致永远也不会回收。
33 |
34 | **可达性分析法** 从一个GC Root的根结点出发,向下搜索,如果一个对象不能从GC Root结点出发到达之后,就说明该对象已经不再被引用了,便可以回收了。
35 |
36 | a.该类的所有实例都已经被回收;
37 | b.加载该类的ClassLoad已经被回收;
38 | c.该类对应的反射类java.lang.Class对象没有被任何地方引用。
39 |
40 | ## 内存分区
41 |
42 | 内存区域主要分为三块,新生代,旧生代,持久代。新生代比较适合生命周期较短,快速创建和销毁的对象,旧生代比较适合生命周期较长的对象,持久代在虚拟机中就是指方法区(有一些JVM中根本没有持久代的概念)
43 |
44 | **新生代** 内部分为Eden区和Survivor区,Survivor区又分为大小相同的两部分:FromSpace和ToSpace。新建的对象是从新生代分配内存,当Eden区不足的时候,会把存活的对象转移到Survivor区。当新生代进行垃圾回收时会发出Minor GC,(也称为Youn GC)。
45 |
46 | **旧生代** 旧生代用于存放新生代多次回收依然存活的对象,如缓存对象,当旧生代满了的时候,会对旧生代进行回收,旧生代的垃圾回收称为Major GC(也称Full GC)
47 |
48 | ## GC回收算法
49 |
50 | 1. **复制-清除** 从根结点进行扫描,将活的对象移动到一块空闲的区域,这样复制完之后,就可以完全释放另一块区域的所有内容,当对象存活的对象较少时,复制算法会比较高效,带来的成本就是需要一块额外的空闲空间和对象的移动。
51 |
52 | 2. **标记-清除** 该方法采用的方式是从根集合开始扫描,对存活的对象进行标记,标记完毕后,再扫描整个空间,将未被标记的对象进行清除。
53 |
54 | 3. **标记-压缩** 该算法与标记-清除算法类似,都是先对存活的对象进行标记,但是在清除后会把活的对象向左端空闲空间移动,然后在更新引用对象的指针
55 |
56 |
57 | 由于进行了移动规整动作,该算法避免了标记-清除的碎片问题,但由于需要进行移动,因此成本也增加了。(该算法适用于旧生代)
58 |
59 |
--------------------------------------------------------------------------------