We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
这道题一开始我没有任何思路,觉得任何一次交换都会影响很大,也不知道如何作交换。
这时的思路是要排除干扰项,抽象成一条核心思路。
观察示例,为什么有的可以交换成功,有的不行呢,比如Example 3。
根据鸽巢定理,假如要交换4个数,使这4个数都跟原来的位置不同,如果其中有超过一半的数(比如4)完全相同,假如[2,2,2,3],则肯定不会出现最后所有位置数字跟原来不一样的结果。
如此,我们理清思路:
感谢@jyy的思路,这是统计(数学)+贪心的想法。
class Solution { public long minimumTotalCost(int[] nums1, int[] nums2) { int n = nums1.length; long ans = 0; boolean[] v = new boolean[n]; Map<Integer, Integer> map = new HashMap<>(); int maxCnt = 0; int maxVal = 0; int equalCnt = 0; for (int i = 0; i < n; ++i) { if (nums1[i] == nums2[i]) { map.put(nums1[i], map.getOrDefault(nums1[i], 0) + 1); if (map.get(nums1[i]) > maxCnt) { maxCnt = map.get(nums1[i]); maxVal = nums1[i]; } ans += i; equalCnt++; v[i] = true; } } if (maxCnt * 2 <= equalCnt) { return ans; } for (int i = 0; i < n && maxCnt * 2 > equalCnt; ++i) { if (v[i]) { continue; } if (nums1[i] != maxVal && nums2[i] != maxVal) { ans += i; equalCnt++; } } return maxCnt * 2 > equalCnt ? -1 : ans; } }
The text was updated successfully, but these errors were encountered:
No branches or pull requests
这道题一开始我没有任何思路,觉得任何一次交换都会影响很大,也不知道如何作交换。
这时的思路是要排除干扰项,抽象成一条核心思路。
观察示例,为什么有的可以交换成功,有的不行呢,比如Example 3。
根据鸽巢定理,假如要交换4个数,使这4个数都跟原来的位置不同,如果其中有超过一半的数(比如4)完全相同,假如[2,2,2,3],则肯定不会出现最后所有位置数字跟原来不一样的结果。
如此,我们理清思路:
感谢@jyy的思路,这是统计(数学)+贪心的想法。
The text was updated successfully, but these errors were encountered: