• leetcode面试准备:Contains Duplicate I && II


    1 题目

    Contains Duplicate I

    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.

    接口: public boolean containsDuplicate(int[] nums)

    Contains Duplicate II

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

    接口public boolean containsNearbyDuplicate(int[] nums, int k)

    2 思路

    I:判断数组中有无重复元素。用HashTable的思想,实现用HashSet来做。
    复杂度: Time:O(n);Space:O(n)

    II : 在I的基础上,判断重复的元素相距离的位置是否在k范围之内。用HashTable的思想,实现用HashMap来做,<key, value> = <数组值,下标index>
    复杂度: Time:O(n);Space:O(n)

    注意:如何更新Map的值?考虑一下注意的测试用例 {1,0,1,1},1

    3 代码

    I

    	public boolean containsDuplicate(int[] nums) {
    		int len = nums.length;
    		Set<Integer> set = new HashSet<Integer>(len);
    		for (int num : nums) {
    			if (set.contains(num)) {
    				return true;
    			} else {
    				set.add(num);
    			}
    		}
    		return false;
    	}
    

    II

    	public boolean containsNearbyDuplicate(int[] nums, int k) {
    		int len = nums.length;
    		Map<Integer, Integer> map = new HashMap<Integer, Integer>(len);
    		for (int i = 0; i < len; i++) {
    			if (map.containsKey(nums[i])) {
    				int diff = i - map.get(nums[i]);
    				if (diff <= k)
    					return true;
    			}
    			map.put(nums[i], i); // 不管有没有这个num,都要更新Map的值。为了通过这样的测试用例:{1,0,1,1},1
    		}
    		return false;
    	}
    

    4 总结

    解题的思想,主要是HashTable。想到就比较简单了。

    5 参考

  • 相关阅读:
    Web端导出CSV
    dojo/dom-style样式操作学习笔记
    dojo/dom源码学习
    上层建筑——DOM元素的特性与属性(dojo/dom-prop)
    上层建筑——DOM元素的特性与属性(dojo/dom-attr)
    返本求源——DOM元素的特性与属性
    DOM扩展札记
    以代码爱好者角度来看AMD与CMD
    dojo事件驱动编程之事件绑定
    通过Web.config中的configSections配置自己系统的全局常量
  • 原文地址:https://www.cnblogs.com/byrhuangqiang/p/4703326.html
Copyright © 2020-2023  润新知