• LeetCode 961. N-Repeated Element in Size 2N Array


    You are given an integer array nums with the following properties:

    • nums.length == 2 * n.
    • nums contains n + 1 unique elements.
    • Exactly one element of nums is repeated n times.

    Return the element that is repeated n times.

    Example 1:

    Input: nums = [1,2,3,3]
    Output: 3
    

    Example 2:

    Input: nums = [2,1,2,5,3,2]
    Output: 2
    

    Example 3:

    Input: nums = [5,1,5,2,5,3,5,4]
    Output: 5
    

    Constraints:

    • 2 <= n <= 5000
    • nums.length == 2 * n
    • 0 <= nums[i] <= 104
    • nums contains n + 1 unique elements and one of them is repeated exactly n times.

    其实就是找一个数组里重复出现的数字/出现次数超过一半的数字。最简单的做法就是用一个set存出现过的数字,如果有重复出现的就return。

    1. class Solution {
    2. public int repeatedNTimes(int[] nums) {
    3. Set<Integer> set = new HashSet<>();
    4. for (int i : nums) {
    5. if (set.contains(i)) {
    6. return i;
    7. }
    8. set.add(i);
    9. }
    10. return -1;
    11. }
    12. }

    然后solutions里还有一种巧妙(并很难想)的解法。看了解答也看了老半天才看懂。它的思想大概是这样的:如果这个数组长度为2n,那么我们把它拆成n个两个一组的pair,那么要么就是每个pair里有一个我们要找的数字x,要么某个pair里就会两个都是x。假如是第一种情况,那么考虑到两个pair(也就是四个数字),最坏情况下就是x在第一个和最后一个,which is [x,a][b,x]。因此在所有情况下,每check连续的四个数字,如果有一个数字出现了两次,那这个数字就是x了。具体还能再简化成,只要check i和i - 1、i - 2这连续的三个数字就行,唯独只有上面列出的情况(which is x在第一个)才会有连续三个里都没有重复的的情况。

    1. class Solution {
    2. public int repeatedNTimes(int[] nums) {
    3. for (int i = 2; i < nums.length; i++) {
    4. if (nums[i - 2] == nums[i] || nums[i - 1] == nums[i]) {
    5. return nums[i];
    6. }
    7. }
    8. return nums[0];
    9. }
    10. }

  • 相关阅读:
    上海亚商投顾:沪指继续震荡向上 零售等消费股表现活跃
    宿舍是我的第二个家
    C++字面量杂谈
    21天学习第十二天-Map集合
    使用Redis做某个时间段在线数统计
    PMP每日一练 | 考试不迷路-9.14(包含敏捷+多选)
    使用Docker搭建Npm私服Verdaccio
    Java+SpringBoot+Vue自习室预约系统全栈开发
    Abp vNext 依赖注入
    【Python学习笔记】字符串格式化
  • 原文地址:https://blog.csdn.net/qq_37333947/article/details/127925046