LeetCode Containsa Duplicate II

来源:互联网 发布:ubuntu winccp 编辑:程序博客网 时间:2024/05/17 03:21

题目:

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 jis at most k.

题意:

给定一个数组和一个K值,然后判断在i和j的两个位置中,是否有重复的数出现,也就是|i - j| <= k。这个题可以采用Set来做,因为Set是可以保证元素不出现重复的,也就是说,我可以利用一个Set来存储长度为k的数组元素,如果在这个K中的元素出现了重复元素,那么就返回true,否则就返回false。但是因为这个窗口需要不停地往前走和删除头结点,所以需要考虑用哪一个Set,这里我采用LinkedHashSet,因为这种类型的Set是可以保证顺序输入即存储的,那么用两个标记为start和end来表示这个Set的窗口大小。

public boolean containsNearbyDuplicate(int[] nums, int k) {          Set<Integer> appearedNum = new LinkedHashSet<Integer>();          int start = 0, end = 0;          for(int i = 0; i < nums.length; i++)        {              if(!appearedNum.contains(nums[i]))            {                  appearedNum.add(nums[i]);                  end++;              }             else             return true;              if(end - start  > k)             {                  appearedNum.remove(nums[start]);                  start++;              }          }          return false;       }
这里需要重新复习的就是关于Set类型。在Java里有好几种Set类型,而且有各种不同的用处,一般我们常用的就是HashSet,如果需要排序,那么就采用TreeSet,如果需要保证顺序输入存储,那么就采用LinkedHashSet,一般的HashSet存储是采用HashCode的大小来存储的。

0 0