mang_dev
맹꽁거리는 개발자
mang_dev
전체 방문자
오늘
어제
  • 분류 전체보기 (185)
    • Frontend (2)
      • Next.js (1)
    • Backend (3)
      • GraphQL (2)
    • Book (1)
      • 기타 (1)
    • Old (177)
      • 알고리즘 퍼즐 (1)
      • 백준 (131)
      • 프로그래머스 (0)
      • Codility (15)
      • LeetCode (7)
      • Codewars (1)
      • Codeforces (0)
      • Django (6)
      • React (2)
      • Naver Map Api (3)
      • Web UI (4)
      • Introduction to Cloud (2)
hELLO · Designed By 정상우.
mang_dev

맹꽁거리는 개발자

LeetCode - 217. Contains Duplicate
Old/LeetCode

LeetCode - 217. Contains Duplicate

2020. 11. 11. 23:28

문제

 

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
    'Old/LeetCode' 카테고리의 다른 글
    • LeetCode - 303. Range Sum Query
    • LeetCode - 226. Invert Binary Tree
    • LeetCode - 50. Pow(x, n) // Java
    • LeetCode - 19. Remove Nth Node From End of List // Java
    mang_dev
    mang_dev

    티스토리툴바