9-line C++ Solution using Quickselect (Write short code for fun~)


  • 0
    W
    int minTotalDistance(vector<vector<int>>& grid) {
            vector<int> Xs, Ys;
            auto push = [&](int i, int j){Xs.push_back(i); Ys.push_back(j);};
            auto minDist = [](vector<int>& nums) {
                nth_element(nums.begin(), nums.begin() + nums.size()/2, nums.end());
                return accumulate(nums.begin(), nums.end(), 0, [&](int x, int y){return x + abs(y-nums[nums.size()/2]);});
            };
            for(int i = 0; i < grid.size(); i++)
                for(int j = 0; j < grid[0].size(); j++) if(grid[i][j] == 1) push(i, j);
            return minDist(Xs) + minDist(Ys);
        }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.