---
title: 'LeetCode 1. Two Sum'
disqus: hackmd
---
# LeetCode 1. Two Sum
## Description
Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target.
You may assume that each input would have exactly one solution, and you may not use the same element twice.
You can return the answer in any order.
## Example
Input: nums = [2,7,11,15], target = 9
Output: [0,1]
Explanation: Because nums[0] + nums[1] == 9, we return [0, 1].
## Constraints
2 <= nums.length <= 10^4^
-10^9^ <= nums[i] <= 10^9^
-10^9^ <= target <= 10^9^
Only one valid answer exists.
## Answer
此題可用雙層for loop將每個數值的組合都跑過一遍來求解,而我們這次稍微改一下,外層for loop的i假設為第一解,找內層for loop是否有target-nums[i] 的值就好,若有就記錄並return。
```Cin=
int* twoSum(int* nums, int numsSize, int target, int* returnSize) {
int i = 0, j = 0, tmp = 0;
int *ans = (int*)malloc(sizeof(int)*2);
*returnSize = 2;
for(i = 0; i < numsSize - 1; i++){
tmp = target - nums[i];
for(j = i + 1; j < numsSize; j++){
if(nums[j] == tmp){
ans[0] = i;
ans[1] = j;
break;
}
}
}
return ans;
}
```
## Link
https://leetcode.com/problems/two-sum/
###### tags: `Leetcode`