Problems using nth_element in C++


  • 1
    S

    The cpp code below fails to pass the following test: [[0,0,0,1,0,1,0,0,0,1,1,0]],
    returning 15 instead of 11.

    int minTotalDistance(vector<vector<int>>& grid) {
        vector<int> x;
        vector<int> y;
        for (int i = 0; i < grid.size(); i++) {
            for (int j = 0; j < grid[0].size(); j++) {
                if (grid[i][j]) {
                    x.push_back(i);
                    y.push_back(j);
                }
            }
        }
        //sort(x.begin(), x.end());
        //sort(y.begin(), y.end());
        nth_element(x.begin(), x.begin() + x.size() / 2, x.end());
        nth_element(y.begin(), x.begin() + y.size() / 2, y.end());
        int mid_x = x[x.size() / 2];
        int mid_y = y[y.size() / 2];
        int sum = 0;
        for (int i = 0; i < grid.size(); i++) {
            for (int j = 0; j < grid[0].size(); j++) {
                if (grid[i][j]) {
                    sum += abs(mid_x - i) + abs(mid_y - j);
                }
            }
        }
        return sum;
    }

  • 0
    S

    why did you remove sorting of y-coordinate?


  • 0
    This post is deleted!

  • 0

    It's just a copy&paste error:

    nth_element(y.begin(), x.begin()
                           ^

Log in to reply
 

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