classSolution: defminimumTotalCost(self, nums1: List[int], nums2: List[int]) -> int: ans = swap_cnt = mode_cnt = mode = 0 cnt = [0] * (len(nums1) + 1) for i, (x, y) inenumerate(zip(nums1, nums2)): if x == y: ans += i swap_cnt += 1 cnt[x] += 1 if cnt[x] > mode_cnt: mode_cnt, mode = cnt[x], x
for i, (x, y) inenumerate(zip(nums1, nums2)): if mode_cnt * 2 <= swap_cnt: break if x != y and x != mode and y != mode: ans += i swap_cnt += 1 return ans if mode_cnt * 2 <= swap_cnt else -1
classSolution { public: longlongminimumTotalCost(vector<int> &nums1, vector<int> &nums2){ long ans = 0L; int swap_cnt = 0, mode_cnt = 0, mode, n = nums1.size(), cnt[n + 1]; memset(cnt, 0, sizeof(cnt)); for (int i = 0; i < n; ++i) if (int x = nums1[i]; x == nums2[i]) { ans += i; ++swap_cnt; ++cnt[x]; if (cnt[x] > mode_cnt) { mode_cnt = cnt[x]; mode = x; } }
for (int i = 0; i < n && mode_cnt * 2 > swap_cnt; ++i) { int x = nums1[i], y = nums2[i]; if (x != y && x != mode && y != mode) { ans += i; ++swap_cnt; } } return mode_cnt * 2 > swap_cnt ? -1 : ans; } };
funcminimumTotalCost(nums1, nums2 []int) (ans int64) { var swapCnt, modeCnt, mode int cnt := make([]int, len(nums1)+1) for i, x := range nums1 { if x == nums2[i] { ans += int64(i) swapCnt++ cnt[x]++ if cnt[x] > modeCnt { modeCnt, mode = cnt[x], x } } }
for i, x := range nums1 { if modeCnt*2 <= swapCnt { break } if x != nums2[i] && x != mode && nums2[i] != mode { ans += int64(i) swapCnt++ } } if modeCnt*2 > swapCnt { return-1 } return }