코린이의 소소한 공부노트

[LeetCode/Easy] 1748. Sum of Unique Elements 본문

코딩테스트 풀이/JAVA

[LeetCode/Easy] 1748. Sum of Unique Elements

무지맘 2023. 4. 17. 01:22

1. Input

1) int[] nums

 

2. Output

1) nums의 요소 중 1개만 있는 요소들의 합을 반환

 

3. Constraint

1) 1 <= nums.length <= 100

2) 1 <= nums[i] <= 100

 

4. Example

Input: nums = [1,2,3,2] -> Output: 4

설명: 1번만 나타나는 요소는 [1,3]이므로 합인 4를 반환한다.

 

5. Code

1) 첫 코드(2023/04/17)

HashMap<Integer,Integer> m = new HashMap<>();
for(int i : nums)
    m.put(i, m.getOrDefault(i,0)+1);
int answer = 0;
Iterator it = m.entrySet().iterator();
while(it.hasNext()){
    Map.Entry e = (Map.Entry)it.next();
    if((int)e.getValue()==1)
        answer += (int)e.getKey();
}
return answer;

2) 메모리 사용량을 줄여보고자 시도했던 코드(2023/04/17)

HashMap<Integer,Integer> m = new HashMap<>();
for(int i : nums)
    m.put(i, m.getOrDefault(i,0)+1);
int answer = 0;
for(int i=0 ; i<nums.length ; i++)
    if(m.containsKey(nums[i]) && m.get(nums[i])==1){
        answer += nums[i]; m.remove(nums[i]);
    }
return answer;

- 몇 mb 차이 나지 않는데 훨씬 좋아진 걸로 나왔다.