Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit aab42e8

Browse files
committed
Refactored 3 solutions
1 parent 399b9c9 commit aab42e8

File tree

3 files changed

+44
-43
lines changed

3 files changed

+44
-43
lines changed

Easy/Height Checker.java

Lines changed: 10 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,13 @@
11
class Solution {
2-
public int heightChecker(int[] heights) {
3-
int[] copy = Arrays.copyOf(heights, heights.length);
4-
Arrays.sort(copy);
5-
6-
int count = 0;
7-
for (int i = 0; i < heights.length; i++) {
8-
if (copy[i] != heights[i]) {
9-
count++;
10-
}
11-
}
12-
13-
return count;
2+
public int heightChecker(int[] heights) {
3+
int[] copy = Arrays.copyOf(heights, heights.length);
4+
Arrays.sort(copy);
5+
int count = 0;
6+
for (int i = 0; i < heights.length; i++) {
7+
if (heights[i] != copy[i]) {
8+
count++;
9+
}
1410
}
11+
return count;
12+
}
1513
}

Easy/Number of 1 bits.java

Lines changed: 11 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,14 @@
11
public class Solution {
2-
// you need to treat n as an unsigned value
3-
public int hammingWeight(int n) {
4-
int count = 0;
5-
for (int i=0; i<32; i++) {
6-
if ((n & 1) == 1) {
7-
count++;
8-
}
9-
10-
n = n >> 1;
11-
}
12-
13-
return count;
2+
// you need to treat n as an unsigned value
3+
public int hammingWeight(int n) {
4+
int bits = 0;
5+
int mask = 1;
6+
for (int i = 0; i < 32; i++) {
7+
if ((n & mask) != 0) {
8+
bits++;
9+
}
10+
mask <<= 1;
1411
}
12+
return bits;
13+
}
1514
}
Lines changed: 23 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -1,23 +1,27 @@
11
class Solution {
2-
int MOD = 1000000007;
3-
public int numRollsToTarget(int d, int f, int target) {
4-
Integer[][] dp = new Integer[d + 1][target + 1];
5-
return helper(d, f, target, dp);
2+
Map<String, Integer> map = new HashMap<>();
3+
final int MODULO = 1000000007;
4+
public int numRollsToTarget(int d, int f, int target) {
5+
if (d == 0 && target == 0) {
6+
return 1;
67
}
7-
8-
private int helper(int d, int f, int target, Integer[][] dp) {
9-
if (d == 0 || target <= 0) {
10-
return d == target ? 1 : 0;
11-
}
12-
if (dp[d][target] != null) {
13-
return dp[d][target];
14-
}
15-
16-
dp[d][target] = 0;
17-
for (int i = 1; i <= f; i++) {
18-
dp[d][target] = (dp[d][target] + helper(d - 1, f, target - i, dp)) % MOD;
19-
}
20-
21-
return dp[d][target];
8+
if (d == 0 || target == 0) {
9+
return 0;
2210
}
11+
String key = d + "|" + target;
12+
if (map.containsKey(key)) {
13+
return map.get(key);
14+
}
15+
int res = 0;
16+
for (int i = 1; i <= f; i++) {
17+
if (target >= i) {
18+
res = (res + numRollsToTarget(d - 1, f, target - i)) % MODULO;
19+
}
20+
else {
21+
break;
22+
}
23+
}
24+
map.put(key, res);
25+
return map.get(key);
26+
}
2327
}

0 commit comments

Comments
 (0)