LeetCode--219--存在重复元素2

问题描述:

给定一个整数数组和一个整数 k,判断数组中是否存在两个不同的索引 i 和 j,使得 nums [i] = nums [j],并且 ij 的差的绝对值最大为 k

示例 1:

输入: nums = [1,2,3,1], k= 3
输出: true

示例 2:

输入: nums = [1,0,1,1], k=1
输出: true

示例 3:

输入: nums = [1,2,3,1,2,3], k=2
输出: false

方法1:(只适用于正数组成的list)erro

 1 class Solution(object):
 2     def containsNearbyDuplicate(self, nums, k):
 3         """
 4         :type nums: List[int]
 5         :type k: int
 6         :rtype: bool
 7         """
 8         flag = True
 9         nums = "".join([str(x) for x in nums])
10         for i in range(len(nums)):
11             index = nums[i+1:].find(nums[i])
12             if index >= 0 :
13                 index += i + 1
14             while True:
15                 if index - i == k:
16                     return True
17                 else:
18                     temp = index
19                     index = nums[temp+1:].find(nums[i])
20                     if index >= 0 :
21                         index += temp+1
22                     else:
23                         return nums[i]
24                         break
25         return False

官方:感觉很无厘头啊,[99,99] k = 2返回True........只能把小于号加上。。。。。理解错误,收到了例子的干扰。说的就是最大不超过K

 1 class Solution(object):
 2     def containsNearbyDuplicate(self, nums, k):
 3         """
 4         :type nums: List[int]
 5         :type k: int
 6         :rtype: bool
 7         """  
 8         num_map={}
 9         for i in xrange(len(nums)):
10             if nums[i] in num_map and i-num_map[nums[i]]<=k:
11                 return True
12             else:
13                 num_map[nums[i]]=i      
14         return False

2018-09-19 14:47:04

转载于:https://www.cnblogs.com/NPC-assange/p/9674545.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值