File tree Expand file tree Collapse file tree 2 files changed +86
-0
lines changed Expand file tree Collapse file tree 2 files changed +86
-0
lines changed Original file line number Diff line number Diff line change 1+ class Solution {
2+ public List <List <String >> groupAnagrams (String [] strs ) {
3+ int [][] alphabets = new int [strs .length ]['z' - 'a' + 1 ];
4+
5+ for (int i = 0 ; i < strs .length ; i ++) {
6+ String str = strs [i ];
7+
8+ for (int j = 0 ; j < str .length (); j ++)
9+ alphabets [i ][str .charAt (j ) - 'a' ]++;
10+ }
11+
12+ boolean [] visited = new boolean [strs .length ];
13+
14+ List <List <String >> answer = new ArrayList <>();
15+
16+ for (int i = 0 ; i < strs .length ; i ++) {
17+ if (visited [i ]) continue ;
18+
19+ List <String > list = new ArrayList <>();
20+
21+ for (int j = i ; j < strs .length ; j ++) {
22+ if (visited [j ]) continue ;
23+ if (isAnagram (alphabets [i ], alphabets [j ])) {
24+ list .add (strs [j ]);
25+ visited [j ] = true ;
26+ }
27+ }
28+
29+ answer .add (list );
30+ }
31+
32+ return answer ;
33+ }
34+
35+ public boolean isAnagram (int [] arr1 , int [] arr2 ) {
36+ for (int i = 0 ; i < arr1 .length ; i ++) {
37+ if (arr1 [i ] != arr2 [i ])
38+ return false ;
39+ }
40+ return true ;
41+ }
42+ }
Original file line number Diff line number Diff line change 1+ import java .util .*;
2+
3+ class Solution {
4+ /*
5+ * I have to save indice for each index.
6+ * So I use the HashMap<Integer, List<Integer>>
7+ */
8+
9+ public boolean containsNearbyDuplicate (int [] nums , int k ) {
10+ HashMap <Integer , List <Integer >> map = new HashMap <>();
11+
12+ for (int i = 0 ; i < nums .length ; i ++) {
13+ if (!map .containsKey (nums [i ])) {
14+ map .put (nums [i ], new ArrayList <>());
15+ }
16+ map .get (nums [i ]).add (i );
17+ }
18+
19+ // use Iterator to find appropriate two indice.
20+ // Each list guarantee ascending.
21+ // So list.get(i) and list.get(i + 1) is minimum.
22+ Iterator <Integer > keys = map .keySet ().iterator ();
23+ boolean answer = false ;
24+
25+ while (keys .hasNext ()) {
26+ int key = keys .next ();
27+ List <Integer > list = map .get (key );
28+
29+ if (list .size () < 2 ) continue ;
30+
31+ for (int i = 1 ; i < list .size (); i ++) {
32+ int a = list .get (i - 1 );
33+ int b = list .get (i );
34+
35+ if (b - a <= k ) {
36+ answer = true ;
37+ break ;
38+ }
39+ }
40+ if (answer ) break ;
41+ }
42+ return answer ;
43+ }
44+ }
You can’t perform that action at this time.
0 commit comments