题目链接:https://leetcode.cn/contest/biweekly-contest-99/
# 第一题:排序 + 奇偶分组
# 解题思路
- 分解每一位数字,并将它们进行排序
- 从第一个不为零的数字开始,进行奇偶分离,再重新组成的两个整数和就是最小和
# 提交结果
# 代码
| class Solution { |
| public int splitNum(int num) { |
| int[] d = new int[10]; |
| int n = 0; |
| |
| while (num > 0) { |
| ++d[num % 10]; |
| num /= 10; |
| } |
| |
| |
| int odd = 0; |
| int even = 0; |
| boolean isOdd = false; |
| int i = 1; |
| while (i < d.length) { |
| if (d[i] < 1) { |
| ++i; |
| continue; |
| } |
| |
| if (isOdd) odd = odd * 10 + i; |
| else even = even * 10 + i; |
| isOdd = !isOdd; |
| --d[i]; |
| } |
| |
| return even + odd; |
| } |
| } |
# 第二题:数学找规律
# 解题思路
- 规律为:
- 1:1
- 2:1 + 3 + 1
- 3:1 + 3 + 5 + 3 + 1
- 4:1 + 3 + 5 + 7 + 5 + 3 + 1
- ......
- 于是,两个等差数列求和:
(1 + 2 * n - 1) * n / 2 * 2 - 2 * n + 1 = n*n + (n - 1) * (n - 1)
# 提交结果
# 代码
| class Solution { |
| public long coloredCells(int n) { |
| long nn = n; |
| return nn*nn + (nn - 1) * (nn - 1); |
| } |
| } |
# 第三题:贪心 + 区间排序 + 数学统计
# 解题思路
- 统计不相交的区间集合数 group
- 对于每个集合,都有两种选择,即属于 A 组或 B 组,故答案就是 2^group
# 提交结果
# 代码
| class Solution { |
| public int countWays(int[][] ranges) { |
| int n = ranges.length; |
| final int MOD = (int) (1e9 + 7); |
| |
| int group = 0; |
| int r = Integer.MIN_VALUE; |
| |
| long res = 1L; |
| |
| Arrays.sort(ranges, (o1, o2) -> o1[0] == o2[0] ? o1[1] - o2[1] : o1[0] - o2[0]); |
| |
| for (int i = 0; i < n; ++i) { |
| if (ranges[i][0] > r) { |
| ++group; |
| res = (res * 2) % MOD; |
| r = ranges[i][1]; |
| continue; |
| } |
| r = Math.max(r, ranges[i][1]); |
| } |
| |
| return (int) res; |
| } |
| } |