The program I am trying to make takes an "n * n" square matrix grid of size "n * n" with values in the range [1,n²]. Each integer appears exactly once except a number 'a' which appears twice and a number 'b' which is missing.
The task is to find the repeating and missing numbers 'a' and 'b'.
It should return a vector of two elements, {a,b}.
i.e. for the matrix {[1,2],[2,3]}, it should return vector {2,4}.
In my program, I am almost certain it logically outputs 'a' and 'b'. However, it always outputs [a,0]. 'b' is always 0.
Element 'b' should never be in the map, and hence the find function should determine the value of 'b'.
vector<int> findMissingAndRepeatedValues(vector<vector<int>>& grid) {
int size = grid.size();
unordered_map<int,int> map;
for(int r = 0; r < size; r++) {
for(int c = 0; c < size; c++) {
map[grid[r][c]]++;
}
}
int a = 0;
int b = 0;
for(int i = 1; i < size*size + 1; i++) {
if(map[i] == 2) {
a = i;
}
else if(map.find(i) == map.end()) {
b = i;
}
}
return vector<int> {a,b};
}
The map is being added created correctly. I believe it's something to do with the second for-loop.