classSolution: defbuildArray(self, target: List[int], n: int) -> List[str]: res = [] prev = 0 for number in target: for _ inrange(number - prev - 1): res.append('Push') res.append('Pop') res.append('Push') prev = number return res
[sol1-Java]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
classSolution { public List<String> buildArray(int[] target, int n) { List<String> res = newArrayList<String>(); intprev=0; for (int number : target) { for (inti=0; i < number - prev - 1; i++) { res.add("Push"); res.add("Pop"); } res.add("Push"); prev = number; } return res; } }
[sol1-C#]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
publicclassSolution { public IList<string> BuildArray(int[] target, int n) { IList<string> res = new List<string>(); int prev = 0; foreach (int number in target) { for (int i = 0; i < number - prev - 1; i++) { res.Add("Push"); res.Add("Pop"); } res.Add("Push"); prev = number; } return res; } }
[sol1-C++]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
classSolution { public: vector<string> buildArray(vector<int>& target, int n){ vector<string> res; int prev = 0; for (int number : target) { for (int i = 0; i < number - prev - 1; i++) { res.emplace_back("Push"); res.emplace_back("Pop"); } res.emplace_back("Push"); prev = number; } return res; } };
[sol1-C]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
char ** buildArray(int* target, int targetSize, int n, int* returnSize) { char **res = (char **)malloc(sizeof(char *) * n * 2); int prev = 0, pos = 0; for (int j = 0; j < targetSize; j++) { for (int i = 0; i < target[j] - prev - 1; i++) { res[pos] = (char *)malloc(sizeof(char) * 8); strcpy(res[pos++], "Push"); res[pos] = (char *)malloc(sizeof(char) * 8); strcpy(res[pos++], "Pop"); } res[pos] = (char *)malloc(sizeof(char) * 8); strcpy(res[pos++], "Push"); prev = target[j]; } *returnSize = pos; return res; }
[sol1-JavaScript]
1 2 3 4 5 6 7 8 9 10 11 12 13
var buildArray = function(target, n) { const res = []; let prev = 0; for (const number of target) { for (let i = 0; i < number - prev - 1; i++) { res.push("Push"); res.push("Pop"); } res.push("Push"); prev = number; } return res; };
[sol1-Golang]
1 2 3 4 5 6 7 8 9 10 11
funcbuildArray(target []int, n int) (ans []string) { prev := 0 for _, number := range target { for i := 0; i < number-prev-1; i++ { ans = append(ans, "Push", "Pop") } ans = append(ans, "Push") prev = number } return }