https://leetcode.com/problems/contains-duplicate/
Contains Duplicate - LeetCode
Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.
leetcode.com
<문제 설명>
int형인 배열 nums이 있다. 같은 값이 배열에서 최소 두번이상 나오면 true를 return하고 모든 요소들이 구별된다면 false를 return해라.
<풀이 과정>
1. 배열이라는 점을 사용해서 정렬한다. 정렬한 후, 인접 인덱스를 비교하여 같은 숫자가 있다면 true를 return하도록 작성한다.
2. LeetCode에서 Hash Table을 사용할 수 있다고 해서 생각해본 해결책이다. HashMap에 각 배열의 숫자를 key로 넣고 value 값을 +1 해준다. 만약 중복 값이 있다면 value가 1보다 커지기 때문에 if문을 통해 각 key에 대한 value 값이 1보다 크다면 true를 return하도록 한다.
<풀이 코드>
1.
class Solution {
public boolean containsDuplicate(int[] nums) {
Arrays.sort(nums);
for (int i = 0; i < nums.length - 1; i++) {
if (nums[i] == nums[i+1]) {
return true;
}
}
return false;
}
}
2.
class Solution {
public boolean containsDuplicate(int[] nums) {
HashMap<Integer, Integer> map = new HashMap<>();
for(int i : nums) {
map.put(i, map.getOrDefault(i, 0) + 1);
if (map.get(i) > 1) {
return true;
}
}
return false;
}
}
'Leetcode' 카테고리의 다른 글
[Day6] Maximum Product Subarray (0) | 2023.02.01 |
---|---|
[Day5] Maximum Subarray (0) | 2022.11.14 |
[Day2] Best Time to Buy and Sell Stock (0) | 2022.10.25 |
[Day1] Two Sum (0) | 2022.10.24 |
오늘부터 하루에 한 문제씩 Leetcode 시작~! (0) | 2022.10.24 |