My simple JAVA solution 9ms beating 85.59%


  • 0
    T

    public class Solution {
    public boolean containsNearbyDuplicate(int[] nums, int k) {
    unit [] units=new unit[nums.length];
    for(int i=0;i<nums.length;i++)
    units[i]=new unit(nums[i],i);
    Arrays.sort(units);
    for(int i=1;i<units.length;i++){
    if(units[i].val==units[i-1].val&&
    Math.abs(units[i].index-units[i-1].index)<=k)return true;
    }
    return false;
    }

    public class unit implements Comparable<unit>{
        int val;
        int index;
        public unit(int val, int index){
            this.val=val;
            this.index=index;
            }
    public int compareTo(unit o){
        return this.val<=o.val? -1:1;
    }
    }
    

    }


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.