Array rotation

48. Rotate Image

/*
* clockwise rotate
* first reverse up to down, then swap the symmetry
* 1 2 3 7 8 9 7 4 1
* 4 5 6 => 4 5 6 => 8 5 2
* 7 8 9 1 2 3 9 6 3
*/
class Solution
{
public:
void rotate(vector<vector<int>>& matrix)
{
reverse(matrix.begin(), matrix.end());
for(int i=0;i<matrix.size();++i)
for(int j=i+1;j<matrix.size();++j)
swap(matrix[i][j], matrix[j][i]);
}
};
/*
* anticlockwise rotate
* first reverse left to right, then swap the symmetry
* 1 2 3 3 2 1 3 6 9
* 4 5 6 => 6 5 4 => 2 5 8
* 7 8 9 9 8 7 1 4 7
*/
void anti_rotate(vector<vector<int> > &matrix) {
for (auto vi : matrix) reverse(vi.begin(), vi.end());
for (int i = 0; i < matrix.size(); ++i) {
for (int j = i + 1; j < matrix[i].size(); ++j)
swap(matrix[i][j], matrix[j][i]);
}
}

1477. Find Two Non-overlapping Sub-arrays Each With Target Sum

1060. Missing Element in Sorted Array

class Solution {
public:
int helper(vector<int>& nums, int i, int k)
{
if (i == nums.size())
{
return nums.back() + k;
}
else if (nums[i] == nums[i-1])
{
return helper(nums, i+1, k);
}
else if (nums[i] - nums[i-1] - 1>=k)
{
return nums[i-1] + k;
}
else
{
return helper(nums, i + 1, k - (nums[i] - nums[i-1] -1));
}
}
int missingElement(vector<int>& nums, int k)
{
return helper(nums, 1, k);
}
};

Data Scientist/MLE/SWE @takemobi