天天看點

LeetCode刷題系列leetcode刷題記錄001

leetcode刷題記錄001

題目描述

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

來源:力扣(LeetCode)

連結:https://leetcode-cn.com/problems/shu-zu-zhong-zhong-fu-de-shu-zi-lcof

著作權歸領扣網絡所有。商業轉載請聯系官方授權,非商業轉載請注明出處。

解題思路

用HashMap,将輸入數組中每個資料值當做key,下标當做value。周遊數組,拿到一個資料時使用containsKey()方法來判斷HashMap中是否已經有了該資料,沒有放入HashMap中,已經有了的話,就傳回

代碼

public class Solution {
    public int findReaptNum(int[] nums){
        int len=nums.length;
        HashMap<Integer,Integer> map=new HashMap<>();
        for(int i=0;i<len;i++){
            if(map.containsKey(nums[i])){
                return nums[i];
            }
            map.put(nums[i], i);
        }
        return -1;
    }
}