You are given a 0-indexed integer array nums
of size n
and a positive integer k
.
We call an index i
in the range k <= i < n - k
good if the following conditions are satisfied:
- The
k
elements that are just before the indexi
are in non-increasing order. - The
k
elements that are just after the indexi
are in non-decreasing order.
Return an array of all good indices sorted in increasing order.
Example 1:
Input: nums = [2,1,1,1,3,4,1], k = 2 Output: [2,3] Explanation: There are two good indices in the array: - Index 2. The subarray [2,1] is in non-increasing order, and the subarray [1,3] is in non-decreasing order. - Index 3. The subarray [1,1] is in non-increasing order, and the subarray [3,4] is in non-decreasing order. Note that the index 4 is not good because [4,1] is not non-decreasing.
Example 2:
Input: nums = [2,1,1,2], k = 2 Output: [] Explanation: There are no good indices in this array.
Constraints:
n == nums.length
3 <= n <= 105
1 <= nums[i] <= 106
1 <= k <= n / 2
Solution: Prefix Sum
Let before[i] = length of longest non-increasing subarray ends of nums[i].
Let after[i] = length of longest non-decreasing subarray ends of nums[i].
An index is good if nums[i – 1] >= k and nums[i + k] >= k
Time complexity: O(n + (n – 2*k))
Space complexity: O(n)
C++
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
// Author: Huahua class Solution { public: vector<int> goodIndices(vector<int>& nums, int k) { const int n = nums.size(); vector<int> before(n, 1); vector<int> after(n, 1); for (int i = 1; i < n; ++i) { if (nums[i] <= nums[i - 1]) before[i] = before[i - 1] + 1; if (nums[i] >= nums[i - 1]) after[i] = after[i - 1] + 1; } vector<int> ans; for (int i = k; i + k < n; ++i) { if (before[i - 1] >= k && after[i + k] >= k) ans.push_back(i); } return ans; } }; |
请尊重作者的劳动成果,转载请注明出处!花花保留对文章/视频的所有权利。
如果您喜欢这篇文章/视频,欢迎您捐赠花花。
If you like my articles / videos, donations are welcome.
Be First to Comment