2021.01.10 연습

 

  • 사용언어 : java

 

1.


class Solution {
    public int singleNumber(int[] nums) {

        Map<Integer, Integer> map = new HashMap<>();
        for (int i : nums) {
            map.put(i, map.getOrDefault(i, 0) + 1);
        }
        
        for(int i : nums) {
            if(map.get(i).equals(1)) { 
                return i;
            } 
        }

        return 0;
    }
}

Runtime: 10 ms, faster than 23.48% of Java online submissions for Single Number. Memory Usage: 39.7 MB, less than 28.39% of Java online submissions for Single Number.


2.

class Solution {
    public int numIdenticalPairs(int[] nums) {
        int count = 0;
        for (int i = 0; i < nums.length-1; i ++) {            
            for (int j = i+1; j < nums.length; j ++) {
                if (nums[i] == nums[j]) count++;
            }
        }
        return count;
    }
}

Runtime: 1 ms, faster than 63.77% of Java online submissions for Number of Good Pairs. Memory Usage: 36.3 MB, less than 79.36% of Java online submissions for Number of Good Pairs.


  • 다른 코드 참고
class Solution {
    public int numIdenticalPairs(int[] nums) {
        Map<Integer, Integer> countMap = new HashMap<>();
        int count = 0;
        
        for(Integer num : nums)
            countMap.put(num, countMap.getOrDefault(num, 0) + 1);
        
        for(Integer currCount : countMap.values())
            count += currCount * (currCount-1)/2;
        
        return count;
    }
}