【566】Reshape the Matrix
class Solution {
public:
vector<vector<int>> matrixReshape(vector<vector<int>>& nums, int r, int c) {
int total = 0;
int a = nums.size();
int b = nums[0].size();
for(int i=0;i<nums.size();i++)
{
total += nums[i].size();
}
if (total < r*c)
return nums;
else
{
vector<vector<int>> n;
vector<int>v;
int t = 0;
for(int i=0;i<a;i++)
{
for(int j=0;j<b;j++)
{
v.push_back(nums[i][j]);
t++;
if (t % c == 0)
{
n.push_back(v);
v.clear();
}
if (t == total)
break;
}
}
for (int i = 0; i < 4; i++)
cout << n[0][i];
return n;
}
}
};
【669】Trim a Binary Tree
class Solution {
public:
TreeNode* trimBST(TreeNode* root, int L, int R) {
TreeNode* n = new TreeNode(-1);
queue<TreeNode*>q;
q.push(root);
while(!q.empty())
{
TreeNode* temp = q.front();
q.pop();
if (temp->left != NULL) q.push(temp->left);
if (temp->right != NULL) q.push(temp->right);
if(temp->val>=L&&temp->val<=R)
{
insert(n,temp->val);
}
}
return n;
}
void insert(TreeNode* n,int val)
{
if(n->val==-1)
{
n->val = val;
}
else
{
TreeNode* temp = new TreeNode(val);
TreeNode* t = n;
while(!(t->left==NULL&&t->right==NULL))
{
if (t->val > val&&t->left!=NULL) t = t->left;
if (t->val < val&&t->right!=NULL) t = t->right;
if(t->val>val&&t->left==NULL)
{
t->left = temp;
return;
}
if(t->val<val&&t->right==NULL)
{
t->right = temp;
return;
}
}
if (t->val > val) t->left = temp;
if (t->val < val)t->right = temp;
}
}
};
【463】Island Perimeter
class Solution {
public:
int islandPerimeter(vector<vector<int>>& grid) {
bool array[100][100];
memset(array, false, sizeof(bool));
int count = 0;
for(int i=0;i<grid.size();i++)
{
for(int j=0;j<grid[i].size();j++)
{
if (grid[i][j])
{
if (i == 0)
{
if (j == 0)
count += 4;
else if (grid[i][j-1])
count += 2;
else count += 4;
}
else if(j==0)
{
if (grid[i - 1][j])
count += 2;
else count += 4;
}
else
{
if (grid[i - 1][j] && grid[i][j - 1]);
else if (grid[i - 1][j]) count += 2;
else if (grid[i][j - 1]) count += 2;
else count += 4;
}
}
}
}
return count;
}
};
【496】Next Greater Element I
class Solution {
public:
vector<int> nextGreaterElement(vector<int>& findNums, vector<int>& nums) {
unordered_map<int, int> hm;
for (int i = 0; i<nums.size(); i++)
{
hm[nums[i]] = i;
}
vector<int> v;
for (int i = 0; i<findNums.size(); i++)
{
int temp = hm[findNums[i]];
while (temp<nums.size()&&(!(nums[temp] > findNums[i])) )
temp++;
if (temp != nums.size())
v.push_back(nums[temp]);
else v.push_back(-1);
}
return v;
}
};
【442】Find All Duplicates in an Array
class Solution {
public:
vector<int> findDuplicates(vector<int>& nums) {
vector<int> ab;
if(nums.empty())
return ab;
int a = nums.size();
vector<int>sol(a+1);
for(int i=0;i<a;i++)
{
sol[nums[i]]++;
}
int mark=0;
for(int i=0;i<sol.size();i++)
{
if (sol[i] != 2)
{
sol.erase(sol.begin() + i );
i--;
mark++;
}
else sol[i]=i+mark;
}
return sol;
}
};