File tree 2 files changed +36
-36
lines changed
2 files changed +36
-36
lines changed Original file line number Diff line number Diff line change 1
1
class Solution {
2
- public int arrayPairSum (int [] nums ) {
3
- Arrays .sort (nums );
4
- int sum = 0 ;
5
- for (int i = 0 ; i < nums .length ; i += 2 ) {
6
- sum += nums [i ];
2
+ public int arrayPairSum (int [] nums ) {
3
+ int [] arr = new int [20001 ];
4
+ for (int num : nums ) {
5
+ arr [num + 10000 ]++;
6
+ }
7
+ int sum = 0 ;
8
+ boolean odd = true ;
9
+ for (int i = 0 ; i < arr .length ; i ++) {
10
+ while (arr [i ] > 0 ) {
11
+ if (odd ) {
12
+ sum += i - 10000 ;
7
13
}
8
-
9
- return sum ;
14
+ odd = !odd ;
15
+ arr [i ]--;
16
+ }
10
17
}
18
+ return sum ;
19
+ }
11
20
}
Original file line number Diff line number Diff line change 1
1
class Solution {
2
- public String countAndSay (int n ) {
3
- String first = "1" ;
4
- String str = "11" ;
5
-
6
- if (n == 1 ) return first ;
7
- if (n == 2 ) return str ;
8
-
9
- for (int i = 3 ; i <=n ; i ++) {
10
- str += "$" ;
11
- int len = str .length ();
12
-
13
- int cnt = 1 ;
14
- String tmp = "" ;
15
-
16
- for (int j = 1 ; j < len ; j ++) {
17
- if (str .charAt (j ) != str .charAt (j -1 )) {
18
- tmp += String .valueOf (cnt );
19
- tmp += str .charAt (j -1 );
20
-
21
- cnt = 1 ;
22
- }
23
-
24
- else cnt ++;
25
- }
26
-
27
- str = tmp ;
28
- }
29
-
30
- return str ;
2
+ public String countAndSay (int n ) {
3
+ return rec (n , "1" );
4
+ }
5
+
6
+ private String rec (int n , String s ) {
7
+ if (n == 1 ) {
8
+ return s ;
31
9
}
10
+ StringBuilder sb = new StringBuilder ();
11
+ int idx = 0 ;
12
+ while (idx < s .length ()) {
13
+ char c = s .charAt (idx );
14
+ int count = 0 ;
15
+ while (idx < s .length () && s .charAt (idx ) == c ) {
16
+ idx ++;
17
+ count ++;
18
+ }
19
+ sb .append (count ).append (c );
20
+ }
21
+ return rec (n - 1 , sb .toString ());
22
+ }
32
23
}
You can’t perform that action at this time.
0 commit comments