Build an Array With Stack Operations
给一个target数组和一个数字n, 从[1..n]中用push和pop两个方法取数, 问怎么才能取到target数组中的数字.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
class Solution { public List<String> buildArray(int[] target, int n) { List<String> res = new ArrayList<>(); int k = target[0]; for(int i = 1; i < target.length; i++) { int t = target[i]; target[i] -= k; k = t; } for(int i = 0; i < target.length; i++) { if(target[i] == 1) res.add("Push"); else { while(target[i] > 1) { res.add("Push"); res.add("Pop"); target[i]--; } res.add("Push"); } } return res; } } |