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.

public class Solution {
    public boolean containsNearbyDuplicate(int[] nums, int k) {
        if(nums.length <1) return false;
        if(k <1) return false;
        int i = 0;
        int j = k < nums.length ? k :nums.length -1;
        while(i<j && j<nums.length){
            if(nums[i] != nums[j]){
                i++;
            }
            else{
                return true;
            }
            if(i==j){
               i = i-k+1;
                j++;  
            }
        }
        return false;
    }
}

本站原创文章皆遵循“署名—非商业性使用—相同方式共享 4.0 协议 (CC BY-NC-SA 4.0)”。共享、演绎请保留以下标注:

原文作者:Jake Tao,来源:「LeetCode – 219. Contains Duplicate II」

135
0 0 135

延伸阅读

发表回复

登录后才能评论
分享本页
返回顶部