Two Sum

PROBLEM :

Given an array of integers, return indices of the two numbers such that they add up to a specific target.

You may assume that each input would have exactly one solution.

Example:

Given nums = [2, 7, 11, 15], target = 9,

Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].


------------------------------------------------------------------------------
SIMPLE C++ IMPLEMENTATION 
----------------------------------------------------------------------------------

/**
 * Note: The returned array must be malloced, assume caller calls free().
 */
int* twoSum(int* nums, int numsSize, int target) {
    int i,j,sum,*data ;
    flag=0 ;
    for(i=0;i<numsSize;i++)
    {
        for(j=i+1;j<numsSize;j++)
        {
            sum=nums[i]+nums[j] ;
            if(sum==target)
            {
                data=(int*)malloc(sizeof(int)*2) ;
                data[0]=i ;
                data[1]=j ;
                break ;
            }

        }
    }
    
    return data ;
}

----------------------------------------------------------------------------------

Comments

Popular posts from this blog

Count ways to N'th Stair(Order does not matter)

Replace all ‘0’ with ‘5’ in an input Integer

Chocolate Distribution Problem

Remove characters from the first string which are present in the second string

Primality Test ( CodeChef Problem code: PRB01 )