[C++] [Java] Clean Code


  • 3

    for every row, whenever add a brick, record the end position as +1.
    goal is to find the position where most row have a break on that position.
    C++

    class Solution {
    public:
        int leastBricks(vector<vector<int>>& wall) {
            map<int, int> ends;
            int maxend = 0;
            for (int i = 0; i < wall.size(); i++) {
                int sum = 0;
                for (int j = 0; j + 1 < wall[i].size(); j++) {
                    ends[sum += wall[i][j]]++;
                    maxend = max(maxend, ends[sum]);
                }
            }
    
            return wall.size() - maxend;
        }
    };
    

    Java

    public class Solution {
        public int leastBricks(List<List<Integer>> wall) {
            Map<Integer, Integer> ends = new HashMap<Integer, Integer>();
            int maxend = 0;
            for (int i = 0; i < wall.size(); i++) {
                int sum = 0;
                for (int j = 0; j + 1 < wall.get(i).size(); j++) {
                    sum += wall.get(i).get(j);
                    ends.put(sum, ends.getOrDefault(sum, 0) + 1);
                    maxend = Math.max(maxend, ends.get(sum));
                }
            }
    
            return wall.size() - maxend;
        }
    }
    

  • 0
    D

    I think there is no need to do comparison in each loop, because the map size is smaller.
    You can find the maximum after each element is traversed.

    for (int j = 0; j + 1 < wall[i].size(); j++) {
        ends[sum += wall[i][j]]++;
    }
    
    // find the maximum value in map
    XXXXXXX
    

  • 1
    Z

    Good code! Here is my C++ code using unordered_map.

    class Solution {
    public:
        int leastBricks(vector<vector<int>>& wall) {
            unordered_map<int, int> count;
            int m = wall.size(), ans = 0;
            for (int i = 0; i < m; ++i) {
                int sum = 0;
                for (int j = 0; j < wall[i].size()-1; ++j) {
                    sum += wall[i][j];
                    ++count[sum];
                }
            }
            for (auto it = count.begin(); it != count.end(); ++it)
                ans = max(ans, it->second);
            return m-ans;
        }
    };
    

Log in to reply
 

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