每日一道Leetcode算法——N-Repeated Element in Size 2N Array——2019.01.18

题干:

中文:

在大小为2N的阵列A中,存在N + 1个元素,并且这些元素中的一个元素重复了N次。

返回重复N次的元素。

Example 1:

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

Example 2:

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

Example 3:

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

Note:

  1. 4 <= A.length <= 10000
  2. 0 <= A[i] < 10000
  3. A的长度是偶数

英文:

In a array A of size 2N, there are N+1 unique elements, and exactly one of these elements is repeated N times.

Return the element repeated N times.

Example 1:

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

Example 2:

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

Example 3:

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

Note:

  1. 4 <= A.length <= 10000
  2. 0 <= A[i] < 10000
  3. A.length is even

解题思路:

这题主要是找到重复的元素,因为数组长度为2N,有N+1个元素,所以可以确定N个元素只出现1次,只有1个元素出现N次。

所以我们找到出现次数大于1的元素。

把数组循环放入map中,然后找到map的value为N的元素返回。

package cn.leetcode.easy;

import java.util.HashMap;
import java.util.Map;

/**
 * In a array A of size 2N, there are N+1 unique elements, and exactly one of these elements is repeated N times.
 * Return the element repeated N times.
 *
 * @author kimtian
 * @date 2039.01.18
 * @num 961
 */
public class NRepeated_Element_in_Size_2N_Array {
    /**
     * 这题主要是找到重复的元素,因为数组长度为2N,有N+1个元素,所以可以确定N个元素只出现1次,只有1个元素出现N次。
     * 所以我们找到出现次数大于1的元素。
     * 把数组循环放入map中,然后找到map的value为N的元素返回。
     *
     * @param A 数组
     * @return 重复元素
     */
    public static int repeatedNTimes(int[] A) {
        //创建一个map存放数组元素和其出现次数
        Map<Integer, Integer> Amap = new HashMap<>();
        //循环数组元素,将数组中的元素和出现次数放入map中,
        for (int i = 0; i < A.length; i++) {
            //如果map中有,则在其原始value的基础上+1
            if (Amap.containsKey(A[i])) {
                Amap.put(A[i], Amap.get(A[i]) + 1);
            }
            //没有,则将其放入map中,value为1,表示只出现一下
            else {
                Amap.put(A[i], 1);
            }
        }
        /**
         *  也可以这样将数组元素和出现次数放入map中
         *  for (int i : A) {
         *     Amap.put(i, Amap.getOrDefault(i, 0) + 1);
         *  }
         */
        //循环map的key元素集合
        for (int j : Amap.keySet()) {
            //并根据key值获取其value值,即出现的次数,如果出现次数超过1次,则表示是我们要找的元素,将其返回
            if (Amap.get(j) > 1) {
                return j;
            }
        }
        return 0;
    }

    public static void main(String[] args) {
        int[] a = new int[]{1, 2, 3, 3};
        System.out.println(repeatedNTimes(a));
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值