File tree Expand file tree Collapse file tree 2 files changed +79
-0
lines changed
0501.Find Mode in Binary Search Tree Expand file tree Collapse file tree 2 files changed +79
-0
lines changed Original file line number Diff line number Diff line change 1+ class Solution {
2+
3+ public String [] findWords (String [] words ) {
4+ if (words == null ) {
5+ return null ;
6+ }
7+ ArrayList <String > list = new ArrayList <>();
8+ String [] keyboards = {"qwertyuiop" , "asdfghjkl" , "zxcvbnm" };
9+ for (int i = 0 ; i < words .length ; i ++) {
10+ String word = words [i ].toLowerCase ();
11+ for (int j = 0 ; j < keyboards .length ; j ++) {
12+ // 先用word首字符确定属于哪一行
13+ if (keyboards [j ].indexOf (word .charAt (0 )) > -1 ) {
14+ // 判断word字符串所有字符是否都属于同一行
15+ boolean match = match (keyboards [j ], word , list );
16+ if (match ) {
17+ list .add (words [i ]);
18+ }
19+ break ;
20+ }
21+ }
22+ }
23+ return list .toArray (new String [list .size ()]);
24+ }
25+
26+ private boolean match (String keyboard , String word , ArrayList <String > list ) {
27+ for (int i = 1 ; i < word .length (); i ++) {
28+ if (keyboard .indexOf (word .charAt (i )) < 0 ) {
29+ return false ;
30+ }
31+ }
32+ return true ;
33+ }
34+ }
Original file line number Diff line number Diff line change 1+ /**
2+ * Definition for a binary tree node.
3+ * public class TreeNode {
4+ * int val;
5+ * TreeNode left;
6+ * TreeNode right;
7+ * TreeNode(int x) { val = x; }
8+ * }
9+ */
10+ class Solution {
11+ int max = 0 ;
12+ int cur = 0 ;
13+ TreeNode preNode = null ;
14+
15+ public int [] findMode (TreeNode root ) {
16+ ArrayList <Integer > list = new ArrayList <>();
17+ findMode (root , list );
18+ int [] res = new int [list .size ()];
19+ for (int i = 0 ; i < list .size (); i ++) {
20+ res [i ] = list .get (i );
21+ }
22+ return res ;
23+ }
24+
25+ private void findMode (TreeNode root , ArrayList <Integer > list ) {
26+ if (root == null ) {
27+ return ;
28+ }
29+ findMode (root .left , list );
30+ if (preNode != null && root .val == preNode .val ) {
31+ cur ++;
32+ } else {
33+ cur = 1 ;
34+ }
35+ if (max < cur ) {
36+ max = cur ;
37+ list .clear ();
38+ list .add (root .val );
39+ } else if (max == cur ) {
40+ list .add (root .val );
41+ }
42+ preNode = root ;
43+ findMode (root .right , list );
44+ }
45+ }
You can’t perform that action at this time.
0 commit comments