最常用的Collection是数组(Array),其最常使用的获取数据的操作是随机获取(Random access), 在C++中一般称作 subscribe。
但是有时,我们想要限制处理数据的顺序。最常见的限制是:先进先出(First in first out), 后进先出(Last in first out)。分别对应2种数据结构 队列(Queue) 和 栈(Stack)。
classSolution { public: vector<int> sumEvenAfterQueries(vector<int>& A, vector<vector<int>>& queries){ vector<int> results; for (const vector<int>& query : queries) { A[query[1]] += query[0]; int total = 0; for (int a : A) { if (a % 2 == 0) total += a; } results.push_back(total); } return results; } };
classSolution { public: vector<int> sumEvenAfterQueries(vector<int>& A, vector<vector<int>>& queries){ vector<int> results; int total = 0; for (int a : A) { if (a % 2 == 0) total += a; } for (const vector<int>& query : queries) { if (A[query[1]] % 2 == 0) total -= A[query[1]]; A[query[1]] += query[0]; if (A[query[1]] % 2 == 0) total += A[query[1]]; results.push_back(total); } return results; } };
classTimeMap { private: /** Intution: 使用hashmap存储<key, vector<pair<int, string>> value>, 每次查找到key对应的vector后,针对pair的第一个值使用二分查找upper_bound timestamp */ unordered_map<string, vector<pair<int, string>>> hashmap; classCmp { public: booloperator()(pair<int, string> a, pair<int, string> b){ return a.first < b.first; } }; public: /** Initialize your data structure here. */ TimeMap() { } voidset(string key, string value, int timestamp){ hashmap[key].push_back({timestamp, value}); } string get(string key, int timestamp){ auto& values = hashmap[key]; // 注意:用引用,千万不要用普通变量存储 if (values.size() == 0) return""; auto val = upper_bound(values.begin(), values.end(), make_pair(timestamp, ""), Cmp()); if (val == values.begin()) return""; return (--val)->second; } };
/** * Your TimeMap object will be instantiated and called as such: * TimeMap* obj = new TimeMap(); * obj->set(key,value,timestamp); * string param_2 = obj->get(key,timestamp); */
classSolution { public: vector<vector<int>> kClosest(vector<vector<int>>& points, int K) { map<int, vector<vector<int>>> distance; for (constauto point: points) { distance[point[0]*point[0] + point[1]*point[1]].push_back(point); } vector<vector<int>> results; int i = 0; for (constauto d: distance) { for (constauto point: d.second) { results.push_back(point); i++; if (i >= K) { return results; } } } return results; } };
976. Largest Perimeter Triangle
只用找最大的3个可以组成三角形的数就可以了。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
classSolution { public: intlargestPerimeter(vector<int>& A){ int result = 0; sort(A.begin(), A.end()); for (int i = A.size() - 3; i >= 0; i--) { if (A[i] + A[i+1] > A[i+2]) { result = A[i] + A[i+1] + A[i+2]; break; } } return result; } };
974. Subarray Sums Divisible by K
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
classSolution { public: intsubarraysDivByK(vector<int>& A, int K){ unordered_map<int, int> prefix_sum; int sum = 0; int result = 0; prefix_sum[0] = 1; for (int i = 0; i < A.size(); i++) { sum = (sum + A[i] % K + K) % K; result += prefix_sum[sum]; prefix_sum[sum]++; } return result; } };