본문 바로가기

DEVELOP/Algorithm

[leetcode] 1748. Sum of Unique Elements

반응형

Q. 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. 

 

  let sumOfUnique = function(nums) {
      let sum = 0;
      nums.forEach(function(idx){
          if(nums.indexOf(idx)===nums.lastIndexOf(idx)){
              sum += idx;
          }
      });
      return sum;
  };
  

 

중복되는 요소들을 제외한 수들만 더한 결과를 리턴해야 하므로 indexOf와 lastIndexOf를 이용하여, 두 값이 같으면 중복이 없는 것이므로 새로운 배열에 추가했다. 두 값이 다르면 중복인 수이므로 더하지 않는다. 푼 방식이 메모리면에서는 나쁘지않지만 중복에 대해 제거를 하지 못해서 배열을 전부 순회하느라 런타임이 길어지는것 같은데 더 줄일 방법이 잘 생각이 안나서 좀 더 고민해봐야겠다. 마음이 급한데 이해는 느린편이라 그런지 코드를 짤 때 정말 두서없고 생각없이 풀게 되는 것 같다..

반응형