【LeetCode】Contains Duplicate II

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.

算法思想

  • 思想一:

    两个数组下标i,j,在叫j-i<=k的范围内扫描判断,直到查找到两个相等的元素nums[i]=nums[j],但问题虽然未提到算法时间的要求,但却不允许这一算法的通过,这个算法的复杂度为(KN)。

  • 思想二:

    一个数组下标i, 使用hashmap记录扫描过得所有数字,利用hashmap.containsKey方法判断当前扫描数是否有和已经扫描过得数相同,如果有并且相差k则返回真。

算法实现

算法一(时间超时)

public class Solution {
    public boolean containsNearbyDuplicate1(int[] nums, int k) {
        int i = 0, j = 0;
        if (nums == null || nums.length < 2)
            return false;
        while (i < nums.length) {
            j = 0;
            while (j < k && i + j + 1 < nums.length) {
                if (nums[i] == nums[i + j + 1]) {
                    return true;
                }
                j++;
            }
            i++;
        }

        return false;
    }
}

算法二:(Accepted)

public class Solution {
    public boolean containsNearbyDuplicate(int[] nums, int k) {
        int i = 0;
        if (nums == null || nums.length < 2 || k < 1)
            return false;
        Map<Integer, Integer> current = new HashMap<Integer, Integer>();

        while (i < nums.length) {
            if (current.containsKey(nums[i])) {
                return true;
            } else {
                current.put(nums[i], i);
                if(i >= k)
                    current.remove(nums[i-k]);
            }
            i++;
        }
        return false;
    }
}

算法时间

T(n) = O(n)

演示测试

import static org.junit.Assert.assertEquals;
import org.junit.Test;

public class SolutionTest {
    private Solution s  = new Solution();
    @Test
    public void test(){
        int [] nums = {11,22,33,44,55,1,2,3,4,5,6,7,8,1};
        int k = 8;
        assertEquals(true,s.containsNearbyDuplicate(nums, k));
    }
}

版权声明:本文为博主原创文章,未经博主允许不得转载。

时间: 2024-08-03 04:51:01

【LeetCode】Contains Duplicate II的相关文章

【LeetCode】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 difference between i and j is at most k. 题目意思就是判断在一个数组中是否存在两个相同的元素,他们之间的距离在k以内. 自己开始的思路是嵌套的两个for循

【Leetcode】Path Sum II

Given a binary tree and a sum, find all root-to-leaf paths where each path's sum equals the given sum. For example: Given the below binary tree and sum = 22, 5 / 4 8 / / 11 13 4 / \ / 7 2 5 1 return [ [5,4,11,2], [5,8,4,5] ] 思路:与[Leetcode]Path Sum 不同

【LeetCode】Spiral Matrix II

Given an integer n, generate a square matrix filled with elements from 1 to n2 in spiral order. For example,Given n = 3, You should return the following matrix: [ [ 1, 2, 3 ], [ 8, 9, 4 ], [ 7, 6, 5 ] ]此题与Spiral Matrix类似,可以用相同的方法解决,相比之下,此题比前一题简单 publ

【leetcode】Word Break II

Given a string s and a dictionary of words dict, add spaces in s to construct a sentence where each word is a valid dictionary word. Return all such possible sentences. For example, givens = "catsanddog",dict = ["cat", "cats"

【Leetcode】Unique Paths II

Follow up for "Unique Paths": Now consider if some obstacles are added to the grids. How many unique paths would there be? An obstacle and empty space is marked as 1 and 0 respectively in the grid. For example, There is one obstacle in the middl

【LeetCode】Jump Game II

Given an array of non-negative integers, you are initially positioned at the first index of the array. Each element in the array represents your maximum jump length at that position. Your goal is to reach the last index in the minimum number of jumps

【LeetCode】Word Search II 解题报告

[题目] Given a 2D board and a list of words from the dictionary, find all words in the board. Each word must be constructed from letters of sequentially adjacent cell, where "adjacent" cells are those horizontally or vertically neighboring. The sa

【LeetCode】Course Schedule II 解题报告

[题目] There are a total of n courses you have to take, labeled from 0 to n - 1. Some courses may have prerequisites, for example to take course 0 you have to first take course 1, which is expressed as a pair: [0,1] Given the total number of courses an

【LeetCode】Jump Game II 解题报告

[题目] Given an array of non-negative integers, you are initially positioned at the first index of the array. Each element in the array represents your maximum jump length at that position. Your goal is to reach the last index in the minimum number of