zoukankan      html  css  js  c++  java
  • 961. N-Repeated Element in Size 2N Array

    961. N-Repeated Element in Size 2N Array

    题目概述:

    在大小为 2N 的数组 A 中有 N+1 个不同的元素,其中有一个元素重复了 N 次。

    返回重复了 N 次的那个元素。

    解法一

    class Solution {
        public int repeatedNTimes(int[] A) {
            int index = 0;
            Set<Integer> set = new LinkedHashSet<>();
            for (int i = 0; i < A.length / 2 + 2; i++) {
                if (set.contains(A[i])) {
                    index = i;break;
                }
                set.add(A[i]);
            }
            return A[index];
        }
    }

    解法二

    class Solution {
        public int repeatedNTimes(int[] A) {
            int[] count = new int[10000];
            for (int a : A) {
                if (count[a]++ == 1) {
                    return a;
                }
            }
            return -1;
        }
    }

    解法三

    class Solution {
        public int repeatedNTimes(int[] A) {
            int i = 0, j = 0, n = A.length;
            while (i == j || A[i] != A[j]) {
                i = (int)(Math.random()*n);
                j = (int)(Math.random()*n);
            }
            return A[i];
        }
    }
  • 相关阅读:
    DHCP DHCPv6
    DHCPv6协议
    IPv6邻居发现协议
    CentOS下禁止防火墙
    centOS下更新yum源
    centOS下yum报错
    Flink+Kafka整合的实例
    Flink基本概念
    Ubuntu16.04下配置ssh免密登录
    Zookeeper+Kafka的单节点配置
  • 原文地址:https://www.cnblogs.com/mrjoker-lzh/p/10259506.html
Copyright © 2011-2022 走看看