LeetCode 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

解析

题目的意思其实就是在k的长度范围内,寻找是不是有相同的两个元素。因此需要遍历整个数组,每个都进行对比,其运行的次数为:
(n - 1) + (n - 2) + ... + 1 = n(n-1)/2
时间复杂度为O(n2)。

代码(C语言)

bool containsNearbyDuplicate(int* nums, int numsSize, int k) {
    if (nums == NULL || numsSize == 0)
        return false;
    
    for (int i = 0; i < numsSize - 1; ++i) {
        for (int j = i + 1; j < numsSize; ++j) {
            if (nums[i] == nums[j]) {
                if (j - i <= k)
                    return true;
            }
        }
    }
    
    return false;
}

你可能感兴趣的:(LeetCode 219. Contains Duplicate II)