24ms Java sorting solution beats 83.86%


  • 0
    class Number {
        int num, index;
        
        public Number(int num, int index){
            this.num = num;
            this.index = index;
        }
    }
    
    public class Solution {
        private boolean isOutOfRange(int n1, int n2) {
            if(n2 == Integer.MAX_VALUE && n1 < 0) {
                return true;
            }
            
            if(n2 == Integer.MIN_VALUE && n1 > 0) {
                return true;
            }
            
            if(n1 == Integer.MAX_VALUE && n2 < 0) {
                return true;
            }
            
            if(n1 == Integer.MIN_VALUE && n2 > 0) {
                return true;
            }
            
            return false;
    
        }
        
        public boolean containsNearbyAlmostDuplicate(int[] nums, int k, int t) {
            if(null == nums) {
                return false;
            }
            
            int len = nums.length;
            if(len <= 1) {
                return false;
            }
            
            if(len == 2) {
                if(1 <= k && !isOutOfRange(nums[0], nums[1]) && Math.abs(nums[1] - nums[0]) <= t) {
                    return true;
                } else {
                    return false;
                }
            }
        
            List<Number> list = new ArrayList<Number>();
            for(int index=0; index<len; index++) {
                list.add(new Number(nums[index], index));
            }
            
            Collections.sort(list, new Comparator<Number>(){
              @Override
              public int compare(Number n1, Number n2){
                  return n1.num - n2.num;
              }
            });
            
            Number n1 = null;
            Number n2 = null;
            boolean result = false;
            
            for(int i=0; i<len-1; i++) {
                for(int j=i+1; j<len; j++) {
                    n1 = list.get(i);
                    n2 = list.get(j);
                    
                    if(!isOutOfRange(nums[0], nums[1])) {
                        if(Math.abs(n2.num - n1.num) > t) {
                            break;
                        }
                        
                        if(Math.abs(n2.index - n1.index) <= k && Math.abs(n2.num - n1.num) <= t) {
                            result = true;
                            break;
                        }
                    }
                }
                
                if(result) {
                    break;
                }
            }
            
            return result;
        }
        
    }
    

Log in to reply
 

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