[Leetcode] 1748. Sum of Unique Elements

유동헌·2021년 8월 7일
0

1일1알고리즘

목록 보기
2/12

You are given an integer array nums. The unique elements of an array are the elements that appear exactly once in the array.

Return the sum of all the unique elements of nums.

Example 1:

Input: nums = [1,2,3,2]
Output: 4
Explanation: The unique elements are [1,3], and the sum is 4.
Example 2:

Input: nums = [1,1,1,1,1]
Output: 0
Explanation: There are no unique elements, and the sum is 0.
Example 3:

Input: nums = [1,2,3,4,5]
Output: 15
Explanation: The unique elements are [1,2,3,4,5], and the sum is 15.

풀이

class Solution:
    def sumOfUnique(self, nums: List[int]) -> int:
        
        data = []
        
        for i in nums:
            if nums.count(i) == 1:
                data.append(i)
        return sum(data)

참고 풀이
hash table 사용한 코드를 작성하기가 어려워, 코드를 참고하고 공부하였다.
출처 : https://goodtecher.com/leetcode-1748-sum-of-unique-elements/

class Solution:
    def sumOfUnique(self, nums: List[int]) -> int:
        
        dict_nums = {} # 빈 딕셔너리 
        sum = 0
        
        for num in nums:
            dict_nums[num] = dict_nums.get(num, 0) + 1
        # 이 코드를 실행하면 딕셔너리의 key 값으로 주어지는 리스트 값이 들어오고, value 값으로 중복 여부가 체크된다. 
            
        for key, value in dict_nums.items():
            if value == 1:
                sum += key
                
        # 딕셔너리 전체에 대한 for loop를 실행하고, value가 1인 값만 sum에 더해주면 값을 찾을 수 있다. 
                
        return sum
profile
지뢰찾기 개발자

0개의 댓글