Java Solution: HashMap and Sort


  • 0
    public class Solution{
    public boolean isReflected(int[][] points){
        if(points==null||points.length==0||points[0].length!=2){
            return true;
        }
    	
    	HashMap<Integer,List<Integer>> map=new HashMap<>();
    	//sort by y
    	for(int[] p:points){
    		if(!map.containsKey(p[1])){
    			map.put(p[1],new ArrayList<Integer>());
    		}
    		map.get(p[1]).add(p[0]);
    	}
    	
    	//sort by x
    	for(Integer key:map.keySet()){
    		Collections.sort(map.get(key));
    	}
    	
    	//check each bucket:use the average of first element and last element in the first bucket as median,then check every bucket
    	int i;
    	int j;
    	List<Integer> val=map.get(map.keySet().iterator().next());
    	int mid=val.get(0)+val.get(val.size()-1);
    	for(Integer key:map.keySet()){
    		List<Integer> tmp=map.get(key);
    		i=0;
    		j=tmp.size()-1;
    		while(i<=j){
    			if(tmp.get(i)+tmp.get(j)!=mid){
    				return false;
    			}
    			i++;
    			j--;
    		}
    	}
    	return true;
    }
        }

Log in to reply
 

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