관리 메뉴

솜씨좋은장씨

[leetCode] 219. Contains Duplicate II (Python) 본문

Programming/코딩 1일 1문제

[leetCode] 219. Contains Duplicate II (Python)

사용자 솜씨좋은장씨 2020. 10. 28. 19:47

Given an array of integers and an integer k, find out whether there are two distinct indices i and j in the array such that nums[i] = nums[j] and the absolute difference between i and j is at most k.

 

Example 1:

Input: nums = [1,2,3,1], k = 3
Output: true

Example 2:

Input: nums = [1,0,1,1], k = 1
Output: true

Example 3:

Input: nums = [1,2,3,1,2,3], k = 2
Output: false

Solution

class Solution:
    def containsNearbyDuplicate(self, nums: List[int], k: int) -> bool:
        if len(list(set(nums))) == len(nums):
            return False
        
        for i in range(len(nums)):
            for j in range(1, k+1):
                if i+j > len(nums) -1:
                    continue
                if nums[i] == nums[i+j]:
                    return True
                
        return False

 

 

SOMJANG/CODINGTEST_PRACTICE

1일 1문제 since 2020.02.07. Contribute to SOMJANG/CODINGTEST_PRACTICE development by creating an account on GitHub.

github.com

0 Comments
댓글쓰기 폼