
方法一:枚举
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
| class Solution { public int countSymmetricIntegers(int low, int high) { int res = 0; for (int i = low; i <= Math.min(high, 99); ++i) { int l = i % 10, r = i / 10; if (l == r) ++res; } if (high > 1000) { for (int i = Math.max(low, 1000); i <= Math.min(high, 10000); ++i) { int pre = 0, suff = 0; int l = i; pre += (l % 10); l /= 10; pre += (l % 10); int r = i / 100; suff += (r % 10); r /= 10; suff += (r % 100); if (pre == suff) ++res; } } return res; } }
|

方法一:贪心
从后往前找,找到子序列25, 50, 75, 00,统计最少需要删除的个数;如果没找到,那么如果字符串中没有0,那么全部删除;如果有0,则删除n-1个字符
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54
| class Solution { public int minimumOperations(String s) { int n = s.length(); int cnt0 = 0;
for (int i = 0; i < n; ++i) { if (s.charAt(i) == '0') cnt0++; } int res = 101; int flag = 0; int cnt = 0; for (int i = n - 1; i >= 0; --i) { char ch = s.charAt(i); if (flag == 0) { if (ch == '0') flag = 1; else ++cnt; } else if (flag == 1) { if (ch == '0' || ch == '5') flag = 2; else ++cnt; } else break; } if (flag == 2) res = Math.min(res, cnt); flag = 0; cnt = 0; for (int i = n - 1; i >= 0; --i) { char ch = s.charAt(i); if (flag == 0) { if (ch == '5') flag = 1; else ++cnt; } else if (flag == 1) { if (ch == '2' || ch == '7') flag = 2; else ++cnt; } else break; } if (flag == 2) res = Math.min(res, cnt); if (res == 101) { res = cnt0 == 0 ? n : n - 1; } return res; } }
|

方法一:前缀和 + HashMap + 公式转换
类似两数之和
1 2 3 4 5 6 7 8 9 10 11 12 13
| public long countInterestingSubarrays(List<Integer> nums, int modulo, int k) { Map<Integer, Integer> map = new HashMap<>(); map.put(0, 1); long res = 0; int s = 0; for (int x : nums) { if (x % modulo == k) s = (s + 1) % modulo; res += map.getOrDefault((s - k + modulo) % modulo, 0); map.put(s, map.getOrDefault(s, 0) + 1); } return res; }
|

