数组中重复的数字

题目

在一个长度为n的数组里的所有数字都在0到n-1的范围内。 数组中某些数字是重复的,但不知道有几个数字是重复的。也不知道每个数字重复几次。请找出数组中任意一个重复的数字。 例如,如果输入长度为7的数组{2,3,1,0,2,5,3},那么对应的输出是第一个重复的数字2。

思路

使用HashSet,在存放时判断每个元素是否已经存在,存在则直接返回这个元素即可。

package com.zhumq.leetcode;
import java.util.HashSet;
import java.util.Scanner;
import org.junit.Test;
public class DuplicateNum {
    public Integer duplicateNum(int arr[]) {
        HashSet hs = new HashSet<>();
        for(int i=0;iif(!hs.contains(arr[i])) {
                hs.add(arr[i]);
            }else {
                return Integer.valueOf(arr[i]);
            }
        }
        return null;
    }

    @Test
    public void test1() {
        Scanner sc = new Scanner(System.in);

        while(sc.hasNext()) {
            int arr[] = new int[6];
            for(int i = 0;i<6;i++) {
                arr[i] = sc.nextInt();  
            }
            System.out.println(duplicateNum(arr));
        }
        sc.close();
    }
}

你可能感兴趣的:(剑指offer,剑指offer)