First Missing Positive題目描述代碼實現Rotate Image題目描述代碼實現
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; }};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); }
新聞熱點
疑難解答