Contains Duplicate - LeetCode
Can you solve this real interview question? Contains Duplicate - 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 Ex
leetcode.com
파이썬 코드
class Solution(object):
def containsDuplicate(self, nums):
_set = set()
for num in nums:
if num in _set:
return True
else:
_set.add(num)
return False
자바 코드
import java.util.*;
class Solution {
public boolean containsDuplicate(int[] nums) {
HashSet<Integer> set = new HashSet<>();
for(int i=0;i<nums.length;i++){
if(set.contains(nums[i])){
return true;
}
set.add(nums[i]);
}
return false;
}
}
이번 문제는 집합 자료형으로 문제를 해결했다.
원리는 Two sum 문제와 같다.
원소가 set 자료구조에 입력되어있지 않으면 추가하고, 입력되어 있다면 같은 숫자가 있다는 의미이므로 True를 반환하면 된다.
[파이썬 PYTHON · 자바 Java] LeetCode【Two sum】
Two Sum - LeetCode Can you solve this real interview question? Two Sum - Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target. You may assume that each input would have exactly one solutio
yinq.tistory.com