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

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

Java中最適合的數據結構是什么?如何有效地實現它?

Java中最適合的數據結構是什么?如何有效地實現它?

呼如林 2019-04-11 14:15:53
這是針對代碼戰的編碼挑戰。挑戰的條件:考慮一個序列u,其中u定義如下:The number u(0) = 1 is the first one in u.For each x in u, then y = 2 * x + 1 and z = 3 * x + 1 must be in u too.There are no other numbers in u.Ex: u = [1, 3, 4, 7, 9, 10, 13, 15, 19, 21, 22, 27, ...]1 gives 3 and 4, then 3 gives 7 and 10, 4 gives 9 and 13, then 7 gives 15 and 22 and so on...Task:Given parameter n the function dbl_linear (or dblLinear...) returns the element u(n) of the ordered (with <) sequence u (so, there are no duplicates).我的天真實現只生成250000個數字:import java.util.List;import java.util.ArrayList;import java.util.TreeSet;import java.util.Set;import java.util.HashSet;class DoubleLinear {        private static Set<Integer> nums;        private static Set<Integer> seen;        public static int dblLinear (int n) {                nums = new TreeSet<>();                seen = new HashSet<>();                nums.add(1);                for (int i = 0; i < 17; i++) {                        generateNumbers();                }                List<Integer> numList = new ArrayList(nums);                return numList.get(n);        }        public static void generateNumbers () {                for (int x : new TreeSet<Integer>(nums)) {                        if (seen.contains(x)) continue;                        if (nums.size() >= 250000) break;                         int y = (2*x) + 1, z = (3*x) + 1;                        if (y > 0) nums.add(y);                        if (z > 0) nums.add(z);                        seen.add(x);                }        }}我很好奇我可以用什么其他結構來提高效率,因為我顯然缺少解決這個問題所需的知識。
查看完整描述

2 回答

?
阿波羅的戰車

TA貢獻1862條經驗 獲得超6個贊

您可以將數字存儲在HashMap中以存儲數字。使用x作為鍵,使用(Y或Z)作為值。


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

添加回答

舉報

0/150
提交
取消
微信客服

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

幫助反饋 APP下載

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

公眾號

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