# Code language: Python classSolution: defbuildArray(self, target: List[int], n: int) -> List[str]: ans, i, j, m = list(), 0, 1, len(target) while i < m: ans.append("Push") if j == target[i]: i += 1 else: ans.append("Pop") j += 1 return ans
1 2 3 4 5 6 7 8 9 10 11 12
// Code language: Java classSolution { public List<String> buildArray(int[] target, int n) { List<String> ans = newArrayList<>(); for (inti=0, j = 1, m = target.length; i < m; ++j) { ans.add("Push"); if (j != target[i]) ans.add("Pop"); else ++i; } return ans; } }
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
// Code language: C++ classSolution { public: vector<string> buildArray(vector<int>& target, int n){ vector<string> ans; for (int i = 0, cur = 1, n = target.size(); i < n; ++i) { while (cur++ != target[i]) { ans.emplace_back("Push"); ans.emplace_back("Pop"); } ans.emplace_back("Push"); } return ans; } };
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
/* Code language: JavaScript */ /** * @param {number[]} target * @param {number} n * @return {string[]} */ var buildArray = function(target, n) { const ans = newArray(); for (let i = 0, j = 1, m = target.length; i < m; ++j) { ans.push("Push"); if (j == target[i]) ++i; else ans.push("Pop"); } return ans; };
1 2 3 4 5 6 7 8 9 10 11 12
/* Code language: Golang */ funcbuildArray(target []int, n int) (ans []string) { for i, j, m := 0, 1, len(target); i < m; j++ { ans = append(ans, "Push") if j == target[i] { i++ } else { ans = append(ans, "Pop") } } return }