Use a min-heap to store the values of each number in nums after taking absolute value and modulo value, then count from the minimum. If the popped value from the min-heap equals the current number, add value to it and push back. Repeat until the heap is empty or a discontinuity appears. However, this O(n log n) method will time out.
classSolution { public: intcel_div(int a, int b) { return (a + b - 1) / b; } intfindSmallestInteger(vector<int> &nums, int value) { // First convert all negative numbers to positive // Then convert all numbers to remainders modulo value
int i; int n = nums.size(); int top_value; int last_value; int count = 0; priority_queue<int, vector<int>, std::greater<int> > min_heap;
for (i = 0; i < n; i++) { if (nums[i] < 0) { nums[i] += cel_div(-nums[i], value) * value; } nums[i] = nums[i] % value; min_heap.push(nums[i]); }
All possible remainders modulo value form a set. Suppose there are group groups of all possible remainders modulo value, then the maximum of the final array is at leastvalue×group−1, remove the values of these groups from nums. Among the remaining, there must be a missing value from all possible remainders modulo value. Find the smallest missing value and addvalue×group−1That’s it. In programming, count the occurrences of each remainder, find the smallest count as group. The smallest cannot be 0,
classSolution { public: intcel_div(int a, int b) { return (a + b - 1) / b; } intfindSmallestInteger(vector<int> &nums, int value) { // First, change all negative numbers to positive numbers. // Then, change all numbers to the remainder when divided by value.
int i; int n = nums.size(); int group = INT_MAX;
int res;
unordered_map<int, int> umap;
if (value == 1) { return n - 1; }
for (i = 0; i < n; i++) { if (nums[i] < 0) { nums[i] += cel_div(-nums[i], value) * value; } nums[i] = nums[i] % value; umap[nums[i]]++; }
for (i = 0; i < value; i++) { if (umap.count(i) == 0) { return i; } }
for (auto &[num, count] : umap) { if (count < group) { group = count; res = num; } elseif (count == group) { res = std::min(res, num); } }