Skip to content

Commit

Permalink
Merge pull request neetcode-gh#1010 from julienChemillier/patch-1
Browse files Browse the repository at this point in the history
Add 167-Two-Sum-II.c
  • Loading branch information
Ahmad-A0 authored Sep 4, 2022
2 parents cd722f4 + 80d5a60 commit 93d844c
Showing 1 changed file with 28 additions and 0 deletions.
28 changes: 28 additions & 0 deletions c/167-Two-Sum-II.c
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@

/*
Given a 1-indexed sorted int array & target:
Return indices (added by 1) of 2 nums that add to target
2 pointers, outside in, iterate i/j if sum is too low/high
Time: O(n)
Space: O(1)
*/

int* twoSum(int* numbers, int numbersSize, int target, int* returnSize){
*returnSize = 2;
int* ans = malloc(sizeof(int)*2);

int i = 0;
int j = numbersSize-1;
int k;
while (true) {
k = numbers[i]+numbers[j]-target;
if (k==0) { // numbers[i]+numbers[j] = target
ans[0] = i+1;
ans[1] = j+1;
return ans;
} else if (k>0) // numbers[i]+numbers[j] > target
j--;
else // numbers[i]+numbers[j] < target
i++;
}
}

0 comments on commit 93d844c

Please sign in to comment.