class Solution { public: int longestAlternatingSubarray(vector<int>& nums, int threshold) { int n = nums.size(); int res = 0; auto check = [&](int l, int r) { if (nums[l] % 2 != 0) { return false; } for (int i = l; i < r; i++) { if ((nums[i] % 2) == (nums[i + 1] % 2)) { return false; } } for (int i = l; i <= r; i++) { if (nums[i] > threshold) { return false; } } return true; }; for (int i = 0; i < n; i++) { for (int j = i; j < n; j++) { if (check(i, j)) { res = max(res, j - i + 1); } } } return res; } };
classSolution { public: intlongestAlternatingSubarray(vector<int>& nums, int threshold){ int n = nums.size(); int i = 0; int res = 0; while (i < n) { while (i < n && ((nums[i] & 1) || nums[i] > threshold)) { i++; } if (i >= n) { break; } int start = i; i++; while (i < n && nums[i] <= threshold && (nums[i] % 2) != (nums[i - 1] % 2)) { i++; } res = max(res, i - start); } return res; } };
2761. 和等于目标值的质数对
给你一个整数 n 。如果两个整数 x 和 y 满足下述条件,则认为二者形成一个质数对:
1 <= x <= y <= n
x + y == n
x 和 y 都是质数
请你以二维有序列表的形式返回符合题目要求的所有 [xi, yi] ,列表需要按 xi 的 非递减顺序 排序。如果不存在符合要求的质数对,则返回一个空数组。
classSolution { public: intsumImbalanceNumbers(vector<int>& nums){ int n = nums.size(); int res = 0; for (int i = 0; i < n; i++) { set<int> cnt; int tot = 0; cnt.emplace(nums[i]); for (int j = i + 1; j < n; j++) { int x = nums[j]; auto it = cnt.lower_bound(x); if (it == cnt.end()) { int a = *cnt.rbegin(); if (x - a > 1) { tot++; } } elseif (it == cnt.begin()) { int a = *cnt.begin(); if (a - x > 1) { tot++; } } else { int a = *it; it--; int b = *it; if (a - b > 1) { if (a - x > 1 && x - b > 1) { tot++; } elseif (a - x <= 1 && x - b <= 1) { tot--; } } } cnt.emplace(nums[j]); res += tot; } } return res; } };