Minimum Number of Operations to Make Array Continuous LeetCode solution in C++

1
// OJ:
2
// https://leetcode.com/problems/minimum-number-of-operations-to-make-array-continuous/
3
// Author: github.com/lzl124631x
4
// Time: O(NlogN)
5
// Space: O(1)
6
class Solution {
7
public:
8
int minOperations(vector<int> &A) {
9
int N = A.size(), ans = N, j = 0;
10
sort(begin(A), end(A));
11
A.erase(unique(begin(A), end(A)), end(A)); // only keep unique elements
12
int M = A.size();
13
for (int i = 0; i < M; ++i) {
14
while (j < M && A[j] < A[i] + N)
15
++j; // let `j` point to the first element that is out of range -- `>=
16
// A[i] + N`.
17
ans = min(ans,
18
N - j + i); // The length of this subarray is `j - i`. We need to
19
// replace `N - j + i` elements to make it continuous.
20
}
21
return ans;
22
}
23
};

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0