Report the indices of two numbers which sum up to the target value in a sorted list

2 visualizaciones (últimos 30 días)
Hi community,
I have a question as below:
How do you report the indices of two numbers which sum up to the target value in a sorted list (no repeating numbers).
Example would be like
nums = [1,2,3,4,7,8,10,11], target = 10, ans = [(1, 5), (2, 4)]
def uniqueSum(nums -> List[int], target -> int):
return

Respuestas (1)

Walter Roberson
Walter Roberson el 16 de Feb. de 2023
nums = [1,2,3,4,7,8,10,11];
target = 10
target = 10
[r,c] = find(triu(nums + nums.' == target));
[r,c]
ans = 2×2
3 5 2 6
You would use a different strategy if the array was significantly longer.
Note: there is a completely different strategy available for the case of sorted inputs only which involes looping and has a much lower computational complexity.

Categorías

Más información sobre Shifting and Sorting Matrices en Help Center y File Exchange.

Etiquetas

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by