下面的代碼在輸入[1,3,2,2,5,2,3,7]后返回5。classSolution{public:intfindLHS(vector&nums){//注意:子序列不要求連續(xù),子串要求連續(xù)//用哈希表統(tǒng)計(jì)一下unordered_mapump;for(intn:nums)if(ump.find(n)==ump.end())ump.insert(make_pair(n,1));elseump[n]++;intans=0;for(autoitem:ump){if(ump.find(item.first+1)!=ump.end())ans=max(ans,ump[item.first+1]+ump[item.first]);if(ump.find(item.first-1)!=ump.end())ans=max(ans,ump[item.first-1]+ump[item.first]);}returnans;}};如果將14,16行的if語(yǔ)句注釋掉,返回的竟然是1?這里明明是求max的操作,無(wú)論如何不可能得到比之前的5更小的值吧?這是在做LeetCode594時(shí)遇到的問(wèn)題。另外,即使使用注釋掉了兩個(gè)if語(yǔ)句后的代碼,如果將輸入的第一個(gè)數(shù)字1改成某些數(shù)字,如數(shù)字8,那么該函數(shù)又能正常返回5了,這是為什么?
在C++里的unordered_map中,訪問(wèn)不存在的一個(gè)元素,出現(xiàn)了問(wèn)題,謝大佬指點(diǎn)一下
三國(guó)紛爭(zhēng)
2019-06-21 16:09:20