Given an array of integers, find the numbers such that they add up to a specific target number.
The function twosum should return indices of the numbers such that they add up to the target, where index1 must is Les S than Index2. Please note that your returned answers (both Index1 and INDEX2) is not zero-based.
You may assume this each input would has exactly one solution.
Input: numbers={2, 7, one, a, target=9
Output: index1=1, index2=2
See the topic, I think, this is not simple, two for the loop is done!!!
Brush Write code, correct small error, Leetcode told me: Time Limit exceeded.
/** * Note:the returned array must be malloced, assume caller calls free (). */int* twosum (int* nums, int numssize, int target) { int i, J; int *r = malloc (sizeof (int) * 2); for (i = 0; i < numssize; i++) { int value = Target-nums[i]; for (j= i + 1; j < Numssize; J + +) { if (nums[j] = = value) { R[0] = i + 1; R[1] = j + 1; return r;}} } Free (r); return NULL;}
I am not accepted ah, incredibly still need to optimize!!!
I think, it seems only to optimize the second cycle of the search, write a hash bar.
/** * Note:the returned array must be malloced, assume caller calls free (). */struct Solt {int value; int POS; struct Solt *next;}; struct Solt * * Create (int *nums, int numssize) {int i = 0; struct Solt * * head = calloc (numssize, sizeof (struct solt *)); for (i = 0; i < numssize; i++) {int key = Nums[i]% Numssize; Key = key > 0? Key: ( -1 * key); struct Solt *s = calloc (1, sizeof (struct solt)); S->value = Nums[i]; S->pos = i; if (Head[key]! = NULL) {s->next = Head[key]; } Head[key] = s; } return head; int Soltfind (struct Solt * * head, int numssize, int value) {int key = value% Numssize; Key = key > 0? Key: ( -1 * key); struct Solt * s = head[key]; while (s! = NULL) {if (S->value = = value) {return s->pos; } s = s->next; } return-1;} void Soltfree (struct solt **head, int numssize) {int i = 0; for (i = 0; i < numssize; i++) {struct Solt *s = head[i]; while (s) {struct Solt * st = s->next; Free (s); s = st; }} free (head);} int* twosum (int* nums, int numssize, int target) {int I, J; int *r = malloc (sizeof (int) * 2); struct Solt * * head = Create (nums, numssize); for (i = 0; i < numssize; i++) {int value = Target-nums[i]; Int J = Soltfind (head, numssize, value); if (j >=0 && J! = i) {soltfree (head, numssize); R[0] = i + 1; R[1] = j + 1; return R; }} soltfree (Head, numssize); Free (R); return NULL;}
Leetcode:two Sum