LeetCode-001.Two Sum

题目描述:

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.

Examples:

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

思路:

题目比较容易,而且题目说了每组输入必有一解,扫描数组,找到i+j=target即可。

C语言解法:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
/**
* Note: The returned array must be malloced, assume caller calls free().
*/
int* twoSum(int* nums, int numsSize, int target) {
int* indices;
int i, j;
indices = (int*)malloc(2*sizeof(int));
for(i=0; i<numsSize-1; i++){
for(j=i+1; j<numsSize; j++){
if(nums[i]+nums[j] == target){
indices[0]=i;
indices[1]=j;
}
}
}
return indices;
}

C++解法:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
vector<int> index(2);
for(int i=0; i<nums.size()-1; i++){
for(int j=i+1; j<nums.size(); j++){
if(nums[i]+nums[j] == target){
index[0]=i;
index[1]=j;
}
}
}
return index;
}
};
觉得文章还凑合,就赏作者一毛钱吧^_^

热评文章