classSolution: defminMoves(self, nums: List[int], k: int) -> int: g, preSum = [], [0] for i, num inenumerate(nums): if num == 1: g.append(i - len(g)) preSum.append(preSum[-1] + g[-1]) m, res = len(g), inf for i inrange(m - k + 1): mid = i + k // 2 r = g[mid] res = min(res, (1 - k % 2) * r + (preSum[i + k] - preSum[mid + 1]) - (preSum[mid] - preSum[i])) return res
publicclassSolution { publicintMinMoves(int[] nums, int k) { IList<int> g = new List<int>(); IList<int> preSum = new List<int>(); preSum.Add(0); for (int i = 0; i < nums.Length; i++) { if (nums[i] == 1) { g.Add(i - g.Count); preSum.Add(preSum[preSum.Count - 1] + g[g.Count - 1]); } } int m = g.Count, res = int.MaxValue; for (int i = 0; i <= m - k; i++) { int mid = i + k / 2; int r = g[mid]; res = Math.Min(res, (1 - k % 2) * r + (preSum[i + k] - preSum[mid + 1]) - (preSum[mid] - preSum[i])); } return res; } }
staticinlineintmin(int a, int b) { return a < b ? a : b; }
intminMoves(int* nums, int numsSize, int k) { int g[numsSize], preSum[numsSize + 1]; int gSize = 0, preSumSize = 0; preSum[preSumSize++] = 0; for (int i = 0; i < numsSize; i++) { if (nums[i] == 1) { g[gSize++] = i - gSize; preSum[preSumSize++] = preSum[preSumSize - 1] + g[gSize - 1]; } } int m = gSize, res = INT_MAX; for (int i = 0; i <= m - k; i++) { int mid = i + k / 2; res = min(res, (1 - k % 2) * g[mid] + \ (preSum[i + k] - preSum[mid + 1]) - \ (preSum[mid] - preSum[i])); } return res; }
[sol1-JavaScript]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
var minMoves = function(nums, k) { const g = []; const preSum = []; preSum.push(0); for (let i = 0; i < nums.length; i++) { if (nums[i] === 1) { g.push(i - g.length); preSum.push(preSum[preSum.length - 1] + g[g.length - 1]); } } let m = g.length, res = Number.MAX_VALUE; for (let i = 0; i <= m - k; i++) { let mid = i + Math.floor(k / 2); let r = g[mid]; res = Math.min(res, (1 - k % 2) * r + (preSum[i + k] - preSum[mid + 1]) - (preSum[mid] - preSum[i])); } return res; };