例子: 3,8,4,5,6,2 返回值應該為 :5
這是昨天做的一道優酷土豆的編程題,和leetcode中的128/ Longest Consecutive Sequence 有點相似,但是leetcode題的公差是確定的1,而這道題的公差是不確定的。
本人的寫出的是一種通過窮舉的方法實現查找最長等差數列,通過hash使查找更為方便,減少了復雜度。
int calcAPLength(const vector<int> &intAr) // 找數列中,最長的等差數列的長度 ,返回該數列的長度 { if (intAr.size() <= 2) return intAr.size(); vector<int> t = intAr; sort(t.begin(),t.end()); auto p=unique(t.begin(),t.end()); int l = p - t.begin(); // 經過排序和unique后數組的長度 注意:unqiue並沒有將重復的元素刪除,而是放在了數組的后面 map<int, int>my; int test = 1; // hash ,並初始化 for (int i = 0; i < l; i++,test++) my[t[i]] = test; int re = 2; int diff; for (int i = 0; i < l; i++) // 遍歷數組, { for (int j = 1; j < l; j++) // 公差: 與第j個元素的差 { int index = j + i; if (index >= l) break; diff = t[index]-t[i]; int temp = 2; while (my[diff + t[index]] <= l && my[diff + t[index]]>0 ) //查找下一個元素是否存在 { index = my.find(diff + t[index])->second-1; temp++; } re = max(re, temp); } } return re; }
注意:unqiue並沒有將重復的元素刪除,原來數組的長度也並沒有改變,而是把重復的元素放在了數組的后面。
希望有人能提出更好的方法!