我試圖來解決代碼戰爭的問題和提供的單元測試做絕對沒有任何意義......代碼的效率和準確性
的問題如下,聽起來絕對夠簡單,有一些在5個工作分鐘
Consider a sequence u where u is defined as follows:
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.
Example:
dbl_linear(10) should return 22
起初,我用了一個SortedSet的使用爲我沒有真正關心效率的LINQ查詢,我很快就發現,該操作將不得不計算出其中n可以相等〜10萬在12秒至。
所以這個憎惡出生了,然後一次又一次地被屠殺,因爲for循環會因某種原因產生問題。然後它被「升級」爲一個while循環,它給出了更多通過的單元測試(4 - > 8)。
public class DoubleLinear {
public static int DblLinear(int n) {
ListSet<int> table = new ListSet<int> {1};
for (int i = 0; i < n; i++) {
table.Put(Y(table[i]));
table.Put(Z(table[i]));
}
table.Sort();
return table[n];
}
private static int Y(int y) {
return 2 * y + 1;
}
private static int Z(int z) {
return 3 * z + 1;
}
}
public class ListSet<T> : List<T> {
public void Put(T item) {
if (!this.Contains(item))
this.Add(item);
}
}
有了這個代碼仍然失敗在超過n = 75000的計算,但通過多達8個試驗。
我檢查過,如果其他人已通過這個,他們有。但是,我無法檢查他們寫了什麼來從中學習。
任何人都可以提供洞察哪裏可能是錯誤的?我敢肯定,答案顯而易見,我很愚蠢。
也是用這種方式自定義列表一個壞主意?有沒有更好的辦法?
使用C#/ Linq來解決它是必須的嗎?我剛剛通過它使用C + +有很多不同的方法 – shole
最好是c#,但不需要linq。在這一點上,我更關心它失敗的原因 – Grey
它太慢了,因爲它是O(N^2)。它使用O(N)在插入它們之前檢查項目是否已經存在於列表中。我接受的解決方案是O(N lg N)和O(N)。O(N lg N)其中一個沒什麼特別之處,但與您使用另一個支持O(lg N)的數據結構類似的想法find – shole