๊ด€๋ฆฌ ๋ฉ”๋‰ด

โœ๐Ÿป๊ธฐ๋กํ•˜๋Š” ๋ธ”๋กœ๊ทธ

leetcode - 217. Contains Duplicate ๋ณธ๋ฌธ

์•Œ๊ณ ๋ฆฌ์ฆ˜

leetcode - 217. Contains Duplicate

์ฉ์‹œํ‚ด 2022. 1. 8. 22:22
728x90

๋‚˜์˜ ํ’€์ด

https://github.com/ZhenxiKim/leetCode/blob/main/217-contains-duplicate/217-contains-duplicate.java

 

GitHub - ZhenxiKim/leetCode: leetCode ํ’€์ด

leetCode ํ’€์ด. Contribute to ZhenxiKim/leetCode development by creating an account on GitHub.

github.com

map์„ ์ด์šฉํ•˜์—ฌ ๋ฐฐ์—ด์˜ ์š”์†Œ๋“ค์˜ count ์ˆ˜๋ฅผ map์˜ value๋กœ ์ง€์ •ํ–ˆ๋‹ค.

import java.util.*;
class Solution {
    public boolean containsDuplicate(int[] nums) {
        Map<Integer, Integer> cntMap = new HashMap<Integer, Integer>();
        for(int i=0; i<nums.length; i++){
            if(cntMap.get(nums[i]) == null){
                cntMap.put(nums[i], 1);
            }else{
                cntMap.put(nums[i], cntMap.get(nums[i]) + 1);
            }
            
            System.out.println(cntMap.get(nums[i]));
        }
        
        boolean result = false;
        
        for(Integer key : cntMap.keySet()){
            if(cntMap.get(key) > 1){
                result = true;
            }
        }
        return result;
    }
}

์ธ์ƒ์ ์ธ ๋‹ค๋ฅธ์‚ฌ๋žŒ์˜ ํ’€์ด

๋ฐฐ์—ด์„ ์ •๋ ฌ ํ›„ ๋ฐ”๋กœ ์˜† ์š”์†Œ์™€ ๋น„๊ตํ•˜์—ฌ ๊ฐ™์œผ๋ฉด true

์ˆ˜ํ–‰ ์†๋„, ์ˆ˜ํ–‰ ์‹œ๊ฐ„์ด ํ›จ์”ฌ ๋นจ๋ผ์กŒ๋‹ค. ๋ฉ”๋ชจ๋ฆฌ ์‚ฌ์šฉ๋Ÿ‰๋„ ํ›จ ์ค„์—ˆ๋‹ค.

import java.util.*;
class Solution {
    public boolean containsDuplicate(int[] nums) {
         Arrays.sort(nums);

     for(int i = 0; i< nums.length-1 ; i++){
         if(nums[i]== nums[i+1])
             return true;
     }
    
    return false;
    }
}

728x90
๋ฐ˜์‘ํ˜•