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

  • 相关阅读:
    pysam操作sam文件
    NCBI SRA数据库
    通过bed文件获取fasta序列
    利用mysql客户端查询UCSC数据库
    Biopython常用功能模块
    FASTX-Toolkit组件用法
    SQL HAVING用法详解
    jquery获取、改变元素属性值
    《JavaScript DOM编程艺术》
    sublime text3使用心得及个人配置 sublime常用快捷键大全
  • 原文地址:https://www.cnblogs.com/wentiliangkaihua/p/11318840.html
Copyright © 2011-2022 走看看