Given typedText containing uppercase and lowercase English letters, return upper_count - lower_count.
Example: typedText = "AbCd" → upper = 2, lower = 2, answer = 0.
解法
单次遍历,分别统计大写和小写字母数后相减。复杂度 O(n)。
def letter_case_diff(s: str) -> int:
return sum(1 for c in s if c.isupper()) - sum(1 for c in s if c.islower())class Solution {
static int letterCaseDiff(String s) {
int u = 0, l = 0;
for (char c : s.toCharArray()) {
if (Character.isUpperCase(c)) u++;
else if (Character.isLowerCase(c)) l++;
}
return u - l;
}
}#include <string>
#include <cctype>
using namespace std;
int letterCaseDiff(string s) {
int u = 0, l = 0;
for (char c : s) {
if (isupper((unsigned char)c)) u++;
else if (islower((unsigned char)c)) l++;
}
return u - l;
}A bird builds a nest by collecting sticks in a forest. forest[] non-negative integers; non-zero = stick of that length, zero = empty cell. Start at index bird, fly right searching the next non-zero cell, take it (mark zero), append the stick to the nest. Then flip direction (right → left → right ...). Continue until total nest length ≥ 100. Return 0-based indices of sticks collected, in order.
Example: forest = [3, 0, 50, 0, 80, 0, 25], bird = 0 → fly right, pick 3 at index 0, total 3; flip left → no stick; flip right → pick 50 at index 2, total 53; flip left → no stick; flip right → pick 80, total 133 ≥ 100, stop.
解法
模拟:维护 pos 和 direction;前进直到非零格收走,翻转方向,循环直到总和 ≥ 100 或越界。复杂度 O(n)。
def bird_sticks(forest: list[int], bird: int) -> list[int]:
f = list(forest)
n = len(f)
out, total = [], 0
pos, d = bird, 1
while total < 100:
i = pos
while 0 <= i < n and f[i] == 0:
i += d
if i < 0 or i >= n:
break
out.append(i)
total += f[i]
f[i] = 0
pos, d = i + d, -d
return outimport java.util.*;
class Solution {
static int[] birdSticks(int[] forest, int bird) {
int n = forest.length, total = 0, pos = bird, dir = 1;
List<Integer> out = new ArrayList<>();
while (total < 100) {
int i = pos;
while (i >= 0 && i < n && forest[i] == 0) i += dir;
if (i < 0 || i >= n) break;
out.add(i);
total += forest[i];
forest[i] = 0;
pos = i + dir;
dir = -dir;
}
int[] arr = new int[out.size()];
for (int k = 0; k < arr.length; k++) arr[k] = out.get(k);
return arr;
}
}#include <vector>
using namespace std;
vector<int> birdSticks(vector<int> forest, int bird) {
int n = forest.size(), total = 0, pos = bird, dir = 1;
vector<int> out;
while (total < 100) {
int i = pos;
while (i >= 0 && i < n && forest[i] == 0) i += dir;
if (i < 0 || i >= n) break;
out.push_back(i);
total += forest[i];
forest[i] = 0;
pos = i + dir;
dir = -dir;
}
return out;
}Events of two types:
MESSAGE id<num> <timestamp> <mention_text>—mention_textis space-separated tokens ofid<num>,ALL, orHERE.OFFLINE id<num>— that user becomes inactive (still exists, butHEREwon't count them).
ALL mentions every existing user; HERE mentions every currently-active user. Each mention token counted once per message regardless of repeats; self-mentions count. Return strings "id<num>=<count>" sorted lexicographically.
解法
维护两个集合 all_users、active_users 和计数表。每条 MESSAGE:把发送者放入两个集合,构造去重 mention 集合,每个成员计数加 1。OFFLINE:仅从 active_users 移除。复杂度 O(total events + total mentions)。
def chat_mentions(events: list[str]) -> list[str]:
all_, active = set(), set()
cnt = {}
for ev in events:
parts = ev.split()
if parts[0] == "MESSAGE":
sender = parts[1]
all_.add(sender); active.add(sender)
mentioned = set()
for tok in parts[3:]:
if tok == "ALL": mentioned |= all_
elif tok == "HERE": mentioned |= active
else: mentioned.add(tok)
for m in mentioned:
cnt[m] = cnt.get(m, 0) + 1
else:
active.discard(parts[1])
return [f"{k}={v}" for k, v in sorted(cnt.items())]import java.util.*;
class Solution {
static List<String> chatMentions(List<String> events) {
Set<String> all = new HashSet<>(), active = new HashSet<>();
Map<String, Integer> cnt = new TreeMap<>();
for (String ev : events) {
String[] parts = ev.split("\\s+");
if (parts[0].equals("MESSAGE")) {
String sender = parts[1];
all.add(sender); active.add(sender);
Set<String> mentioned = new HashSet<>();
for (int i = 3; i < parts.length; i++) {
if (parts[i].equals("ALL")) mentioned.addAll(all);
else if (parts[i].equals("HERE")) mentioned.addAll(active);
else mentioned.add(parts[i]);
}
for (String m : mentioned) cnt.merge(m, 1, Integer::sum);
} else {
active.remove(parts[1]);
}
}
List<String> out = new ArrayList<>();
for (var e : cnt.entrySet()) out.add(e.getKey() + "=" + e.getValue());
return out;
}
}#include <vector>
#include <string>
#include <sstream>
#include <unordered_set>
#include <map>
using namespace std;
vector<string> chatMentions(vector<string>& events) {
unordered_set<string> all_, active;
map<string, int> cnt;
for (auto& ev : events) {
stringstream ss(ev);
vector<string> parts;
string tok;
while (ss >> tok) parts.push_back(tok);
if (parts[0] == "MESSAGE") {
const string& sender = parts[1];
all_.insert(sender); active.insert(sender);
unordered_set<string> mentioned;
for (int i = 3; i < (int)parts.size(); i++) {
if (parts[i] == "ALL") mentioned.insert(all_.begin(), all_.end());
else if (parts[i] == "HERE") mentioned.insert(active.begin(), active.end());
else mentioned.insert(parts[i]);
}
for (auto& m : mentioned) cnt[m]++;
} else {
active.erase(parts[1]);
}
}
vector<string> out;
for (auto& [k, v] : cnt) out.push_back(k + "=" + to_string(v));
return out;
}Given lamps[m][2] (each [l, r] lit segment) and points[k] query positions. For each points[i], return how many lamps illuminate it (i.e. l ≤ points[i] ≤ r).
Example: lamps = [[1,5], [3,7]], points = [4, 6] → [2, 1].
Given arr[], repeatedly filter: keep only elements strictly greater than both neighbors (first and last elements are always kept). Iterate until the array stops changing. Return the final array.
Example: [3, 6, 4, 8, 2, 9] → [3, 6, 8, 9] → [3, 9].
Given word of lowercase letters, you may apply exactly one operation: reverse the first k characters or reverse the last k characters (1 ≤ k ≤ |word|). Return the lexicographically smallest string achievable.
Example: word = "edcba" → reverse all 5 → "abcde".
A square 4n × 4n matrix is divided into n² size-4 × 4 sub-squares. Each sub-square has all integers 1..16 except one missing (-1). Steps:
- For each sub-square, fill in the missing value (
136 − sum, where136 = 1+2+…+16). - Collect the filled values across all sub-squares, sort them ascending, and place them back to the missing positions in row-major order of those positions.
Return the updated matrix.
Given book names titles[n] (lowercase letters). Count the number of ordered pairs (i, j) with i ≠ j such that titles[i] is a prefix of titles[j] (identical strings also count).
Example: titles = ["ab", "abc", "ab"] → ordered prefix pairs (0,1), (0,2), (2,0), (2,1) → 4.
Design a banking system that supports the operations: create_account, deposit, pay, top_activity (top-N accounts by outgoing volume), transfer (initiated; recipient must accept within 24h), accept_transfer, merge_accounts, and get_balance(time_at) (balance at a historical timestamp). Methods are called with monotonic timestamps.
Example: deposit, then pay, then get_balance at the deposit timestamp returns the post-deposit balance, while at a later timestamp returns the post-pay balance.
Given an integer n and an integer array arr[n]. Choose at most k operations. Each operation picks an index i and does arr[i] = arr[i] · arr[i+1]. Maximize the sum of all elements after performing operations.
Example: arr = [2, 3, 4], k = 1 → either keep sum 9, or replace arr[0] with 2*3 = 6 (sum 13), or replace arr[1] with 3*4 = 12 (sum 18). Answer 18.
Given n distinct positive integers d[n] and threshold t, count index triplets (a, b, c) with d[a] < d[b] < d[c] such that d[a] + d[b] + d[c] ≤ t.
Example: d = [1,2,3,4,5], t = 8 → 4 triplets.
Implement a cache query handler that manages entries of the form {timestamp, key, value}:
timestamp:"hh:mm:ss".key: alphanumeric ID (e.g."a2er5i80").value: integer stored as string (e.g."125").
You are given:
cache_entries: array of[timestamp, key, value]strings.queries: array of[key, timestamp]strings.
For each query, return the integer value stored for that exact {key, timestamp} pair. It is guaranteed each queried pair exists in the cache.
Example: cache_entries = [["12:30:22","a2er5i80","125"], ["09:07:47","io09ju56","341"], ["01:23:09","a2er5i80","764"]], queries = [["a2er5i80","01:23:09"], ["io09ju56","09:07:47"]] → [764, 341].
You are given an integer array arr of size n. You may perform the following operation any number of times (including zero): choose two distinct indices i and j and multiply both arr[i] and arr[j] by -1. Return the maximum possible sum of the array.
Example: arr = [-5, -1, 7] → flip indices 0 and 1 → [5, 1, 7], sum 13.
Constraints
2 ≤ n ≤ 2*10⁵, -10⁹ ≤ arr[i] ≤ 10⁹.
A variant of Restore Missing Squares: a 4 × (4n) grid contains n size-4 × 4 sub-squares laid side-by-side. Each sub-square is missing one cell (marked -1). For each sub-square compute the missing value (136 − sum); then reorder the entire sub-squares left-to-right so that their missing values are in ascending order. Return the rearranged grid.
Example: 2 side-by-side 4 × 4 blocks with missing values 12, 7 → after rearrangement the block with missing value 7 comes first.
You are tasked with analyzing the pote
Example 1
Input:
cityline = [1, 2, 3, 2, 1]
Output:
4
Explanation: In this configuration, there are several 2x2 squares that can be accommodated within the skyscrapers, but no larger square can fit owing to the limitations of their heights.
You are given two integer arrays A and B of equal length.
For any contiguous subarray of indices, you may choose exactly one value from either A[i] or B[i] at each index i in that subarray. Your goal is to make the chosen values form a non-decreasing sequence.
Return the maximum possible length of such a contiguous subarray.
Function Description
Complete the function longestSelectableNonDecreasingSubarray in the editor below.
longestSelectableNonDecreasingSubarray has the following parameters:
int[] A: the first arrayint[] B: the second array Returnsint: the maximum valid contiguous length.
Constraints
The source thread did not provide explicit numeric bounds.
A.length == B.length- You must choose exactly one of
A[i]orB[i]for each index in the selected subarray.
Example 1
Input:
A = [1, 3, 5, 4]
B = [2, 2, 6, 7]
Output:
4
Explanation:
Choose the sequence [1, 2, 5, 7] by taking A[0], B[1], A[2], and B[3]. It is non-decreasing, so the full length 4 is valid.
Example 2
Input:
A = [5, 4, 3]
B = [1, 2, 3]
Output:
3
Explanation:
Choose [1, 2, 3] from array B. The entire array is a valid non-decreasing contiguous subarray.
You are given two integer arrays a and b of the same length and an integer k. For each index i, that index contributes min(a[i], b[i]) to a total sum.
You may choose at most k distinct indices. For each chosen index, replace b[i] with 2 * b[i]. After applying those changes, the contribution of that index becomes min(a[i], 2 * b[i]).
Return the maximum possible total contribution.
Function Description
Complete the function maximizeCappedContributionSum in the editor below.
maximizeCappedContributionSum has the following parameters:
int[] a: the first arrayint[] b: the second arrayint k: the maximum number of indices whoseb[i]value can be doubled Returnslong: the maximum possible total sum.
Constraints
The source thread did not provide explicit numeric bounds.
a.length == b.length0 ≤ k ≤ a.length- Each index may be doubled at most once.
Example 1
Input:
a = [5, 8, 4]
b = [3, 6, 10]
k = 1
Output:
15
Explanation:
The initial contribution is min(5,3) + min(8,6) + min(4,10) = 3 + 6 + 4 = 13. If you double b[0], the first contribution becomes min(5,6) = 5. If you double b[1], the second becomes min(8,12) = 8. Either choice gives a gain of 2, so the best total is 15.
Example 2
Input:
a = [10, 7, 6, 4]
b = [2, 5, 4, 3]
k = 2
Output:
18
Explanation:
The initial total is 2 + 5 + 4 + 3 = 14. Doubling index 0 changes its contribution to min(10,4)=4, a gain of 2. Doubling index 1 changes its contribution to min(7,10)=7, a gain of 2. Doubling index 2 changes its contribution to min(6,8)=6, a gain of 2. Any two of those three gains produce the maximum total 14 + 2 + 2 = 18.
There are n people. Person i has hiring cost costs[i] and may have Skill 1, Skill 2, both skills, or neither skill.
For every K from 1 to n, compute the minimum total hiring cost needed so that the selected subset contains at least K people with Skill 1 and at least K people with Skill 2. A person who has both skills contributes to both counts.
Return an array ans of length n where ans[K - 1] is the minimum cost for that quota, or -1 if it is impossible.
Function Description
Complete the function minimumCostForSkillQuotas in the editor below.
minimumCostForSkillQuotas has the following parameters:
int[] costs: hiring costs for each personint[] skill1:1if the person has Skill 1, else0int[] skill2:1if the person has Skill 2, else0Returnslong[]: the minimum cost for every quota sizeK = 1..n.
解锁全部 15 道题的解法
题面你已经看到了 — 解法 + 三语代码 + 复杂度推导 + 边界讨论, Pro 解锁.
- 📚1000+ 道真实北美 OA, Python / Java / C++ 三语题解
- 📊个人 dashboard + 进度可视化 + 14 天活跃图
- 📝题目笔记跨设备同步 + 个人复盘库
- 🔓随时取消下次续费, Stripe Customer Portal 自助管理