class Solution { public: bool searchMatrix(vector>& matrix, int target) { int row = matrix.size(); int col = matrix[0].size(); for(int i=0;i //先排除一下不存在的情况 if(i>0&&matrix[i][0]>target && matrix[i-1][col-1]=target) { int begin=0,end=col-1; while(begin<=end) { int mid = begin + (end-begin)/2; if(matrix[i][mid] > target) { end = mid-1; } else if(matrix[i][mid] < target) { begin = mid+1; } if(matrix[i][mid]==target) return true; } } } return false; } };
二分法,稍微区分了一下左侧有序还是右侧有序
class Solution { public: int search(vector& nums, int target) { if(nums.size()==0) return -1; if(nums.size()==1) return nums[0]==target?0:-1; int left = 0, right = nums.size()-1; while(left<=right) { int mid = left+(right-left)/2; if(nums[mid]==target) return mid; else if(nums[0] <= nums[mid]) { if(nums[0] <=target && target < nums[mid]) right = mid-1; else left = mid+1; } else { if(nums[mid]
class Solution { public: int findMin(vector& nums) { if(nums.size()==1) return nums[0]; int n = nums.size()-1; int left = -1,right = n; int res = nums[0]; if(nums[0] < nums[n]) return res; while(left+1 int mid = left+(right-left)/2; if(nums[mid] < nums.back()) right = mid; else left = mid; } return nums[right]; } };
通过中序遍历,得到有序的数组,在判断数组是否严格递增
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode() : val(0), left(nullptr), right(nullptr) {} * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} * }; */ class Solution { public: void traversal(TreeNode* root,vector& res) { if(root==NULL) return; if(root->left) traversal(root->left,res); res.push_back(root->val); if(root->right) traversal(root->right,res); } bool isValidBST(TreeNode* root) { if(!root) return true; vector res; traversal(root,res); for(int i=1;i if(res[i] <= res[i-1]) return false; } return true; } };
res即dp数组,寻找res[i][j]的更新规律
class Solution { public: vector> generate(int numRows) { vector> res(numRows); for(int i=0;i res[i].resize(i+1); res[i][0] = res[i][i] = 1; for(int j=1;j res[i][j] = res[i-1][j]+res[i-1][j-1]; } } return res; } };
上一篇:必备科技微扑克AI原来真的有挂,太过分了原来是有挂,详细教程(有挂透视)
下一篇:vscode 打开远程bug vscode Failed to parse remote port from server output