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

(LeetCode)Contains Duplicate II --- 查找重复的元素升级版

2016-07-27 10:23 441 查看
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 difference
between i and j is at most k.

Subscribe to see which companies asked this question

题意:
首先要读懂题意,题目意思理解了就简单了。
首先给出一个整数数组,和一个K元素
然后判断是否含有重复的元素,并比较两个重复元素的索引,下表 i, j 是否满足 | i - j | < K
如果满足返回True,否则返回 False。注意:最多只能有一对重复的。
解题分析:
首先判断是否有重复的元素,如果有找到两个元素的索引,此处可以用hash的方法,找到第一个的时候index保存它的索引,
再找到第二个的时候用循环的变量 i 保存第二个索引,然后进行 i - index 求出结果,返回True或者False.

# -*- coding:utf-8 -*-
__author__ = 'jiuzhang'

class Solution(object):
def containsNearbyDuplicate(self, nums, k):
numsDict = dict()
for i in range(len(nums)):
index = numsDict.get(nums[i])
if (index >= 0 and i - index <= k):
return True
numsDict[nums[i]] = i
return False
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: