owned this note
owned this note
Published
Linked with GitHub
# 1. Two Sum
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 1:
```
Input: nums = [2,7,11,15], target = 9
Output: [0,1]
Output: Because nums[0] + nums[1] == 9, we return [0, 1].
```
- Example 2:
```
Input: nums = [3,2,4], target = 6
Output: [1,2]
```
- Example 3:
```
Input: nums = [3,3], target = 6
Output: [0,1]
```
- Constraints:
```
2 <= nums.length <= 104
-109 <= nums[i] <= 109
-109 <= target <= 109
Only one valid answer exists.
```
## C
Greedy
```C=
#include <stdlib.h>
#include <stdio.h>
//1. Two Sum
int* twoSum(int* nums, int numsSize, int target, int* returnSize) {
int* ret = (int*)malloc(2 * sizeof(int));
int temp;
for (int i = 0; i < numsSize; i++) {
temp = target - nums[i];
for (int j = i + 1; j < numsSize; j++) {
if (temp == nums[j]) {
ret[0] = i;
ret[1] = j;
return ret;
}
}
}
return ret;
}
void main() {
//1. Two Sum
int numsSize = 3;
int* nums = (int*)malloc(sizeof(int) * numsSize);
nums[0] = 2;
nums[1] = 3;
nums[2] = 4;
int target = 6;
int* returnSize = (int*)malloc(sizeof(int) * 2);
returnSize = twoSum(nums, numsSize, target, returnSize);
printf("[%d,%d]\n", returnSize[0], returnSize[1]);
}
```

> 動態記憶體分配
C 會用 malloc()、calloc()、realloc()、free() 這四個函數
* 分配空間
* void *malloc(size_t size):
輸入:字節數
回傳:已分配空間的地址,失敗返回 NULL 。
如果 size = 0 ,也會回傳一個合法的指標。
* void *calloc(size_t nitems, size_t size):
輸入:要分配的元素數目、每一格元素的字節數
回傳:已分配空間的地址,失敗返回 NULL 。
同時把所有空間的數值初始化為 0 。
* 釋放空間
* void free(void *ptr):
輸入:地址
釋放從該地址分配的空間。 (哪裏分配哪裏釋放)
沒有回傳。
* 改變已經分配的空間大小
* void *realloc(void *ptr, size_t size):
輸入:曾經分配過空間的地址、新的字節數
回傳:新已分配空間的地址,失敗返回 NULL 。
如果 ptr = NULL ,
等價呼叫 malloc(size) 。
如果 size = 0 ,
等價呼叫 free(ptr) 。
// malloc 會回傳一個合法的指標,這個不會。
> **realloc() 特殊的行為**
> 如果原空間其後的連續記憶體足夠,
> 會擴大原本的空間,
> 回傳 原空間的地址。
>
> 如果其後的連續記憶體不足,
> 會尋找新的、足夠長的記憶體空間,
> 把原本空間的數據複製至新空間,
> 釋放 原空間,
> 回傳 新空間的地址。
## C++
```C++=
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
int temp;
vector<int> results;
for(int i = 0 ; i < nums.size(); i++){
temp = target - nums[i];
for(int j = i + 1 ; j < nums.size(); j++){
if(temp == nums[j]){
results.push_back(i);
results.push_back(j);
return results;
}
}
}
return results;
}
};
```

* vector 常用功能
push_back:把元素加到尾巴,必要時會進行記憶體配置
pop_back:移除尾巴的元素
insert:插入元素
erase:移除某個位置元素, 也可以移除某一段範圍的元素
clear:清空容器裡所有元素
size:回傳目前長度
empty:回傳是否為空
[i]:隨機存取索引值為i的元素,跟傳統陣列一樣索引值從 0 開始
at(i):隨機存取索引值為i的元素,跟上面 operator[] 差異是 at(i) 會作邊界檢查,存取越界會拋出一個例外
reserve():預先配置大小