Skip to content

Commit 468da7d

Browse files
author
zhuchen
committed
2020-6-20
1 parent 641f44d commit 468da7d

File tree

3 files changed

+91
-0
lines changed

3 files changed

+91
-0
lines changed

question0458_poor_pigs/Solution.java

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
package question0458_poor_pigs;
2+
3+
public class Solution {
4+
5+
public int poorPigs(int buckets, int minutesToDie, int minutesToTest) {
6+
int states = minutesToTest / minutesToDie + 1;
7+
return (int) Math.ceil(Math.log(buckets) / Math.log(states));
8+
}
9+
10+
}
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
package question0479_largest_palindrome_product;
2+
3+
public class Solution {
4+
5+
public int largestPalindrome(int n) {
6+
if (n == 1) {
7+
return 9;
8+
}
9+
int upper = (int) (Math.pow(10, n) - 1), lower = (int) Math.pow(10, n - 1);
10+
for (int i = upper; i >= lower; i--) {
11+
String s = String.valueOf(i);
12+
String reverseS = reverse(s);
13+
long num = Long.parseLong(s + reverseS);
14+
for (long j = upper; j * j >= num; j--) {
15+
if (num % j == 0) {
16+
return (int) (num % 1337);
17+
}
18+
}
19+
}
20+
return -1;
21+
}
22+
23+
private static String reverse(String s) {
24+
StringBuilder sb = new StringBuilder();
25+
for (int i = s.length() - 1; i >= 0; i--) {
26+
sb.append(s.charAt(i));
27+
}
28+
return sb.toString();
29+
}
30+
31+
}
Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
package question0493_reverse_pairs;
2+
3+
public class Solution {
4+
5+
public int reversePairs(int[] nums) {
6+
if (nums.length == 0) {
7+
return 0;
8+
}
9+
return reversePairsRecursive(nums, 0, nums.length - 1);
10+
}
11+
12+
public int reversePairsRecursive(int[] nums, int left, int right) {
13+
if (left == right) {
14+
return 0;
15+
}
16+
int mid = left + ((right - left) >> 1), resultLeft = reversePairsRecursive(nums, left, mid),
17+
resultRight = reversePairsRecursive(nums, mid + 1, right),
18+
result = resultLeft + resultRight;
19+
// 首先统计下标对的数量
20+
int i = left, j = mid + 1;
21+
while (i <= mid) {
22+
while (j <= right && (long) nums[i] > 2 * (long) nums[j]) {
23+
j++;
24+
}
25+
result += j - mid - 1;
26+
i++;
27+
}
28+
// 随后合并两个排序数组
29+
int[] copy = new int[right - left + 1];
30+
int index1 = left, index2 = mid + 1, index = 0;
31+
while (index1 <= mid || index2 <= right) {
32+
if (index1 > mid) {
33+
copy[index++] = nums[index2++];
34+
} else if (index2 > right) {
35+
copy[index++] = nums[index1++];
36+
} else {
37+
if (nums[index1] < nums[index2]) {
38+
copy[index++] = nums[index1++];
39+
} else {
40+
copy[index++] = nums[index2++];
41+
}
42+
}
43+
}
44+
for (int k = 0; k < copy.length; k++) {
45+
nums[left + k] = copy[k];
46+
}
47+
return result;
48+
}
49+
50+
}

0 commit comments

Comments
 (0)