[JAVA] Change one manhattan distance / T : O(N), S : O(1)


  • 0
    J
    public class Solution {
        public int minDistance(int height, int width, int[] tree, int[] squirrel, int[][] nuts) {
            
            int dist = Integer.MIN_VALUE;
            int index = 0;
            int sum = 0;
            for(int i = 0; i < nuts.length; i++){
                int distToT = getDistance(nuts[i], tree);
                int distToS = getDistance(nuts[i], squirrel);
                
                if((distToT - distToS) > dist){
                    index = i;
                    dist = (distToT - distToS);
                }
                sum += 2*distToT;
            }
            
            int distToT = getDistance(nuts[index], tree);
            int distToS = getDistance(nuts[index], squirrel);
            sum -= (distToT - distToS);
            return sum;
        }
        
        public int getDistance(int[] nut, int[] object){
            return Math.abs(nut[0] - object[0]) + Math.abs(nut[1] - object[1]);
        }
    }
    

Log in to reply
 

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