Leetcode 存在重复元素 (219,220)

219. 存在重复元素 II

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

// 实现原理:这里面要求的一点是,其距离问题,也就是最大为K,name也就是说只要在距离的K的范围内,找到重复元素
// 即返回true,同样的范围已经大于K值的时候,这时候就要更新序列的起始位置。使用双指针策略进行。

public boolean containsNearbyDuplicate(int[] nums, int k) {
		int low=0;
		int high=0;
		
		Set<Integer> result=new HashSet<>();
		for(int i=0;i<nums.length;i++){
			if(!result.contains(nums[i])){
				high++;
				result.add(nums[i]);
			}
			else if(high-low<=k){
				return true;
			}
			if(high-low>k){
				low++;
				result.remove(nums[low]);
			}
			
		}

		return false;
        
    }

220. 存在重复元素 III

给定一个整数数组,判断数组中是否有两个不同的索引 i 和 j,使得 nums [i] 和 nums [j] 的差的绝对值最大为 t,并且 i 和 j 之间的差的绝对值最大为 ķ

/*
* 借助treeset的subset函数,看看是否有在对应区间内的数据
*同时维护一个长度为K的窗口,超过这个窗口,就将其最前面的元素将其拿掉。
* */

public boolean containsNearbyAlmostDuplicate(int[] nums, int k, int t) {
		 if (nums==null || nums.length<2 || k<1|| t<0){
			 return false;
		 }
		 
		 TreeSet<Long> result=new TreeSet<>();
		 for(int i=0;i<nums.length;i++){
			 SortedSet<Long> set=result.subSet((long)nums[i]-t,true, (long)nums[i]+t,true);
			 if(!set.isEmpty()){
				 return true;
			 }
			 else if(i>=k){
					 result.remove((long)nums[i-k]);
				 }
				 result.add((long)nums[i]);
			 }
		 return false;
} 

  暴力求解:

 public boolean containsNearbyAlmostDuplicate2(int[] nums, int k, int t) {
		 int j=0;
		 for(int i=0;i<nums.length;i++){
			 j=i+1;
			 while(j<nums.length && j-i<=k){
				 int data1=nums[j];
				 int data2=nums[i];
				 if(Math.abs(data1-data2)<=t){
					 return true;
				 }
				 j++;
			 }
		 }
		 return false;
	 }

  

217. 存在重复元素

给定一个整数数组,判断是否存在重复元素。

如果任何值在数组中出现至少两次,函数返回 true。如果数组中每个元素都不相同,则返回 false。

策略:

对数组进行预排序

public boolean containsDuplicate(int[] nums) {
        // 对数组进行排序o(nlogn)
		Arrays.sort(nums);
		boolean same=false;
		if(nums==null ){
			return true;
		}
		int i=0;
		while(i<nums.length){
			if(i==nums.length-1){
				break;
			}
			if(nums[i]==nums[i+1]){
				return true;
			}
			i++;
		}
		return false;

    }

  


posted @ 2019-02-26 17:54  Qian1996  阅读(145)  评论(0编辑  收藏  举报