LeetCode - 周赛 - 191
理解错误,无脑暴力了一发居然过了
class Solution { public: int maxProduct(vector<int>& nums) { int res=0; for(int i=0;i<nums.size()-1;++i) { for(int j=i+1;j<nums.size();++j) { int temp=nums[i]*nums[j]-nums[i]-nums[j]; if(temp>res) res=temp+1; } } return res; } };
求个偏导就能发现,数组中两元素的最大乘积=数组中两最大元素的乘积
寻找序列中最大的两个数。
class Solution { public: int maxProduct(vector<int>& nums) { int max=0; int subMax=0; for(int i=0;i<nums.size();++i) { if(nums[i]>max) { subMax=max; max=nums[i]; } else if(nums[i]>subMax) subMax=nums[i]; } return max*subMax-max-subMax+1; } };
时间复杂度O(n),空间复杂度O(1)
关键在于根据数组求出所有的长和宽,并筛选出其中最大的。
class Solution { #define max(a,b) a>b?a:b public: int maxArea(int h, int w, vector<int>& horizontalCuts, vector<int>& verticalCuts) { sort(horizontalCuts.begin(),horizontalCuts.end()); sort(verticalCuts.begin(),verticalCuts.end()); long maxHeight=horizontalCuts[0]-0; int i=1; for(i=1;i<horizontalCuts.size();++i) maxHeight=max(maxHeight,horizontalCuts[i]-horizontalCuts[i-1]); maxHeight=max(maxHeight,h-horizontalCuts[i-1]); long maxWidth=verticalCuts[0]-0; int j=1; for(j=1;j<verticalCuts.size();++j) maxWidth=max(maxWidth,verticalCuts[j]-verticalCuts[j-1]); maxWidth=max(maxWidth,w-verticalCuts[j-1]); return (maxHeight*maxWidth)%1000000007; } };
注意点有两个:1.给数组排序 2.long防止溢出
sort为改进的快排,时间复杂度为O(nlogn)
一看就知道是并查集,然而我不会...
愚蠢的bfs
class Solution { public: int minReorder(int n, vector<vector<int>> &connections) { int res = 0; vector<bool> vis(n, false); vector<vector<int>> reach(n, vector<int>()); vector<vector<int>> canReach(n, vector<int>()); for (int i = 0; i < connections.size(); i++) { reach[connections[i][0]].push_back(connections[i][1]); canReach[connections[i][1]].push_back(connections[i][0]); } queue<int> q; q.push(0); vis[0] = true; while (!q.empty()) { for (int i = q.size()-1; i > -1; --i) { int val = q.front(); q.pop(); for (int j = 0; j < reach[val].size(); j++) { if (vis[reach[val][j]] == false) { res+=1; vis[reach[val][j]] = true; q.push(reach[val][j]); } } for (int j = 0; j < canReach[val].size(); j++) { if (vis[canReach[val][j]] == false) { vis[canReach[val][j]] = true; q.push(canReach[val][j]); } } } } return res; } };
学完并查集来补个并查集的解法