【Leetcode】Contains Duplicate 1 and 2

来源:互联网 发布:2016年贵州旅游数据 编辑:程序博客网 时间:2024/05/18 00:04

【题目】

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.

【思路】

这个 easy题目 还是相当的 easy的。。。解法 的话我感觉也是比较直观。

就是先进行 排序 ,然后设一个变量 用来记录上一个值,如果当前这个 和 上一个相同,就返回true,如果遍历 了一遍都没有 相同的,那么就返回 false.

【代码】

public class Solution {    public boolean containsDuplicate(int[] nums) {       if(nums == null || nums.length == 0 ) return false;Arrays.sort(nums);int last = nums[0];for(int i = 1;i<nums.length;i++){if(last == nums[i]){return true;}else{    last = nums[i];}}return false;     }}

或者 还可以用hash table

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

【题目2】

Given an array of integers and an integer k, find out whether there there are two distinct indices i and j in the array such that nums[i] = nums[j] and the difference between and j is at most k.

【思路】

其实 思路还是比较清晰的,就是用hashmap, key就是数组中第i个元素,value就是这个元素的位置。

遍历一遍数组,每一个都判断一下,map里面是否已经有这个元素了,如果没有这个元素就直接加进去,如果有这个元素了,就看一下map记录的上一次出现这个元素的位置,然后对比一下现在的位置,如果差值小于k,那么就返回true; 否则!!!!!这点很重要,第一次就是没考虑到这个情况!!要把map里面的位置更新成新的位置,以防这种case:

【1,0,1,1】,k=1 ,元素1出现多次,虽然第二次出现的时候,差距大于k,但是后面有符合条件的情况,所以我们要更新一下map里面记录的位置。


【代码】

第一次没有通过

第二次通过 :

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



0 0
原创粉丝点击