[劍之offer] 03 陣列中重複的數字

努力的陽光藍孩發表於2020-10-13

一、問題

1、在一個長度為 n 的陣列 nums 裡的所有數字都在 0~n-1 的範圍內。陣列中某些數字是重複的,但不知道有幾個數字重複了,也不知道每個數字重複了幾次。請找出陣列中任意一個重複的數字。

2、例子

輸入:[2, 3, 1, 0, 2, 5, 3]

輸出:2 或 3

3、限制

2 <= n <= 100000

package com.haoxiansheng.demo01.SwordfingerOffer;

import lombok.extern.slf4j.Slf4j;

import java.util.HashSet;
import java.util.Set;

/**
 * @author flame
 * @data 2020/10/13
 */
@Slf4j
public class FindRepeatNumber {
    public static void main(String[] args) {
        int[] ints = {1, 2, 3, 1, 3, 4, 5, 6, 6, 3, 7};
        log.info("findRepeatNumber=>{}", findRepeatNumber(ints));
        log.info("findRepeatNumbers=>{}", findRepeatNumbers(ints).toString());
    }

    /**
     * 找出任意重複的數字
     *
     * @param nums
     * @return
     */
    public static int findRepeatNumber(int[] nums) {
        Set<Integer> temp = new HashSet<>();
        int repeat = -1;
        for (int num : nums) {
            if (!temp.add(num)) {
                repeat = num;
                break;
            }
        }
        return repeat;
    }

    /**
     * 找出所有重複的 數字
     *
     * @param nums
     * @return
     */
    public static Set<Integer> findRepeatNumbers(int[] nums) {
        Set<Integer> result = new HashSet<>();
        Set<Integer> temp = new HashSet<>();
        for (int num : nums) {
            if (!temp.add(num)) {
                result.add(num);
            }
        }
        return result;
    }
}


相關文章