Question
public static int twoSum(int[] arr) returns the number of pairs of unique values whose sum equals zero. Assume that the input array is sorted in
public static int twoSum(int[] arr) returns the number of pairs of unique values whose sum equals zero. Assume that the input array is sorted in ascending order and the values stored in the array are unique.
Example: If arr = {-13, -9, -2, 0, 1, 2, 4, 9, 11} then there are two pairs whose sum is zero. (-9 + 9 = 0 and -2 + 2 = 0).
Each array element can be inspected at most one time. Therefore, you cannot use a nested loop. Stop iterating once the method determines there are no more remaining pairs that sum to zero.
Set an int variable called numPairs to 0.
Set an int variable called left to 0 and an int variable called right to arr.length 1.
Iterate if (i) left < right and (ii) the values stored at left and right have different signs.
If the values stored at left and right have a sum = 0 then increase numPairs by 1, increase left by 1 and decrease right by 1.
If the absolute value stored at left is greater than the value stored at right then increase left by 1. Otherwise, decrease right by 1.
public static int[] convertToOneD(int[][] arr) returns a one-dimensional int array that stores the values contained in arr. The length of the array returned by the method should be equal to the number of int values stored in arr. The returned array should first contain the values stored in row 0, then the values stored in row 1, etc. Do not use a nested loop.
Hint: Use the length property and the System.arraycopy method.
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started