Java O(n) Solution


  • 0
    W
    	public int minDistance(int height, int width, int[] tree, int[] squirrel, int[][] nuts) {
    		int min = Integer.MAX_VALUE;
    		int totalToTreeOneWay = 0;
    		for (int i = 0; i < nuts.length; i++) {
    			int distanceToSquirrel = getDistance(squirrel, nuts[i]);
    			int distanceToTree = getDistanceToTree(tree, nuts[i]);
    			totalToTreeOneWay += distanceToTree;
    			min = distanceToSquirrel - distanceToTree < min ? distanceToSquirrel - distanceToTree : min;
    		}
    		return totalToTreeOneWay * 2 + min;
    	}
    
    	public int getDistance(int[] obj1, int[] obj2) {
    		return Math.abs(obj1[0] - obj1[0]) + Math.abs(obj1[1] - obj2[1]);
    	}
    
    	public int getDistanceToTree(int[] tree, int[] obj) {
    		return getDistance(tree, obj);
    	}
    

Log in to reply
 

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