【题目1】

Given an array of integers, find if the array contains any duplicates.

Your function should return true if any value appears at least twice in the array, and it should return false if every element is distinct.

判断是否存在重复数字

【思路】

1、想复杂了,用了HashSet/HashMap,不过有利于解后面的Contains Duplicate II

2、直接sort+遍历一遍

【代码】

 法一、HashSet速度比HashMap快些。

class Solution {
    public boolean containsDuplicate(int[] nums) {
        if(nums.length==0) return false;
        Set<Integer>set=new HashSet<Integer>();
        for(int i=0;i<nums.length;i++)
        {
            if(set.contains(nums[i])) return true;
            set.add(nums[i]);
        }
        return false;
    }
}

法二

        Arrays.sort(nums);
        for (int i = 0; i < nums.length - 1; i++) {
            if (nums[i] == nums[i+1])
                return true;
        }

 

【题目2】

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.

AT MOST意思是当num[i]=num[j]时,i-j的最大间隔为k。j-i≤k。

Example 1:

Input: nums = [1,2,3,1], k = 3

Output: true

Example 2:

Input: nums = [1,0,1,1], k = 1

Output: true

 

【思路】

 用HashMap,int i,for循环。

当不包含key时,放入key,value到map中。

当包含key时,比较此时的循环i和value差值,i-data.get(nums[i])<=k,返回true。

否则返回false。

【代码】

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

 

 posted on 2018-11-26 20:00  alau  阅读(119)  评论(0编辑  收藏  举报