Storing a two-integer element (coordinate, result set)?

I did a little test today about how to store a two-integer element like coordinate or global/local result set.

The most compact way, which I prefer, is to use a long to store the two results.

public static void main (String[] args) {
	long point = 0L;
	long lowMask = 0x00000000FFFFFFFF;
	int x = -7;
	int y = 10000;
        //CAUTION: Don't use point |= (x << 32) 
        //because this will only trim off excessive digits and fill 0s to right
        //shifting execute before assignment
	point = ((point | x) << 32) | y; 
	System.out.println("point value is: " + point);
 	System.out.println("y value is: " + ((int) (point & lowMask)));
 	System.out.println("x value is: " + ((int) (point >>> 32)));
}
Output:
point value is: -30064761072
y value is: 10000
x value is: -7

For result set purpose, it is very handy to use an array of two element.
The reason is that using array we can pass the reference from previous process(for example recursion) to
the next one. Just like we do in Binary Tree Maximum Path Sum.

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public int maxPathSum(TreeNode root) {
        long[] ret = new long[] {(long) Integer.MIN_VALUE, (long) Integer.MIN_VALUE};
        getSum(root, ret);
        return (int) Math.max(ret[0], ret[1]);
    }
    
    private void getSum(TreeNode root, long[] ret) {
        if (root == null) return;
        
        long[] leftRet = new long[] {(long) Integer.MIN_VALUE, (long) Integer.MIN_VALUE};
        getSum(root.left, leftRet);
        long[] rightRet = new long[] {(long) Integer.MIN_VALUE, (long) Integer.MIN_VALUE};
        getSum(root.right, rightRet);
        
        ret[0] = Math.max(0, Math.max(leftRet[0], rightRet[0])) + root.val;
        ret[1] = Math.max(Math.max(leftRet[0] + rightRet[0] + root.val, ret[0]), Math.max(leftRet[1], rightRet[1]));
        return;
    }
}

Leave a Reply