簡體   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