Skip to content

Commit d886046

Browse files
committed
Modified 2 solutions
1 parent 2cc697f commit d886046

File tree

2 files changed

+36
-36
lines changed

2 files changed

+36
-36
lines changed

Easy/Array Partition I.java

Lines changed: 16 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,20 @@
11
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;
713
}
8-
9-
return sum;
14+
odd = !odd;
15+
arr[i]--;
16+
}
1017
}
18+
return sum;
19+
}
1120
}

Easy/Count and Say.java

Lines changed: 20 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -1,32 +1,23 @@
11
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;
319
}
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+
}
3223
}

0 commit comments

Comments
 (0)