TwoSum IN LeetCode

# quetion

Given an array of integers, return indices of the two numbers such that they add up to a specific target.

You may assume that each input would have exactly one solution, and you may not use the same element twice.

Example:

Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].

# Solution

## C

``````int* twoSum(int* nums, int numsSize, int target, int* returnSize){
int x,y,m,n;
int* array = (int*)malloc(2 * sizeof(int));
while(x <= (numsSize - 2)){
y = x + 1;
while(y <= (numsSize - 1)){
if((*(nums + x) + *(nums + y) ) == target ){
m = x;
n = y;
break;
}
y++;
}
x++;
}
array[0] = m;
array[1] = n;
*returnSize = 2;
return array;
} ``````

I try to set up an Array and return the fist address of this Array is no ok!(自己直接定义一个数组，返回数组头地址失败！)

## C++

``````class Solution {
public:
vector<int> twoSum(vector<int> &nums, int target) {
int x,y,m,n;
x = y = m = n = 0;
//int num = sizeof(nums) / sizeof(int);
//It's not working on top way!
int num = nums.size();
while(x <= num - 2){
y = x + 1;
while(y <= num - 1){
if(nums[x] + nums[y] == target){
m = x;
n = y;
break;
}
y++;
}
x++;
}
vector<int> z(2);
z[0] = m;
z[1] = n;
return z;
}
}; ``````

The first time I know there is a vector in C++!(第一次知道C++中有向量这个东西)

## JAVA

``````class Solution {
public int[] twoSum(int[] nums, int target) {
int x,y,m,n;
x = y = m = n = 0;
while(x <= nums.length - 2){
y = x + 1;
while(y <= nums.length - 1){
if(nums[x] + nums[y] == target){
m = x;
n = y;
break;
}
y++;
}
x++;
}
int[] o = {m,n};
return o;
}
} ``````

Long time not using JAVA,Forgeting how tow set up and use an Array!(好久没尝试用JAVA了，自己已经忘了数组的用法了！)

## python

``````class Solution(object):
def twoSum(self, nums, target):
list = []
for index in range(len(nums)-1):
for index2 in range(index+1,len(nums)):
if(nums[index] + nums[index2] == target):
list.append(index)
list.append(index2)
break
return list``````

Try to rember the class in Python!(尽力去尝试会议Python的类用法！)

### 要不赞赏一下?

 微信 支付宝 PayPal Bitcoin

``https://www.emperinter.info/2020/04/06/two-sum-in-leetcode/``

 阿里云国际版 20美元 Vultr 10美元 搬瓦工 | Bandwagon 应该有折扣吧？ Just My Socks JMS9272283 【注意手动复制去跳转】 域名 | namesilo `emperinter`(1美元) 币安 币安