Given an array of integers, write a function that returns the indices of the two numbers that
Fantastic news! We've Found the answer you've been seeking!
Question:
Given an array of integers, write a function that returns the indices of the two numbers that add up to a specific target. You may assume that each input would have exactly one solution, and you may not use the same element twice.
Example:
Input: numbers = [2, 7, 11, 15], target = 9 Output: [0, 1] Explanation: numbers[0] + numbers[1] = 2 + 7 = 9, so we return [0, 1].
Requirements:
- The function must have a signature of
int[] twoSum(int[] numbers, int target)
. - You should aim for an efficient solution; discuss the time and space complexity of your approach.
Follow-up Discussion:
- How would you handle the case if the input array is sorted? Would your approach change?
- Can you think of a way to solve this problem with a single pass through the array?
Related Book For
Introduction to Java Programming, Comprehensive Version
ISBN: 978-0133761313
10th Edition
Authors: Y. Daniel Liang
Posted Date: