2016年10月8日星期六

Longest Subset

longest subset from array such that no two elements of the subset differ by more than the interval

input: int[] nums, int interval



2.算法
if(interval) < 0 return {};
so i need to make subset sub[i+1] - sub[i] <= interval

1. sort nums
2. form subset, if illegal, do not add



      public static List<Integer> longestSubset(int[] nums, int interval){  
           List<List<Integer>> ans = new ArrayList<>();  
           if(interval < 0) return new ArrayList<>();  
           Arrays.sort(nums);  
           for(int num: nums){  
                int size = ans.size();  
                for(int i = 0; i < size; i++){  
                     if(ans.get(i).get(ans.get(i).size()-1) >= num - interval){  
                          ans.get(i).add(num);  
                     }  
                }  
                ans.add(new ArrayList<>(Arrays.asList(num)));  
           }  
           int j = 0, max = 0;  
           for(int i = 0; i < ans.size(); i++){  
                if(ans.get(i).size() >= max){  
                     max = ans.get(i).size() ;  
                     j = i;  
                }  
           }  
           return max == 0? new ArrayList<>() : ans.get(j);  
      }  

没有评论:

发表评论