classSolution { public: intminAreaRect(vector<vector<int>>& points){ auto cmp = [](constvector<int> &a, constvector<int> &b){ return a[0] < b[0] || a[0] == b[0] && a[1] < b[1]; }; sort(begin(points), end(points), cmp); vector<int> xs; unordered_map<int, vector<int>> m; for (constauto &p : points) { m[p[0]].push_back(p[1]); if (xs.empty() || xs.back() != p[0]) { xs.push_back(p[0]); } } int res = INT_MAX; int nx = xs.size(); for (int i = 0; i < nx; ++i) { if (m[xs[i]].size() == 1) continue; for (int j = i + 1; j < nx; ++j) { if (m[xs[j]].size() == 1) continue; res = min(res, helper(m, xs[i], xs[j])); } } return res == INT_MAX ? 0 : res; }
inthelper(unordered_map<int, vector<int>> &m, int a, int b){ unordered_set<int> s(begin(m[a]), end(m[a])); int n = m[b].size(); int diff = INT_MAX; for (int i = 0; i < n; ++i) { if (!s.count(m[b][i])) continue; int j = i + 1; while (j < n && !s.count(m[b][j])) ++j; if (j == n) break; diff = min(diff, m[b][j] - m[b][i]); i = j - 1; } return diff == INT_MAX ? diff : (b - a) * diff; } };
Posted onEdited onInLeetCodeDisqus: Symbols count in article: 882Reading time ≈1 mins.
二分猜数
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
classSolution { public: intminEatingSpeed(vector<int>& piles, int H){ int lo = 1, hi = 1e9; while (lo < hi) { int m = lo + (hi - lo) / 2; if (isValid(piles, H, m)) { hi = m; } else { lo = m + 1; } } return lo; }
boolisValid(constvector<int> &piles, int H, int m){ return accumulate(begin(piles), end(piles), 0, [m](int x, int y) { return x + (y - 1) / m + 1; }) <= H; } };
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
classSolution { public: intminEatingSpeed(vector<int>& piles, int H){ int lo = 1, hi = *max_element(begin(piles), end(piles)); while (lo < hi) { int m = lo + (hi - lo) / 2; if (isValid(piles, H, m)) { hi = m; } else { lo = m + 1; } } return lo; }
boolisValid(constvector<int> &piles, int H, int m){ return accumulate(begin(piles), end(piles), 0, [m](int x, int y) { return x + ceil(y / (double)m); }) <= H; } };
voiddfs(int s, constvector<int> &A, int b){ for (int i = b; i < A.size(); ++i) { s += A[i]; if (t - s <= res) return; if ((t - s) % 3 == 0) { res = max(res, t - s); return; } else { dfs(s, A, i + 1); } s -= A[i]; } }
classSolution { public: interaseOverlapIntervals(vector<vector<int>>& intervals){ sort(begin(intervals), end(intervals)); int res = 0, e = INT_MIN; for (constauto &i : intervals) { if (i[0] < e) { ++res; e = min(e, i[1]); } else { e = i[1]; } } return res; } };
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
classSolution { public: interaseOverlapIntervals(vector<vector<int>>& intervals){ int n = size(intervals); if (n < 2) return0; sort(begin(intervals), end(intervals)); int res = 0; for (int e = intervals[0][1], i = 1; i < n; ++i) { if (intervals[i][0] < e) { ++res; e = min(e, intervals[i][1]); } else { e = intervals[i][1]; } } return res; } };