A warm-up problem. Use a set to record vowels, then count one by one.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
classSolution { public: boolhalvesAreAlike(string s){ unordered_set<char> yuan = {'a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U'}; constint n = s.size(); int first = 0; for (int i = 0; i < n / 2; ++i) { if (yuan.find(s[i]) != yuan.end()) ++first; } int last = 0; for (int i = n / 2; i < n; ++i) { if (yuan.find(s[i]) != yuan.end()) ++last; } return first == last; } };
Time complexity: O(N), Space complexity: O(1).
5638. Maximum Number of Eaten Apples
Greedy. Eat the apples that are about to expire first.
Use TreeMap to maintain expiration time, and binary search to find the apple with the nearest expiration time.
classSolution { public: vector<int> findBall(vector<vector<int>>& grid){ constint m = grid.size(); constint n = grid[0].size(); function<int(constint, constint)> dfs = [&](constint row, constint col) -> int { if (row == m) { return col; } else { if (grid[row][col] == 1) { if (col == n - 1 || grid[row][col + 1] == -1) { return-1; } returndfs(row + 1, col + 1); } else { if (col == 0 || grid[row][col - 1] == 1) { return-1; } returndfs(row + 1, col - 1); } } }; vector<int> ans(n); for (int i = 0; i < n; ++i) { ans[i] = dfs(0, i); } return ans; } };
Time complexity: O(n * m).
5640. Maximum XOR With an Element From Array
Classic 0-1 Trie.
In the last problem, I was trapped by smart pointer shared_ptr and got TLE three times. After switching to raw pointers, it passed. Although the cost of smart pointers is small, shared_ptr is not zero-overhead. Even so, being blocked by LeetCode constant factors is still so annoying!