1. 程式人生 > 實用技巧 >LeetCode第33場雙週賽

LeetCode第33場雙週賽

1. 千位分隔數

模擬題,時間複雜度\(O(n)\)

class Solution {
public:
    string thousandSeparator(int n) {
        string res = to_string(n);
        for(int i = res.size() - 3; i > 0; i -= 3) res.insert(res.begin() + i, '.');
        return res;
    }
};

2. 可以到達所有點的最少點數目

等價於沒有父節點的點數目,時間複雜度\(O(n)\)

class Solution {
public:
    vector<int> findSmallestSetOfVertices(int n, vector<vector<int>>& edges) {
        vector<int> vis(n), res;
        for(int i = 0; i < edges.size(); i++) vis[edges[i][1]] = 1;
        for(int i = 0; i < n; i++) if(!vis[i]) res.push_back(i);
        return res;
    }
};

3. 得到目標陣列的最少函式呼叫次數

貪心,時間複雜度\(O(n)\)

class Solution {
public:
    int minOperations(vector<int>& nums) {
        int res = 0, c = 0;
        for(int i = 0; i < nums.size(); i++) {
            c = max(c, nums[i]);
            while(nums[i]) {
                if(nums[i] & 1) res++;
                nums[i] /= 2;
            }
        }
        return res + (int)(log(c) / log(2));
    }
};

4. 二維網格圖中探測環

DFS判斷環,時間複雜度\(O(nm)\)

class Solution {
public:
    int n, m, dx[4] = {-1, 1, 0, 0}, dy[4] = {0, 0, -1, 1};
    vector<vector<int>> vis;
 
    bool dfs(int x, int y, vector<vector<char>>& grid) {
        vis[x][y] = 1;
        int s = 0;
        for(int i = 0; i < 4; i++) {
            int px = x + dx[i], py = y + dy[i];
            if(px < n && px > -1 && py < m && py > -1 && grid[x][y] == grid[px][py]) {
                if(!vis[px][py]) {
                    if(dfs(px, py, grid)) return true;
                }
                else s++;
            }
        }
        return s > 1;
    }
 
    bool containsCycle(vector<vector<char>>& grid) {
        n = grid.size(), m = grid[0].size();
        vis.resize(n, vector<int>(m));
        for(int i = 0; i < n; i++) {
            for(int j = 0; j < m; j++) {
                if(!vis[i][j] && dfs(i, j, grid)) return true;
            }
        }
        return false;
    }
};