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
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
相关文章推荐
- maven项目配置Project Facets时further configuration available不出来问题
- AI中的几种搜索算法---A*搜索算法
- AI中的几种搜索算法---SA搜索算法
- AI中的几种搜索算法---Tabu搜索算法
- git修改user.name和user.email
- AI中的几种搜索算法---基因算法
- Lightoj 1071 - Baker Vai (双线程DP)
- LeetCode-Contains Duplicate-解题报告
- LeetCode-Contains Duplicate II-解题报告
- ORA-01274: cannot add datafile '/oradata/orauat/tbs_captain01.dbf'
- LeetCode-Contains Duplicate III-解题报告
- Is the onDestroy method of Activity certain to call?
- 关于main函数的参数
- LeetCode Climbing Stairs
- BZOJ4155 : [Ipsc2015]Humble Captains
- CheeseZH: Stanford University: Machine Learning Ex4:Training Neural Network(Backpropagation Algorithm)
- How to run oaisim with virtual MME on same machine
- AS 学习笔记之Error:Execution failed for task ':dynamicgrid:packageReleaseResources'.
- vs2010:无法解析的外部符号 _main
- hdu 3394 railway 点连通分量判环