-
1. Problem
대충 문자열 안에 같은 값이 있으면 "트루"를 뽑아 내라는 말
Given an integer array nums, return true if any value appears at least twice in the array, and return false if every element is distinct.
Example 1:
Input: nums = [1,2,3,1]
Output: true
Example 2:
Input: nums = [1,2,3,4]
Output: false
Example 3:
Input: nums = [1,1,1,3,3,4,3,2,4,2]
Output: true
2. Solve
2-1 Using Hash
루프를 돌려서 각 숫자의 개수를 배열에 저장하려고 했습니다.
하지만, 이런 경우에는 숫자의 개수를 입력 받을 Array의 크기를 무한정으로 늘려 줘야 하기에, 메모리 및 속도 저하가 되는 모습을 볼 수 있습니다.
*예제 1번 예시
[ 0, 2, 1, 1 ] => if ( arr[i] > 2) true
Code
function solution(nums) { let result = false; let obj = Array(100).fill(0); for (let i = 0; i < nums.length; i++) { obj[nums[i]] += 1; if (obj[nums[i]] >= 2) { result = true; return result; } } return false; }
2-2 Using Set
Set()은 중복된 값은 무시하고 배열을 만들어주는 내장함수입니다.
[1,2,3,4,1] 의 경우 Set을 이용하면 [1,2,3,4] 로 변환이 되는데, 이 성질을 이용해서 문제를 풀었습니다.
만약, Set을 사용하고도 Nums의 값과 길이가 다르면 중복된 값이 있기에 True를 출력 해주면 됩니다.
function solution(nums) { const set = new Set(nums); if (set.size !== nums.length) { return true; } return false; }
'PS > LeetCode' 카테고리의 다른 글
[ LeetCode _ 141 & 142 ] Linked List Cycle 1,2 (0) 2021.05.16 [ LeetCode _ 11 ] Container With Most Water ( by using JavaScript ) (0) 2021.05.15 [LeetCode_15] 3 Sum ( by using JavaScript ) (0) 2021.05.15 [ LeetCode_152 ] Maximum Product SubArray ( by using JavaScript ) (0) 2021.05.14 [LeetCode_53] Maximum SubArray ( by using JavaScript) (0) 2021.05.13 댓글