1. Two Sum

Given an array of integers, return indices of 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].

/**
 * Note: The returned array must be malloced, assume caller calls free().
 */
int* twoSum(int* nums, int numsSize, int target) {
    
}

My Solution.

  1. brute force.
  • Just utilize two for statement
  • So after that I have to check if each sum is the same value given.
  • after finding solution, just you have to checking order of index. So if returnArr[0] is greater than returnArr[1], you have to change value of each returnArr
int* twoSum(int* nums, int numsSize, int target) {

 int * returnArr = (int*)malloc(sizeof(int)*2);
 int i =0, j=0;
 
// memset(returnArr, 0 , sizeof(returnArr)); 
 
 for(i = 0 ; i < numsSize ; i++) {
   for(j = 0 ; j < numsSize ; j++) {
   
      if (i == j)
        continue; 
      
      if ( (nums[i] + nums[j]) == target){
          returnArr[0] = i;
          returnArr[1] = j;
          break;
      }
   }
 }
 
 if(returnArr[0] > returnArr[1]) {
     int temp = returnArr[0];
     
     returnArr[0]=returnArr[1];
     returnArr[1]=temp;
 }
  
 return returnArr;
}  
  1. slightly better method.
  • basically, the concept is the same from the above.
  • But, If you change order of statement, performance is much better.
  • i.e if you change order of operation, the needless operation disappears
int* twoSum(int* nums, int numsSize, int target) {

 int * returnArr = (int*)malloc(sizeof(int)*2);
 int i =0, j=0;
 
memset(returnArr, 0 , sizeof(returnArr)); 
 
 for(i = 0 ; i < numsSize ; i++) {
   for(j = numsSize ; j > 0 ; j--) {
   
      if (i == (j-1))
        break; 
      
      if ( (nums[i] + nums[j-1]) == target){
          returnArr[0] = i;
          returnArr[1] = j-1;
          break;
      }
   }
 }
   
 return returnArr;
}  

memset function is include in .

be carfule,

void* memset(void *str, int c, size_t n)

value of c is converted into the type of unsigned char, so with that value, this function fills the block of memory.

more details, In this URL

in my case, mainly in algorithm competition, I use this function to initialize the memory to 0 or -1