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

  • 相关阅读:
    NumPy 字符串函数
    NumPy 位运算
    Numpy 数组操作
    最小二乘法的原理与计算
    NumPy 迭代数组
    Making AJAX Applications Crawlable
    mac, start sublime from terminal
    Speed Up Your WordPress Site
    To Support High-Density Retina Displays
    HTML5 tricks for mobile
  • 原文地址:https://www.cnblogs.com/wentiliangkaihua/p/11318840.html
Copyright © 2011-2022 走看看