58同城筆試(09-14)
阿新 • • 發佈:2020-09-14
1 求疫情聚集區域的個數
其實就是求連續的1的區域個數,簡單DFS。
int mapp[110][110]; int dfs(int rows, int cols, int x, int y){ if((x < 0) || (x >= cols) || (y < 0) || (y >= rows) || mapp[y][x] == 0) return 0; mapp[y][x] = 0; return dfs(rows, cols, x - 1, y) + dfs(rows, cols, x + 1, y) + dfs(rows, cols, x, y - 1) + dfs(rows, cols, x, y + 1) + 1; } int main(){ int m, n; scanf("%d %d", &m, &n); for(int i = 0; i < m; i++){ for(int j = 0; j < n; j++) scanf("%d", &mapp[i][j]); } int count = 0; for(int i = 0; i < n; i++){ for(int j = 0; j < m; j++) if(mapp[j][i] == 1) if(dfs(m, n, i, j) >= 1) count++; } printf("%d\n", count); return 0; }
2 將二叉樹進行二維列印
劍指offer原題,按層列印二叉樹。
/* struct TreeNode { int val; struct TreeNode *left; struct TreeNode *right; TreeNode(int x) : val(x), left(NULL), right(NULL) { } }; */ class Solution { public: queue<TreeNode *> queueTreeNode; vector<vector<int> > Print(TreeNode* pRoot){ vector<vector<int> > ans; vector<int> vecNew; if(pRoot == nullptr) return ans; int nextLevel = 0; int toBePrinted = 1; queueTreeNode.push(pRoot); while(queueTreeNode.size() > 0){ TreeNode* pNode = queueTreeNode.front(); cout<<pNode->val<<" "; vecNew.push_back(pNode->val); queueTreeNode.pop(); if(pNode->left != nullptr){ queueTreeNode.push(pNode->left); nextLevel++; } if(pNode->right != nullptr){ queueTreeNode.push(pNode->right); nextLevel++; } toBePrinted--; if(toBePrinted == 0){ ans.push_back(vecNew); vecNew.clear(); cout<<endl; toBePrinted = nextLevel; nextLevel = 0; } } return ans; } };
3 求最小未出現的正整數
巧用TreeSet
,暴力求解。
TreeSet
不重複的排序的集合
public static int firstMissingPositive (int[] nums) { // write code here Set<Integer> mySet = new TreeSet<Integer>(); for(int i = 0; i < nums.length; i++) mySet.add(num[i]); int ans = 1; // 迴圈到nums.length + 1以防出現1,2,3,4則返回5 while(ans < nums.length + 1){ if(!mySet.contains(ans)) return ans; ans++; } return ans; }