数组元素为负数时的twosum问题

时间:2019-06-13 22:54:56

标签: c data-structures

我正在解决一个leetcode问题:“给出一个整数数组,返回两个数字的索引,以便它们加起来成为一个特定的目标。 您可以假定每个输入都只有一个解决方案,并且不能两次使用相同的元素。”

如果数组元素为正,我就能解决问题。 我创建了一个适用于正数的哈希表。如何使它适用于非正数。

#include "stdio.h"
#include "stdlib.h"
#include "assert.h"


/**
 * Note: The returned array must be malloced, assume caller calls free(). [2,7,11,15]
 */
int* twoSum(int* nums, int numsSize, int target, int* returnSize){

       //create a hashmap
       int *hashmap = (int*)malloc(100000*sizeof(int));
       int *retarray = NULL;

      //memset all values to -1;
      memset(hashmap,-1,(100000*sizeof(int)));

      int i = 0;
      int complement;

      for(i=0;i<numsSize;i++){
            complement = abs(target-nums[i]);
            if(hashmap[complement]!= -1){
                  *returnSize = 2;
                  retarray = (int*)malloc(*returnSize*sizeof(int));
                  retarray[0] = hashmap[complement];
                  retarray[1] = i;
                  return retarray;
            }
            hashmap[nums[i]] = i;

      }

     *returnSize = 0;
     return retarray;

}

int main(){
    int i = 0;
   // int arr[4] = {2,7,11,15};
    int arr[4] = {-3,3,11,15}; //fails for this.
    int *ret_arr;
    int returnSize;
    ret_arr = twoSum(arr,4,9,&returnSize);
    assert(returnSize==2);
    printf("ret array %d %d \n",ret_arr[0],ret_arr[1]);

}

0 个答案:

没有答案
相关问题