Python, using sort, easy to understand

  • 0

    First, based on nums, add numbers to build a new array.
    Then, sort the new array.
    Finally, go though the new array to check if there are duplicate elements.

    class Solution(object):
    def containsNearbyDuplicate(self, nums, k):
    if (len(nums)==1):
    return False
    for i in range(len(nums)):
    newNums=sorted(newNums, key=lambda newNums : newNums[1])
    print (newNums)
    for i in range(len(nums)-1):
    if (newNums[i][1]==newNums[i+1][1]):
    if abs(newNums[i][0]-newNums[i+1][0])<=k:
    return True
    return False

Log in to reply

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.