亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

可以有效存儲和檢查任何三個連續添加的元素的總數是否等于給定總數的數據結構

可以有效存儲和檢查任何三個連續添加的元素的總數是否等于給定總數的數據結構

皈依舞 2021-05-05 17:05:19
例子:沒有總計的空容器。添加{1,2,3},這意味著僅存在一個總數(1 + 2 + 3 = 6)。現在添加{4}元素,它從{2,3,4}創建額外的總數?,F在將有兩個總數(1 + 2 + 3 = 6和2 + 3 + 4 = 9)。
查看完整描述

2 回答

?
慕娘9325324

TA貢獻1783條經驗 獲得超4個贊

您可以結合使用列表(以跟蹤添加的元素)和從總和到元素的映射的組合:


public class SummingList {

    // Store the elements added in order

    private List<Integer> elements = new ArrayList<>();


    // Map form the sum to the index(es) that sum up to that number

    private Map<Integer, List<Integer>> sumIndexes;


    /** Expose elements from the list:

    public int get(int index) {

        return list.get(index);

    }


    /** Add an element to the data structure */

    public add(int element) {

        list.add(element);


        // If there are now at least three elements in the data structure,

        // sum them:

        int size = list.size();

        if (size >= 3) {

             int sum = list.get(size - 3) + list.get(size - 2) + list.get(size - 1);

             sumIndexes.computeIfAbsent(sum, k -> new LinkedList<>()).add(size - 3);

        }

    }


    /** 

     * Returns a list of indexes in the list, where each index is the beginning

     * of a series of three elements who's sum is the passed {@code sum}.

     * If no such indexes exist, an empty list is returned.

     */

    public List<Integer> getSequencesWIthSum(int sum) {

        return Collections.unmodifiable(

            sumIndexes.getOrDefault(sum, Collections.emptyList());

    }

}

筆記:

  1. 雖然這個示例中的API很奇怪,但是它顯示了該思想的基礎??梢院苋菀椎貙ζ溥M行調整,以返回更適合您需求的東西。

  2. 如果您需要概括實現以容納更大系列的總和,而不僅僅是三胞胎,那么緩存“滾動窗口”總和可能是個好主意。為了使代碼更簡潔,我沒有這樣做。


查看完整回答
反對 回復 2021-05-26
  • 2 回答
  • 0 關注
  • 161 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號