迭代器只有++ ,--,==,!=四種運算方法,不能將iter = iteration+ 1,由於迭代器是指針類型,1是整數類型,不能直接相加賦值給一個指針。spa
//超時牛客不能經過 class Solution { public: int LastRemaining_Solution(int n, int m){ if(n == 1){ return 0; } if(n == 0){ return -1; } list<int> num; for(int i = 0;i < n;++i){//存儲節點 num.push_back(i); } list<int>::iterator iter = num.begin(); while(num.size() > 1){ for(int i = 1;i < m;++i){//找到指定節點 ++iter; if(iter == num.end()){ iter = num.begin(); } } ++iter; list<int>::iterator next = iter;//保存下一節點 if(next == num.end()){ next = num.begin(); } num.erase(--iter);//刪除找到的節點 iter = next; } return *iter; } };
解法2:指針
class Solution { public: int LastRemaining_Solution(int n, int m){ if(n < 1 ||m < 1){ return -1; } int last = 0; for(int i = 1;i <= n;++i){ last = (last + m) % i; } return last; } };