2899. Last Visited Integers¶

• Time: $O(n)$
• Space: $O(n)$
  1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 class Solution { public: vector lastVisitedIntegers(vector& words) { vector ans; vector nums; int k = 0; for (const string& word : words) if (word == "prev") { ++k; ans.push_back(k > nums.size() ? -1 : nums[nums.size() - k]); } else { k = 0; nums.push_back(stoi(word)); } return ans; } }; 
  1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 class Solution { public List lastVisitedIntegers(List words) { List ans = new ArrayList<>(); List nums = new ArrayList<>(); int k = 0; for (final String word : words) if (word.equals("prev")) { ++k; ans.add(k > nums.size() ? -1 : nums.get(nums.size() - k)); } else { k = 0; nums.add(Integer.valueOf(word)); } return ans; } } 
  1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 class Solution: def lastVisitedIntegers(self, words: List[str]) -> List[int]: ans = [] nums = [] k = 0 for word in words: if word == 'prev': k += 1 ans.append(-1 if k > len(nums) else nums[-k]) else: k = 0 nums.append(int(word)) return ans