Sum of two

Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target.

You may assume that each input would have exactly one solution, and you may not use the same element twice.

Solution

Beginning

I can observe that class has name Solution and has a public method twoSum with simple types int. There are two types of data array nums with type int and variable int target.

My task is to find sum of two numbers so I am using loops to find numbers.

The outer loop iterates through each element in nums using index i.The inner loop starts from i+1 to avoid using the same element twice.

Next on is method if which is searching proper numbers by comparing int target to 2 numbers from nums array with index i and j.

If the sum of nums[i] and nums[j] equals target, the method returns an array containing the indices [i, j].

If no such pair is found, the method returns [-1, -1], indicating that no valid indices were found.

Leave a comment