문제
Given an array of integers, find if the array contains any duplicates.
Your function should return true if any value appears at least twice in the array, and it should return false if every element is distinct.
Example 1:
Input: [1,2,3,1] Output: true
Example 2:
Input: [1,2,3,4] Output: false
Example 3:
Input: [1,1,1,3,3,4,3,2,4,2] Output: true
풀이
배열에서 중복된 값이 있는지를 찾는 문제이다.
배열을 정렬한 뒤, 하나씩 탐색하며 이전 index에 있는 값과 같으면 true를 반환
배열의 크기가 0이거나, 모든 탐색을 성공적으로 마치면 false를 반환
코드
더보기
class Solution {
public boolean containsDuplicate(int[] nums) {
if(nums.length == 0)
return false;
Arrays.sort(nums);
int prev = nums[0];
for(int i=1;i<nums.length;i++){
if(prev == nums[i])
return true;
prev = nums[i];
}
return false;
}
}
'Old > LeetCode' 카테고리의 다른 글
LeetCode - 746. Min Cost Climbing Stairs (0) | 2021.02.06 |
---|---|
LeetCode - 303. Range Sum Query (2) | 2021.02.05 |
LeetCode - 226. Invert Binary Tree (0) | 2020.11.12 |
LeetCode - 50. Pow(x, n) // Java (0) | 2020.11.10 |
LeetCode - 19. Remove Nth Node From End of List // Java (0) | 2020.11.10 |