繁体   English   中英

添加类 Cell 的对象值

[英]Adding object values of the class Cell

我得到了一个类和一个接口,我被要求实现这个接口:

    public class Cell {
        private int column;
        private int row;
        public int getColumn(){ return column;}
        public void setColumn(int column){this.column = column;}
        public int getRow(){return row;}
        public void setRow(int row){this.row = row;}
    }
    public interface ITable {
        void set(Cell cell, long value); //sets the value of the cell
        long get(Cell cell); //gets the value of the cell
        long sum(Cell fromCell, Cell toCell); //adds all the cell values between fromCell to toCell
        long avg(Cell fromCell, Cell toCell); //computes average between the values of fromCell to toCell
    }

注意:范围[fromCell:toCell]表示一个矩形,左上角在fromCell ,右下角在toCell

限制:
最大列数为 1000
最大行数为 1000
非空单元格的最大数量为 1000

这是面试问题之一,我在面试过程中或之后都无法解决。 我什至向面试官询问了解决方案,但他无法提供。 我很想知道这个问题的解决方案。

如果 A1 为 1,A2 为 2,A3 为 3,则 sum(A1,A3) = 6

问题不是要求您将对象添加到单元格。 单元格对象只是一种保存行和列数据的方式。 您要检索的任何长值都将存储在您创建的新类中。

例如:

public class MyTable implements ITable {
   long[][] table;
   public MyTable(int r, int c) {
      table = new long[r][c];
   }
   void set(Cell cell, long value) {
        table[cell.getRow()][cell.getColumn()] = value;
   }
   long get(Cell cell) {
        return table[cell.getRow()][cell.getColumn()];
   }       
   long sum(Cell fromCell, Cell toCell) {
        long sum = 0;
        for(int r = fromCell.getRow(); r <= toCell.getRow(); r++) {
            for(int c = fromCell.getColumn(); c <= toCell.getColumn(); c++) {
                sum += table[r][c];
            } 
        }
        return sum;
   }
   long avg(Cell fromCell, Cell toCell) {
        long num = 0;
        long sum = 0;
        for(int r = fromCell.getRow(); r <= toCell.getRow(); r++) {
            for(int c = fromCell.getColumn(); c <= toCell.getColumn(); c++) {
                sum += table[r][c];
                num++;
            } 
        }
        return sum/num;
   }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM