Test cases need improving


  • 1
    Q

    This solution is incorrect, as it only considers adjacent sorted values, and ADJACENT non-sorted values. Yet it passed all test cases. Simple test case for which it returns false, but should return true: [1,9,3,16,21,2], 2, 2

    public class Solution {
        public boolean containsNearbyAlmostDuplicate(int[] nums, int k, int t) {
            if (nums == null || nums.length <=1 || k==0){
                return false;
            }
            
            Comparator<Number> c1 = new Comparator<Number>(){
                 public int compare(Number n1, Number n2){
                    return new Integer(n1.val).compareTo(new Integer(n2.val));
                }
            };
            
            List<Number> list1= new ArrayList<Number>();
            List<Number> list2= new ArrayList<Number>();
            for (int i=0;i<nums.length;i++){
                Number n = new Number();
                n.val = nums[i];
                n.index = i;
                list1.add(n);
                list2.add(n);
            }
            Collections.sort(list1, c1);
            
            for (int i=0;i<list1.size()-1;i++){
                Number n1 = list1.get(i);
                Number n2 = list1.get(i+1);
                if ((long)n2.val - (long)n1.val <= t && Math.abs(n2.index - n1.index) <= k){
                    return true;
                }
            }
            
            for (int i=0;i<list2.size()-1;i++){
                Number n1 = list2.get(i);
                Number n2 = list2.get(i+1);
                if (Math.abs((long)n2.val - (long)n1.val) <= t){
                    return true;
                }
            }
            return false;
        }
        
        class Number{
            int val;
            int index;
        }
    

    }


  • 1
    R

    I agree.
    The test case did not well reflect the possible considerations due to duplicates.


  • 0

    Thanks for your test case, I have just added it.


Log in to reply
 

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