oj219. Contains Duplicate II

来源:互联网 发布:unity3d行走播放动画 编辑:程序博客网 时间:2024/06/16 17:06

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 absolute difference between i and j is at most k.

翻译:

给定整数数组和整数k,找出数组中是否有两个不同的索引ij,使得nums [i] = nums [j]ij之间绝对差值最多为k

注意:英语不好,我一开始一直理解错误,认为只要出现不满足条件的情况就返回false,但是看答案才知道,只要有满足条件的情况就返回ture。全不满足才返回false。

自己思路(超时):

通过新建list来逐个存取数组,每次存新元素时如果list中已有重复元素,就拿出最靠后的重复元素下标,判断差值是否小于等于k。但是查找的时候应该会很费时。

 public boolean containsNearbyDuplicate(int[] nums, int k) {        if(nums.length ==0) return false;        List<Integer> l = new ArrayList<Integer>();        for(int i =0;i<nums.length;i++){            if(l.lastIndexOf(nums[i]) != -1){                int j = l.lastIndexOf(nums[i]);                if(i-j <= k) {                    return true;                }else{                    l.add(nums[i]);                }            }            else{                l.add(nums[i]);            }        }        return false;    }
答案思路:

用hashMap存值和下标,出现相同元素就判断差值是否小于等于k,满足条件就返回true,否则put该元素,这里重复元素下标会替换已有元素的下标。节省空间和查找时间。

public boolean containsNearbyDuplicate(int[] nums, int k) {        Map<Integer,Integer> m = new HashMap<Integer,Integer>();        for(int i =0;i<nums.length;i++){           if(m.containsKey(nums[i])){               if(i - m.get(nums[i]) <=k){                   return true;               }           }           m.put(nums[i],i);        }        return false;    }




0 0