41. First Missing Positive
题目描述
Given an unsorted integer array, find the first missing positive integer.
For example,
Given [1,2,0] return 3,
and [3,4,-1,1] return 2.
Your algorithm should run in O(n) time and uses constant space.
代码实现
法一: 使用set进行排序,然后使用计数器计算正整数的个数。
class Solution {
public:
int firstMissingPositive(vector<int>& nums) {
set<int> sortnum(nums.begin(), nums.end());
int nlen = nums.size();
int cnt = 0;
for(set<int>:: iterator it = sortnum.begin(); it != sortnum.end(); it++) {
if(*it > 0) {
cnt++;
if(cnt < *it) return cnt;
}
}
return cnt + 1;
}
};
法二:把A[i](> 0)移到A[A[i]-1]的地方,然后再遍历看少了哪个。
class Solution {
public:
int firstMissingPositive(vector<int>& A) {
int n = A.size();
for(int i = 0; i < n; ++ i)
while(A[i] > 0 && A[i] <= n && A[A[i] - 1] != A[i])
swap(A[i], A[A[i] - 1]);
for(int i = 0; i < n; ++ i)
if(A[i] != i + 1)
return i + 1;
return n + 1;
}
};
48. Rotate Image
题目描述
You are given an n x n 2D matrix representing an image.
Rotate the image by 90 degrees (clockwise).
Follow up:
Could you do this in-place?
代码实现
使用旋转矩阵计算它的变换分方程,然后加一个shift让索引为正。
class Solution {
public:
void rotate(vector<vector<int>>& matrix) {
int dim = matrix.size();
vector<vector<int>> mc(matrix);
for(int row = 0; row < dim; row++)
for(int col = 0; col < dim; col++)
matrix[col][dim - 1 - row] = mc[row][col];
}
};
上面的方法使用空间换时间,其实有很不错的方法,在discussion上有个做法就是根据对角线分成四个部分,然后把在第一部分的数字和第二部分的换,第二和第三换,第三和第四换。
class Solution {
public:
int move(vector<vector<int>> &matrix,int val, int x, int y){
int store = matrix[y][x];
matrix[y][x]=val;
return store;
}
void rotate(vector<vector<int>>& matrix) {
int n = matrix.size();
for(int y=0;y<n/2;y++){
for(int x=y;x < n-y-1;x++){
int temp=matrix[y][x];
temp=move(matrix,temp,(n-1)-y,x);
temp=move(matrix,temp,(n-1)-x,(n-1)-y);
temp=move(matrix,temp,y,(n-1)-x);
temp=move(matrix,temp,x,y);
}
}
}
};
参考链接:
矩阵拷贝:
方法1:
vector v1(v2);//声明
方法2:使用swap进行赋值:
vector v1();v1.swap(v2);//将v2赋值给v1,此时v2变成了v1
方法3:使用函数assign进行赋值:
vector v1;//声明v1
v1.assign(v2.begin(), v2.end());//将v2赋值给v1
方法4:使用循环语句赋值,效率较差
vector::iterator it;//声明迭代器
for(it = v2.begin();it!=v2.end();++it){//遍历v2,赋值给v1
v1.push_back(it);
}