classSolution: defminOperations(self, boxes: str) -> List[int]: res = [] for i inrange(len(boxes)): s = sum(abs(j - i) for j, c inenumerate(boxes) if c == '1') res.append(s) return res
[sol1-Java]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
classSolution { publicint[] minOperations(String boxes) { intn= boxes.length(); int[] res = newint[n]; for (inti=0; i < n; i++) { intsm=0; for (intj=0; j < n; j++) { if (boxes.charAt(j) == '1') { sm += Math.abs(j - i); } } res[i] = sm; } return res; } }
[sol1-C#]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
publicclassSolution { publicint[] MinOperations(string boxes) { int n = boxes.Length; int[] res = newint[n]; for (int i = 0; i < n; i++) { int sm = 0; for (int j = 0; j < n; j++) { if (boxes[j] == '1') { sm += Math.Abs(j - i); } } res[i] = sm; } return res; } }
[sol1-C++]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
classSolution { public: vector<int> minOperations(string boxes){ int n = boxes.size(); vector<int> res(n); for (int i = 0; i < n; i++) { int sm = 0; for (int j = 0; j < n; j++) { if (boxes[j] == '1') { sm += abs(j - i); } } res[i] = sm; } return res; } };
[sol1-C]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
int* minOperations(char * boxes, int* returnSize) { int n = strlen(boxes); int *res = (int *)malloc(sizeof(int) * n); for (int i = 0; i < n; i++) { int sm = 0; for (int j = 0; j < n; j++) { if (boxes[j] == '1') { sm += abs(j - i); } } res[i] = sm; } *returnSize = n; return res; }
[sol1-JavaScript]
1 2 3 4 5 6 7 8 9 10 11 12 13 14
var minOperations = function(boxes) { const n = boxes.length; const res = []; for (let i = 0; i < n; i++) { let sm = 0; for (let j = 0; j < n; j++) { if (boxes[j] === '1') { sm += Math.abs(j - i); } } res.push(sm); } return res; };
[sol1-Golang]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
funcminOperations(boxes string) []int { ans := make([]int, len(boxes)) for i := range boxes { for j, c := range boxes { if c == '1' { ans[i] += abs(i - j) } } } return ans }
funcabs(x int)int { if x < 0 { return -x } return x }
classSolution: defminOperations(self, boxes: str) -> List[int]: left, right, operations = int(boxes[0]), 0, 0 for i inrange(1, len(boxes)): if boxes[i] == '1': right += 1 operations += i res = [operations] for i inrange(1, len(boxes)): operations += left - right if boxes[i] == '1': left += 1 right -= 1 res.append(operations) return res
funcminOperations(boxes string) []int { left := int(boxes[0] - '0') right := 0 operations := 0 n := len(boxes) for i := 1; i < n; i++ { if boxes[i] == '1' { right++ operations += i } } ans := make([]int, n) ans[0] = operations for i := 1; i < n; i++ { operations += left - right if boxes[i] == '1' { left++ right-- } ans[i] = operations } return ans }