(Easy) Relative Sort Array LeetCode

class Solution {
    public int[] relativeSortArray(int[] arr1, int[] arr2) {
     
        
        int k = 0;
        
        int t = 0;
        
        int[] res = new int[arr1.length];
        
        int[] tmp = new int[arr1.length];
        
        Set<Integer> set = new HashSet<Integer>();
        Set<Integer> set1 = new HashSet<Integer>();
        
        for(int num : arr1){
            
            set.add(num);
            
        }
        
        for(int i = 0; i<arr2.length; i++){
            for(int j = 0; j<arr1.length; j++){
                
                if(set.contains(arr2[i])){
                    
                    if(arr2[i]==arr1[j]){
                        
                        res[k++]=arr1[j];
                        
                        set1.add(arr1[j]);
                        
                    }
                    
                }   
                
            }
        }
        
      
        for(int i =0; i <arr1.length; i++){
            
            if(!set1.contains(arr1[i])){
                
                tmp[t++]=arr1[i];
            }
        }
        
       int[] tmp2 = new int[t];
    
        for(int i = 0; i<t; i++){
            
            tmp2[i]=tmp[i];
        }
        
        Arrays.sort(tmp2);
        
        for(int i = 0; i<t; i++){
            
            res[k+i] = tmp2[i];
        }
        return res;
    }
}

猜你喜欢

转载自www.cnblogs.com/codingyangmao/p/11284057.html