20ms C solution


  • 0
    G
    class Solution {
    public:
    	int minTotalDistance(vector<vector<int>>& grid) 
    	{
    		if (grid.size() == 0) return 0;
    		vector<int> xv;
    		vector<int> yv;
    
    		for (int i = 0; i < grid.size(); i++)
    		{
    			for (int j = 0; j < grid[0].size(); j++)
    			{
    				if (grid[i][j] == 1)
    				{
    					xv.push_back(j);
    					yv.push_back(i);
    				}
    			}
    		}
    
    		sort(xv.begin(), xv.end());
    		sort(yv.begin(), yv.end());
    
    		int sum=0;
    		int m = yv[yv.size() / 2];
    		for (int i = 0; i < yv.size(); i++)
    		{
    			sum += (abs(yv[i] - m));
    		}
    
    		m = xv[xv.size() / 2];
    		for (int i = 0; i < xv.size(); i++)
    		{
    			sum += (abs(xv[i] - m));
    		}
    
    		return sum;
    	}
    };

Log in to reply
 

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