zoukankan      html  css  js  c++  java
  • 219. Contains Duplicate II

    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.

    Example 1:

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

    Example 2:

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

    Example 3:

    Input: nums = [1,2,3,1,2,3], k = 2
    Output: false
    class Solution {
        public boolean containsNearbyDuplicate(int[] nums, int k) {
            boolean result = false;
            for(int i = 0; i < nums.length - 1; i++){
                for(int j = i+1; j < nums.length; j++){
                    if((nums[i]==nums[j]) && Math.abs(i - j) <= k) result = true;
                }
            }
            return result;
        }
    }

    1。 懒人方法,双重循环

    class Solution {
        public boolean containsNearbyDuplicate(int[] nums, int k) {
            // boolean result = false;
            // for(int i = 0; i < nums.length - 1; i++){
            //     for(int j = i+1; j < nums.length; j++){
            //         if((nums[i]==nums[j]) && Math.abs(i - j) <= k) result = true;
            //     }
            // }
            // return result;
    

    HashMap<Integer, Integer> hashMap = new HashMap<Integer, Integer>();

    for (int i = 0; i < nums.length; i++) {
    if (hashMap.containsKey(nums[i]) && i - hashMap.get(nums[i]) <= k) {
    return true;
    }
    hashMap.put(nums[i], i);
    }

    return false;

    
        }
    }

    方法2:用hashmap来读和存数,遇到相同的计算一下距离。注意题目是只要存在有两个相同的,而且index之差小于等于k即可,一经成立就可以返回true。

    https://my.oschina.net/Tsybius2014/blog/517511

  • 相关阅读:
    最近这段时间
    一元多项式的
    珍藏
    运行命令大全
    Google
    Windows Live Writer插件
    Word写论文的技
    安装Windows Live Writer后Ƃ
    比尔盖茨给人
    不经意的感悟
  • 原文地址:https://www.cnblogs.com/wentiliangkaihua/p/11318840.html
Copyright © 2011-2022 走看看