3880. Minimum Absolute Difference Between Two Values
You are given an integer array nums consisting only of 0, 1, and 2.
A pair of indices (i, j) is called valid if nums[i] == 1 and nums[j] == 2.
Return the minimum absolute difference between i and j among all valid pairs. If no valid pair exists, return -1.
The absolute difference between indices i and j is defined as abs(i - j).
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| class Solution { public: int minAbsoluteDifference(vector<int>& nums) { unordered_map<int,vector<int>> at; for(int i = 0; i < nums.size(); i++) at[nums[i]].push_back(i); int res = INT_MAX, i = 0, j = 0, n = at[1].size(), m = at[2].size(); for(int i = 0; i < n; i++) { while(j < m and at[2][j] <= at[1][i]) j++; if(j != m) { res = min(res, at[2][j] - at[1][i]); } if(j) { res = min(res, at[1][i] - at[2][j-1]); } } return res == INT_MAX ? -1 : res; } };
|