力扣第 339 场周赛
题目链接:https://leetcode.cn/contest/weekly-contest-339/
# T1. 最长平衡子字符串
链接:https://leetcode.cn/problems/find-the-longest-balanced-substring-of-a-binary-string/
# 思路
从左到右遍历字符数组 chs:
- 若 
chs[i] == '0',zero 加一,继续遍历 - 若 
chs[i] == '1',统计从 i 位置开始的最大连续 1 的子字符串长度 len,则当前得到最长平衡子字符串的长度为:min(zero, len) * 2。 
因此,整个字符串的最长平衡子字符串的长度就是变量过程中产生的最长平衡子字符串的最大值
# 代码
class Solution {  | |
public int findTheLongestBalancedSubstring(String s) {  | |
char[] chs = s.toCharArray();  | |
int n = chs.length;  | |
int ret = 0;  | |
int zero = 0;  | |
for (int i = 0; i < n; ++i) {  | |
if (chs[i] == '0') {  | |
++zero;  | |
} else {  | |
                // 记录连续 1 的个数 | |
int j = i;  | |
while (j < n && chs[j] == '1') ++j;  | |
ret = Math.max(ret, Math.min(j - i, zero) * 2);  | |
zero = 0;  | |
                // 更新 i | |
i = j - 1;  | |
            } | |
        } | |
return ret;  | |
    } | |
} | 
# 提交结果

# T2. 转换二维数组
链接:https://leetcode.cn/problems/convert-an-array-into-a-2d-array-with-conditions/
# 思路
hash 计数,统计数组每个数出现的次数,次数最大值就是二维数组的行数,之后就是将每个数分别加入对应的行数组中即可,具体看代码。
# 代码
class Solution {  | |
public List<List<Integer>> findMatrix(int[] nums) {  | |
int[] cnt = new int[201];  | |
int row = 0;  | |
for (int num : nums) {  | |
++cnt[num];  | |
row = Math.max(cnt[num], row);  | |
        } | |
List<List<Integer>> list = new ArrayList<>(row);  | |
for (int i = 0; i < row; ++i) {  | |
list.add(new ArrayList<>());  | |
        } | |
for (int i = cnt.length - 1; i >= 0; --i) {  | |
int j = 0;  | |
while (cnt[i] > 0) {  | |
list.get(j++).add(i);  | |
--cnt[i];  | |
            } | |
        } | |
return list;  | |
    } | |
} | 
# 提交结果

# T3. 老鼠和奶酪
链接:https://leetcode.cn/problems/mice-and-cheese/solution/tan-xin-by-nifty-meitnerjyw-skfw/
# 思路
对于第 i,j 个奶酪,有以下选择:
- 第 i 个给老鼠一吃,第 j 个给老鼠二吃,则收益为: 
reward1[i] + reward2[j] - 第 i 个给老鼠二吃,第 j 个给老鼠一吃,则收益为: 
reawrd2[i] + reward1[j] 
要想老鼠一吃最大化收益,则:
reward1[i] + reward2[j] > reawrd2[i] + reward1[j] -> reward1[i] - reward2[i] > reward1[j] - reward2[j]
假设数组 arr=reward1[i]-reward2[i] ,则:
arr 最大的 k 个值对应的奶酪给老鼠一,其余给老鼠二
# 代码
class Solution {  | |
public int miceAndCheese(int[] reward1, int[] reward2, int k) {  | |
int n = reward1.length;  | |
int[][] d = new int[n][2];  | |
for (int i = 0; i < n; ++i) {  | |
d[i][0] = reward1[i] - reward2[i];  | |
d[i][1] = i;  | |
        } | |
        // 从大到小进行排序 | |
Arrays.sort(d, (a, b) -> b[0] - a[0]);  | |
int ans = 0;  | |
        // 前 k 个给老鼠一 | |
for (int i = 0; i < k; ++i) {  | |
ans += reward1[d[i][1]];  | |
        } | |
        // 剩余的给老鼠二 | |
for(int i = k; i < n; ++i) {  | |
ans += reward2[d[i][1]];  | |
        } | |
return ans;  | |
    } | |
} | 
# 提交结果
