您的位置:首页 > 大数据 > 人工智能

Contains Duplicate II

2015-06-30 10:24 387 查看
题目:

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

解法:

class Solution:

# @param {integer[]} nums

# @param {integer} k

# @return {boolean}

def containsNearbyDuplicate(self, nums, k):

sorted_nums = nums[:]

sorted_nums.sort()

if len(nums)<=1:

return False

for index,value in enumerate(sorted_nums):

if index<len(sorted_nums)-1 and value==sorted_nums[index+1]:

index1 = nums.index(value)

nums.remove(value)

index2 = nums.index(value)+1

if index2-index1<=k:

return True

return False
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: